Debian Codegraph @

docs/tutorials/sqlalchemy/0-introduction.rst

raw
1 Introduction
2 ------------
3
4 We start with a full script that shows how you can use SQLAlchemy with Litestar. In this app, we interact with
5 SQLAlchemy in the manner described by the
6 `SQLAlchemy documentation <https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html#synopsis-orm>`_, and so if you
7 are looking for more information about any of the SQLAlchemy code, this will be a great place to start.
8
9 You'll notice that we use a couple of Litestar features that you may not have encountered yet:
10
11 1. Management and injection of :ref:`application state <application-state>`
12 2. Use of a :ref:`Lifespan context manager <lifespan-context-managers>`
13
14 And we will continue to learn about other Litestar features as we work through the tutorial, such as:
15
16 1. Dependency injection
17 2. Plugins
18
19 The full app
20 ============
21
22 While it may look imposing, this app only has minor behavioral differences to the previous example. It is still an app
23 that maintains a TODO list, that allows for adding, updating and viewing the collection of TODO items.
24
25 Don't worry if there are things in this example that you don't understand. We will cover all of the components in detail
26 in the following sections.
27
28 .. literalinclude::
29 /examples/contrib/sqlalchemy/plugins/tutorial/full_app_no_plugins.py
30 :language: python
31 :linenos:
32
33 The differences
34 ===============
35
36 Apart from the obvious differences due to the SQLAlchemy code, there are a few things worth mentioning from the outset.
37
38 Complexity
39 ++++++++++
40
41 This code is undoubtedly more complex than the code we have seen so far - although a crude measure of complexity, we can
42 see that there are more than double the lines of code to the previous example.
43
44 Lifespan context manager
45 ++++++++++++++++++++++++
46
47 When using a database, we need to ensure that we clean up our resources correctly. To do this, we create a context
48 manager called ``db_connection()`` that creates a new :class:`engine <sqlalchemy.ext.asyncio.AsyncEngine>` and disposes
49 of it when we are done. This context manager is added to the application's ``lifespan`` argument.
50
51 .. literalinclude::
52 /examples/contrib/sqlalchemy/plugins/tutorial/full_app_no_plugins.py
53 :language: python
54 :linenos:
55 :lines: 28-41,100
56
57 Database creation
58 +++++++++++++++++
59 Before we can use the database we need to make sure it exists and the tables are created as defined by the ``TodoItem``
60 class. This can be done by a synchronous call to ``Base.metadata.create_all`` which is invoked by ``run_sync``. If the
61 tables are already setup according to the model, the call does nothing.
62
63 .. literalinclude::
64 /examples/contrib/sqlalchemy/plugins/tutorial/full_app_no_plugins.py
65 :language: python
66 :linenos:
67 :lines: 28-41
68 :emphasize-lines: 8-9
69
70 Application state
71 +++++++++++++++++
72
73 We see two examples of access and use of application state. The first is in the ``db_connection()`` context manager,
74 where we use the ``app.state`` object to store the engine.
75
76 .. literalinclude::
77 /examples/contrib/sqlalchemy/plugins/tutorial/full_app_no_plugins.py
78 :language: python
79 :linenos:
80 :lines: 28-41
81 :emphasize-lines: 3,6
82
83 The second is by using the ``state`` keyword argument in our handler functions, so that we can access the engine in our
84 handlers.
85
86 .. literalinclude::
87 /examples/contrib/sqlalchemy/plugins/tutorial/full_app_no_plugins.py
88 :language: python
89 :linenos:
90 :lines: 69-72
91 :emphasize-lines: 2,3
92
93 Serialization
94 +++++++++++++
95
96 Now that we are using SQLAlchemy models, Litestar cannot automatically handle (de)serialization of our data. We have
97 to convert the SQLAlchemy models to a type that Litestar can serialize. This example introduces two type aliases,
98 ``TodoType`` and ``TodoCollectionType`` to help us represent this data at the boundaries of our handlers. It also
99 introduces the ``serialize_todo()`` to help us convert our data from the ``TodoItem`` type to a type that is
100 serializable by Litestar.
101
102 .. literalinclude::
103 /examples/contrib/sqlalchemy/plugins/tutorial/full_app_no_plugins.py
104 :language: python
105 :linenos:
106 :lines: 2-3,14-15,47-50,91-97
107 :emphasize-lines: 3,4,6,7,10,15
108
109 Behavior
110 ++++++++
111
112 The ``add_item()`` and ``update_item()`` routes no longer return the full collection, instead they return the item that
113 was added or updated. This is a minor detail change, but it is worth noting as it brings the behavior of the app closer
114 to what we would expect from a conventional API.
115
116 Next steps
117 ==========
118
119 Lets start cleaning this app up a little.
120
121 One of the standout issues is that we repeat the logic to create a database session in every handler. This is
122 something that we can fix with dependency injection.