2

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;

Before

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;

After

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"}
  • My first question is; Is it safe to use it like that?
  • Secondly; what's the best practice on operating asynchronous operations outside of routes; like initializing db only once when program starts up?
Fatih Ersoy
  • 680
  • 1
  • 5
  • 24
  • 1
    yes that is safe to do, though you will have to worry about connection timeouts, when calling your route, the connection could drop if it takes to long. normally routes should return data or the resulted action in between 160milisecond to 2seconds, if its longer than this, then you would want to change how your route works, good luck. – Dean Van Greunen Jul 13 '23 at 13:51

0 Answers0