Sanic (asyncio + uvloop 网络服务器) - Return 自定义响应

Sanic (asyncio + uvloop webserver) - Return a custom response

我从 Sanic...

开始

Sanic is a Flask-like Python 3.5+ web server that's written to go fast. (...) On top of being Flask-like, Sanic supports async request handlers. This means you can use the new shiny async/await syntax from Python 3.5, making your code non-blocking and speedy.

...直到现在,关于如何使用他的例子很少,文档也不是很好。

根据文档基本示例,我们有

from sanic import Sanic
from sanic.response import json

app = Sanic()

@app.route("/")
async def test(request):
    return json({"test": True})

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8000)

例如,我如何 return 具有自定义状态代码的自定义响应?

Sanic the HTTP responses are instances of HTTPResponse, as you can see in its below code implementation, and the functions json, text and html just encapsulated the object creation, following the factory pattern

from ujson import dumps as json_dumps
 ...    

def json(body, status=200, headers=None):
    return HTTPResponse(json_dumps(body), headers=headers, status=status,
    content_type="application/json")



def text(body, status=200, headers=None):
    return HTTPResponse(body, status=status, headers=headers,
                        content_type="text/plain; charset=utf-8")


def html(body, status=200, headers=None):
    return HTTPResponse(body, status=status, headers=headers,
                        content_type="text/html; charset=utf-8")

函数 json({"test": True}) 只是使用超快 ujsondict 对象转储为 JSON 字符串并设置 content_type 参数。

所以你可以 return 一个自定义状态代码 returning json({"message": "bla"}, status=201) 或创建一个 HTTPResponse 作为上面的代码。

示例来自 documentation

from sanic import response

@app.route('/json')
def handle_request(request):
    return response.json(
        {'message': 'Hello world!'},
        headers={'X-Served-By': 'sanic'},
        status=200
    )