簡體   English   中英

Sanic(asyncio + uvloop webserver) - 返回自定義響應

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

我是從Sanic開始的......

Sanic是一款類似Flask的Python 3.5+ Web服務器,可以快速編寫。 (...)除了像Flask一樣,Sanic支持異步請求處理程序。 這意味着您可以使用Python 3.5中新的閃亮的async / await語法,使您的代碼無阻塞且快速。

......到目前為止,關於如何使用他的例子很少,而且文檔也不是那么好。

按照文檔基本示例,我們有

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)

例如,如何使用自定義狀態代碼返回自定義響應?

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

函數json({"test": True})只是使用超快ujsondict對象轉儲為JSON字符串並設置content_type參數。

因此,您可以返回返回json({"message": "bla"}, status=201)的自定義狀態代碼或創建HTTPResponse作為上述代碼。

文檔示例

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