request-Flask的请求对象
请求解析和响应封装大部分是有Werkzeug完成的,Flask子类化Werkzeug的请求(Request)对象和响应(Response)对象,并添加了和程序的特定功能。
#encoding=utf-8
from flask import Flask,request
app=Flask(__name__)
@app.route('/hello/')
def hello():
name = request.args.get('name','Flask') #获取查询参数name的值,默认是Flask
return '<h1>Hello, %s</h1>' % name #替换到返回值中 if __name__ == '__main__':
app.run(debug=True)
结果:
当url中不指定name和值,默认返回name的值为Flask
打印request对象的属性信息
#encoding=utf-8 from flask import Flask,request
app=Flask(__name__) @app.route('/hello/')
def hello():
name = request.args.get('name','Flask') #获取查询参数name的值
print "request.args:",request.args
print "request.args.items():",request.args.items()
print "request.full_path:",request.full_path
print "request.path:",request.path
print "request.host:",request.host
print "request.host_url:",request.host_url
print "request.headers:\n",request.headers
print u"请求数据request.data:",request.data
print "request.endpoint:",request.endpoint
print "request.json:",request.json
print "request.method:",request.method
print u"请求的url模式(http或https)request.scheme:",request.scheme
print "request.user_agent:\n",request.user_agent
return '<h1>Hello, %s</h1>' % name # 替换到返回值中 if __name__ == '__main__':
app.run(debug=True)
刷新页面请求后输入结果:可以看到url的信息
request.args: ImmutableMultiDict([('name', u'xiaxiaoxu')])
request.args.items(): [('name', u'xiaxiaoxu')]
request.full_path: /hello/?name=xiaxiaoxu
request.path: /hello/
request.host: 127.0.0.1:5000
request.host_url: http://127.0.0.1:5000/
request.headers:
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
Connection: keep-alive
Host: 127.0.0.1:5000
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.9
Accept-Encoding: gzip, deflate, br
请求数据request.data:
request.endpoint: hello
request.json: None
request.method: GET
请求的url模式(http或https)request.scheme: http
request.user_agent:
Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
127.0.0.1 - - [25/Dec/2018 22:08:19] "GET /hello/?name=xiaxiaoxu HTTP/1.1" 200 -