Skip to content

python#

Using Python SQLAlchemy session in concurrent threads or tasks

SQLAlchemy DB session is not thread safe for both sync and async session. AsyncSession is only a thin proxy on top of a Session

The concurrency model for SQLAlchemy's Session and AsyncSession is therefore Session per thread, AsyncSession per task.

The best way to ensure this use is by using the standard context manager pattern locally within the top level Python function that is inside the thread or task, which will ensure the lifespan of the Session or AsyncSession is maintained within a local scope.

For applications that benefit from having a "global" Session where it's not an option to pass the Session object to specific functions and methods which require it, the scoped_session approach can provide for a "thread local" Session object; see the section Contextual/Thread-local Sessions for background. Within the asyncio context, the async_scoped_session object is the asyncio analogue for scoped_session, however is more challenging to configure as it requires a custom "context" function.

Creating Custom Python Request Auth Class

When you need to use a complicated, or a non-standard API authentication method, or your dev and prd environments don't use the same API authentication method, it might be better to create a Python requests auth method to reduce your work.

Use python tabulate module to create tables

If you want to create some tables from a python list, you can use the tabulate module, it can generate the table easily in text mode and in many formats, than you can past it into markdown, wiki files or add the print version to your python CLI in order to give a beautiful output to the CLI users.