django是个大而全的框架,flask是一个轻量级的框架。
django内部为我们提供了非常多的组件:orm / session / cookie / admin / form / modelform / 路由 / 视图 / 模板 / 中间件 / 分页 / auth / contenttype / 缓存 / 信号 / 多数据库连接
flask框架本身没有太多的功能:路由/视图/模板(jinja2)/session/中间件 ,第三方组件非常齐全。
注意:django的请求处理是逐一封装和传递; flask的请求是利用上下文管理来实现的。
安装
pip3 install flask #会自动安装依赖
1. 依赖wsgi Werkzeug
from werkzeug.serving import run_simple
def func(environ, start_response):
print('请求来了')
pass
if __name__ == '__main__':
run_simple('127.0.0.1', 5000, func)
from werkzeug.serving import run_simple
class Flask(object):
def __call__(self,environ, start_response):
return "xx"
app = Flask()
if __name__ == '__main__':
run_simple('127.0.0.1', 5000, app)
from werkzeug.serving import run_simple
class Flask(object):
def __call__(self,environ, start_response):
return "xx"
def run(self):
run_simple('127.0.0.1', 5000, self)
app = Flask()
if __name__ == '__main__':
app.run()
2. 快速使用flask
from flask import Flask
# 创建flask对象
app = Flask(__name__)
@app.route('/index')
def index():
return 'hello world'
@app.route('/login')
def login():
return 'login'
if __name__ == '__main__':
app.run()
总结:
- flask框架是基于werkzeug的wsgi实现,flask自己没有wsgi。
- 用户请求一旦到来,就会之
app.__call__
方法 。 - 写flaks标准流程
3.用户登录&用户管理
from flask import Flask,render_template,jsonify,request,redirect,url_for,session
import functools
app = Flask(__name__)
app.secret_key = 'zbbzxy521521!'
DATA_DICT = {
1:{'name':'zbb','age':24},
2:{'name':'zxy','age':18}
}
def auth(func):
@functools.wraps(func)
def inner(*args,**kwargs):
username = session.get('xxx')
if not username:
return redirect(url_for('login'))
return func(*args,**kwargs)
return inner
@app.route('/login',methods=['GET','POST'])
def login():
if request.method == 'GET':
return render_template('login.html')
user = request.form.get('user')
pwd = request.form.get('pwd')
if user == 'zbb' and pwd == 'zxy':
session['xxx'] = 'zbb'
return redirect('/index')
error = "输入哟有误"
return render_template('login.html',error=error)
@app.route('/index',endpoint='idx')
@auth
def index():
data_dict = DATA_DICT
return render_template('index.html',data_dict=data_dict)
@app.route('/edit',methods=['GET','POST'])
@auth
def edit():
nid = request.args.get('nid')
nid = int(nid)
info = DATA_DICT[nid]
if request.method == "GET":
return render_template('edit.html',info=info)
user = request.form.get('name')
pwd = request.form.get('age')
DATA_DICT[nid]['name']=user
DATA_DICT[nid]['age']=pwd
return redirect(url_for('idx'))
@app.route('/del/<int:nid>')
@auth
def delete(nid):
del DATA_DICT[nid]
return redirect(url_for('idx'))
if __name__ == '__main__':
app.run()
edit.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post">
<input type="text" name = 'name' value="{{ info.name }}">
<input type="text" name = age value="{{ info.age }}">
<input type="submit" name = '提交'>>
</form>
</body>
</html>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>用户列表</h1>
<table border="1">
<thead>
<tr>
<th>id</th>
<th>用户名</th>
<th>年龄</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for key,value in data_dict.items() %}
<tr>
<td>{{ key }}</td>
<td>{{ value.name }}</td>
<td>{{ value.age }}</td>
<td>
<a href="/edit?nid={{key}}">编辑</a>
<a href="/del/{{key}}">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>用户登录</h1>
<form method="post">
<input type="text" name = 'user'>
<input type="text" name = pwd>
<input type="submit" name = '提交'><span style="color: red;">{{ error }}</span>
</form>
</body>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
</html>
4.总结
1.flask路由
@app.route('/login',methods=['GET','POST'])
def login():
pass
2.路由的参数
@app.route('/login',methods=['GET','POST'],endpoint="login")
def login():
pass
# 注意:endpoint不能重名
3.动态路由
@app.route('/index')
def login():
pass
@app.route('/index/<name>')
def login(name):
pass
@app.route('/index/<int:nid>')
def login(nid):
pass
4.获取提交的数据
from flask import request
@app.route('/index')
def login():
request.args # GET形式传递的参数
request.form # POST形式提交的参数
5.返回数据
@app.route('/index')
def login():
return render_template('模板文件')
return jsonify()
reutrn redirect('/index/') # reutrn redirect(url_for('idx'))
return "...."
6.模板处理
{{ x }}
{% for item in list %}
{{item}}
{% endfor %}
7.session处理
app.secret_key = 'zbbzxy521521!' #设置key
session['xxx'] = 'zbb' #登录功之后添加session