请求参数

  • sanic 自带了支持请求参数的基本路由

  • 指定参数,请使用尖括号括起来:<PARAM>。将请求参数将作为关键字传递给路由处理函数。

 from sanic.response import text

@app.route('/tag/<tag>')
async def tag_handler(request, tag):
    return text('Tag - {}'.format(tag))
  • 指定参数的类型,在参数名后的括号添加 :tpye,如果参数不匹配指定的类型,sanic将抛出 NotFound 异常,显示404 页面不存在。
from sanic.response import text

@app.route('/number/<integer_arg:int>')
async def integer_handler(request, integer_arg):
    return text('Integer - {}'.format(integer_arg))

@app.route('/number/<number_arg:number>')
async def number_handler(request, number_arg):
    return text('Number - {}'.format(number_arg))

@app.route('/person/<name:[A-z]>')
async def person_handler(request, name):
    return text('Person - {}'.format(name))

@app.route('/folder/<folder_id:[A-z0-9]{0,4}>')
async def folder_handler(request, folder_id):
    return text('Folder - {}'.format(folder_id))

HTTP请求类型

  • 定义一个路由默认只提供 GET请求,当然也可以 在@app.route 中指定可选参数method , 可以选用任意的http请求。
from sanic.response import text

@app.route('/post', methods=['POST'])
async def post_handler(request):
    return text('POST request - {}'.format(request.json))

@app.route('/get', methods=['GET'])
async def get_handler(request):
    return text('GET request - {}'.format(request.args))
  • 还有一个可选参数 host 可以是字符串或者列表,限定指定的主机进出,没有则使用默认值。
@app.route('/get', methods=['GET'], host='example.com')
async def get_handler(request):
    return text('GET request - {}'.format(request.args))

# if the host header doesn't match example.com, this route will be used
@app.route('/get', methods=['GET'])
async def get_handler(request):
    return text('GET request in default - {}'.format(request.args))
  • 常用的还GET 和 POST
from sanic.response import text

@app.post('/post')
async def post_handler(request):
    return text('POST request - {}'.format(request.json))

@app.get('/get')
async def get_handler(request):

url_for 构建 URL

  • sanic提供方法 url_for 生成url,如果不想硬编码写死URL 路径的话,这个方法是非常实用的。

    @app.route('/')
    async def index(request):

      # generate a URL for the endpoint `post_handler`
      url = app.url_for('post_handler', post_id=5)
      # the URL is `/posts/5`, redirect to it
      return redirect(url)
    
@app.route('/posts/<post_id>')
async def post_handler(request, post_id):
    return text('Post - {}'.format(post_id))

使用URL—for 要牢记以下几点

  1. 传递给url_for的不是请求参数的关键字参数将包含在URL的查询字符串中
url = app.url_for('post_handler', post_id=5, arg_one='one', arg_two='two')
# /posts/5?arg_one=one&arg_two=two
2.url\_for可以传递多个值
url = app.url_for('post_handler', post_id=5, arg_one=['one', 'two'])
# /posts/5?arg_one=one&arg_one=two

3.url_for 也可以包含一些特别的参数, (_anchor, _external, _scheme, _method, _server)

rl = app.url_for('post_handler', post_id=5, arg_one='one', _anchor='anchor')
# /posts/5?arg_one=one#anchor

url = app.url_for('post_handler', post_id=5, arg_one='one', _external=True)
# //server/posts/5?arg_one=one
# _external requires passed argument _server or SERVER_NAME in app.config or url will be same as no _external

url = app.url_for('post_handler', post_id=5, arg_one='one', _scheme='http', _external=True)
# http://server/posts/5?arg_one=one
# when specifying _scheme, _external must be True

# you can pass all special arguments one time
url = app.url_for('post_handler', post_id=5, arg_one=['one', 'two'], arg_two=2, _anchor='anchor', _scheme='http', _external=True, _server='another_server:8888')
# http://another_server:8888/posts/5?arg_one=one&arg_one=two&arg_two=2#anchor
  • 必须将所有有效参数传递给url_for以构建URL,如果未提供参数,或者参数与指定类型不匹配,则会抛出一个URLBuildError

WebSocket路由

  • 可以使用@ app.websocket装饰器定义WebSocket协议的路由:
@app.websocket('/feed')
async def feed(request, ws):
    while True:
        data = 'hello!'
        print('Sending: ' + data)
        await ws.send(data)
        data = await ws.recv()
        print('Received: ' + data)
  • 也可以使用app.add_websocket_route方法代替装饰器:
async def feed(request, ws):
    pass

app.add_websocket_route(my_websocket_handler, '/feed')
  • WebSocket路由的处理程序将请求作为第一个参数传递,并将WebSocket协议对象作为第二个参数传递。协议对象分别具有发送和接收数据的方法。

WebSocket支持需要由Aymeric Augustin提供的websockets包。

results matching ""

    No results matching ""