Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 293
GustavoIP Avatar asked Feb 06 '23 12:02

GustavoIP


1 Answers

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.

like image 69
GustavoIP Avatar answered Feb 08 '23 16:02

GustavoIP