介绍
django是大而全,flask是轻量级的框架
django提供非常多组件:orm/session/cookie/admin/form/modelform/路由/视图/模板/中间件/分页/auth/contentype/缓存/信号/多数据库连接
flask本身没有太多的功能:路由/试视图/模板/session/中间件,第三方组件齐全
注意:django的请求处理是逐一封装和传递;flask请求是利用上下文管理实现的
快速使用
安装
pip install flask
依赖
Werkzeug
基于wsgi的服务
from werkzeug.serving import run_simple
def func(environ,start_response):
print("请求来了")
pass
if __name__ =='__main__':
run_simple('127.0.0.1', 5000, func)
基于flask服务
# flask 基于werkzeug的wsgi实现,flask自己没有wgsi # 用户一旦请求到来,就会调用app.__call__方法
from flask import Flask
app = Flask(__name__)
@app.route('/index')
def index():
return "hello word"
if __name__ == '__main__':
app.run()
简单操作
工程目录
主文件s2.py
from flask import Flask, render_template, jsonify, request, redirect, url_for
app = Flask(__name__)
DATA_DICT = {
1: {'name': '袁山山', 'age': 13},
2: {'name': '张涛', 'age': 18}
}
@app.route('/login', methods=['GET', 'POST'])
def login():
# return '登录'
if request.method == 'GET':
return render_template('login.html')
# return jsonify({'code': 1000, 'data': [1, 2, 3]})
user = request.form.get('user')
pwd = request.form.get('pwd')
print(user, pwd)
if user == '1' and pwd == '1':
return redirect('/index')
error_message = '用户名或密码错误'
return render_template('login.html', **{'error_message': "用户名或密码错误"})
@app.route('/index', endpoint='idx')
def index():
data_dict = DATA_DICT
return render_template('index.html', data_dict=data_dict)
@app.route('/edit', methods=['GET', 'POST'])
def edit():
nid = int(request.args.get('nid'))
if request.method == 'GET':
info = DATA_DICT[nid]
return render_template('edit.html', info=info)
username = request.form.get('username')
age = request.form.get('age')
DATA_DICT[nid]["username"] = username
DATA_DICT[nid]["age"] = age
return render_template('index.html', data_dict=DATA_DICT)
# url_for使用接口别名访问,使用endpoint起别名
@app.route('/delete/<int:nid>')
def delete(nid):
print(nid)
del DATA_DICT[nid]
# return redirect('/index')
return redirect(url_for('idx'))
if __name__ == '__main__':
app.run()
登录界面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录界面</title>
</head>
<body>
<h1>hello ,哈哈哈哈哈哈哈哈哈哈哈</h1>
<form method="post">
<input type="text" name="user">
<input type="password" name="pwd">
<input type="submit" value="提交">
{{error_message}}
</form>
</body>
</html>
主页
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<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="/delete/{{key}}">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
修改
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>修改界面</title>
</head>
<body>
<h1>修改用户信息</h1>
<form method="post">
<input type="text" name="username" value="{{info.name}}">
<input type="number" name="age" value="{{info.age}}">
<input type="submit" value="提交">
</form>
</body>
</html>
总结
flask路由
@app.route('/login', methods=['GET', 'POST']) def login():
路由参数:endpoint为页面的别名,不可以重复,可以使用url_for直接引用别名跳转
@app.route('/index', methods=['GET', 'POST'], endpoint='idx') def index(): pass@app.route('/delete/<int:nid>') def delete(nid): print(nid) del DATA_DICT[nid] # return redirect('/index') return redirect(url_for('idx'))
动态路由(路径传参,get传参)
@app.route('/index')
def index():
pass
路径传参:
@app.route('/index/<name>')
def index():
pass
@app.route('/index/<int:nid>')
def index(nid):
pass
get传参
from flask import requesr
@app.route('/index')
def index():
username= reques.args.get("")获取url中的参数数据
username = request.form.get("")获取表单的数据
返回数据
@app.route('/index')
def login():
return render_template(“模板文件”)
return jsonify()
return redirect("/index/")
return redirect(url_for('index'))
return str
模板处理
{{x}}
{% for item in list %}
{{item}}
{% endfor %}