| 1 |
Using the init plugin |
| 2 |
--------------------- |
| 3 |
|
| 4 |
In our example application, we've seen that we need to manage the database engine within the scope of the application's |
| 5 |
lifespan, and the session within the scope of a request. This is a common pattern, and the |
| 6 |
:class:`SQLAlchemyInitPlugin <litestar.contrib.sqlalchemy.plugins.SQLAlchemyInitPlugin>` plugin provides assistance for |
| 7 |
this. |
| 8 |
|
| 9 |
In our latest update, we leverage two features of the plugin: |
| 10 |
|
| 11 |
1. The plugin will automatically create a database engine for us and manage it within the scope of the application's |
| 12 |
lifespan. |
| 13 |
2. The plugin will automatically create a database session for us and manage it within the scope of a request. |
| 14 |
|
| 15 |
We access the database session via dependency injection, using the ``db_session`` parameter. |
| 16 |
|
| 17 |
Here's the updated code: |
| 18 |
|
| 19 |
.. literalinclude:: /examples/contrib/sqlalchemy/plugins/tutorial/full_app_with_init_plugin.py |
| 20 |
:language: python |
| 21 |
:linenos: |
| 22 |
:emphasize-lines: 12, 28, 76-78, 85 |
| 23 |
|
| 24 |
The most notable difference is that we no longer need the ``db_connection()`` lifespan context manager - the plugin |
| 25 |
handles this for us. It also handles the creation of the tables in our database if we supply our metadata and |
| 26 |
set ``create_all=True`` when creating a ``SQLAlchemyAsyncConfig`` instance. |
| 27 |
|
| 28 |
Additionally, we have a new ``db_session`` dependency available to us, which we use in our ``provide_transaction()`` |
| 29 |
dependency provider, instead of creating our own session. |
| 30 |
|
| 31 |
Next steps |
| 32 |
========== |
| 33 |
|
| 34 |
Next up, we'll make one final change to our application, and then we'll be recap! |