Flask——request的form_data_args用法
request中包含了前端发送过来的所有请求数据,在使用前要进行导入request库
from flask import Flask,request
1.form和data是用来提取请求体数据,通过request.form可以直接提取请求体中的表单格式的数据,是一个类字典的对象,例如:
from flask import Flask,requestapp = Flask(__name__)@app.route("/index",methods=["GET","POST"])
def index():# request中包含了前端发送过来的所有请求数据# form和data是用来提取请求体数据# 通过request.form可以直接提取请求体中的表单格式的数据,是一个类字典的对象name = request.form.get("name")age = request.form.get("age")return "hello world name=%s ,age=%s"%(name, age)if __name__ == '__main__':app.run(host="127.0.0.1", port=8000,debug=True)
但是通过get方法只能拿到多个同名参数的第一个,getlist方法可以拿到多个同名参数的列表,例如:
from flask import Flask,requestapp = Flask(__name__)@app.route("/index",methods=["GET","POST"])
def index():# request中包含了前端发送过来的所有请求数据# form和data是用来提取请求体数据# 通过request.form可以直接提取请求体中的表单格式的数据,是一个类字典的对象# 通过get方法只能拿到多个同名参数的第一个name = request.form.get("name")age = request.form.get("age")print(request.data)# getlist方法可以拿到多个同名参数的列表name_li = request.form.getlist("name")return "hello world name=%s ,age=%s, name_li=%s"%(name, age, name_li)if __name__ == '__main__':app.run(host="127.0.0.1", port=8000,debug=True)
2.若数据不是表单格式的数据,可用requset.data来进行提取
from flask import Flask,requestapp = Flask(__name__)@app.route("/index",methods=["GET","POST"])
def index():result= request.datareturn resultif __name__ == '__main__':app.run(host="127.0.0.1", port=8000,debug=True)
3.args是用来提取url中的参数,例如http://127.0.0.1:8000/index?city=BeiJing
查询字符串,可以用args方式进行提取city参数,范例如下:
from flask import Flask,requestapp = Flask(__name__)# http://127.0.0.1:8000/index?city=huizhou 查询字符串 可以用args方式进行提取
@app.route("/index",methods=["GET","POST"])
def index():# args是用来提取url中的参数city = request.args.get("city")day = request.args.get("day")return "hello world city=%s, day=%s"%( city, day)if __name__ == '__main__':app.run(host="127.0.0.1", port=8000,debug=True)
request的form_data_args用法就先写到这里,读者有什么疑问可以评论或私信,博主看到会进行解答的。