| 1 |
Using the serialization plugin |
| 2 |
------------------------------ |
| 3 |
|
| 4 |
Our next improvement is to leverage the |
| 5 |
:class:`SQLAlchemySerializationPlugin <litestar.contrib.sqlalchemy.plugins.SQLAlchemySerializationPlugin>` |
| 6 |
so that we can receive and return our SQLAlchemy models directly to and from our handlers. |
| 7 |
|
| 8 |
Here's the code: |
| 9 |
|
| 10 |
.. literalinclude:: /examples/contrib/sqlalchemy/plugins/tutorial/full_app_with_serialization_plugin.py |
| 11 |
:language: python |
| 12 |
:linenos: |
| 13 |
:emphasize-lines: 12, 75-77, 80-83, 86-91, 98 |
| 14 |
|
| 15 |
We've simply imported the plugin and added it to our app's plugins list, and now we can receive and return our |
| 16 |
SQLAlchemy data models directly to and from our handler. |
| 17 |
|
| 18 |
We've also been able to remove the ``TodoType`` and ``TodoCollectionType`` aliases, and the ``serialize_todo()`` |
| 19 |
function, making the implementation even more concise. |
| 20 |
|
| 21 |
Compare handlers before and after Serialization Plugin |
| 22 |
====================================================== |
| 23 |
|
| 24 |
Once more, let's compare the sets of application handlers before and after our refactoring: |
| 25 |
|
| 26 |
.. tab-set:: |
| 27 |
|
| 28 |
.. tab-item:: After |
| 29 |
|
| 30 |
.. literalinclude:: /examples/contrib/sqlalchemy/plugins/tutorial/full_app_with_serialization_plugin.py |
| 31 |
:language: python |
| 32 |
:linenos: |
| 33 |
:lines: 1-13, 73-99 |
| 34 |
|
| 35 |
.. tab-item:: Before |
| 36 |
|
| 37 |
.. literalinclude:: /examples/contrib/sqlalchemy/plugins/tutorial/full_app_no_plugins.py |
| 38 |
:language: python |
| 39 |
:linenos: |
| 40 |
:lines: 1-12, 67-100 |
| 41 |
|
| 42 |
Very nice! But, we can do better. |
| 43 |
|
| 44 |
Next steps |
| 45 |
========== |
| 46 |
|
| 47 |
In our application, we've had to build a bit of scaffolding to integrate SQLAlchemy with our application. We've had to |
| 48 |
define the ``db_connection()`` lifespan context manager, and the ``provide_transaction()`` dependency provider. |
| 49 |
|
| 50 |
Next we'll look at how the :class:`SQLAlchemyInitPlugin <litestar.contrib.sqlalchemy.plugins.SQLAlchemyInitPlugin>` can |
| 51 |
help us. |