【问题标题】:Sanic (asyncio + uvloop webserver) - Return a custom responseSanic (asyncio + uvloop webserver) - 返回自定义响应
【发布时间】:2017-04-30 00:03:24
【问题描述】:

我从Sanic开始...

Sanic 是一个类似 Flask 的 Python 3.5+ 网络服务器,专为 go 快速地。 (...) 除了类似于 Flask 之外,Sanic 还支持异步请求处理程序。 这意味着您可以使用 Python 中新的闪亮 async/await 语法 3.5,让你的代码无阻塞且快速。

...到目前为止,关于如何使用他的示例很少,文档也不是很好。

按照文档基本示例,我们有

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)

例如,如何返回带有自定义状态代码的自定义响应?

【问题讨论】:

    标签: python python-3.5 python-asyncio sanic


    【解决方案1】:

    Sanic 中,HTTP 响应是HTTPResponse 的实例,正如您在下面的代码实现中所见,函数jsontexthtml 只是封装了对象创建,遵循@ 987654323@

    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 作为上述代码。

    【讨论】:

      【解决方案2】:

      来自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
          )
      

      【讨论】:

        猜你喜欢
        • 2019-08-06
        • 2021-05-10
        • 2019-07-23
        • 1970-01-01
        • 2013-12-13
        • 2017-03-11
        • 2019-10-28
        • 2021-08-27
        • 1970-01-01
        相关资源
        最近更新 更多