import jsonfrom flask import Flask, requestapp = Flask(__name__)@app.route("/form1", methods=["post"])
def form1():"""获取客户端请求的请求体[表单]:return:""""""获取表单数据请求url:""""""获取表单数据[不包含上传文件]"""#print(request.form)# # ImmutableMultiDict([('username', 'root'), ('password', '123456'), ('fav', 'swimming'), ('fav', 'watch TV')])# # 获取表单项数据[单个值]#print(request.form.get("username")) # root# # 获取表单项数据[多个值]#print(request.form.getlist("fav")) # ['swimming', 'watch TV']"""获取表单数据的上传文件"""#print(request.form.get("username"))# # 获取所有上传文件#print(request.files) # ImmutableMultiDict([('avatar', <FileStorage: 's.png' ('image/png')>)])# # 根据name值获取单个上传文件#print(request.files.get("pt")) # <FileStorage: 's.png' ('image/png')># # 根据name值获取多个上传文件#print(request.files.getlist("pt")) # [<FileStorage: 'a.png' ('image/png')>, <FileStorage: 's.png' ('image/png')>]return "hello, flask"@app.route("/data", methods=["post"])
def data():"""获取客户端请求的请求体[ajax]:return:""""""判断本次客户端是否是ajax请求获取本次客户端提交的数据格式是否是json"""print(request.is_json)"""获取客户端请求体中的json数据"""print(request.json) # {'username': 'root', 'password': '123456'}"""获取客户端请求体的原始数据"""print(request.data) # b'{\n "username": "root",\n "password": "123456"\n}'# 原始数据转json格式print(json.loads(request.data)) # {'username': 'root', 'password': '123456'}"""接收其他格式类型的数据"""# print(request.data)return "hello, flask"@app.route("/file", methods=["post", "put", "patch"])
def file():"""接收上传文件并保存文件:return:"""pt = request.files.get("pt")print(pt)# 调用FileStorage提供的save方法就可以保存文件了pt.save("./avatar.png")#文件会保存在代码路径下return "hello, flask"if __name__ == '__main__':app.run(host="0.0.0.0", port=5000, debug=True)
表单数据上传/不包含文件
表单数据上传/包含文件
左边目录可看到多了一个文件
客户端请求体数据// 右边的数据类型记得设置为json