简体   繁体   English

Sanic(asyncio + uvloop webserver) - 返回自定义响应

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

I'm starting with Sanic ... 我是从Sanic开始的......

Sanic is a Flask-like Python 3.5+ web server that's written to go fast. Sanic是一款类似Flask的Python 3.5+ Web服务器,可以快速编写。 (...) On top of being Flask-like, Sanic supports async request handlers. (...)除了像Flask一样,Sanic支持异步请求处理程序。 This means you can use the new shiny async/await syntax from Python 3.5, making your code non-blocking and speedy. 这意味着您可以使用Python 3.5中新的闪亮的async / await语法,使您的代码无阻塞且快速。

... 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 Sanic中 ,HTTP响应是HTTPResponse的实例,正如您在其下面的代码实现中看到的那样,函数jsontexthtml只是按照工厂模式封装了对象创建

 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. 函数json({"test": True})只是使用超快ujsondict对象转储为JSON字符串并设置content_type参数。

So you can return a custom status code returning json({"message": "bla"}, status=201) or creating a HTTPResponse as the above code. 因此,您可以返回返回json({"message": "bla"}, status=201)的自定义状态代码或创建HTTPResponse作为上述代码。

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
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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