FLASK学习记录-Flask视图之URL
HTTP请求报文
在请求行中请求的方法通常有几种:GET 、Post 、PUT、DELETE 、TRACE、HEAD、OPTION
request对象
1.request.url: http://xxx:8000/requestInfo?date=2022 2.request.base_url: http://xxx:8000/requestInfo 3.request.url_root: http://xxx:8000/ 4.request.path: /requestInfo 5.request.full_path: /requestInfo?date=2022 6.request.host: xxx:8000 7.request.host_url: http://xxx:8000/ 8.request.json: GET 9.request.json: None 10.request.json: http 11.request.json: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 CCleaner/122.0.0.0 12.request.args: 2022 183.238.113.222 - - [28/Mar/2024 13:15:48] "GET /requestInfo?date=2022 HTTP/1.1" 200 -
URL传参
方法一:URL转换器:string(默认), int, float, path, any, uuid
#字符串 @app.route("/index1/<name>") #整数 @app.route("/index2/<int:num>") #path @app.route("/index3/<path:subpath>") #any @app.route("/index4/<any(a,b,c):word>") #uuid @app.route("/index5/<uuid:uid>")
方法二:查询字符串
@app.route("/get1") def get1(): return request.args.get("str1"),request.args.get("num1") :8000/get1?str1=SB&num1=100 @app.route("/post1",methods=["POST"]) def post1(): return request.form.get("str1"),request.form.get("num1")
:8000/post1?str1=SB&num1=100
两种传参方式各有优劣:其中,URL定义参数可以约束数据类型,而查询字符串传参不用修改URL,更加灵活
URL反转
使用场景:根据视图函数得到所指的URL,可通过url_for函数实现
@app.route('/') def index(): url=url_for("prod",id=10) return "url反转内容{}".format(url) @app.route("/prod/<id>") def prod(id): return "{}".format(id)
@app.route('/') def index(): url=url_for("prod",id=10) return "url反转内容{}".format(url) @app.route("/prod/<id>") def prod(id): return "{}".format(id)
response对象:from flask import Flask,make_response,json,jsonify
URL重定向
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from flask import Flask,abort,request app=Flask(__name__) @app.route("/") def root(): return redirect(url_for("index")) @app.route('/index') def index(): return 'index' @app.route("/login", methods=['GET']) def login(): name = request.args.get("name") pwd = request.args.get("pwd") if name != "aaa" or pwd != "123456": abort(404) return "login successful!" @app.errorhandler(404) def no_found(error): return "wrong name or pwd" if __name__ == '__main__': app.run(host='0.0.0.0',port=8000,debug=True) 验证 :8000/login?name=aaa&pwd=123456