栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Flask——request的form

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Flask——request的form

request中包含了前端发送过来的所有请求数据,在使用前要进行导入request库

from flask import Flask,request

1.form和data是用来提取请求体数据,通过request.form可以直接提取请求体中的表单格式的数据,是一个类字典的对象,例如:

from flask import Flask,request

app = 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,request

app = 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,request

app = Flask(__name__)

@app.route("/index",methods=["GET","POST"])
def index():
    result= request.data
    return result

if __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,request

app = 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用法就先写到这里,读者有什么疑问可以评论或私信,博主看到会进行解答的。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/360244.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号