Sanic官翻-请求数据
请求数据
当端点接收到HTTP请求时,将向路由功能传递一个Request对象。
请求对象属性
以下变量可以作为请求对象的属性访问
属性 | 类型 | 说明 |
---|---|---|
json |
any | json的body类型 |
args |
dict | 查询字符串的字典形式 |
query_args |
list | 查询字符串的列表形式 |
raw_args |
dict | 查询字符串的首个变量 |
files |
dict或file | 具有name、body和type的文件列表 |
form |
dict | 提交的表单变量 |
body |
bytes | 提交的原始body |
headers |
dict | 包含请求标头的不区分大小写的字典。 |
method |
str | 请求的HTTP方法,如GET、POST |
ip |
str | 请求者的ip地址 |
port |
str | 请求者的port地址 |
socket |
tuple | 请求者的(ip, port) |
app |
对正在处理此请求的Sanic应用程序对象的引用。 | |
url |
请求的URL的完整形式,如http://localhost:8000/posts/1/?foo=bar |
|
scheme |
与请求关联的URL方案,“http/https/ ws/wss”或标题给定的任意值。 | |
host |
与请求关联的主机(位于Host header中),如localhost:8080 |
|
server_name |
服务器的主机名,不带端口号,从如下顺序中找到config.SERVER_NAME, x-forwarded-host标头, Request.host() |
|
server_port |
服务器的端口号,在如下顺序中找到x-forwarded-port标头,Request.host(),传输层套接字使用的实际端口 |
|
path |
请求的路径,如/posts/1/ |
|
query_string |
请求的查询字符串:foo = bar或空白字符串“” | |
uri_template |
匹配路由处理程序的模板:/ posts / <id> / |
|
token |
授权标头的值:Basic YWRtaW46YWRtaW4 = |
|
url_for |
就像sanic.Sanic.url_for一样,但是会根据请求自动确定scheme和netloc。由于此方法旨在生成正确的scheme和Netloc,因此应用_external。 |
json(any)
Json body
from sanic.response import json
@app.route("/json")
def post_json(request):
return json({ "received": True, "message": request.json })
args(dict)
查询字符串变量。查询字符串是URL中类似于?key1 = value1&key2 = value2
的部分。
如果要解析该URL,则args词典将类似于{'key1':['value1'],'key2':['value2']}
。请求的query_string变量包含未解析的字符串值。
属性提供默认的解析策略。如果要更改它,请查看下面的部分(更改queryset的默认解析规则)。
from sanic.response import json
@app.route("/query_string")
def query_string(request):
return json({ "parsed": True, "args": request.args, "url": request.url, "query_string": request.query_string })
query_args(list)
在许多情况下,您将需要使用较少打包的形式访问url参数。query_args是(键,值)元组的列表。
属性提供默认的解析策略。如果要更改它,请查看下面的部分(更改queryset的默认解析规则)。
对于相同的先前URL查询集?key1 = value1&key2 = value2
,query_args列表类似于[('key1','value1'),('key2','value2')]
。如果多个参数具有相同的键,例如?key1 = value1&key2 = value2&key1 = value3
,则query_args列表看起来像[('key1','value1'),('key2', 'value2'),('key1','value3')]
。
对于参数?key1=value1&key2=value2&key1=value3
在Request.args
以及Request.query
区别
from sanic import Sanic
from sanic.response import json
app = Sanic(__name__)
@app.route("/test_request_args")
async def test_request_args(request):
return json({
"parsed": True,
"url": request.url,
"query_string": request.query_string,
"args": request.args,
"query_args": request.query_args,
})
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8000)
# Output
{
"parsed":true,
"url":"http:\/\/0.0.0.0:8000\/test_request_args?key1=value1&key2=value2&key1=value3",
"query_string":"key1=value1&key2=value2&key1=value3",
"args":{"key1":["value1","value3"],"key2":["value2"]},
"query_args":[["key1","value1"],["key2","value2"],["key1","value3"]]
}
files(dictionary of File objects)
具有名称,主体和类型的文件列表
@app.route("/files")
def post_json(request):
test_file = request.files.get('test')
file_parameters = {
'body': test_file.body,
'name': test_file.name,
'type': test_file.type,
}
return json({ "received": True, "file_names": request.files.keys(), "test_file_parameters": file_parameters }
form(dict)
提交的表单变量
from sanic.response import json
@app.route("/form")
def post_json(request):
return json({ "received": True, "form_data": request.form, "test": request.form.get('test') })
body(bytes)
提交的原始body。该属性允许检索请求的原始数据,而与内容类型无关。
from sanic.response import text
@app.route("/users", methods=["POST",])
def create_user(request):
return text("You are trying to create a user with the following POST: %s" % request.body)
app
对正在处理此请求的Sanic应用程序对象的引用。
当在无法访问全局应用程序对象的模块中的蓝图或其他处理程序内部时,此功能很有用。
from sanic.response import json
from sanic import Blueprint
bp = Blueprint('my_blueprint')
@bp.route('/')
async def bp_root(request):
if request.app.config['DEBUG']:
return json({'status': 'debug'})
else:
return json({'status': 'production'})
其他
- headers(dict)-包含请求头的不区分大小写的字典。
- method(str)-请求的HTTP方法(即GET、POST)。
- ip(str)-从
request
中解析出ip地址。 - port(str)-从
request
中解析出端口地址。 - socket(tuple)-从
request
中解析出(IP,port)
。 - url: The full URL of the request,如
http://localhost:8000/posts/1/?foo=bar
- scheme: The URL scheme associated with the request: ‘http|https|ws|wss’ or arbitrary value given by the headers.
- host: The host associated with the request(which in the Host header): localhost:8080
- server_name: The hostname of the server, without port number. the value is seeked in this order: config.SERVER_NAME, x-forwarded-host header,
Request.host()
- server_port: Like server_name. Seeked in this order: x-forwarded-port header,
Request.host()
, actual port used by the transport layer socket. - path: The path of the request:
/posts/1/
- query_string: The query string of the request:
foo=bar或''
- uri_template: Template for matching route handler:
/posts/<id>/
- token: The value of Authorization header:
Basic YWRtaW46YWRtaW4=
- url_for: Just like sanic.Sanic.url_for, but automatically determine scheme and netloc base on the request. Since this method is aiming to generate correct schema & netloc, _external is implied.
更改查询集的默认解析规则
在args和query_args属性内部使用的默认参数来解析queryset
Keep_blank_value(bool)
Fasle
标志,指示是否应将百分比编码查询中的空白值视为空白字符串。True表示应将空格保留为空白字符串。默认的False值指示将忽略空白值并将其视为未包含空白值。
strict_parsing(bool)
False
标志,指示如何处理解析错误。如果为false(默认值),错误将被忽略。如果为true,则错误引发ValueError异常。
encoding和errors(str)
'utf-8'和'replace'
指定bytes.decode()
方法所接受的如何将百分比编码的序列解码为Unicode字符。
如果要更改默认参数,可以使用新值调用get_args和get_query_args方法。
对于查询集/?test1=value1&test2=&test3=value3
from sanic.response import json
@app.route("/query_string")
def query_string(request):
args_with_blank_values = request.get_args(keep_blank_values=True)
return json({
"parsed": True,
"url": request.url,
"args_with_blank_values": args_with_blank_values,
"query_string": request.query_string
})
输出
{
"parsed": true,
"url": "http:\/\/0.0.0.0:8000\/query_string?test1=value1&test2=&test3=value3",
"args_with_blank_values": {"test1": ["value1"], "test2": "", "test3": ["value3"]},
"query_string": "test1=value1&test2=&test3=value3"
}
使用get和getlist访问值
request.args返回字典的子类,称为RequestParameters。使用此对象时的主要区别是get和getlist方法之间的区别。
get(key, default=None)
正常运行,不同之处在于当给定键的值是列表时,仅返回第一项。
getlist(key, default=None)
正常运行,返回整个列表
from sanic.request import RequestParameters
args = RequestParameters()
args['titles'] = ['Post 1', 'Post 2']
args.get('titles') # => 'Post 1'
args.getlist('titles') # => ['Post 1', 'Post 2']
使用request.endpoint
属性访问处理程序名称
request.endpoint
属性保存处理程序的名称。例如,以下路由将返回hello。
from sanic.response import text
from sanic import Sanic
app = Sanic()
@app.get("/")
def hello(request):
return text(request.endpoint)
或者,使用蓝图将包括两者,并以句点分隔。例如,以下路由将返回foo.bar:
from sanic import Sanic
from sanic import Blueprint
from sanic.response import text
app = Sanic(__name__)
blueprint = Blueprint('foo')
@blueprint.get('/')
async def bar(request):
return text(request.endpoint)
app.blueprint(blueprint)
app.run(host="0.0.0.0", port=8000, debug=True)