请求数据

当端点接收到HTTP请求时,route函数被传递给 Request 对象。

以下变量可以作为上的属性访问 Request 物体:

  • json (任意)-JSON正文

from sanic.response import json

@app.route("/json")
def post_json(request):
  return json({ "received": True, "message": request.json })
  • args (dict)-查询字符串变量。查询字符串是类似于 ?key1=value1&key2=value2 .

如果要解析该URL,则 args 字典看起来像 {{'key1': ['value1'], 'key2': ['value2']}} . 请求的 query_string 变量保存未分析的字符串值。属性提供默认的分析策略。如果您想更改它,请查看下面的部分 (Changing the default parsing rules of the 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(key, value) 元组。

属性提供默认的分析策略。如果您想更改它,请查看下面的部分 (Changing the default parsing rules of the queryset ). 对于相同的上一个URL queryset ?key1=value1&key2=value2 , the query_args 列表看起来像 [('key1', 'value1'), ('key2', 'value2')] . 如果多个参数有相同的键 ?key1=value1&key2=value2&key1=value3 这个 query_args 列表看起来像 [('key1', 'value1'), ('key2', 'value2'), ('key1', 'value3')] .

queryset的Request.args和Request.query_args之间的区别 ?key1=value1&key2=value2&key1=value3

  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 (字典 File 对象)-具有名称、正文和类型的文件列表

from sanic.response import json

@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 (字节)-已发布的原始正文。此属性允许检索请求的原始数据,而不考虑内容类型。

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)
  • headers (dict)-包含请求头的不区分大小写字典。

  • method (str)-请求的HTTP方法(即 GETPOST

  • ip (str)-请求者的IP地址。

  • port (str)-请求程序的端口地址。

  • socket (元组)—(IP,端口)请求程序。

  • app -对处理此请求的Sanic应用程序对象的引用。当模块中的蓝图或其他处理程序无法访问全局 app 对象。

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'})
  • url: The full URL of the request, ie: http://localhost:8000/posts/1/?foo=bar

  • scheme :与请求关联的URL方案:“http” |https| ws wss'或头文件给出的任意值。

  • 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 :喜欢 server_name . 按此顺序搜索: x-forwarded-port 页眉, Request.host() ,传输层套接字使用的实际端口。

  • path: The path of the request: /posts/1/

  • query_string: The query string of the request: foo=bar or a blank string ''

  • uri_template: Template for matching route handler: /posts/<id>/

  • token: The value of Authorization header: Basic YWRtaW46YWRtaW4=

  • url_for :就像 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”。

更改查询集的默认分析规则

在内部使用的默认参数 argsquery_args 要分析queryset的属性:

  • keep_blank_values (布尔): False -指示百分比编码查询中的空值是否应视为空字符串的标志。真值表示空白应保留为空白字符串。默认的false值表示将忽略空白值,并将其视为未包含。

  • strict_parsing (布尔): False -指示如何处理解析错误的标志。如果为false(默认值),则会自动忽略错误。如果为true,则错误会引发ValueError异常。

  • encodingerrors (str):“utf-8”和“replace”-指定如何将百分比编码的序列解码为bytes.decode()方法接受的Unicode字符。

如果要更改默认参数,可以调用 get_argsget_query_args 具有新值的方法。

为queryset /?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"
}

使用访问值 getgetlist

这个 request.args 返回的子类 dict 打电话 RequestParameters . 使用此对象时的关键区别在于 getgetlist 方法。

  • 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(__name__)

@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)