【问题标题】:How to use async await in python falcon?如何在 python falcon 中使用异步等待?
【发布时间】:2021-04-13 15:32:22
【问题描述】:

我正在寻找使用 python 3 的异步等待功能的示例。我正在使用 falcon 框架来构建 rest api。无法弄清楚如何使用异步等待。

请通过提供一些示例来帮助我,也许还有其他框架。

谢谢!

【问题讨论】:

  • 根据完成请求所需的时间,您可以使用 [celery](docs.celeryproject.org/),它是一个任务队列,或者使用 webhook?
  • 如果您愿意使用其他框架,请查看sanic。它似乎是为了这个确切的目的而制作的。不过,我自己还没有尝试过。

标签: python async-await falconframework


【解决方案1】:

更新:截至Falcon 3.0,框架通过ASGI协议支持async/await

为了编写异步Falcon代码,你需要使用the ASGI flavour of App,例如:

import http

import falcon
import falcon.asgi


class MessageResource:
    def __init__(self):
        self._message = 'Hello, World!'

    async def on_get(self, req, resp):
        resp.media = {'message': self._message}

    async def on_put(self, req, resp):
        media = await req.get_media()
        message = media.get('message')
        if not message:
            raise falcon.HTTPBadRequest

        self._message = message
        resp.status = http.HTTPStatus.NO_CONTENT


app = falcon.asgi.App()
app.add_route('/message', MessageResource())

假设上述sn-p保存为test.py,则ASGI应用可以运行为

uvicorn test:app

使用HTTPie 设置和检索消息:

$ http PUT http://localhost:8000/message message=StackOverflow
HTTP/1.1 204 No Content
server: uvicorn
$ http http://localhost:8000/message 
HTTP/1.1 200 OK
content-length: 28
content-type: application/json
server: uvicorn

{
    "message": "StackOverflow"
}

注意,当使用 Falcon 的 ASGI 风格时,所有响应者、钩子、中间件方法、错误处理程序等都必须是可等待的协程函数,因为框架不会在执行人。

另见Falcon's ASGI tutorial

【讨论】:

    【解决方案2】:

    Falson's FAQs 声明他们目前不支持asyncio

    【讨论】:

      猜你喜欢
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-15
      • 2021-10-22
      相关资源
      最近更新 更多