Debian Codegraph @

docs/contexts.rst

raw
1 Flask Application Context
2 =========================
3
4 An active Flask application context is required to make queries and to access
5 ``db.engine`` and ``db.session``. This is because the session is scoped to the context
6 so that it is cleaned up properly after every request or CLI command.
7
8 Regardless of how an application is initialized with the extension, it is not stored for
9 later use. Instead, the extension uses Flask's ``current_app`` proxy to get the active
10 application, which requires an active application context.
11
12
13 Automatic Context
14 -----------------
15
16 When Flask is handling a request or a CLI command, an application context will
17 automatically be pushed. Therefore you don't need to do anything special to use the
18 database during requests or CLI commands.
19
20
21 Manual Context
22 --------------
23
24 If you try to use the database when an application context is not active, you will see
25 the following error.
26
27 .. code-block:: text
28
29 RuntimeError: Working outside of application context.
30
31 This typically means that you attempted to use functionality that needed
32 the current application. To solve this, set up an application context
33 with app.app_context(). See the documentation for more information.
34
35 If you find yourself in a situation where you need the database and don't have a
36 context, you can push one with ``app_context``. This is common when calling
37 ``db.create_all`` to create the tables, for example.
38
39 .. code-block:: python
40
41 def create_app():
42 app = Flask(__name__)
43 app.config.from_object("project.config")
44
45 import project.models
46
47 with app.app_context():
48 db.create_all()
49
50 return app
51
52
53 Tests
54 -----
55
56 If you test your application using the Flask test client to make requests to your
57 endpoints, the context will be available as part of the request. If you need to test
58 something about your database or models directly, rather than going through a request,
59 you need to push a context manually.
60
61 Only push a context exactly where and for how long it's needed for each test. Do not
62 push an application context globally for every test, as that can interfere with how the
63 session is cleaned up.
64
65 .. code-block:: python
66
67 def test_user_model(app):
68 user = User()
69
70 with app.app_context():
71 db.session.add(user)
72 db.session.commit()
73
74 If you find yourself writing many tests like that, you can use a pytest fixture to push
75 a context for a specific test.
76
77 .. code-block:: python
78
79 import pytest
80
81 @pytest.fixture
82 def app_ctx(app):
83 with app.app_context():
84 yield
85
86 @pytest.mark.usefixtures("app_ctx")
87 def test_user_model():
88 user = User()
89 db.session.add(user)
90 db.session.commit()