一、flask请求对象request
request是flask框架的全局对象,你可以通过它来获得当前进入的请求数据,如果是在多线程环境下,flask可以保证你所使用的request对象就是当前这个线程所处理的请求。
服务端代码:
from flask import Flask, request app = Flask(__name__) @app.route('/users', methods=['GET', 'POST']) def users(): print(request.method) # 请求方法 print(request.headers) # 请求的headers print(request.path) # 资源路径 print(request.url) # 完整的url print(request.remote_addr) # 客户端IP print(request.cookies) # 请求的cookie return 'ok' if __name__ == '__main__': app.run(debug=True)
客户端代码:
import requests cookie_dict = {'name': 'python'} res = requests.get('http://127.0.0.1:5000/users', cookies=cookie_dict)
服务端程序返回结果:
GET # 请求方法 Content-Type: Content-Length: Host: 127.0.0.1:5000 User-Agent: python-requests/2.22.0 Accept-Encoding: gzip, deflate Accept: */* Connection: keep-alive Cookie: name=python /users # 资源路径 http://127.0.0.1:5000/users # 完整路径 127.0.0.1 # 客户端ip {'name': 'python'} # 请求的cookie
二、flask解析http请求数据
flask如何解析http的get请求的参数, 解析post请求提交的表单和json数据,详情可见以下示例
服务端代码:
from flask import Flask,request app = Flask(__name__) import pysnooper #1、解析get请求数据(get请求的参数可以通过request.args来获得,也可以通过request.values来获得) @pysnooper.snoop() @app.route('/users1',methods=['GET','POST']) def users1(): name=request.values['name'] age=request.args['age'] print(name,age) return 'ok' #2、获得post请求表单数据(可以通过request.form,也可以通过request.values获得) @pysnooper.snoop() @app.route('/users2',methods=['POST']) def users2(): name=request.form['name'] age=request.values['age'] print(name,age) return 'ok' #3、获得json请求数据(post提交的json数据,不能通过args,form.values来获取,而是要用get_json()方法来获取) @app.route('/users3',methods=['POST']) def users3(): data=request.get_json() print(data) return 'ok' if __name__ == '__main__': app.run(debug=True)
响应结果:
客户端代码:
import requests def request01(): param={ "name":"poly", "age":14 } res=requests.get("http://127.0.0.1:5000/users1",params=param,verify=True) print(res.text) def request02(): data = { "name": "poly1", "age": 15 } res = requests.post("http://127.0.0.1:5000/users2", data=data, verify=True) print(res.text) def request03(): json={'name': 'poly2', 'age': 16} res=requests.post("http://127.0.0.1:5000/users3",json=json,verify=True) print(res.text) if __name__ == '__main__': request01() request02() request03()
响应结果:
标签:__,http,请求,Flask,request,flask,print,name From: https://www.cnblogs.com/xfbk/p/16720866.html