jsonify模块
可以将Python的数据结构快速转为Json格式字符串。
GET快捷参数
1. 使用尖括号
@app.route('/user/<id>') # <int:id> id作为int类型,来过滤 <string:id>def user_info(id):print(id)return id
2. 使用参数列表
GET请求为
http://127.0.0.1:5000/user/?id=1532
则代码需要引入request来进行参数解析
@app.route('/user/', methods=['GET'])def user_info():id = request.args.get('id')print(id)return id
http://127.0.0.1:5000/user/?id=1532&pwd=16
GET参数使用字符来替换操作语句,类似于SQL的结构。例如& 替换and,?替换where
@app.route('/user/', methods=['GET'])def user_info():id = request.args.get('id')pwd = request.args.get('pwd')print(pwd)print(id)return f"您的id为{id},密码为{pwd}"
3. methods 只允许列表中的请求类型
如果不在列表中,则会返回Methods NOT Allow错误。
构造URL
url_for可以通过函数名来寻找URL。
如果需要发生跳转,但是URL已经改变,因此直接通过字符串寻找URL来实现功能就无法应对URL改变的情况。
例如函数甲需要跳转到函数乙,但是函数乙的URL已经改变,则需要url_for,而非使用硬编码
url_for可以自动转义Unicode字符串。例如GET方法的空格和中文会被转化。
@app.route('/info/<msg>')def re_msg(msg):return msg@app.route('/api/user/',methods=['GET'])def api_info():myid = request.args.get('id')mymsg = request.args.get('msg')print(myid)redirectUrl = url_for("re_msg", msg=mymsg)print(redirectUrl)return mymsg
GET请求为:
http://127.0.0.1:5000/api/user/?id=12&msg=asd
重定向和跳转
永久重定向
暂时性重定向
导入redirect包
from flask import redirect
@app.route('/login/<id>')def login(id):if id == 1:return "correct" # 永久重定向else:return redirect(url_for("index")) # 临时重定向,返回302
