Async and db_session

Pony was not developed for async usage, and it may be tricky to use it correctly in an async environment. However, if only part of your application is async, you will be fine if you stick to these two rules:

You cannot use the @db_session decorator on async functions, use a context manager for wrapping lines of code that really work with the database. Secondly, do not call async functions inside a db_session, only normal function calls are possible. Use little shortliving sessions and don’t interrupt them with async:

  1. async def func():
  2. with db_session:
  3. thing = database.MyEntity()
  4. await async_func(ABC, thing)