简体   繁体   中英

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

I'm starting with 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.

... and until this point, there are very few examples on how to use him and the docs are not so good.

Following the docs basic example, we have

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)

How can I return a custom response with a custom status code, for example?

In 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") 

The function json({"test": True}) just dumps a dict object as a JSON string using the ultra fast ujson and set the content_type param.

So you can return a custom status code returning json({"message": "bla"}, status=201) or creating a HTTPResponse as the above code.

Example from 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
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM