I am looking for example of using async await features of python 3. I am using falcon framework for building rest api. Can’t figure out how to use async await with it.
Please help me, by providing some examples, maybe with other frameworks.
Thank you!
Advertisement
Answer
Update: as of Falcon 3.0, the framework supports async
/ await
via the ASGI protocol.
In order to write async Falcon code, you need to use the ASGI flavour of App
, for instance:
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())
Assuming the above snippet is saved as test.py
, the ASGI application can be run as
uvicorn test:app
Setting and retrieving the message with 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" }
Note that when using the ASGI flavour of Falcon, all responders, hooks, middleware methods, error handlers etc must be awaitable coroutine functions, as the framework does not perform any implicit wrapping or scheduling in an executor.
See also Falcon’s ASGI tutorial.