1. request请求最常用的两种:
get
请求
GET
把参数包含在URL
中,访问时会在地址栏直接显示参数不安全,且参数大小比较小。post
请求
参数通过request body
传递。
2. GET请求方式获取参数
在route
装饰器语句中,通过methods
指定请求方式,如下:
@app.route("/", methods=["GET"])
获取参数:
if request.method == "GET":
comment = request.args.get("key")
comment = request.values.get("key")
3. POST请求方式获取参数
POST请求概述:
客户端在发送post
请求时,数据可以使用不同的Content-Type
来发送。比如:以 application/json
的方式 ,请求body
体的内容就是{"a": "b", "c": "d"}
以 application/x-www-form-urlencoded
的方式,则body体的内容就是 a=b&c=d
。在Postman
中,可以方便的查看参数是以什么形式发送的,对应的Content-Type
是什么。
在postman
中:
-
Body中选择
raw
,则对应的Headers
中的Content-Type
是application/json
,参数形式是{"content":"很好"}
-
Body中选择
x-www-form-urlencoded
,则对应的Headers
中的Content-Type
是application/x-www-form-urlencoded
,参数形式是Key-Value
。 -
Body中选择
form-data
, 则对应的Headers
中的Content-Type
是multipart/form-data
,参数形式是Key-Value
。
POST请求不同Content-Type的处理方式
Content-Type
为application/json
,获取json参数
# 获取所有参数,一般情况下满足使用,不需要`json.loads()`来序列化。打印出结果就是`json`串。
request.get_json()
# 获取指定的参数
request.get_json()['key']
# 或者
request.json.get('key')
Content-Type
为application/x-www-form-urlencoded
request.values.get('key')
Content-Type
为multipart/form-data
,获取表单参数
request.form.get('key')
# 或者
request.form['key']