本章内容
flask入门
先贴个学习的文档,flask只是python其中的一部分,但是单单一个flask就不那么简单。
http://docs.jinkan.org/docs/flask/
先来个简单的小练习:
a.txt 文件中有python:123 java:456 文件,然后使之在浏览器中显示
from flask import Flask
app = Flask(__name__)
@app.route('/user')
def user():
temp = '<tr><td>%s</td><td>%s</td></tr>'
res = '<table border="1">'
res += '<tr><td>USER</td><td>PASSWD</td></tr>'
with open('a.txt') as f:
for line in f:
user = line.split(':')[0] #把一行的文件已冒号为分割,然后取出
passw = line.split(':')[1]
res += temp%(user,passw)
res += '</table>'
return res
if __name__ == '__main__':
app.run(host='0.0.0.0',port=9911,debug=True)
运行结果如下:
USER | PASSWD |
python | 123 |
java | 456 |
厉害了我的哥,看学来的简便的方法。
user = line.split(':')[0] #把一行的文件已冒号为分割,然后取出
passw = line.split(':')[1]
res += temp%(user,passw)
缩减为一行了:res += tmp%tuple(line.split(':'))
小知识点:
with open('a.txt') as f:
for line in f:
print line.split(':') #被split后就变成了一个list了。初始的line是string,python:123
userlist.append(line.split(':'))
print userlist
先鲁代码吧,课堂上的练习
from flask import Flask,render_template,request,redirect,session
app = Flask(__name__)
app.secret_key='abcdefghigklmnopgistuvwxyz'
@app.route('/login',methods=['GET','POST'])
def login():
if request.method == 'GET':
return render_template('login.html')
elif request.method == 'POST':
user = request.form.get('username')
pwd = request.form.get('pwd')
if user and pwd:
if user == 'admin' and pwd == 'admin':
session['user'] = 'admin'
return redirect('/userlist')
else:
return 'wrong username or passwd!try again'
else:
return 'you need input your username or passwd'
@app.route('/logout')
def logout():
del session['user']
return redirect('/login')
@app.route('/userlist')
def userlist():
userlist = []
with open('a.txt') as f:
for line in f:
userlist.append(line.split(':'))
return render_template('userlist.html',userxxx=userlist)
@app.route('/adduser',methods = ['GET','POST'])
def adduser():
print session.get('user')
print '*'*50
if session.get('user') != 'admin':
return 'you need login or not allowed this user'
if request.method == 'GET':
return render_template('adduser.html')
elif request.method =='POST':
user = request.form.get('user')
pwd = request.form.get('pwd')
with open('a.txt','a') as f:
f.write(user+':'+pwd+' ')
return redirect('/userlist')
if __name__ == '__main__':
app.run(host='0.0.0.0',port=7777,debug=True)
login简化版写法
#flask代码
@app.route('/login',methods=['GET','POST']) def login(): if request.method == 'POST': user_info = { k:v[0] for k,v in dict(request.form).items()} #转化为字典的形式,格式看下面print print 'request.form',request.form print 'user_info',user_info res = getone('user',field,user_info) if res['code'] == 0: if res['msg']['password'] == user_info['password']: session['username'] = user_info['username'] session['role'] = res['msg']['role'] return json.dumps(res) else: res['code'] = 1 res['errmsg'] = 'user is exsit,but password is wrong' return json.dumps(res) else: res['errmsg'] = 'user is not exist!' return json.dumps(res) return render_template('login.html') #代码解析 request.form ImmutableMultiDict([('username', u'pc'), ('password', u'12345')]) #转换前 user_info {'username': u'pc', 'password': u'12345'} #转换后
#操作数据库,验证登录用户的信息
def getone(table,field,data): if data.has_key("username"): sql = 'select * from %s where username="%s"' % (table,data['username']) else: sql = 'select * from %s where id="%s"' % (table,data['id']) cur.execute(sql) res = cur.fetchone() print 'sql,sql_res',sql,res #print结果详见下面 if res: user = {k:res[i] for i,k in enumerate(field)} print 'user:',user #print结果详见下面 result = {'code':0,'msg':user} else: result = {'code':1,'msg':"data is null"} return result #运行结果: sql,sql_res select * from user where username="pc" (7L, u'pc', u'1234567', 1L) user: {'username': u'pc', 'password': u'1234567', 'role': 1L, 'id': 7L}
login.html代码,主部分主要是通过jinjia2和ajax去完成了,抛开了默认提交的功能
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> 登录 | TXadmin</title> <link rel="shortcut icon" href="/static/img/facio.ico" type="image/x-icon"> <link href="/static/css/bootstrap.min.css" rel="stylesheet"> <link href="/static/css/style.css" rel="stylesheet"> <link href="/static/css/sweetalert.css" rel="stylesheet"> </head> <body class="gray-bg"> <div class="middle-box text-center loginscreen animated fadeInDown"> <div> <div> <h1 class="logo-name"><img src="/static/img/1.png"></h1> </div> <h2>Welcome to TXadmin</h2> <form id="loginForm" method="post"> <div class="form-group"> <input id="name" type="text" name="username" class="form-control" placeholder="Username" required="length[6~50]"> </div> <div class="form-group"> <input id="password" type="password" name="password" class="form-control" placeholder="Password" required=""> </div> <button id="loginbtn" type="submit" class="btn btn-primary block full-width m-b">登录</button> </form> <p style="color:blue">管理员账号:pc, 密码:1234567</p> <p class="m-t"> <small><b>Copyright</b> Mr.python © 2017-2018</small> </p> </div> </div> <!-- Mainly scripts --> <script src="/static/js/jquery-2.1.1.js"></script> <script src="/static/js/sweetalert.min.js"></script> <script src="/static/js/bootstrap.min.js"></script> <script> $('#loginbtn').on('click',function(){ var user_info = $('#loginForm').serialize() console.log(user_info) $.post('/login',user_info,function(data){ console.log(data) data = JSON.parse(data) console.log(data) if (data['code']==0){ swal({ title: "登录成功", text: data['result'], type: "success", confirmButtonText: "确定" },function(){ location.href="/" }); }else{ swal("MY GOD",data['errmsg'],"error"); } }) return false #作用是不在走默认的表单操作了 }) </script> </body> </html>
Flask + Mysql |
连接数据库的5个步骤
conn = MySQLdb.connect(host=DB_HOST, port=DB_PORT, user=DB_USER, passwd=DB_PASSWD, db=DB_DBNAME, charset=DB_CHARSET)
cur = conn.cursor()
cur.execute(SQL_USER_UPDATE, (clazz, tel, addr, age, uid))
conn.commit()
cur.close()
conn.close()
con.autocommit(True) #可以添加这一行,自动提交修改的内容到数据库
request.form.get #获取post请求提交的参数
request.args.get #获取get请求提交的参数