Debian Codegraph @

docs/quickstart.rst

raw
1 .. _quickstart:
2
3 Quick Start
4 ===========
5
6 .. currentmodule:: flask_sqlalchemy
7
8 Flask-SQLAlchemy simplifies using SQLAlchemy by automatically handling creating, using,
9 and cleaning up the SQLAlchemy objects you'd normally work with. While it adds a few
10 useful features, it still works like SQLAlchemy.
11
12 This page will walk you through the basic use of Flask-SQLAlchemy. For full capabilities
13 and customization, see the rest of these docs, including the API docs for the
14 :class:`SQLAlchemy` object.
15
16
17 Check the SQLAlchemy Documentation
18 ----------------------------------
19
20 Flask-SQLAlchemy is a wrapper around SQLAlchemy. You should follow the
21 `SQLAlchemy Tutorial`_ to learn about how to use it, and consult its documentation
22 for detailed information about its features. These docs show how to set up
23 Flask-SQLAlchemy itself, not how to use SQLAlchemy. Flask-SQLAlchemy sets up the
24 engine and scoped session automatically, so you can skip those
25 parts of the SQLAlchemy tutorial.
26
27 .. _SQLAlchemy Tutorial: https://docs.sqlalchemy.org/en/20/tutorial/index.html
28
29 This guide assumes you are using SQLAlchemy 2.x, which has a new API for defining models
30 and better support for Python type hints and data classes. If you are using SQLAlchemy 1.x,
31 see :doc:`legacy-quickstart`.
32
33 Installation
34 ------------
35
36 Flask-SQLAlchemy is available on `PyPI`_ and can be installed with various Python tools.
37 For example, to install or update the latest version using pip:
38
39 .. code-block:: text
40
41 $ pip install -U Flask-SQLAlchemy
42
43 .. _PyPI: https://pypi.org/project/Flask-SQLAlchemy/
44
45
46 Initialize the Extension
47 ------------------------
48
49 First create the ``db`` object using the ``SQLAlchemy`` constructor.
50
51 Pass a subclass of either `DeclarativeBase`_ or `DeclarativeBaseNoMeta`_
52 to the constructor.
53
54 .. code-block:: python
55
56 from flask import Flask
57 from flask_sqlalchemy import SQLAlchemy
58 from sqlalchemy.orm import DeclarativeBase
59
60 class Base(DeclarativeBase):
61 pass
62
63 db = SQLAlchemy(model_class=Base)
64
65
66 Learn more about customizing the base model class in :doc:`models`.
67
68 .. _DeclarativeBase: https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.DeclarativeBase
69 .. _DeclarativeBaseNoMeta: https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.DeclarativeBaseNoMeta
70
71 About the ``SQLAlchemy`` object
72 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
73
74 Once constructed, the ``db`` object gives you access to the :attr:`db.Model <.SQLAlchemy.Model>` class to
75 define models, and the :attr:`db.session <.SQLAlchemy.session>` to execute queries.
76
77 The :class:`SQLAlchemy` object also takes additional arguments to customize the
78 objects it manages.
79
80 Configure the Extension
81 -----------------------
82
83 The next step is to connect the extension to your Flask app.
84 The only required Flask app config is the :data:`.SQLALCHEMY_DATABASE_URI` key. That
85 is a connection string that tells SQLAlchemy what database to connect to.
86
87 Create your Flask application object, load any config, and then initialize the
88 :class:`SQLAlchemy` extension class with the application by calling
89 :meth:`db.init_app <.SQLAlchemy.init_app>`. This example connects to a SQLite database,
90 which is stored in the app's instance folder.
91
92 .. code-block:: python
93
94 # create the app
95 app = Flask(__name__)
96 # configure the SQLite database, relative to the app instance folder
97 app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///project.db"
98 # initialize the app with the extension
99 db.init_app(app)
100
101 See :doc:`config` for an explanation of connections strings and what other configuration
102 keys are used.
103
104
105 Define Models
106 -------------
107
108 Subclass ``db.Model`` to define a model class.
109 The model will generate a table name by converting the ``CamelCase`` class name to
110 ``snake_case``.
111
112 .. code-block:: python
113
114 from sqlalchemy import Integer, String
115 from sqlalchemy.orm import Mapped, mapped_column
116
117 class User(db.Model):
118 id: Mapped[int] = mapped_column(Integer, primary_key=True)
119 username: Mapped[str] = mapped_column(String, unique=True, nullable=False)
120 email: Mapped[str] = mapped_column(String)
121
122
123 See :doc:`models` for more information about defining and creating models and tables.
124
125
126 Create the Tables
127 -----------------
128
129 After all models and tables are defined, call :meth:`.SQLAlchemy.create_all` to create
130 the table schema in the database. This requires an application context. Since you're not
131 in a request at this point, create one manually.
132
133 .. code-block:: python
134
135 with app.app_context():
136 db.create_all()
137
138 If you define models in other modules, you must import them before calling
139 ``create_all``, otherwise SQLAlchemy will not know about them.
140
141 ``create_all`` does not update tables if they are already in the database. If you change
142 a model's columns, use a migration library like `Alembic`_ with `Flask-Alembic`_ or
143 `Flask-Migrate`_ to generate migrations that update the database schema.
144
145 .. _Alembic: https://alembic.sqlalchemy.org/
146 .. _Flask-Alembic: https://flask-alembic.readthedocs.io/
147 .. _Flask-Migrate: https://flask-migrate.readthedocs.io/
148
149
150 Query the Data
151 --------------
152
153 Within a Flask view or CLI command, you can use ``db.session`` to execute queries and
154 modify model data.
155
156 SQLAlchemy automatically defines an ``__init__`` method for each model that assigns any
157 keyword arguments to corresponding database columns and other attributes.
158
159 ``db.session.add(obj)`` adds an object to the session, to be inserted. Modifying an
160 object's attributes updates the object. ``db.session.delete(obj)`` deletes an object.
161 Remember to call ``db.session.commit()`` after modifying, adding, or deleting any data.
162
163 ``db.session.execute(db.select(...))`` constructs a query to select data from the
164 database. Building queries is the main feature of SQLAlchemy, so you'll want to read its
165 `tutorial on select`_ to learn all about it. You'll usually use the ``Result.scalars()``
166 method to get a list of results, or the ``Result.scalar()`` method to get a single
167 result.
168
169 .. _tutorial on select: https://docs.sqlalchemy.org/tutorial/data_select.html
170
171 .. code-block:: python
172
173 @app.route("/users")
174 def user_list():
175 users = db.session.execute(db.select(User).order_by(User.username)).scalars()
176 return render_template("user/list.html", users=users)
177
178 @app.route("/users/create", methods=["GET", "POST"])
179 def user_create():
180 if request.method == "POST":
181 user = User(
182 username=request.form["username"],
183 email=request.form["email"],
184 )
185 db.session.add(user)
186 db.session.commit()
187 return redirect(url_for("user_detail", id=user.id))
188
189 return render_template("user/create.html")
190
191 @app.route("/user/<int:id>")
192 def user_detail(id):
193 user = db.get_or_404(User, id)
194 return render_template("user/detail.html", user=user)
195
196 @app.route("/user/<int:id>/delete", methods=["GET", "POST"])
197 def user_delete(id):
198 user = db.get_or_404(User, id)
199
200 if request.method == "POST":
201 db.session.delete(user)
202 db.session.commit()
203 return redirect(url_for("user_list"))
204
205 return render_template("user/delete.html", user=user)
206
207 You may see uses of ``Model.query`` to build queries. This is an older interface for
208 queries that is considered legacy in SQLAlchemy. Prefer using
209 ``db.session.execute(db.select(...))`` instead.
210
211 See :doc:`queries` for more information about queries.
212
213
214 What to Remember
215 ----------------
216
217 For the most part, you should use SQLAlchemy as usual. The :class:`SQLAlchemy` extension
218 instance creates, configures, and gives access to the following things:
219
220 - :attr:`.SQLAlchemy.Model` declarative model base class. It sets the table
221 name automatically instead of needing ``__tablename__``.
222 - :attr:`.SQLAlchemy.session` is a session that is scoped to the current
223 Flask application context. It is cleaned up after every request.
224 - :attr:`.SQLAlchemy.metadata` and :attr:`.SQLAlchemy.metadatas` gives access to each
225 metadata defined in the config.
226 - :attr:`.SQLAlchemy.engine` and :attr:`.SQLAlchemy.engines` gives access to each
227 engine defined in the config.
228 - :meth:`.SQLAlchemy.create_all` creates all tables.
229 - You must be in an active Flask application context to execute queries and to access
230 the session and engine.