Reputation: 739
The framework we're using is Chalice (AWS) but in this case I think framework doesn't matter alot. Simply, it does not support async routes like some other Python frameworks and uses Python.
Chalice official documentation: https://aws.github.io/chalice/
You can refer to the discussion here for further reading on sync/async issue: https://github.com/aws/chalice/issues/637
We would like to use Beanie ODM for our project which is an ODM with asynchronous functions, so we needed to convert our routes into async one (since functions on Beanie are async).
What we have done to overcome this issue lays below. A simple Chalice backend would look like this;
from chalice import Chalice
app = Chalice(app_name="helloworld")
@app.route("/")
def index():
# You can't do await HelloModel.find_all() since route is not async
return {"hello": "world"}
So we prepared a basic asyncio decorator to run each request in coroutine;
def async_route(function):
def run_async_task(*args, **kwargs):
# any algorithm can be used
result = asyncio.run(function(*args, **kwargs))
return result
return run_async_task
And added this decorator to the routes;
from chalice import Chalice
app = Chalice(app_name="helloworld")
@app.route("/")
@async_route
def index():
# this way we can use async abilities.
await init_db()
hello_list = await HelloModel.find_all().to_list()
return {"hello": "world"}
Upvotes: 3
Views: 98