diff --git a/_build/.buildinfo b/_build/.buildinfo new file mode 100644 index 00000000..e14f39ca --- /dev/null +++ b/_build/.buildinfo @@ -0,0 +1,4 @@ +# Sphinx build info version 1 +# This file records the configuration used when building these files. When it is not found, a full rebuild will be done. +config: 600360abbe6c4808701ab5031e46e0b0 +tags: d77d1c0d9ca2f4c8421862c7c5a0d620 diff --git a/_build/.doctrees/api.doctree b/_build/.doctrees/api.doctree new file mode 100644 index 00000000..ba0dc74d Binary files /dev/null and b/_build/.doctrees/api.doctree differ diff --git a/_build/.doctrees/appcontext.doctree b/_build/.doctrees/appcontext.doctree new file mode 100644 index 00000000..f2a03fb3 Binary files /dev/null and b/_build/.doctrees/appcontext.doctree differ diff --git a/_build/.doctrees/async-await.doctree b/_build/.doctrees/async-await.doctree new file mode 100644 index 00000000..b5bc3507 Binary files /dev/null and b/_build/.doctrees/async-await.doctree differ diff --git a/_build/.doctrees/blueprints.doctree b/_build/.doctrees/blueprints.doctree new file mode 100644 index 00000000..dfad35a5 Binary files /dev/null and b/_build/.doctrees/blueprints.doctree differ diff --git a/_build/.doctrees/changes.doctree b/_build/.doctrees/changes.doctree new file mode 100644 index 00000000..ca488940 Binary files /dev/null and b/_build/.doctrees/changes.doctree differ diff --git a/_build/.doctrees/cli.doctree b/_build/.doctrees/cli.doctree new file mode 100644 index 00000000..4ae1a3f4 Binary files /dev/null and b/_build/.doctrees/cli.doctree differ diff --git a/_build/.doctrees/config.doctree b/_build/.doctrees/config.doctree new file mode 100644 index 00000000..0bbc90bd Binary files /dev/null and b/_build/.doctrees/config.doctree differ diff --git a/_build/.doctrees/contributing.doctree b/_build/.doctrees/contributing.doctree new file mode 100644 index 00000000..215fa7c0 Binary files /dev/null and b/_build/.doctrees/contributing.doctree differ diff --git a/_build/.doctrees/debugging.doctree b/_build/.doctrees/debugging.doctree new file mode 100644 index 00000000..9a80fa88 Binary files /dev/null and b/_build/.doctrees/debugging.doctree differ diff --git a/_build/.doctrees/deploying/apache-httpd.doctree b/_build/.doctrees/deploying/apache-httpd.doctree new file mode 100644 index 00000000..f30bf9c2 Binary files /dev/null and b/_build/.doctrees/deploying/apache-httpd.doctree differ diff --git a/_build/.doctrees/deploying/asgi.doctree b/_build/.doctrees/deploying/asgi.doctree new file mode 100644 index 00000000..313505ca Binary files /dev/null and b/_build/.doctrees/deploying/asgi.doctree differ diff --git a/_build/.doctrees/deploying/eventlet.doctree b/_build/.doctrees/deploying/eventlet.doctree new file mode 100644 index 00000000..17addf71 Binary files /dev/null and b/_build/.doctrees/deploying/eventlet.doctree differ diff --git a/_build/.doctrees/deploying/gevent.doctree b/_build/.doctrees/deploying/gevent.doctree new file mode 100644 index 00000000..04bb5684 Binary files /dev/null and b/_build/.doctrees/deploying/gevent.doctree differ diff --git a/_build/.doctrees/deploying/gunicorn.doctree b/_build/.doctrees/deploying/gunicorn.doctree new file mode 100644 index 00000000..7c6f7171 Binary files /dev/null and b/_build/.doctrees/deploying/gunicorn.doctree differ diff --git a/_build/.doctrees/deploying/index.doctree b/_build/.doctrees/deploying/index.doctree new file mode 100644 index 00000000..39165830 Binary files /dev/null and b/_build/.doctrees/deploying/index.doctree differ diff --git a/_build/.doctrees/deploying/mod_wsgi.doctree b/_build/.doctrees/deploying/mod_wsgi.doctree new file mode 100644 index 00000000..d0dfa131 Binary files /dev/null and b/_build/.doctrees/deploying/mod_wsgi.doctree differ diff --git a/_build/.doctrees/deploying/nginx.doctree b/_build/.doctrees/deploying/nginx.doctree new file mode 100644 index 00000000..415820bf Binary files /dev/null and b/_build/.doctrees/deploying/nginx.doctree differ diff --git a/_build/.doctrees/deploying/proxy_fix.doctree b/_build/.doctrees/deploying/proxy_fix.doctree new file mode 100644 index 00000000..1f2da1cc Binary files /dev/null and b/_build/.doctrees/deploying/proxy_fix.doctree differ diff --git a/_build/.doctrees/deploying/uwsgi.doctree b/_build/.doctrees/deploying/uwsgi.doctree new file mode 100644 index 00000000..a4908f31 Binary files /dev/null and b/_build/.doctrees/deploying/uwsgi.doctree differ diff --git a/_build/.doctrees/deploying/waitress.doctree b/_build/.doctrees/deploying/waitress.doctree new file mode 100644 index 00000000..ceebc6ea Binary files /dev/null and b/_build/.doctrees/deploying/waitress.doctree differ diff --git a/_build/.doctrees/design.doctree b/_build/.doctrees/design.doctree new file mode 100644 index 00000000..0010a8e5 Binary files /dev/null and b/_build/.doctrees/design.doctree differ diff --git a/_build/.doctrees/environment.pickle b/_build/.doctrees/environment.pickle new file mode 100644 index 00000000..8d4ee411 Binary files /dev/null and b/_build/.doctrees/environment.pickle differ diff --git a/_build/.doctrees/errorhandling.doctree b/_build/.doctrees/errorhandling.doctree new file mode 100644 index 00000000..1d293328 Binary files /dev/null and b/_build/.doctrees/errorhandling.doctree differ diff --git a/_build/.doctrees/extensiondev.doctree b/_build/.doctrees/extensiondev.doctree new file mode 100644 index 00000000..624048cd Binary files /dev/null and b/_build/.doctrees/extensiondev.doctree differ diff --git a/_build/.doctrees/extensions.doctree b/_build/.doctrees/extensions.doctree new file mode 100644 index 00000000..c463e314 Binary files /dev/null and b/_build/.doctrees/extensions.doctree differ diff --git a/_build/.doctrees/index.doctree b/_build/.doctrees/index.doctree new file mode 100644 index 00000000..8c3fea75 Binary files /dev/null and b/_build/.doctrees/index.doctree differ diff --git a/_build/.doctrees/installation.doctree b/_build/.doctrees/installation.doctree new file mode 100644 index 00000000..cd1e8516 Binary files /dev/null and b/_build/.doctrees/installation.doctree differ diff --git a/_build/.doctrees/license.doctree b/_build/.doctrees/license.doctree new file mode 100644 index 00000000..7cc13b80 Binary files /dev/null and b/_build/.doctrees/license.doctree differ diff --git a/_build/.doctrees/lifecycle.doctree b/_build/.doctrees/lifecycle.doctree new file mode 100644 index 00000000..d21786cf Binary files /dev/null and b/_build/.doctrees/lifecycle.doctree differ diff --git a/_build/.doctrees/logging.doctree b/_build/.doctrees/logging.doctree new file mode 100644 index 00000000..529d704d Binary files /dev/null and b/_build/.doctrees/logging.doctree differ diff --git a/_build/.doctrees/patterns/appdispatch.doctree b/_build/.doctrees/patterns/appdispatch.doctree new file mode 100644 index 00000000..2decb3a1 Binary files /dev/null and b/_build/.doctrees/patterns/appdispatch.doctree differ diff --git a/_build/.doctrees/patterns/appfactories.doctree b/_build/.doctrees/patterns/appfactories.doctree new file mode 100644 index 00000000..b7d9baa2 Binary files /dev/null and b/_build/.doctrees/patterns/appfactories.doctree differ diff --git a/_build/.doctrees/patterns/caching.doctree b/_build/.doctrees/patterns/caching.doctree new file mode 100644 index 00000000..cd0bd4fb Binary files /dev/null and b/_build/.doctrees/patterns/caching.doctree differ diff --git a/_build/.doctrees/patterns/celery.doctree b/_build/.doctrees/patterns/celery.doctree new file mode 100644 index 00000000..d618887e Binary files /dev/null and b/_build/.doctrees/patterns/celery.doctree differ diff --git a/_build/.doctrees/patterns/deferredcallbacks.doctree b/_build/.doctrees/patterns/deferredcallbacks.doctree new file mode 100644 index 00000000..71145354 Binary files /dev/null and b/_build/.doctrees/patterns/deferredcallbacks.doctree differ diff --git a/_build/.doctrees/patterns/favicon.doctree b/_build/.doctrees/patterns/favicon.doctree new file mode 100644 index 00000000..644fca15 Binary files /dev/null and b/_build/.doctrees/patterns/favicon.doctree differ diff --git a/_build/.doctrees/patterns/fileuploads.doctree b/_build/.doctrees/patterns/fileuploads.doctree new file mode 100644 index 00000000..37aebbeb Binary files /dev/null and b/_build/.doctrees/patterns/fileuploads.doctree differ diff --git a/_build/.doctrees/patterns/flashing.doctree b/_build/.doctrees/patterns/flashing.doctree new file mode 100644 index 00000000..7e52d4c0 Binary files /dev/null and b/_build/.doctrees/patterns/flashing.doctree differ diff --git a/_build/.doctrees/patterns/index.doctree b/_build/.doctrees/patterns/index.doctree new file mode 100644 index 00000000..9434b44a Binary files /dev/null and b/_build/.doctrees/patterns/index.doctree differ diff --git a/_build/.doctrees/patterns/javascript.doctree b/_build/.doctrees/patterns/javascript.doctree new file mode 100644 index 00000000..9ef9ab30 Binary files /dev/null and b/_build/.doctrees/patterns/javascript.doctree differ diff --git a/_build/.doctrees/patterns/jquery.doctree b/_build/.doctrees/patterns/jquery.doctree new file mode 100644 index 00000000..cfd15a9b Binary files /dev/null and b/_build/.doctrees/patterns/jquery.doctree differ diff --git a/_build/.doctrees/patterns/lazyloading.doctree b/_build/.doctrees/patterns/lazyloading.doctree new file mode 100644 index 00000000..1e5a7315 Binary files /dev/null and b/_build/.doctrees/patterns/lazyloading.doctree differ diff --git a/_build/.doctrees/patterns/methodoverrides.doctree b/_build/.doctrees/patterns/methodoverrides.doctree new file mode 100644 index 00000000..f726b91c Binary files /dev/null and b/_build/.doctrees/patterns/methodoverrides.doctree differ diff --git a/_build/.doctrees/patterns/mongoengine.doctree b/_build/.doctrees/patterns/mongoengine.doctree new file mode 100644 index 00000000..7da26327 Binary files /dev/null and b/_build/.doctrees/patterns/mongoengine.doctree differ diff --git a/_build/.doctrees/patterns/packages.doctree b/_build/.doctrees/patterns/packages.doctree new file mode 100644 index 00000000..5bc20c52 Binary files /dev/null and b/_build/.doctrees/patterns/packages.doctree differ diff --git a/_build/.doctrees/patterns/requestchecksum.doctree b/_build/.doctrees/patterns/requestchecksum.doctree new file mode 100644 index 00000000..96de457b Binary files /dev/null and b/_build/.doctrees/patterns/requestchecksum.doctree differ diff --git a/_build/.doctrees/patterns/singlepageapplications.doctree b/_build/.doctrees/patterns/singlepageapplications.doctree new file mode 100644 index 00000000..745860dc Binary files /dev/null and b/_build/.doctrees/patterns/singlepageapplications.doctree differ diff --git a/_build/.doctrees/patterns/sqlalchemy.doctree b/_build/.doctrees/patterns/sqlalchemy.doctree new file mode 100644 index 00000000..ce06cedb Binary files /dev/null and b/_build/.doctrees/patterns/sqlalchemy.doctree differ diff --git a/_build/.doctrees/patterns/sqlite3.doctree b/_build/.doctrees/patterns/sqlite3.doctree new file mode 100644 index 00000000..21043455 Binary files /dev/null and b/_build/.doctrees/patterns/sqlite3.doctree differ diff --git a/_build/.doctrees/patterns/streaming.doctree b/_build/.doctrees/patterns/streaming.doctree new file mode 100644 index 00000000..b82008cc Binary files /dev/null and b/_build/.doctrees/patterns/streaming.doctree differ diff --git a/_build/.doctrees/patterns/subclassing.doctree b/_build/.doctrees/patterns/subclassing.doctree new file mode 100644 index 00000000..3b160552 Binary files /dev/null and b/_build/.doctrees/patterns/subclassing.doctree differ diff --git a/_build/.doctrees/patterns/templateinheritance.doctree b/_build/.doctrees/patterns/templateinheritance.doctree new file mode 100644 index 00000000..c70dea19 Binary files /dev/null and b/_build/.doctrees/patterns/templateinheritance.doctree differ diff --git a/_build/.doctrees/patterns/urlprocessors.doctree b/_build/.doctrees/patterns/urlprocessors.doctree new file mode 100644 index 00000000..576cceb1 Binary files /dev/null and b/_build/.doctrees/patterns/urlprocessors.doctree differ diff --git a/_build/.doctrees/patterns/viewdecorators.doctree b/_build/.doctrees/patterns/viewdecorators.doctree new file mode 100644 index 00000000..9ac4135d Binary files /dev/null and b/_build/.doctrees/patterns/viewdecorators.doctree differ diff --git a/_build/.doctrees/patterns/wtforms.doctree b/_build/.doctrees/patterns/wtforms.doctree new file mode 100644 index 00000000..a58f1fe4 Binary files /dev/null and b/_build/.doctrees/patterns/wtforms.doctree differ diff --git a/_build/.doctrees/quickstart.doctree b/_build/.doctrees/quickstart.doctree new file mode 100644 index 00000000..7436ad27 Binary files /dev/null and b/_build/.doctrees/quickstart.doctree differ diff --git a/_build/.doctrees/reqcontext.doctree b/_build/.doctrees/reqcontext.doctree new file mode 100644 index 00000000..2561fb6d Binary files /dev/null and b/_build/.doctrees/reqcontext.doctree differ diff --git a/_build/.doctrees/server.doctree b/_build/.doctrees/server.doctree new file mode 100644 index 00000000..c27b28f9 Binary files /dev/null and b/_build/.doctrees/server.doctree differ diff --git a/_build/.doctrees/shell.doctree b/_build/.doctrees/shell.doctree new file mode 100644 index 00000000..28fde8b9 Binary files /dev/null and b/_build/.doctrees/shell.doctree differ diff --git a/_build/.doctrees/signals.doctree b/_build/.doctrees/signals.doctree new file mode 100644 index 00000000..1ab3b478 Binary files /dev/null and b/_build/.doctrees/signals.doctree differ diff --git a/_build/.doctrees/templating.doctree b/_build/.doctrees/templating.doctree new file mode 100644 index 00000000..50a32879 Binary files /dev/null and b/_build/.doctrees/templating.doctree differ diff --git a/_build/.doctrees/testing.doctree b/_build/.doctrees/testing.doctree new file mode 100644 index 00000000..b9d9ea8a Binary files /dev/null and b/_build/.doctrees/testing.doctree differ diff --git a/_build/.doctrees/tutorial/blog.doctree b/_build/.doctrees/tutorial/blog.doctree new file mode 100644 index 00000000..c1f9f03d Binary files /dev/null and b/_build/.doctrees/tutorial/blog.doctree differ diff --git a/_build/.doctrees/tutorial/database.doctree b/_build/.doctrees/tutorial/database.doctree new file mode 100644 index 00000000..aec4389d Binary files /dev/null and b/_build/.doctrees/tutorial/database.doctree differ diff --git a/_build/.doctrees/tutorial/deploy.doctree b/_build/.doctrees/tutorial/deploy.doctree new file mode 100644 index 00000000..0b3bc5a8 Binary files /dev/null and b/_build/.doctrees/tutorial/deploy.doctree differ diff --git a/_build/.doctrees/tutorial/factory.doctree b/_build/.doctrees/tutorial/factory.doctree new file mode 100644 index 00000000..516ae908 Binary files /dev/null and b/_build/.doctrees/tutorial/factory.doctree differ diff --git a/_build/.doctrees/tutorial/index.doctree b/_build/.doctrees/tutorial/index.doctree new file mode 100644 index 00000000..fb9369a2 Binary files /dev/null and b/_build/.doctrees/tutorial/index.doctree differ diff --git a/_build/.doctrees/tutorial/install.doctree b/_build/.doctrees/tutorial/install.doctree new file mode 100644 index 00000000..a4d71d8a Binary files /dev/null and b/_build/.doctrees/tutorial/install.doctree differ diff --git a/_build/.doctrees/tutorial/layout.doctree b/_build/.doctrees/tutorial/layout.doctree new file mode 100644 index 00000000..92f5a469 Binary files /dev/null and b/_build/.doctrees/tutorial/layout.doctree differ diff --git a/_build/.doctrees/tutorial/next.doctree b/_build/.doctrees/tutorial/next.doctree new file mode 100644 index 00000000..30d4d07e Binary files /dev/null and b/_build/.doctrees/tutorial/next.doctree differ diff --git a/_build/.doctrees/tutorial/static.doctree b/_build/.doctrees/tutorial/static.doctree new file mode 100644 index 00000000..b5ba1dca Binary files /dev/null and b/_build/.doctrees/tutorial/static.doctree differ diff --git a/_build/.doctrees/tutorial/templates.doctree b/_build/.doctrees/tutorial/templates.doctree new file mode 100644 index 00000000..6e9e745d Binary files /dev/null and b/_build/.doctrees/tutorial/templates.doctree differ diff --git a/_build/.doctrees/tutorial/tests.doctree b/_build/.doctrees/tutorial/tests.doctree new file mode 100644 index 00000000..264e2ac0 Binary files /dev/null and b/_build/.doctrees/tutorial/tests.doctree differ diff --git a/_build/.doctrees/tutorial/views.doctree b/_build/.doctrees/tutorial/views.doctree new file mode 100644 index 00000000..40267908 Binary files /dev/null and b/_build/.doctrees/tutorial/views.doctree differ diff --git a/_build/.doctrees/views.doctree b/_build/.doctrees/views.doctree new file mode 100644 index 00000000..32bbbbec Binary files /dev/null and b/_build/.doctrees/views.doctree differ diff --git a/_build/.doctrees/web-security.doctree b/_build/.doctrees/web-security.doctree new file mode 100644 index 00000000..72292465 Binary files /dev/null and b/_build/.doctrees/web-security.doctree differ diff --git a/_build/404/index.html b/_build/404/index.html new file mode 100644 index 00000000..c96a9c9c --- /dev/null +++ b/_build/404/index.html @@ -0,0 +1,82 @@ + + + + + + + + Page Not Found — Flask Documentation (3.1.x) + + + + + + + + + + + + +
+
+
+
+ +

Page Not Found

+

+ The page you requested does not exist. You may have followed a bad + link, or the page may have been moved or removed. + + +

+
+
+
+ + +
+
+ + + diff --git a/_build/_images/debugger.png b/_build/_images/debugger.png new file mode 100644 index 00000000..7d4181f6 Binary files /dev/null and b/_build/_images/debugger.png differ diff --git a/_build/_images/flask-horizontal.png b/_build/_images/flask-horizontal.png new file mode 100644 index 00000000..a0df2c61 Binary files /dev/null and b/_build/_images/flask-horizontal.png differ diff --git a/_build/_images/flaskr_edit.png b/_build/_images/flaskr_edit.png new file mode 100644 index 00000000..6cd6e398 Binary files /dev/null and b/_build/_images/flaskr_edit.png differ diff --git a/_build/_images/flaskr_index.png b/_build/_images/flaskr_index.png new file mode 100644 index 00000000..aa2b50f5 Binary files /dev/null and b/_build/_images/flaskr_index.png differ diff --git a/_build/_images/flaskr_login.png b/_build/_images/flaskr_login.png new file mode 100644 index 00000000..d482c645 Binary files /dev/null and b/_build/_images/flaskr_login.png differ diff --git a/_build/_images/pycharm-run-config.png b/_build/_images/pycharm-run-config.png new file mode 100644 index 00000000..ad025545 Binary files /dev/null and b/_build/_images/pycharm-run-config.png differ diff --git a/_build/_sources/api.rst.txt b/_build/_sources/api.rst.txt new file mode 100644 index 00000000..1aa8048f --- /dev/null +++ b/_build/_sources/api.rst.txt @@ -0,0 +1,717 @@ +API +=== + +.. module:: flask + +This part of the documentation covers all the interfaces of Flask. For +parts where Flask depends on external libraries, we document the most +important right here and provide links to the canonical documentation. + + +Application Object +------------------ + +.. autoclass:: Flask + :members: + :inherited-members: + + +Blueprint Objects +----------------- + +.. autoclass:: Blueprint + :members: + :inherited-members: + +Incoming Request Data +--------------------- + +.. autoclass:: Request + :members: + :inherited-members: + :exclude-members: json_module + +.. attribute:: request + + To access incoming request data, you can use the global `request` + object. Flask parses incoming request data for you and gives you + access to it through that global object. Internally Flask makes + sure that you always get the correct data for the active thread if you + are in a multithreaded environment. + + This is a proxy. See :ref:`notes-on-proxies` for more information. + + The request object is an instance of a :class:`~flask.Request`. + + +Response Objects +---------------- + +.. autoclass:: flask.Response + :members: + :inherited-members: + :exclude-members: json_module + +Sessions +-------- + +If you have set :attr:`Flask.secret_key` (or configured it from +:data:`SECRET_KEY`) you can use sessions in Flask applications. A session makes +it possible to remember information from one request to another. The way Flask +does this is by using a signed cookie. The user can look at the session +contents, but can't modify it unless they know the secret key, so make sure to +set that to something complex and unguessable. + +To access the current session you can use the :class:`session` object: + +.. class:: session + + The session object works pretty much like an ordinary dict, with the + difference that it keeps track of modifications. + + This is a proxy. See :ref:`notes-on-proxies` for more information. + + The following attributes are interesting: + + .. attribute:: new + + ``True`` if the session is new, ``False`` otherwise. + + .. attribute:: modified + + ``True`` if the session object detected a modification. Be advised + that modifications on mutable structures are not picked up + automatically, in that situation you have to explicitly set the + attribute to ``True`` yourself. Here an example:: + + # this change is not picked up because a mutable object (here + # a list) is changed. + session['objects'].append(42) + # so mark it as modified yourself + session.modified = True + + .. attribute:: permanent + + If set to ``True`` the session lives for + :attr:`~flask.Flask.permanent_session_lifetime` seconds. The + default is 31 days. If set to ``False`` (which is the default) the + session will be deleted when the user closes the browser. + + +Session Interface +----------------- + +.. versionadded:: 0.8 + +The session interface provides a simple way to replace the session +implementation that Flask is using. + +.. currentmodule:: flask.sessions + +.. autoclass:: SessionInterface + :members: + +.. autoclass:: SecureCookieSessionInterface + :members: + +.. autoclass:: SecureCookieSession + :members: + +.. autoclass:: NullSession + :members: + +.. autoclass:: SessionMixin + :members: + +.. admonition:: Notice + + The :data:`PERMANENT_SESSION_LIFETIME` config can be an integer or ``timedelta``. + The :attr:`~flask.Flask.permanent_session_lifetime` attribute is always a + ``timedelta``. + + +Test Client +----------- + +.. currentmodule:: flask.testing + +.. autoclass:: FlaskClient + :members: + + +Test CLI Runner +--------------- + +.. currentmodule:: flask.testing + +.. autoclass:: FlaskCliRunner + :members: + + +Application Globals +------------------- + +.. currentmodule:: flask + +To share data that is valid for one request only from one function to +another, a global variable is not good enough because it would break in +threaded environments. Flask provides you with a special object that +ensures it is only valid for the active request and that will return +different values for each request. In a nutshell: it does the right +thing, like it does for :class:`request` and :class:`session`. + +.. data:: g + + A namespace object that can store data during an + :doc:`application context `. This is an instance of + :attr:`Flask.app_ctx_globals_class`, which defaults to + :class:`ctx._AppCtxGlobals`. + + This is a good place to store resources during a request. For + example, a ``before_request`` function could load a user object from + a session id, then set ``g.user`` to be used in the view function. + + This is a proxy. See :ref:`notes-on-proxies` for more information. + + .. versionchanged:: 0.10 + Bound to the application context instead of the request context. + +.. autoclass:: flask.ctx._AppCtxGlobals + :members: + + +Useful Functions and Classes +---------------------------- + +.. data:: current_app + + A proxy to the application handling the current request. This is + useful to access the application without needing to import it, or if + it can't be imported, such as when using the application factory + pattern or in blueprints and extensions. + + This is only available when an + :doc:`application context ` is pushed. This happens + automatically during requests and CLI commands. It can be controlled + manually with :meth:`~flask.Flask.app_context`. + + This is a proxy. See :ref:`notes-on-proxies` for more information. + +.. autofunction:: has_request_context + +.. autofunction:: copy_current_request_context + +.. autofunction:: has_app_context + +.. autofunction:: url_for + +.. autofunction:: abort + +.. autofunction:: redirect + +.. autofunction:: make_response + +.. autofunction:: after_this_request + +.. autofunction:: send_file + +.. autofunction:: send_from_directory + + +Message Flashing +---------------- + +.. autofunction:: flash + +.. autofunction:: get_flashed_messages + + +JSON Support +------------ + +.. module:: flask.json + +Flask uses Python's built-in :mod:`json` module for handling JSON by +default. The JSON implementation can be changed by assigning a different +provider to :attr:`flask.Flask.json_provider_class` or +:attr:`flask.Flask.json`. The functions provided by ``flask.json`` will +use methods on ``app.json`` if an app context is active. + +Jinja's ``|tojson`` filter is configured to use the app's JSON provider. +The filter marks the output with ``|safe``. Use it to render data inside +HTML `` + +.. autofunction:: jsonify + +.. autofunction:: dumps + +.. autofunction:: dump + +.. autofunction:: loads + +.. autofunction:: load + +.. autoclass:: flask.json.provider.JSONProvider + :members: + :member-order: bysource + +.. autoclass:: flask.json.provider.DefaultJSONProvider + :members: + :member-order: bysource + +.. automodule:: flask.json.tag + + +Template Rendering +------------------ + +.. currentmodule:: flask + +.. autofunction:: render_template + +.. autofunction:: render_template_string + +.. autofunction:: stream_template + +.. autofunction:: stream_template_string + +.. autofunction:: get_template_attribute + +Configuration +------------- + +.. autoclass:: Config + :members: + + +Stream Helpers +-------------- + +.. autofunction:: stream_with_context + +Useful Internals +---------------- + +.. autoclass:: flask.ctx.RequestContext + :members: + +.. data:: flask.globals.request_ctx + + The current :class:`~flask.ctx.RequestContext`. If a request context + is not active, accessing attributes on this proxy will raise a + ``RuntimeError``. + + This is an internal object that is essential to how Flask handles + requests. Accessing this should not be needed in most cases. Most + likely you want :data:`request` and :data:`session` instead. + +.. autoclass:: flask.ctx.AppContext + :members: + +.. data:: flask.globals.app_ctx + + The current :class:`~flask.ctx.AppContext`. If an app context is not + active, accessing attributes on this proxy will raise a + ``RuntimeError``. + + This is an internal object that is essential to how Flask handles + requests. Accessing this should not be needed in most cases. Most + likely you want :data:`current_app` and :data:`g` instead. + +.. autoclass:: flask.blueprints.BlueprintSetupState + :members: + +.. _core-signals-list: + +Signals +------- + +Signals are provided by the `Blinker`_ library. See :doc:`signals` for an introduction. + +.. _blinker: https://blinker.readthedocs.io/ + +.. data:: template_rendered + + This signal is sent when a template was successfully rendered. The + signal is invoked with the instance of the template as `template` + and the context as dictionary (named `context`). + + Example subscriber:: + + def log_template_renders(sender, template, context, **extra): + sender.logger.debug('Rendering template "%s" with context %s', + template.name or 'string template', + context) + + from flask import template_rendered + template_rendered.connect(log_template_renders, app) + +.. data:: flask.before_render_template + :noindex: + + This signal is sent before template rendering process. The + signal is invoked with the instance of the template as `template` + and the context as dictionary (named `context`). + + Example subscriber:: + + def log_template_renders(sender, template, context, **extra): + sender.logger.debug('Rendering template "%s" with context %s', + template.name or 'string template', + context) + + from flask import before_render_template + before_render_template.connect(log_template_renders, app) + +.. data:: request_started + + This signal is sent when the request context is set up, before + any request processing happens. Because the request context is already + bound, the subscriber can access the request with the standard global + proxies such as :class:`~flask.request`. + + Example subscriber:: + + def log_request(sender, **extra): + sender.logger.debug('Request context is set up') + + from flask import request_started + request_started.connect(log_request, app) + +.. data:: request_finished + + This signal is sent right before the response is sent to the client. + It is passed the response to be sent named `response`. + + Example subscriber:: + + def log_response(sender, response, **extra): + sender.logger.debug('Request context is about to close down. ' + 'Response: %s', response) + + from flask import request_finished + request_finished.connect(log_response, app) + +.. data:: got_request_exception + + This signal is sent when an unhandled exception happens during + request processing, including when debugging. The exception is + passed to the subscriber as ``exception``. + + This signal is not sent for + :exc:`~werkzeug.exceptions.HTTPException`, or other exceptions that + have error handlers registered, unless the exception was raised from + an error handler. + + This example shows how to do some extra logging if a theoretical + ``SecurityException`` was raised: + + .. code-block:: python + + from flask import got_request_exception + + def log_security_exception(sender, exception, **extra): + if not isinstance(exception, SecurityException): + return + + security_logger.exception( + f"SecurityException at {request.url!r}", + exc_info=exception, + ) + + got_request_exception.connect(log_security_exception, app) + +.. data:: request_tearing_down + + This signal is sent when the request is tearing down. This is always + called, even if an exception is caused. Currently functions listening + to this signal are called after the regular teardown handlers, but this + is not something you can rely on. + + Example subscriber:: + + def close_db_connection(sender, **extra): + session.close() + + from flask import request_tearing_down + request_tearing_down.connect(close_db_connection, app) + + As of Flask 0.9, this will also be passed an `exc` keyword argument + that has a reference to the exception that caused the teardown if + there was one. + +.. data:: appcontext_tearing_down + + This signal is sent when the app context is tearing down. This is always + called, even if an exception is caused. Currently functions listening + to this signal are called after the regular teardown handlers, but this + is not something you can rely on. + + Example subscriber:: + + def close_db_connection(sender, **extra): + session.close() + + from flask import appcontext_tearing_down + appcontext_tearing_down.connect(close_db_connection, app) + + This will also be passed an `exc` keyword argument that has a reference + to the exception that caused the teardown if there was one. + +.. data:: appcontext_pushed + + This signal is sent when an application context is pushed. The sender + is the application. This is usually useful for unittests in order to + temporarily hook in information. For instance it can be used to + set a resource early onto the `g` object. + + Example usage:: + + from contextlib import contextmanager + from flask import appcontext_pushed + + @contextmanager + def user_set(app, user): + def handler(sender, **kwargs): + g.user = user + with appcontext_pushed.connected_to(handler, app): + yield + + And in the testcode:: + + def test_user_me(self): + with user_set(app, 'john'): + c = app.test_client() + resp = c.get('/users/me') + assert resp.data == 'username=john' + + .. versionadded:: 0.10 + +.. data:: appcontext_popped + + This signal is sent when an application context is popped. The sender + is the application. This usually falls in line with the + :data:`appcontext_tearing_down` signal. + + .. versionadded:: 0.10 + +.. data:: message_flashed + + This signal is sent when the application is flashing a message. The + messages is sent as `message` keyword argument and the category as + `category`. + + Example subscriber:: + + recorded = [] + def record(sender, message, category, **extra): + recorded.append((message, category)) + + from flask import message_flashed + message_flashed.connect(record, app) + + .. versionadded:: 0.10 + + +Class-Based Views +----------------- + +.. versionadded:: 0.7 + +.. currentmodule:: None + +.. autoclass:: flask.views.View + :members: + +.. autoclass:: flask.views.MethodView + :members: + +.. _url-route-registrations: + +URL Route Registrations +----------------------- + +Generally there are three ways to define rules for the routing system: + +1. You can use the :meth:`flask.Flask.route` decorator. +2. You can use the :meth:`flask.Flask.add_url_rule` function. +3. You can directly access the underlying Werkzeug routing system + which is exposed as :attr:`flask.Flask.url_map`. + +Variable parts in the route can be specified with angular brackets +(``/user/``). By default a variable part in the URL accepts any +string without a slash however a different converter can be specified as +well by using ````. + +Variable parts are passed to the view function as keyword arguments. + +The following converters are available: + +=========== =============================================== +`string` accepts any text without a slash (the default) +`int` accepts integers +`float` like `int` but for floating point values +`path` like the default but also accepts slashes +`any` matches one of the items provided +`uuid` accepts UUID strings +=========== =============================================== + +Custom converters can be defined using :attr:`flask.Flask.url_map`. + +Here are some examples:: + + @app.route('/') + def index(): + pass + + @app.route('/') + def show_user(username): + pass + + @app.route('/post/') + def show_post(post_id): + pass + +An important detail to keep in mind is how Flask deals with trailing +slashes. The idea is to keep each URL unique so the following rules +apply: + +1. If a rule ends with a slash and is requested without a slash by the + user, the user is automatically redirected to the same page with a + trailing slash attached. +2. If a rule does not end with a trailing slash and the user requests the + page with a trailing slash, a 404 not found is raised. + +This is consistent with how web servers deal with static files. This +also makes it possible to use relative link targets safely. + +You can also define multiple rules for the same function. They have to be +unique however. Defaults can also be specified. Here for example is a +definition for a URL that accepts an optional page:: + + @app.route('/users/', defaults={'page': 1}) + @app.route('/users/page/') + def show_users(page): + pass + +This specifies that ``/users/`` will be the URL for page one and +``/users/page/N`` will be the URL for page ``N``. + +If a URL contains a default value, it will be redirected to its simpler +form with a 301 redirect. In the above example, ``/users/page/1`` will +be redirected to ``/users/``. If your route handles ``GET`` and ``POST`` +requests, make sure the default route only handles ``GET``, as redirects +can't preserve form data. :: + + @app.route('/region/', defaults={'id': 1}) + @app.route('/region/', methods=['GET', 'POST']) + def region(id): + pass + +Here are the parameters that :meth:`~flask.Flask.route` and +:meth:`~flask.Flask.add_url_rule` accept. The only difference is that +with the route parameter the view function is defined with the decorator +instead of the `view_func` parameter. + +=============== ========================================================== +`rule` the URL rule as string +`endpoint` the endpoint for the registered URL rule. Flask itself + assumes that the name of the view function is the name + of the endpoint if not explicitly stated. +`view_func` the function to call when serving a request to the + provided endpoint. If this is not provided one can + specify the function later by storing it in the + :attr:`~flask.Flask.view_functions` dictionary with the + endpoint as key. +`defaults` A dictionary with defaults for this rule. See the + example above for how defaults work. +`subdomain` specifies the rule for the subdomain in case subdomain + matching is in use. If not specified the default + subdomain is assumed. +`**options` the options to be forwarded to the underlying + :class:`~werkzeug.routing.Rule` object. A change to + Werkzeug is handling of method options. methods is a list + of methods this rule should be limited to (``GET``, ``POST`` + etc.). By default a rule just listens for ``GET`` (and + implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is + implicitly added and handled by the standard request + handling. They have to be specified as keyword arguments. +=============== ========================================================== + + +View Function Options +--------------------- + +For internal usage the view functions can have some attributes attached to +customize behavior the view function would normally not have control over. +The following attributes can be provided optionally to either override +some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior: + +- `__name__`: The name of a function is by default used as endpoint. If + endpoint is provided explicitly this value is used. Additionally this + will be prefixed with the name of the blueprint by default which + cannot be customized from the function itself. + +- `methods`: If methods are not provided when the URL rule is added, + Flask will look on the view function object itself if a `methods` + attribute exists. If it does, it will pull the information for the + methods from there. + +- `provide_automatic_options`: if this attribute is set Flask will + either force enable or disable the automatic implementation of the + HTTP ``OPTIONS`` response. This can be useful when working with + decorators that want to customize the ``OPTIONS`` response on a per-view + basis. + +- `required_methods`: if this attribute is set, Flask will always add + these methods when registering a URL rule even if the methods were + explicitly overridden in the ``route()`` call. + +Full example:: + + def index(): + if request.method == 'OPTIONS': + # custom options handling here + ... + return 'Hello World!' + index.provide_automatic_options = False + index.methods = ['GET', 'OPTIONS'] + + app.add_url_rule('/', index) + +.. versionadded:: 0.8 + The `provide_automatic_options` functionality was added. + +Command Line Interface +---------------------- + +.. currentmodule:: flask.cli + +.. autoclass:: FlaskGroup + :members: + +.. autoclass:: AppGroup + :members: + +.. autoclass:: ScriptInfo + :members: + +.. autofunction:: load_dotenv + +.. autofunction:: with_appcontext + +.. autofunction:: pass_script_info + + Marks a function so that an instance of :class:`ScriptInfo` is passed + as first argument to the click callback. + +.. autodata:: run_command + +.. autodata:: shell_command diff --git a/_build/_sources/appcontext.rst.txt b/_build/_sources/appcontext.rst.txt new file mode 100644 index 00000000..5509a9a7 --- /dev/null +++ b/_build/_sources/appcontext.rst.txt @@ -0,0 +1,147 @@ +.. currentmodule:: flask + +The Application Context +======================= + +The application context keeps track of the application-level data during +a request, CLI command, or other activity. Rather than passing the +application around to each function, the :data:`current_app` and +:data:`g` proxies are accessed instead. + +This is similar to :doc:`/reqcontext`, which keeps track of +request-level data during a request. A corresponding application context +is pushed when a request context is pushed. + +Purpose of the Context +---------------------- + +The :class:`Flask` application object has attributes, such as +:attr:`~Flask.config`, that are useful to access within views and +:doc:`CLI commands `. However, importing the ``app`` instance +within the modules in your project is prone to circular import issues. +When using the :doc:`app factory pattern ` or +writing reusable :doc:`blueprints ` or +:doc:`extensions ` there won't be an ``app`` instance to +import at all. + +Flask solves this issue with the *application context*. Rather than +referring to an ``app`` directly, you use the :data:`current_app` +proxy, which points to the application handling the current activity. + +Flask automatically *pushes* an application context when handling a +request. View functions, error handlers, and other functions that run +during a request will have access to :data:`current_app`. + +Flask will also automatically push an app context when running CLI +commands registered with :attr:`Flask.cli` using ``@app.cli.command()``. + + +Lifetime of the Context +----------------------- + +The application context is created and destroyed as necessary. When a +Flask application begins handling a request, it pushes an application +context and a :doc:`request context `. When the request +ends it pops the request context then the application context. +Typically, an application context will have the same lifetime as a +request. + +See :doc:`/reqcontext` for more information about how the contexts work +and the full life cycle of a request. + + +Manually Push a Context +----------------------- + +If you try to access :data:`current_app`, or anything that uses it, +outside an application context, you'll get this error message: + +.. code-block:: pytb + + RuntimeError: Working outside of application context. + + This typically means that you attempted to use functionality that + needed to interface with the current application object in some way. + To solve this, set up an application context with app.app_context(). + +If you see that error while configuring your application, such as when +initializing an extension, you can push a context manually since you +have direct access to the ``app``. Use :meth:`~Flask.app_context` in a +``with`` block, and everything that runs in the block will have access +to :data:`current_app`. :: + + def create_app(): + app = Flask(__name__) + + with app.app_context(): + init_db() + + return app + +If you see that error somewhere else in your code not related to +configuring the application, it most likely indicates that you should +move that code into a view function or CLI command. + + +Storing Data +------------ + +The application context is a good place to store common data during a +request or CLI command. Flask provides the :data:`g object ` for this +purpose. It is a simple namespace object that has the same lifetime as +an application context. + +.. note:: + The ``g`` name stands for "global", but that is referring to the + data being global *within a context*. The data on ``g`` is lost + after the context ends, and it is not an appropriate place to store + data between requests. Use the :data:`session` or a database to + store data across requests. + +A common use for :data:`g` is to manage resources during a request. + +1. ``get_X()`` creates resource ``X`` if it does not exist, caching it + as ``g.X``. +2. ``teardown_X()`` closes or otherwise deallocates the resource if it + exists. It is registered as a :meth:`~Flask.teardown_appcontext` + handler. + +For example, you can manage a database connection using this pattern:: + + from flask import g + + def get_db(): + if 'db' not in g: + g.db = connect_to_database() + + return g.db + + @app.teardown_appcontext + def teardown_db(exception): + db = g.pop('db', None) + + if db is not None: + db.close() + +During a request, every call to ``get_db()`` will return the same +connection, and it will be closed automatically at the end of the +request. + +You can use :class:`~werkzeug.local.LocalProxy` to make a new context +local from ``get_db()``:: + + from werkzeug.local import LocalProxy + db = LocalProxy(get_db) + +Accessing ``db`` will call ``get_db`` internally, in the same way that +:data:`current_app` works. + + +Events and Signals +------------------ + +The application will call functions registered with :meth:`~Flask.teardown_appcontext` +when the application context is popped. + +The following signals are sent: :data:`appcontext_pushed`, +:data:`appcontext_tearing_down`, and :data:`appcontext_popped`. diff --git a/_build/_sources/async-await.rst.txt b/_build/_sources/async-await.rst.txt new file mode 100644 index 00000000..16b61945 --- /dev/null +++ b/_build/_sources/async-await.rst.txt @@ -0,0 +1,125 @@ +.. _async_await: + +Using ``async`` and ``await`` +============================= + +.. versionadded:: 2.0 + +Routes, error handlers, before request, after request, and teardown +functions can all be coroutine functions if Flask is installed with the +``async`` extra (``pip install flask[async]``). This allows views to be +defined with ``async def`` and use ``await``. + +.. code-block:: python + + @app.route("/get-data") + async def get_data(): + data = await async_db_query(...) + return jsonify(data) + +Pluggable class-based views also support handlers that are implemented as +coroutines. This applies to the :meth:`~flask.views.View.dispatch_request` +method in views that inherit from the :class:`flask.views.View` class, as +well as all the HTTP method handlers in views that inherit from the +:class:`flask.views.MethodView` class. + +.. admonition:: Using ``async`` with greenlet + + When using gevent or eventlet to serve an application or patch the + runtime, greenlet>=1.0 is required. When using PyPy, PyPy>=7.3.7 is + required. + + +Performance +----------- + +Async functions require an event loop to run. Flask, as a WSGI +application, uses one worker to handle one request/response cycle. +When a request comes in to an async view, Flask will start an event loop +in a thread, run the view function there, then return the result. + +Each request still ties up one worker, even for async views. The upside +is that you can run async code within a view, for example to make +multiple concurrent database queries, HTTP requests to an external API, +etc. However, the number of requests your application can handle at one +time will remain the same. + +**Async is not inherently faster than sync code.** Async is beneficial +when performing concurrent IO-bound tasks, but will probably not improve +CPU-bound tasks. Traditional Flask views will still be appropriate for +most use cases, but Flask's async support enables writing and using +code that wasn't possible natively before. + + +Background tasks +---------------- + +Async functions will run in an event loop until they complete, at +which stage the event loop will stop. This means any additional +spawned tasks that haven't completed when the async function completes +will be cancelled. Therefore you cannot spawn background tasks, for +example via ``asyncio.create_task``. + +If you wish to use background tasks it is best to use a task queue to +trigger background work, rather than spawn tasks in a view +function. With that in mind you can spawn asyncio tasks by serving +Flask with an ASGI server and utilising the asgiref WsgiToAsgi adapter +as described in :doc:`deploying/asgi`. This works as the adapter creates +an event loop that runs continually. + + +When to use Quart instead +------------------------- + +Flask's async support is less performant than async-first frameworks due +to the way it is implemented. If you have a mainly async codebase it +would make sense to consider `Quart`_. Quart is a reimplementation of +Flask based on the `ASGI`_ standard instead of WSGI. This allows it to +handle many concurrent requests, long running requests, and websockets +without requiring multiple worker processes or threads. + +It has also already been possible to run Flask with Gevent or Eventlet +to get many of the benefits of async request handling. These libraries +patch low-level Python functions to accomplish this, whereas ``async``/ +``await`` and ASGI use standard, modern Python capabilities. Deciding +whether you should use Flask, Quart, or something else is ultimately up +to understanding the specific needs of your project. + +.. _Quart: https://github.com/pallets/quart +.. _ASGI: https://asgi.readthedocs.io/en/latest/ + + +Extensions +---------- + +Flask extensions predating Flask's async support do not expect async views. +If they provide decorators to add functionality to views, those will probably +not work with async views because they will not await the function or be +awaitable. Other functions they provide will not be awaitable either and +will probably be blocking if called within an async view. + +Extension authors can support async functions by utilising the +:meth:`flask.Flask.ensure_sync` method. For example, if the extension +provides a view function decorator add ``ensure_sync`` before calling +the decorated function, + +.. code-block:: python + + def extension(func): + @wraps(func) + def wrapper(*args, **kwargs): + ... # Extension logic + return current_app.ensure_sync(func)(*args, **kwargs) + + return wrapper + +Check the changelog of the extension you want to use to see if they've +implemented async support, or make a feature request or PR to them. + + +Other event loops +----------------- + +At the moment Flask only supports :mod:`asyncio`. It's possible to +override :meth:`flask.Flask.ensure_sync` to change how async functions +are wrapped to use a different library. diff --git a/_build/_sources/blueprints.rst.txt b/_build/_sources/blueprints.rst.txt new file mode 100644 index 00000000..d5cf3d82 --- /dev/null +++ b/_build/_sources/blueprints.rst.txt @@ -0,0 +1,315 @@ +Modular Applications with Blueprints +==================================== + +.. currentmodule:: flask + +.. versionadded:: 0.7 + +Flask uses a concept of *blueprints* for making application components and +supporting common patterns within an application or across applications. +Blueprints can greatly simplify how large applications work and provide a +central means for Flask extensions to register operations on applications. +A :class:`Blueprint` object works similarly to a :class:`Flask` +application object, but it is not actually an application. Rather it is a +*blueprint* of how to construct or extend an application. + +Why Blueprints? +--------------- + +Blueprints in Flask are intended for these cases: + +* Factor an application into a set of blueprints. This is ideal for + larger applications; a project could instantiate an application object, + initialize several extensions, and register a collection of blueprints. +* Register a blueprint on an application at a URL prefix and/or subdomain. + Parameters in the URL prefix/subdomain become common view arguments + (with defaults) across all view functions in the blueprint. +* Register a blueprint multiple times on an application with different URL + rules. +* Provide template filters, static files, templates, and other utilities + through blueprints. A blueprint does not have to implement applications + or view functions. +* Register a blueprint on an application for any of these cases when + initializing a Flask extension. + +A blueprint in Flask is not a pluggable app because it is not actually an +application -- it's a set of operations which can be registered on an +application, even multiple times. Why not have multiple application +objects? You can do that (see :doc:`/patterns/appdispatch`), but your +applications will have separate configs and will be managed at the WSGI +layer. + +Blueprints instead provide separation at the Flask level, share +application config, and can change an application object as necessary with +being registered. The downside is that you cannot unregister a blueprint +once an application was created without having to destroy the whole +application object. + +The Concept of Blueprints +------------------------- + +The basic concept of blueprints is that they record operations to execute +when registered on an application. Flask associates view functions with +blueprints when dispatching requests and generating URLs from one endpoint +to another. + +My First Blueprint +------------------ + +This is what a very basic blueprint looks like. In this case we want to +implement a blueprint that does simple rendering of static templates:: + + from flask import Blueprint, render_template, abort + from jinja2 import TemplateNotFound + + simple_page = Blueprint('simple_page', __name__, + template_folder='templates') + + @simple_page.route('/', defaults={'page': 'index'}) + @simple_page.route('/') + def show(page): + try: + return render_template(f'pages/{page}.html') + except TemplateNotFound: + abort(404) + +When you bind a function with the help of the ``@simple_page.route`` +decorator, the blueprint will record the intention of registering the +function ``show`` on the application when it's later registered. +Additionally it will prefix the endpoint of the function with the +name of the blueprint which was given to the :class:`Blueprint` +constructor (in this case also ``simple_page``). The blueprint's name +does not modify the URL, only the endpoint. + +Registering Blueprints +---------------------- + +So how do you register that blueprint? Like this:: + + from flask import Flask + from yourapplication.simple_page import simple_page + + app = Flask(__name__) + app.register_blueprint(simple_page) + +If you check the rules registered on the application, you will find +these:: + + >>> app.url_map + Map([' (HEAD, OPTIONS, GET) -> static>, + ' (HEAD, OPTIONS, GET) -> simple_page.show>, + simple_page.show>]) + +The first one is obviously from the application itself for the static +files. The other two are for the `show` function of the ``simple_page`` +blueprint. As you can see, they are also prefixed with the name of the +blueprint and separated by a dot (``.``). + +Blueprints however can also be mounted at different locations:: + + app.register_blueprint(simple_page, url_prefix='/pages') + +And sure enough, these are the generated rules:: + + >>> app.url_map + Map([' (HEAD, OPTIONS, GET) -> static>, + ' (HEAD, OPTIONS, GET) -> simple_page.show>, + simple_page.show>]) + +On top of that you can register blueprints multiple times though not every +blueprint might respond properly to that. In fact it depends on how the +blueprint is implemented if it can be mounted more than once. + +Nesting Blueprints +------------------ + +It is possible to register a blueprint on another blueprint. + +.. code-block:: python + + parent = Blueprint('parent', __name__, url_prefix='/parent') + child = Blueprint('child', __name__, url_prefix='/child') + parent.register_blueprint(child) + app.register_blueprint(parent) + +The child blueprint will gain the parent's name as a prefix to its +name, and child URLs will be prefixed with the parent's URL prefix. + +.. code-block:: python + + url_for('parent.child.create') + /parent/child/create + +In addition a child blueprint's will gain their parent's subdomain, +with their subdomain as prefix if present i.e. + +.. code-block:: python + + parent = Blueprint('parent', __name__, subdomain='parent') + child = Blueprint('child', __name__, subdomain='child') + parent.register_blueprint(child) + app.register_blueprint(parent) + + url_for('parent.child.create', _external=True) + "child.parent.domain.tld" + +Blueprint-specific before request functions, etc. registered with the +parent will trigger for the child. If a child does not have an error +handler that can handle a given exception, the parent's will be tried. + + +Blueprint Resources +------------------- + +Blueprints can provide resources as well. Sometimes you might want to +introduce a blueprint only for the resources it provides. + +Blueprint Resource Folder +````````````````````````` + +Like for regular applications, blueprints are considered to be contained +in a folder. While multiple blueprints can originate from the same folder, +it does not have to be the case and it's usually not recommended. + +The folder is inferred from the second argument to :class:`Blueprint` which +is usually `__name__`. This argument specifies what logical Python +module or package corresponds to the blueprint. If it points to an actual +Python package that package (which is a folder on the filesystem) is the +resource folder. If it's a module, the package the module is contained in +will be the resource folder. You can access the +:attr:`Blueprint.root_path` property to see what the resource folder is:: + + >>> simple_page.root_path + '/Users/username/TestProject/yourapplication' + +To quickly open sources from this folder you can use the +:meth:`~Blueprint.open_resource` function:: + + with simple_page.open_resource('static/style.css') as f: + code = f.read() + +Static Files +```````````` + +A blueprint can expose a folder with static files by providing the path +to the folder on the filesystem with the ``static_folder`` argument. +It is either an absolute path or relative to the blueprint's location:: + + admin = Blueprint('admin', __name__, static_folder='static') + +By default the rightmost part of the path is where it is exposed on the +web. This can be changed with the ``static_url_path`` argument. Because the +folder is called ``static`` here it will be available at the +``url_prefix`` of the blueprint + ``/static``. If the blueprint +has the prefix ``/admin``, the static URL will be ``/admin/static``. + +The endpoint is named ``blueprint_name.static``. You can generate URLs +to it with :func:`url_for` like you would with the static folder of the +application:: + + url_for('admin.static', filename='style.css') + +However, if the blueprint does not have a ``url_prefix``, it is not +possible to access the blueprint's static folder. This is because the +URL would be ``/static`` in this case, and the application's ``/static`` +route takes precedence. Unlike template folders, blueprint static +folders are not searched if the file does not exist in the application +static folder. + +Templates +````````` + +If you want the blueprint to expose templates you can do that by providing +the `template_folder` parameter to the :class:`Blueprint` constructor:: + + admin = Blueprint('admin', __name__, template_folder='templates') + +For static files, the path can be absolute or relative to the blueprint +resource folder. + +The template folder is added to the search path of templates but with a lower +priority than the actual application's template folder. That way you can +easily override templates that a blueprint provides in the actual application. +This also means that if you don't want a blueprint template to be accidentally +overridden, make sure that no other blueprint or actual application template +has the same relative path. When multiple blueprints provide the same relative +template path the first blueprint registered takes precedence over the others. + + +So if you have a blueprint in the folder ``yourapplication/admin`` and you +want to render the template ``'admin/index.html'`` and you have provided +``templates`` as a `template_folder` you will have to create a file like +this: :file:`yourapplication/admin/templates/admin/index.html`. The reason +for the extra ``admin`` folder is to avoid getting our template overridden +by a template named ``index.html`` in the actual application template +folder. + +To further reiterate this: if you have a blueprint named ``admin`` and you +want to render a template called :file:`index.html` which is specific to this +blueprint, the best idea is to lay out your templates like this:: + + yourpackage/ + blueprints/ + admin/ + templates/ + admin/ + index.html + __init__.py + +And then when you want to render the template, use :file:`admin/index.html` as +the name to look up the template by. If you encounter problems loading +the correct templates enable the ``EXPLAIN_TEMPLATE_LOADING`` config +variable which will instruct Flask to print out the steps it goes through +to locate templates on every ``render_template`` call. + +Building URLs +------------- + +If you want to link from one page to another you can use the +:func:`url_for` function just like you normally would do just that you +prefix the URL endpoint with the name of the blueprint and a dot (``.``):: + + url_for('admin.index') + +Additionally if you are in a view function of a blueprint or a rendered +template and you want to link to another endpoint of the same blueprint, +you can use relative redirects by prefixing the endpoint with a dot only:: + + url_for('.index') + +This will link to ``admin.index`` for instance in case the current request +was dispatched to any other admin blueprint endpoint. + + +Blueprint Error Handlers +------------------------ + +Blueprints support the ``errorhandler`` decorator just like the :class:`Flask` +application object, so it is easy to make Blueprint-specific custom error +pages. + +Here is an example for a "404 Page Not Found" exception:: + + @simple_page.errorhandler(404) + def page_not_found(e): + return render_template('pages/404.html') + +Most errorhandlers will simply work as expected; however, there is a caveat +concerning handlers for 404 and 405 exceptions. These errorhandlers are only +invoked from an appropriate ``raise`` statement or a call to ``abort`` in another +of the blueprint's view functions; they are not invoked by, e.g., an invalid URL +access. This is because the blueprint does not "own" a certain URL space, so +the application instance has no way of knowing which blueprint error handler it +should run if given an invalid URL. If you would like to execute different +handling strategies for these errors based on URL prefixes, they may be defined +at the application level using the ``request`` proxy object:: + + @app.errorhandler(404) + @app.errorhandler(405) + def _handle_api_error(ex): + if request.path.startswith('/api/'): + return jsonify(error=str(ex)), ex.code + else: + return ex + +See :doc:`/errorhandling`. diff --git a/_build/_sources/changes.rst.txt b/_build/_sources/changes.rst.txt new file mode 100644 index 00000000..955deaf2 --- /dev/null +++ b/_build/_sources/changes.rst.txt @@ -0,0 +1,4 @@ +Changes +======= + +.. include:: ../CHANGES.rst diff --git a/_build/_sources/cli.rst.txt b/_build/_sources/cli.rst.txt new file mode 100644 index 00000000..a72e6d51 --- /dev/null +++ b/_build/_sources/cli.rst.txt @@ -0,0 +1,556 @@ +.. currentmodule:: flask + +Command Line Interface +====================== + +Installing Flask installs the ``flask`` script, a `Click`_ command line +interface, in your virtualenv. Executed from the terminal, this script gives +access to built-in, extension, and application-defined commands. The ``--help`` +option will give more information about any commands and options. + +.. _Click: https://click.palletsprojects.com/ + + +Application Discovery +--------------------- + +The ``flask`` command is installed by Flask, not your application; it must be +told where to find your application in order to use it. The ``--app`` +option is used to specify how to load the application. + +While ``--app`` supports a variety of options for specifying your +application, most use cases should be simple. Here are the typical values: + +(nothing) + The name "app" or "wsgi" is imported (as a ".py" file, or package), + automatically detecting an app (``app`` or ``application``) or + factory (``create_app`` or ``make_app``). + +``--app hello`` + The given name is imported, automatically detecting an app (``app`` + or ``application``) or factory (``create_app`` or ``make_app``). + +---- + +``--app`` has three parts: an optional path that sets the current working +directory, a Python file or dotted import path, and an optional variable +name of the instance or factory. If the name is a factory, it can optionally +be followed by arguments in parentheses. The following values demonstrate these +parts: + +``--app src/hello`` + Sets the current working directory to ``src`` then imports ``hello``. + +``--app hello.web`` + Imports the path ``hello.web``. + +``--app hello:app2`` + Uses the ``app2`` Flask instance in ``hello``. + +``--app 'hello:create_app("dev")'`` + The ``create_app`` factory in ``hello`` is called with the string ``'dev'`` + as the argument. + +If ``--app`` is not set, the command will try to import "app" or +"wsgi" (as a ".py" file, or package) and try to detect an application +instance or factory. + +Within the given import, the command looks for an application instance named +``app`` or ``application``, then any application instance. If no instance is +found, the command looks for a factory function named ``create_app`` or +``make_app`` that returns an instance. + +If parentheses follow the factory name, their contents are parsed as +Python literals and passed as arguments and keyword arguments to the +function. This means that strings must still be in quotes. + + +Run the Development Server +-------------------------- + +The :func:`run ` command will start the development server. It +replaces the :meth:`Flask.run` method in most cases. :: + + $ flask --app hello run + * Serving Flask app "hello" + * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) + +.. warning:: Do not use this command to run your application in production. + Only use the development server during development. The development server + is provided for convenience, but is not designed to be particularly secure, + stable, or efficient. See :doc:`/deploying/index` for how to run in production. + +If another program is already using port 5000, you'll see +``OSError: [Errno 98]`` or ``OSError: [WinError 10013]`` when the +server tries to start. See :ref:`address-already-in-use` for how to +handle that. + + +Debug Mode +~~~~~~~~~~ + +In debug mode, the ``flask run`` command will enable the interactive debugger and the +reloader by default, and make errors easier to see and debug. To enable debug mode, use +the ``--debug`` option. + +.. code-block:: console + + $ flask --app hello run --debug + * Serving Flask app "hello" + * Debug mode: on + * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) + * Restarting with inotify reloader + * Debugger is active! + * Debugger PIN: 223-456-919 + +The ``--debug`` option can also be passed to the top level ``flask`` command to enable +debug mode for any command. The following two ``run`` calls are equivalent. + +.. code-block:: console + + $ flask --app hello --debug run + $ flask --app hello run --debug + + +Watch and Ignore Files with the Reloader +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When using debug mode, the reloader will trigger whenever your Python code or imported +modules change. The reloader can watch additional files with the ``--extra-files`` +option. Multiple paths are separated with ``:``, or ``;`` on Windows. + +.. code-block:: text + + $ flask run --extra-files file1:dirA/file2:dirB/ + * Running on http://127.0.0.1:8000/ + * Detected change in '/path/to/file1', reloading + +The reloader can also ignore files using :mod:`fnmatch` patterns with the +``--exclude-patterns`` option. Multiple patterns are separated with ``:``, or ``;`` on +Windows. + + +Open a Shell +------------ + +To explore the data in your application, you can start an interactive Python +shell with the :func:`shell ` command. An application +context will be active, and the app instance will be imported. :: + + $ flask shell + Python 3.10.0 (default, Oct 27 2021, 06:59:51) [GCC 11.1.0] on linux + App: example [production] + Instance: /home/david/Projects/pallets/flask/instance + >>> + +Use :meth:`~Flask.shell_context_processor` to add other automatic imports. + + +.. _dotenv: + +Environment Variables From dotenv +--------------------------------- + +The ``flask`` command supports setting any option for any command with +environment variables. The variables are named like ``FLASK_OPTION`` or +``FLASK_COMMAND_OPTION``, for example ``FLASK_APP`` or +``FLASK_RUN_PORT``. + +Rather than passing options every time you run a command, or environment +variables every time you open a new terminal, you can use Flask's dotenv +support to set environment variables automatically. + +If `python-dotenv`_ is installed, running the ``flask`` command will set +environment variables defined in the files ``.env`` and ``.flaskenv``. +You can also specify an extra file to load with the ``--env-file`` +option. Dotenv files can be used to avoid having to set ``--app`` or +``FLASK_APP`` manually, and to set configuration using environment +variables similar to how some deployment services work. + +Variables set on the command line are used over those set in :file:`.env`, +which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be +used for public variables, such as ``FLASK_APP``, while :file:`.env` should not +be committed to your repository so that it can set private variables. + +Directories are scanned upwards from the directory you call ``flask`` +from to locate the files. + +The files are only loaded by the ``flask`` command or calling +:meth:`~Flask.run`. If you would like to load these files when running in +production, you should call :func:`~cli.load_dotenv` manually. + +.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme + + +Setting Command Options +~~~~~~~~~~~~~~~~~~~~~~~ + +Click is configured to load default values for command options from +environment variables. The variables use the pattern +``FLASK_COMMAND_OPTION``. For example, to set the port for the run +command, instead of ``flask run --port 8000``: + +.. tabs:: + + .. group-tab:: Bash + + .. code-block:: text + + $ export FLASK_RUN_PORT=8000 + $ flask run + * Running on http://127.0.0.1:8000/ + + .. group-tab:: Fish + + .. code-block:: text + + $ set -x FLASK_RUN_PORT 8000 + $ flask run + * Running on http://127.0.0.1:8000/ + + .. group-tab:: CMD + + .. code-block:: text + + > set FLASK_RUN_PORT=8000 + > flask run + * Running on http://127.0.0.1:8000/ + + .. group-tab:: Powershell + + .. code-block:: text + + > $env:FLASK_RUN_PORT = 8000 + > flask run + * Running on http://127.0.0.1:8000/ + +These can be added to the ``.flaskenv`` file just like ``FLASK_APP`` to +control default command options. + + +Disable dotenv +~~~~~~~~~~~~~~ + +The ``flask`` command will show a message if it detects dotenv files but +python-dotenv is not installed. + +.. code-block:: bash + + $ flask run + * Tip: There are .env files present. Do "pip install python-dotenv" to use them. + +You can tell Flask not to load dotenv files even when python-dotenv is +installed by setting the ``FLASK_SKIP_DOTENV`` environment variable. +This can be useful if you want to load them manually, or if you're using +a project runner that loads them already. Keep in mind that the +environment variables must be set before the app loads or it won't +configure as expected. + +.. tabs:: + + .. group-tab:: Bash + + .. code-block:: text + + $ export FLASK_SKIP_DOTENV=1 + $ flask run + + .. group-tab:: Fish + + .. code-block:: text + + $ set -x FLASK_SKIP_DOTENV 1 + $ flask run + + .. group-tab:: CMD + + .. code-block:: text + + > set FLASK_SKIP_DOTENV=1 + > flask run + + .. group-tab:: Powershell + + .. code-block:: text + + > $env:FLASK_SKIP_DOTENV = 1 + > flask run + + +Environment Variables From virtualenv +------------------------------------- + +If you do not want to install dotenv support, you can still set environment +variables by adding them to the end of the virtualenv's :file:`activate` +script. Activating the virtualenv will set the variables. + +.. tabs:: + + .. group-tab:: Bash + + Unix Bash, :file:`.venv/bin/activate`:: + + $ export FLASK_APP=hello + + .. group-tab:: Fish + + Fish, :file:`.venv/bin/activate.fish`:: + + $ set -x FLASK_APP hello + + .. group-tab:: CMD + + Windows CMD, :file:`.venv\\Scripts\\activate.bat`:: + + > set FLASK_APP=hello + + .. group-tab:: Powershell + + Windows Powershell, :file:`.venv\\Scripts\\activate.ps1`:: + + > $env:FLASK_APP = "hello" + +It is preferred to use dotenv support over this, since :file:`.flaskenv` can be +committed to the repository so that it works automatically wherever the project +is checked out. + + +Custom Commands +--------------- + +The ``flask`` command is implemented using `Click`_. See that project's +documentation for full information about writing commands. + +This example adds the command ``create-user`` that takes the argument +``name``. :: + + import click + from flask import Flask + + app = Flask(__name__) + + @app.cli.command("create-user") + @click.argument("name") + def create_user(name): + ... + +:: + + $ flask create-user admin + +This example adds the same command, but as ``user create``, a command in a +group. This is useful if you want to organize multiple related commands. :: + + import click + from flask import Flask + from flask.cli import AppGroup + + app = Flask(__name__) + user_cli = AppGroup('user') + + @user_cli.command('create') + @click.argument('name') + def create_user(name): + ... + + app.cli.add_command(user_cli) + +:: + + $ flask user create demo + +See :ref:`testing-cli` for an overview of how to test your custom +commands. + + +Registering Commands with Blueprints +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your application uses blueprints, you can optionally register CLI +commands directly onto them. When your blueprint is registered onto your +application, the associated commands will be available to the ``flask`` +command. By default, those commands will be nested in a group matching +the name of the blueprint. + +.. code-block:: python + + from flask import Blueprint + + bp = Blueprint('students', __name__) + + @bp.cli.command('create') + @click.argument('name') + def create(name): + ... + + app.register_blueprint(bp) + +.. code-block:: text + + $ flask students create alice + +You can alter the group name by specifying the ``cli_group`` parameter +when creating the :class:`Blueprint` object, or later with +:meth:`app.register_blueprint(bp, cli_group='...') `. +The following are equivalent: + +.. code-block:: python + + bp = Blueprint('students', __name__, cli_group='other') + # or + app.register_blueprint(bp, cli_group='other') + +.. code-block:: text + + $ flask other create alice + +Specifying ``cli_group=None`` will remove the nesting and merge the +commands directly to the application's level: + +.. code-block:: python + + bp = Blueprint('students', __name__, cli_group=None) + # or + app.register_blueprint(bp, cli_group=None) + +.. code-block:: text + + $ flask create alice + + +Application Context +~~~~~~~~~~~~~~~~~~~ + +Commands added using the Flask app's :attr:`~Flask.cli` or +:class:`~flask.cli.FlaskGroup` :meth:`~cli.AppGroup.command` decorator +will be executed with an application context pushed, so your custom +commands and parameters have access to the app and its configuration. The +:func:`~cli.with_appcontext` decorator can be used to get the same +behavior, but is not needed in most cases. + +.. code-block:: python + + import click + from flask.cli import with_appcontext + + @click.command() + @with_appcontext + def do_work(): + ... + + app.cli.add_command(do_work) + + +Plugins +------- + +Flask will automatically load commands specified in the ``flask.commands`` +`entry point`_. This is useful for extensions that want to add commands when +they are installed. Entry points are specified in :file:`pyproject.toml`: + +.. code-block:: toml + + [project.entry-points."flask.commands"] + my-command = "my_extension.commands:cli" + +.. _entry point: https://packaging.python.org/tutorials/packaging-projects/#entry-points + +Inside :file:`my_extension/commands.py` you can then export a Click +object:: + + import click + + @click.command() + def cli(): + ... + +Once that package is installed in the same virtualenv as your Flask project, +you can run ``flask my-command`` to invoke the command. + + +.. _custom-scripts: + +Custom Scripts +-------------- + +When you are using the app factory pattern, it may be more convenient to define +your own Click script. Instead of using ``--app`` and letting Flask load +your application, you can create your own Click object and export it as a +`console script`_ entry point. + +Create an instance of :class:`~cli.FlaskGroup` and pass it the factory:: + + import click + from flask import Flask + from flask.cli import FlaskGroup + + def create_app(): + app = Flask('wiki') + # other setup + return app + + @click.group(cls=FlaskGroup, create_app=create_app) + def cli(): + """Management script for the Wiki application.""" + +Define the entry point in :file:`pyproject.toml`: + +.. code-block:: toml + + [project.scripts] + wiki = "wiki:cli" + +Install the application in the virtualenv in editable mode and the custom +script is available. Note that you don't need to set ``--app``. :: + + $ pip install -e . + $ wiki run + +.. admonition:: Errors in Custom Scripts + + When using a custom script, if you introduce an error in your + module-level code, the reloader will fail because it can no longer + load the entry point. + + The ``flask`` command, being separate from your code, does not have + this issue and is recommended in most cases. + +.. _console script: https://packaging.python.org/tutorials/packaging-projects/#console-scripts + + +PyCharm Integration +------------------- + +PyCharm Professional provides a special Flask run configuration to run the development +server. For the Community Edition, and for other commands besides ``run``, you need to +create a custom run configuration. These instructions should be similar for any other +IDE you use. + +In PyCharm, with your project open, click on *Run* from the menu bar and go to *Edit +Configurations*. You'll see a screen similar to this: + +.. image:: _static/pycharm-run-config.png + :align: center + :class: screenshot + :alt: Screenshot of PyCharm run configuration. + +Once you create a configuration for the ``flask run``, you can copy and change it to +call any other command. + +Click the *+ (Add New Configuration)* button and select *Python*. Give the configuration +a name such as "flask run". + +Click the *Script path* dropdown and change it to *Module name*, then input ``flask``. + +The *Parameters* field is set to the CLI command to execute along with any arguments. +This example uses ``--app hello run --debug``, which will run the development server in +debug mode. ``--app hello`` should be the import or file with your Flask app. + +If you installed your project as a package in your virtualenv, you may uncheck the +*PYTHONPATH* options. This will more accurately match how you deploy later. + +Click *OK* to save and close the configuration. Select the configuration in the main +PyCharm window and click the play button next to it to run the server. + +Now that you have a configuration for ``flask run``, you can copy that configuration and +change the *Parameters* argument to run a different CLI command. diff --git a/_build/_sources/config.rst.txt b/_build/_sources/config.rst.txt new file mode 100644 index 00000000..5695bbd0 --- /dev/null +++ b/_build/_sources/config.rst.txt @@ -0,0 +1,836 @@ +Configuration Handling +====================== + +Applications need some kind of configuration. There are different settings +you might want to change depending on the application environment like +toggling the debug mode, setting the secret key, and other such +environment-specific things. + +The way Flask is designed usually requires the configuration to be +available when the application starts up. You can hard code the +configuration in the code, which for many small applications is not +actually that bad, but there are better ways. + +Independent of how you load your config, there is a config object +available which holds the loaded configuration values: +The :attr:`~flask.Flask.config` attribute of the :class:`~flask.Flask` +object. This is the place where Flask itself puts certain configuration +values and also where extensions can put their configuration values. But +this is also where you can have your own configuration. + + +Configuration Basics +-------------------- + +The :attr:`~flask.Flask.config` is actually a subclass of a dictionary and +can be modified just like any dictionary:: + + app = Flask(__name__) + app.config['TESTING'] = True + +Certain configuration values are also forwarded to the +:attr:`~flask.Flask` object so you can read and write them from there:: + + app.testing = True + +To update multiple keys at once you can use the :meth:`dict.update` +method:: + + app.config.update( + TESTING=True, + SECRET_KEY='192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf' + ) + + +Debug Mode +---------- + +The :data:`DEBUG` config value is special because it may behave inconsistently if +changed after the app has begun setting up. In order to set debug mode reliably, use the +``--debug`` option on the ``flask`` or ``flask run`` command. ``flask run`` will use the +interactive debugger and reloader by default in debug mode. + +.. code-block:: text + + $ flask --app hello run --debug + +Using the option is recommended. While it is possible to set :data:`DEBUG` in your +config or code, this is strongly discouraged. It can't be read early by the +``flask run`` command, and some systems or extensions may have already configured +themselves based on a previous value. + + +Builtin Configuration Values +---------------------------- + +The following configuration values are used internally by Flask: + +.. py:data:: DEBUG + + Whether debug mode is enabled. When using ``flask run`` to start the development + server, an interactive debugger will be shown for unhandled exceptions, and the + server will be reloaded when code changes. The :attr:`~flask.Flask.debug` attribute + maps to this config key. This is set with the ``FLASK_DEBUG`` environment variable. + It may not behave as expected if set in code. + + **Do not enable debug mode when deploying in production.** + + Default: ``False`` + +.. py:data:: TESTING + + Enable testing mode. Exceptions are propagated rather than handled by the + the app's error handlers. Extensions may also change their behavior to + facilitate easier testing. You should enable this in your own tests. + + Default: ``False`` + +.. py:data:: PROPAGATE_EXCEPTIONS + + Exceptions are re-raised rather than being handled by the app's error + handlers. If not set, this is implicitly true if ``TESTING`` or ``DEBUG`` + is enabled. + + Default: ``None`` + +.. py:data:: TRAP_HTTP_EXCEPTIONS + + If there is no handler for an ``HTTPException``-type exception, re-raise it + to be handled by the interactive debugger instead of returning it as a + simple error response. + + Default: ``False`` + +.. py:data:: TRAP_BAD_REQUEST_ERRORS + + Trying to access a key that doesn't exist from request dicts like ``args`` + and ``form`` will return a 400 Bad Request error page. Enable this to treat + the error as an unhandled exception instead so that you get the interactive + debugger. This is a more specific version of ``TRAP_HTTP_EXCEPTIONS``. If + unset, it is enabled in debug mode. + + Default: ``None`` + +.. py:data:: SECRET_KEY + + A secret key that will be used for securely signing the session cookie + and can be used for any other security related needs by extensions or your + application. It should be a long random ``bytes`` or ``str``. For + example, copy the output of this to your config:: + + $ python -c 'import secrets; print(secrets.token_hex())' + '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf' + + **Do not reveal the secret key when posting questions or committing code.** + + Default: ``None`` + +.. py:data:: SECRET_KEY_FALLBACKS + + A list of old secret keys that can still be used for unsigning, most recent + first. This allows a project to implement key rotation without invalidating + active sessions or other recently-signed secrets. + + Keys should be removed after an appropriate period of time, as checking each + additional key adds some overhead. + + Flask's built-in secure cookie session supports this. Extensions that use + :data:`SECRET_KEY` may not support this yet. + + Default: ``None`` + + .. versionadded:: 3.1 + +.. py:data:: SESSION_COOKIE_NAME + + The name of the session cookie. Can be changed in case you already have a + cookie with the same name. + + Default: ``'session'`` + +.. py:data:: SESSION_COOKIE_DOMAIN + + The value of the ``Domain`` parameter on the session cookie. If not set, browsers + will only send the cookie to the exact domain it was set from. Otherwise, they + will send it to any subdomain of the given value as well. + + Not setting this value is more restricted and secure than setting it. + + Default: ``None`` + + .. warning:: + If this is changed after the browser created a cookie is created with + one setting, it may result in another being created. Browsers may send + send both in an undefined order. In that case, you may want to change + :data:`SESSION_COOKIE_NAME` as well or otherwise invalidate old sessions. + + .. versionchanged:: 2.3 + Not set by default, does not fall back to ``SERVER_NAME``. + +.. py:data:: SESSION_COOKIE_PATH + + The path that the session cookie will be valid for. If not set, the cookie + will be valid underneath ``APPLICATION_ROOT`` or ``/`` if that is not set. + + Default: ``None`` + +.. py:data:: SESSION_COOKIE_HTTPONLY + + Browsers will not allow JavaScript access to cookies marked as "HTTP only" + for security. + + Default: ``True`` + +.. py:data:: SESSION_COOKIE_SECURE + + Browsers will only send cookies with requests over HTTPS if the cookie is + marked "secure". The application must be served over HTTPS for this to make + sense. + + Default: ``False`` + +.. py:data:: SESSION_COOKIE_PARTITIONED + + Browsers will send cookies based on the top-level document's domain, rather + than only the domain of the document setting the cookie. This prevents third + party cookies set in iframes from "leaking" between separate sites. + + Browsers are beginning to disallow non-partitioned third party cookies, so + you need to mark your cookies partitioned if you expect them to work in such + embedded situations. + + Enabling this implicitly enables :data:`SESSION_COOKIE_SECURE` as well, as + it is only valid when served over HTTPS. + + Default: ``False`` + + .. versionadded:: 3.1 + +.. py:data:: SESSION_COOKIE_SAMESITE + + Restrict how cookies are sent with requests from external sites. Can + be set to ``'Lax'`` (recommended) or ``'Strict'``. + See :ref:`security-cookie`. + + Default: ``None`` + + .. versionadded:: 1.0 + +.. py:data:: PERMANENT_SESSION_LIFETIME + + If ``session.permanent`` is true, the cookie's expiration will be set this + number of seconds in the future. Can either be a + :class:`datetime.timedelta` or an ``int``. + + Flask's default cookie implementation validates that the cryptographic + signature is not older than this value. + + Default: ``timedelta(days=31)`` (``2678400`` seconds) + +.. py:data:: SESSION_REFRESH_EACH_REQUEST + + Control whether the cookie is sent with every response when + ``session.permanent`` is true. Sending the cookie every time (the default) + can more reliably keep the session from expiring, but uses more bandwidth. + Non-permanent sessions are not affected. + + Default: ``True`` + +.. py:data:: USE_X_SENDFILE + + When serving files, set the ``X-Sendfile`` header instead of serving the + data with Flask. Some web servers, such as Apache, recognize this and serve + the data more efficiently. This only makes sense when using such a server. + + Default: ``False`` + +.. py:data:: SEND_FILE_MAX_AGE_DEFAULT + + When serving files, set the cache control max age to this number of + seconds. Can be a :class:`datetime.timedelta` or an ``int``. + Override this value on a per-file basis using + :meth:`~flask.Flask.get_send_file_max_age` on the application or + blueprint. + + If ``None``, ``send_file`` tells the browser to use conditional + requests will be used instead of a timed cache, which is usually + preferable. + + Default: ``None`` + +.. py:data:: TRUSTED_HOSTS + + Validate :attr:`.Request.host` and other attributes that use it against + these trusted values. Raise a :exc:`~werkzeug.exceptions.SecurityError` if + the host is invalid, which results in a 400 error. If it is ``None``, all + hosts are valid. Each value is either an exact match, or can start with + a dot ``.`` to match any subdomain. + + Validation is done during routing against this value. ``before_request`` and + ``after_request`` callbacks will still be called. + + Default: ``None`` + + .. versionadded:: 3.1 + +.. py:data:: SERVER_NAME + + Inform the application what host and port it is bound to. + + Must be set if ``subdomain_matching`` is enabled, to be able to extract the + subdomain from the request. + + Must be set for ``url_for`` to generate external URLs outside of a + request context. + + Default: ``None`` + + .. versionchanged:: 3.1 + Does not restrict requests to only this domain, for both + ``subdomain_matching`` and ``host_matching``. + + .. versionchanged:: 1.0 + Does not implicitly enable ``subdomain_matching``. + + .. versionchanged:: 2.3 + Does not affect ``SESSION_COOKIE_DOMAIN``. + +.. py:data:: APPLICATION_ROOT + + Inform the application what path it is mounted under by the application / + web server. This is used for generating URLs outside the context of a + request (inside a request, the dispatcher is responsible for setting + ``SCRIPT_NAME`` instead; see :doc:`/patterns/appdispatch` + for examples of dispatch configuration). + + Will be used for the session cookie path if ``SESSION_COOKIE_PATH`` is not + set. + + Default: ``'/'`` + +.. py:data:: PREFERRED_URL_SCHEME + + Use this scheme for generating external URLs when not in a request context. + + Default: ``'http'`` + +.. py:data:: MAX_CONTENT_LENGTH + + The maximum number of bytes that will be read during this request. If + this limit is exceeded, a 413 :exc:`~werkzeug.exceptions.RequestEntityTooLarge` + error is raised. If it is set to ``None``, no limit is enforced at the + Flask application level. However, if it is ``None`` and the request has no + ``Content-Length`` header and the WSGI server does not indicate that it + terminates the stream, then no data is read to avoid an infinite stream. + + Each request defaults to this config. It can be set on a specific + :attr:`.Request.max_content_length` to apply the limit to that specific + view. This should be set appropriately based on an application's or view's + specific needs. + + Default: ``None`` + + .. versionadded:: 0.6 + +.. py:data:: MAX_FORM_MEMORY_SIZE + + The maximum size in bytes any non-file form field may be in a + ``multipart/form-data`` body. If this limit is exceeded, a 413 + :exc:`~werkzeug.exceptions.RequestEntityTooLarge` error is raised. If it is + set to ``None``, no limit is enforced at the Flask application level. + + Each request defaults to this config. It can be set on a specific + :attr:`.Request.max_form_memory_parts` to apply the limit to that specific + view. This should be set appropriately based on an application's or view's + specific needs. + + Default: ``500_000`` + + .. versionadded:: 3.1 + +.. py:data:: MAX_FORM_PARTS + + The maximum number of fields that may be present in a + ``multipart/form-data`` body. If this limit is exceeded, a 413 + :exc:`~werkzeug.exceptions.RequestEntityTooLarge` error is raised. If it + is set to ``None``, no limit is enforced at the Flask application level. + + Each request defaults to this config. It can be set on a specific + :attr:`.Request.max_form_parts` to apply the limit to that specific view. + This should be set appropriately based on an application's or view's + specific needs. + + Default: ``1_000`` + + .. versionadded:: 3.1 + +.. py:data:: TEMPLATES_AUTO_RELOAD + + Reload templates when they are changed. If not set, it will be enabled in + debug mode. + + Default: ``None`` + +.. py:data:: EXPLAIN_TEMPLATE_LOADING + + Log debugging information tracing how a template file was loaded. This can + be useful to figure out why a template was not loaded or the wrong file + appears to be loaded. + + Default: ``False`` + +.. py:data:: MAX_COOKIE_SIZE + + Warn if cookie headers are larger than this many bytes. Defaults to + ``4093``. Larger cookies may be silently ignored by browsers. Set to + ``0`` to disable the warning. + +.. py:data:: PROVIDE_AUTOMATIC_OPTIONS + + Set to ``False`` to disable the automatic addition of OPTIONS + responses. This can be overridden per route by altering the + ``provide_automatic_options`` attribute. + +.. versionadded:: 0.4 + ``LOGGER_NAME`` + +.. versionadded:: 0.5 + ``SERVER_NAME`` + +.. versionadded:: 0.6 + ``MAX_CONTENT_LENGTH`` + +.. versionadded:: 0.7 + ``PROPAGATE_EXCEPTIONS``, ``PRESERVE_CONTEXT_ON_EXCEPTION`` + +.. versionadded:: 0.8 + ``TRAP_BAD_REQUEST_ERRORS``, ``TRAP_HTTP_EXCEPTIONS``, + ``APPLICATION_ROOT``, ``SESSION_COOKIE_DOMAIN``, + ``SESSION_COOKIE_PATH``, ``SESSION_COOKIE_HTTPONLY``, + ``SESSION_COOKIE_SECURE`` + +.. versionadded:: 0.9 + ``PREFERRED_URL_SCHEME`` + +.. versionadded:: 0.10 + ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_PRETTYPRINT_REGULAR`` + +.. versionadded:: 0.11 + ``SESSION_REFRESH_EACH_REQUEST``, ``TEMPLATES_AUTO_RELOAD``, + ``LOGGER_HANDLER_POLICY``, ``EXPLAIN_TEMPLATE_LOADING`` + +.. versionchanged:: 1.0 + ``LOGGER_NAME`` and ``LOGGER_HANDLER_POLICY`` were removed. See + :doc:`/logging` for information about configuration. + + Added :data:`ENV` to reflect the :envvar:`FLASK_ENV` environment + variable. + + Added :data:`SESSION_COOKIE_SAMESITE` to control the session + cookie's ``SameSite`` option. + + Added :data:`MAX_COOKIE_SIZE` to control a warning from Werkzeug. + +.. versionchanged:: 2.2 + Removed ``PRESERVE_CONTEXT_ON_EXCEPTION``. + +.. versionchanged:: 2.3 + ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_MIMETYPE``, and + ``JSONIFY_PRETTYPRINT_REGULAR`` were removed. The default ``app.json`` provider has + equivalent attributes instead. + +.. versionchanged:: 2.3 + ``ENV`` was removed. + +.. versionadded:: 3.10 + Added :data:`PROVIDE_AUTOMATIC_OPTIONS` to control the default + addition of autogenerated OPTIONS responses. + + +Configuring from Python Files +----------------------------- + +Configuration becomes more useful if you can store it in a separate file, ideally +located outside the actual application package. You can deploy your application, then +separately configure it for the specific deployment. + +A common pattern is this:: + + app = Flask(__name__) + app.config.from_object('yourapplication.default_settings') + app.config.from_envvar('YOURAPPLICATION_SETTINGS') + +This first loads the configuration from the +`yourapplication.default_settings` module and then overrides the values +with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS` +environment variable points to. This environment variable can be set +in the shell before starting the server: + +.. tabs:: + + .. group-tab:: Bash + + .. code-block:: text + + $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg + $ flask run + * Running on http://127.0.0.1:5000/ + + .. group-tab:: Fish + + .. code-block:: text + + $ set -x YOURAPPLICATION_SETTINGS /path/to/settings.cfg + $ flask run + * Running on http://127.0.0.1:5000/ + + .. group-tab:: CMD + + .. code-block:: text + + > set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg + > flask run + * Running on http://127.0.0.1:5000/ + + .. group-tab:: Powershell + + .. code-block:: text + + > $env:YOURAPPLICATION_SETTINGS = "\path\to\settings.cfg" + > flask run + * Running on http://127.0.0.1:5000/ + +The configuration files themselves are actual Python files. Only values +in uppercase are actually stored in the config object later on. So make +sure to use uppercase letters for your config keys. + +Here is an example of a configuration file:: + + # Example configuration + SECRET_KEY = '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf' + +Make sure to load the configuration very early on, so that extensions have +the ability to access the configuration when starting up. There are other +methods on the config object as well to load from individual files. For a +complete reference, read the :class:`~flask.Config` object's +documentation. + + +Configuring from Data Files +--------------------------- + +It is also possible to load configuration from a file in a format of +your choice using :meth:`~flask.Config.from_file`. For example to load +from a TOML file: + +.. code-block:: python + + import tomllib + app.config.from_file("config.toml", load=tomllib.load, text=False) + +Or from a JSON file: + +.. code-block:: python + + import json + app.config.from_file("config.json", load=json.load) + + +Configuring from Environment Variables +-------------------------------------- + +In addition to pointing to configuration files using environment +variables, you may find it useful (or necessary) to control your +configuration values directly from the environment. Flask can be +instructed to load all environment variables starting with a specific +prefix into the config using :meth:`~flask.Config.from_prefixed_env`. + +Environment variables can be set in the shell before starting the +server: + +.. tabs:: + + .. group-tab:: Bash + + .. code-block:: text + + $ export FLASK_SECRET_KEY="5f352379324c22463451387a0aec5d2f" + $ export FLASK_MAIL_ENABLED=false + $ flask run + * Running on http://127.0.0.1:5000/ + + .. group-tab:: Fish + + .. code-block:: text + + $ set -x FLASK_SECRET_KEY "5f352379324c22463451387a0aec5d2f" + $ set -x FLASK_MAIL_ENABLED false + $ flask run + * Running on http://127.0.0.1:5000/ + + .. group-tab:: CMD + + .. code-block:: text + + > set FLASK_SECRET_KEY="5f352379324c22463451387a0aec5d2f" + > set FLASK_MAIL_ENABLED=false + > flask run + * Running on http://127.0.0.1:5000/ + + .. group-tab:: Powershell + + .. code-block:: text + + > $env:FLASK_SECRET_KEY = "5f352379324c22463451387a0aec5d2f" + > $env:FLASK_MAIL_ENABLED = "false" + > flask run + * Running on http://127.0.0.1:5000/ + +The variables can then be loaded and accessed via the config with a key +equal to the environment variable name without the prefix i.e. + +.. code-block:: python + + app.config.from_prefixed_env() + app.config["SECRET_KEY"] # Is "5f352379324c22463451387a0aec5d2f" + +The prefix is ``FLASK_`` by default. This is configurable via the +``prefix`` argument of :meth:`~flask.Config.from_prefixed_env`. + +Values will be parsed to attempt to convert them to a more specific type +than strings. By default :func:`json.loads` is used, so any valid JSON +value is possible, including lists and dicts. This is configurable via +the ``loads`` argument of :meth:`~flask.Config.from_prefixed_env`. + +When adding a boolean value with the default JSON parsing, only "true" +and "false", lowercase, are valid values. Keep in mind that any +non-empty string is considered ``True`` by Python. + +It is possible to set keys in nested dictionaries by separating the +keys with double underscore (``__``). Any intermediate keys that don't +exist on the parent dict will be initialized to an empty dict. + +.. code-block:: text + + $ export FLASK_MYAPI__credentials__username=user123 + +.. code-block:: python + + app.config["MYAPI"]["credentials"]["username"] # Is "user123" + +On Windows, environment variable keys are always uppercase, therefore +the above example would end up as ``MYAPI__CREDENTIALS__USERNAME``. + +For even more config loading features, including merging and +case-insensitive Windows support, try a dedicated library such as +Dynaconf_, which includes integration with Flask. + +.. _Dynaconf: https://www.dynaconf.com/ + + +Configuration Best Practices +---------------------------- + +The downside with the approach mentioned earlier is that it makes testing +a little harder. There is no single 100% solution for this problem in +general, but there are a couple of things you can keep in mind to improve +that experience: + +1. Create your application in a function and register blueprints on it. + That way you can create multiple instances of your application with + different configurations attached which makes unit testing a lot + easier. You can use this to pass in configuration as needed. + +2. Do not write code that needs the configuration at import time. If you + limit yourself to request-only accesses to the configuration you can + reconfigure the object later on as needed. + +3. Make sure to load the configuration very early on, so that + extensions can access the configuration when calling ``init_app``. + + +.. _config-dev-prod: + +Development / Production +------------------------ + +Most applications need more than one configuration. There should be at +least separate configurations for the production server and the one used +during development. The easiest way to handle this is to use a default +configuration that is always loaded and part of the version control, and a +separate configuration that overrides the values as necessary as mentioned +in the example above:: + + app = Flask(__name__) + app.config.from_object('yourapplication.default_settings') + app.config.from_envvar('YOURAPPLICATION_SETTINGS') + +Then you just have to add a separate :file:`config.py` file and export +``YOURAPPLICATION_SETTINGS=/path/to/config.py`` and you are done. However +there are alternative ways as well. For example you could use imports or +subclassing. + +What is very popular in the Django world is to make the import explicit in +the config file by adding ``from yourapplication.default_settings +import *`` to the top of the file and then overriding the changes by hand. +You could also inspect an environment variable like +``YOURAPPLICATION_MODE`` and set that to `production`, `development` etc +and import different hard-coded files based on that. + +An interesting pattern is also to use classes and inheritance for +configuration:: + + class Config(object): + TESTING = False + + class ProductionConfig(Config): + DATABASE_URI = 'mysql://user@localhost/foo' + + class DevelopmentConfig(Config): + DATABASE_URI = "sqlite:////tmp/foo.db" + + class TestingConfig(Config): + DATABASE_URI = 'sqlite:///:memory:' + TESTING = True + +To enable such a config you just have to call into +:meth:`~flask.Config.from_object`:: + + app.config.from_object('configmodule.ProductionConfig') + +Note that :meth:`~flask.Config.from_object` does not instantiate the class +object. If you need to instantiate the class, such as to access a property, +then you must do so before calling :meth:`~flask.Config.from_object`:: + + from configmodule import ProductionConfig + app.config.from_object(ProductionConfig()) + + # Alternatively, import via string: + from werkzeug.utils import import_string + cfg = import_string('configmodule.ProductionConfig')() + app.config.from_object(cfg) + +Instantiating the configuration object allows you to use ``@property`` in +your configuration classes:: + + class Config(object): + """Base config, uses staging database server.""" + TESTING = False + DB_SERVER = '192.168.1.56' + + @property + def DATABASE_URI(self): # Note: all caps + return f"mysql://user@{self.DB_SERVER}/foo" + + class ProductionConfig(Config): + """Uses production database server.""" + DB_SERVER = '192.168.19.32' + + class DevelopmentConfig(Config): + DB_SERVER = 'localhost' + + class TestingConfig(Config): + DB_SERVER = 'localhost' + DATABASE_URI = 'sqlite:///:memory:' + +There are many different ways and it's up to you how you want to manage +your configuration files. However here a list of good recommendations: + +- Keep a default configuration in version control. Either populate the + config with this default configuration or import it in your own + configuration files before overriding values. +- Use an environment variable to switch between the configurations. + This can be done from outside the Python interpreter and makes + development and deployment much easier because you can quickly and + easily switch between different configs without having to touch the + code at all. If you are working often on different projects you can + even create your own script for sourcing that activates a virtualenv + and exports the development configuration for you. +- Use a tool like `fabric`_ to push code and configuration separately + to the production server(s). + +.. _fabric: https://www.fabfile.org/ + + +.. _instance-folders: + +Instance Folders +---------------- + +.. versionadded:: 0.8 + +Flask 0.8 introduces instance folders. Flask for a long time made it +possible to refer to paths relative to the application's folder directly +(via :attr:`Flask.root_path`). This was also how many developers loaded +configurations stored next to the application. Unfortunately however this +only works well if applications are not packages in which case the root +path refers to the contents of the package. + +With Flask 0.8 a new attribute was introduced: +:attr:`Flask.instance_path`. It refers to a new concept called the +“instance folder”. The instance folder is designed to not be under +version control and be deployment specific. It's the perfect place to +drop things that either change at runtime or configuration files. + +You can either explicitly provide the path of the instance folder when +creating the Flask application or you can let Flask autodetect the +instance folder. For explicit configuration use the `instance_path` +parameter:: + + app = Flask(__name__, instance_path='/path/to/instance/folder') + +Please keep in mind that this path *must* be absolute when provided. + +If the `instance_path` parameter is not provided the following default +locations are used: + +- Uninstalled module:: + + /myapp.py + /instance + +- Uninstalled package:: + + /myapp + /__init__.py + /instance + +- Installed module or package:: + + $PREFIX/lib/pythonX.Y/site-packages/myapp + $PREFIX/var/myapp-instance + + ``$PREFIX`` is the prefix of your Python installation. This can be + ``/usr`` or the path to your virtualenv. You can print the value of + ``sys.prefix`` to see what the prefix is set to. + +Since the config object provided loading of configuration files from +relative filenames we made it possible to change the loading via filenames +to be relative to the instance path if wanted. The behavior of relative +paths in config files can be flipped between “relative to the application +root” (the default) to “relative to instance folder” via the +`instance_relative_config` switch to the application constructor:: + + app = Flask(__name__, instance_relative_config=True) + +Here is a full example of how to configure Flask to preload the config +from a module and then override the config from a file in the instance +folder if it exists:: + + app = Flask(__name__, instance_relative_config=True) + app.config.from_object('yourapplication.default_settings') + app.config.from_pyfile('application.cfg', silent=True) + +The path to the instance folder can be found via the +:attr:`Flask.instance_path`. Flask also provides a shortcut to open a +file from the instance folder with :meth:`Flask.open_instance_resource`. + +Example usage for both:: + + filename = os.path.join(app.instance_path, 'application.cfg') + with open(filename) as f: + config = f.read() + + # or via open_instance_resource: + with app.open_instance_resource('application.cfg') as f: + config = f.read() diff --git a/_build/_sources/contributing.rst.txt b/_build/_sources/contributing.rst.txt new file mode 100644 index 00000000..d44f865f --- /dev/null +++ b/_build/_sources/contributing.rst.txt @@ -0,0 +1,8 @@ +Contributing +============ + +See the Pallets `detailed contributing documentation <_contrib>`_ for many ways +to contribute, including reporting issues, requesting features, asking or +answering questions, and making PRs. + +.. _contrib: https://palletsprojects.com/contributing/ diff --git a/_build/_sources/debugging.rst.txt b/_build/_sources/debugging.rst.txt new file mode 100644 index 00000000..f6b56cab --- /dev/null +++ b/_build/_sources/debugging.rst.txt @@ -0,0 +1,99 @@ +Debugging Application Errors +============================ + + +In Production +------------- + +**Do not run the development server, or enable the built-in debugger, in +a production environment.** The debugger allows executing arbitrary +Python code from the browser. It's protected by a pin, but that should +not be relied on for security. + +Use an error logging tool, such as Sentry, as described in +:ref:`error-logging-tools`, or enable logging and notifications as +described in :doc:`/logging`. + +If you have access to the server, you could add some code to start an +external debugger if ``request.remote_addr`` matches your IP. Some IDE +debuggers also have a remote mode so breakpoints on the server can be +interacted with locally. Only enable a debugger temporarily. + + +The Built-In Debugger +--------------------- + +The built-in Werkzeug development server provides a debugger which shows +an interactive traceback in the browser when an unhandled error occurs +during a request. This debugger should only be used during development. + +.. image:: _static/debugger.png + :align: center + :class: screenshot + :alt: screenshot of debugger in action + +.. warning:: + + The debugger allows executing arbitrary Python code from the + browser. It is protected by a pin, but still represents a major + security risk. Do not run the development server or debugger in a + production environment. + +The debugger is enabled by default when the development server is run in debug mode. + +.. code-block:: text + + $ flask --app hello run --debug + +When running from Python code, passing ``debug=True`` enables debug mode, which is +mostly equivalent. + +.. code-block:: python + + app.run(debug=True) + +:doc:`/server` and :doc:`/cli` have more information about running the debugger and +debug mode. More information about the debugger can be found in the `Werkzeug +documentation `__. + + +External Debuggers +------------------ + +External debuggers, such as those provided by IDEs, can offer a more +powerful debugging experience than the built-in debugger. They can also +be used to step through code during a request before an error is raised, +or if no error is raised. Some even have a remote mode so you can debug +code running on another machine. + +When using an external debugger, the app should still be in debug mode, otherwise Flask +turns unhandled errors into generic 500 error pages. However, the built-in debugger and +reloader should be disabled so they don't interfere with the external debugger. + +.. code-block:: text + + $ flask --app hello run --debug --no-debugger --no-reload + +When running from Python: + +.. code-block:: python + + app.run(debug=True, use_debugger=False, use_reloader=False) + +Disabling these isn't required, an external debugger will continue to work with the +following caveats. + +- If the built-in debugger is not disabled, it will catch unhandled exceptions before + the external debugger can. +- If the reloader is not disabled, it could cause an unexpected reload if code changes + during a breakpoint. +- The development server will still catch unhandled exceptions if the built-in + debugger is disabled, otherwise it would crash on any error. If you want that (and + usually you don't) pass ``passthrough_errors=True`` to ``app.run``. + + .. code-block:: python + + app.run( + debug=True, passthrough_errors=True, + use_debugger=False, use_reloader=False + ) diff --git a/_build/_sources/deploying/apache-httpd.rst.txt b/_build/_sources/deploying/apache-httpd.rst.txt new file mode 100644 index 00000000..bdeaf626 --- /dev/null +++ b/_build/_sources/deploying/apache-httpd.rst.txt @@ -0,0 +1,66 @@ +Apache httpd +============ + +`Apache httpd`_ is a fast, production level HTTP server. When serving +your application with one of the WSGI servers listed in :doc:`index`, it +is often good or necessary to put a dedicated HTTP server in front of +it. This "reverse proxy" can handle incoming requests, TLS, and other +security and performance concerns better than the WSGI server. + +httpd can be installed using your system package manager, or a pre-built +executable for Windows. Installing and running httpd itself is outside +the scope of this doc. This page outlines the basics of configuring +httpd to proxy your application. Be sure to read its documentation to +understand what features are available. + +.. _Apache httpd: https://httpd.apache.org/ + + +Domain Name +----------- + +Acquiring and configuring a domain name is outside the scope of this +doc. In general, you will buy a domain name from a registrar, pay for +server space with a hosting provider, and then point your registrar +at the hosting provider's name servers. + +To simulate this, you can also edit your ``hosts`` file, located at +``/etc/hosts`` on Linux. Add a line that associates a name with the +local IP. + +Modern Linux systems may be configured to treat any domain name that +ends with ``.localhost`` like this without adding it to the ``hosts`` +file. + +.. code-block:: python + :caption: ``/etc/hosts`` + + 127.0.0.1 hello.localhost + + +Configuration +------------- + +The httpd configuration is located at ``/etc/httpd/conf/httpd.conf`` on +Linux. It may be different depending on your operating system. Check the +docs and look for ``httpd.conf``. + +Remove or comment out any existing ``DocumentRoot`` directive. Add the +config lines below. We'll assume the WSGI server is listening locally at +``http://127.0.0.1:8000``. + +.. code-block:: apache + :caption: ``/etc/httpd/conf/httpd.conf`` + + LoadModule proxy_module modules/mod_proxy.so + LoadModule proxy_http_module modules/mod_proxy_http.so + ProxyPass / http://127.0.0.1:8000/ + RequestHeader set X-Forwarded-Proto http + RequestHeader set X-Forwarded-Prefix / + +The ``LoadModule`` lines might already exist. If so, make sure they are +uncommented instead of adding them manually. + +Then :doc:`proxy_fix` so that your application uses the ``X-Forwarded`` +headers. ``X-Forwarded-For`` and ``X-Forwarded-Host`` are automatically +set by ``ProxyPass``. diff --git a/_build/_sources/deploying/asgi.rst.txt b/_build/_sources/deploying/asgi.rst.txt new file mode 100644 index 00000000..1dc0aa24 --- /dev/null +++ b/_build/_sources/deploying/asgi.rst.txt @@ -0,0 +1,27 @@ +ASGI +==== + +If you'd like to use an ASGI server you will need to utilise WSGI to +ASGI middleware. The asgiref +`WsgiToAsgi `_ +adapter is recommended as it integrates with the event loop used for +Flask's :ref:`async_await` support. You can use the adapter by +wrapping the Flask app, + +.. code-block:: python + + from asgiref.wsgi import WsgiToAsgi + from flask import Flask + + app = Flask(__name__) + + ... + + asgi_app = WsgiToAsgi(app) + +and then serving the ``asgi_app`` with the ASGI server, e.g. using +`Hypercorn `_, + +.. sourcecode:: text + + $ hypercorn module:asgi_app diff --git a/_build/_sources/deploying/eventlet.rst.txt b/_build/_sources/deploying/eventlet.rst.txt new file mode 100644 index 00000000..8a718b22 --- /dev/null +++ b/_build/_sources/deploying/eventlet.rst.txt @@ -0,0 +1,80 @@ +eventlet +======== + +Prefer using :doc:`gunicorn` with eventlet workers rather than using +`eventlet`_ directly. Gunicorn provides a much more configurable and +production-tested server. + +`eventlet`_ allows writing asynchronous, coroutine-based code that looks +like standard synchronous Python. It uses `greenlet`_ to enable task +switching without writing ``async/await`` or using ``asyncio``. + +:doc:`gevent` is another library that does the same thing. Certain +dependencies you have, or other considerations, may affect which of the +two you choose to use. + +eventlet provides a WSGI server that can handle many connections at once +instead of one per worker process. You must actually use eventlet in +your own code to see any benefit to using the server. + +.. _eventlet: https://eventlet.net/ +.. _greenlet: https://greenlet.readthedocs.io/en/latest/ + + +Installing +---------- + +When using eventlet, greenlet>=1.0 is required, otherwise context locals +such as ``request`` will not work as expected. When using PyPy, +PyPy>=7.3.7 is required. + +Create a virtualenv, install your application, then install +``eventlet``. + +.. code-block:: text + + $ cd hello-app + $ python -m venv .venv + $ . .venv/bin/activate + $ pip install . # install your application + $ pip install eventlet + + +Running +------- + +To use eventlet to serve your application, write a script that imports +its ``wsgi.server``, as well as your app or app factory. + +.. code-block:: python + :caption: ``wsgi.py`` + + import eventlet + from eventlet import wsgi + from hello import create_app + + app = create_app() + wsgi.server(eventlet.listen(("127.0.0.1", 8000)), app) + +.. code-block:: text + + $ python wsgi.py + (x) wsgi starting up on http://127.0.0.1:8000 + + +Binding Externally +------------------ + +eventlet should not be run as root because it would cause your +application code to run as root, which is not secure. However, this +means it will not be possible to bind to port 80 or 443. Instead, a +reverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used +in front of eventlet. + +You can bind to all external IPs on a non-privileged port by using +``0.0.0.0`` in the server arguments shown in the previous section. +Don't do this when using a reverse proxy setup, otherwise it will be +possible to bypass the proxy. + +``0.0.0.0`` is not a valid address to navigate to, you'd use a specific +IP address in your browser. diff --git a/_build/_sources/deploying/gevent.rst.txt b/_build/_sources/deploying/gevent.rst.txt new file mode 100644 index 00000000..448b93e7 --- /dev/null +++ b/_build/_sources/deploying/gevent.rst.txt @@ -0,0 +1,80 @@ +gevent +====== + +Prefer using :doc:`gunicorn` or :doc:`uwsgi` with gevent workers rather +than using `gevent`_ directly. Gunicorn and uWSGI provide much more +configurable and production-tested servers. + +`gevent`_ allows writing asynchronous, coroutine-based code that looks +like standard synchronous Python. It uses `greenlet`_ to enable task +switching without writing ``async/await`` or using ``asyncio``. + +:doc:`eventlet` is another library that does the same thing. Certain +dependencies you have, or other considerations, may affect which of the +two you choose to use. + +gevent provides a WSGI server that can handle many connections at once +instead of one per worker process. You must actually use gevent in your +own code to see any benefit to using the server. + +.. _gevent: https://www.gevent.org/ +.. _greenlet: https://greenlet.readthedocs.io/en/latest/ + + +Installing +---------- + +When using gevent, greenlet>=1.0 is required, otherwise context locals +such as ``request`` will not work as expected. When using PyPy, +PyPy>=7.3.7 is required. + +Create a virtualenv, install your application, then install ``gevent``. + +.. code-block:: text + + $ cd hello-app + $ python -m venv .venv + $ . .venv/bin/activate + $ pip install . # install your application + $ pip install gevent + + +Running +------- + +To use gevent to serve your application, write a script that imports its +``WSGIServer``, as well as your app or app factory. + +.. code-block:: python + :caption: ``wsgi.py`` + + from gevent.pywsgi import WSGIServer + from hello import create_app + + app = create_app() + http_server = WSGIServer(("127.0.0.1", 8000), app) + http_server.serve_forever() + +.. code-block:: text + + $ python wsgi.py + +No output is shown when the server starts. + + +Binding Externally +------------------ + +gevent should not be run as root because it would cause your +application code to run as root, which is not secure. However, this +means it will not be possible to bind to port 80 or 443. Instead, a +reverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used +in front of gevent. + +You can bind to all external IPs on a non-privileged port by using +``0.0.0.0`` in the server arguments shown in the previous section. Don't +do this when using a reverse proxy setup, otherwise it will be possible +to bypass the proxy. + +``0.0.0.0`` is not a valid address to navigate to, you'd use a specific +IP address in your browser. diff --git a/_build/_sources/deploying/gunicorn.rst.txt b/_build/_sources/deploying/gunicorn.rst.txt new file mode 100644 index 00000000..c50edc23 --- /dev/null +++ b/_build/_sources/deploying/gunicorn.rst.txt @@ -0,0 +1,130 @@ +Gunicorn +======== + +`Gunicorn`_ is a pure Python WSGI server with simple configuration and +multiple worker implementations for performance tuning. + +* It tends to integrate easily with hosting platforms. +* It does not support Windows (but does run on WSL). +* It is easy to install as it does not require additional dependencies + or compilation. +* It has built-in async worker support using gevent or eventlet. + +This page outlines the basics of running Gunicorn. Be sure to read its +`documentation`_ and use ``gunicorn --help`` to understand what features +are available. + +.. _Gunicorn: https://gunicorn.org/ +.. _documentation: https://docs.gunicorn.org/ + + +Installing +---------- + +Gunicorn is easy to install, as it does not require external +dependencies or compilation. It runs on Windows only under WSL. + +Create a virtualenv, install your application, then install +``gunicorn``. + +.. code-block:: text + + $ cd hello-app + $ python -m venv .venv + $ . .venv/bin/activate + $ pip install . # install your application + $ pip install gunicorn + + +Running +------- + +The only required argument to Gunicorn tells it how to load your Flask +application. The syntax is ``{module_import}:{app_variable}``. +``module_import`` is the dotted import name to the module with your +application. ``app_variable`` is the variable with the application. It +can also be a function call (with any arguments) if you're using the +app factory pattern. + +.. code-block:: text + + # equivalent to 'from hello import app' + $ gunicorn -w 4 'hello:app' + + # equivalent to 'from hello import create_app; create_app()' + $ gunicorn -w 4 'hello:create_app()' + + Starting gunicorn 20.1.0 + Listening at: http://127.0.0.1:8000 (x) + Using worker: sync + Booting worker with pid: x + Booting worker with pid: x + Booting worker with pid: x + Booting worker with pid: x + +The ``-w`` option specifies the number of processes to run; a starting +value could be ``CPU * 2``. The default is only 1 worker, which is +probably not what you want for the default worker type. + +Logs for each request aren't shown by default, only worker info and +errors are shown. To show access logs on stdout, use the +``--access-logfile=-`` option. + + +Binding Externally +------------------ + +Gunicorn should not be run as root because it would cause your +application code to run as root, which is not secure. However, this +means it will not be possible to bind to port 80 or 443. Instead, a +reverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used +in front of Gunicorn. + +You can bind to all external IPs on a non-privileged port using the +``-b 0.0.0.0`` option. Don't do this when using a reverse proxy setup, +otherwise it will be possible to bypass the proxy. + +.. code-block:: text + + $ gunicorn -w 4 -b 0.0.0.0 'hello:create_app()' + Listening at: http://0.0.0.0:8000 (x) + +``0.0.0.0`` is not a valid address to navigate to, you'd use a specific +IP address in your browser. + + +Async with gevent or eventlet +----------------------------- + +The default sync worker is appropriate for many use cases. If you need +asynchronous support, Gunicorn provides workers using either `gevent`_ +or `eventlet`_. This is not the same as Python's ``async/await``, or the +ASGI server spec. You must actually use gevent/eventlet in your own code +to see any benefit to using the workers. + +When using either gevent or eventlet, greenlet>=1.0 is required, +otherwise context locals such as ``request`` will not work as expected. +When using PyPy, PyPy>=7.3.7 is required. + +To use gevent: + +.. code-block:: text + + $ gunicorn -k gevent 'hello:create_app()' + Starting gunicorn 20.1.0 + Listening at: http://127.0.0.1:8000 (x) + Using worker: gevent + Booting worker with pid: x + +To use eventlet: + +.. code-block:: text + + $ gunicorn -k eventlet 'hello:create_app()' + Starting gunicorn 20.1.0 + Listening at: http://127.0.0.1:8000 (x) + Using worker: eventlet + Booting worker with pid: x + +.. _gevent: https://www.gevent.org/ +.. _eventlet: https://eventlet.net/ diff --git a/_build/_sources/deploying/index.rst.txt b/_build/_sources/deploying/index.rst.txt new file mode 100644 index 00000000..4135596a --- /dev/null +++ b/_build/_sources/deploying/index.rst.txt @@ -0,0 +1,79 @@ +Deploying to Production +======================= + +After developing your application, you'll want to make it available +publicly to other users. When you're developing locally, you're probably +using the built-in development server, debugger, and reloader. These +should not be used in production. Instead, you should use a dedicated +WSGI server or hosting platform, some of which will be described here. + +"Production" means "not development", which applies whether you're +serving your application publicly to millions of users or privately / +locally to a single user. **Do not use the development server when +deploying to production. It is intended for use only during local +development. It is not designed to be particularly secure, stable, or +efficient.** + +Self-Hosted Options +------------------- + +Flask is a WSGI *application*. A WSGI *server* is used to run the +application, converting incoming HTTP requests to the standard WSGI +environ, and converting outgoing WSGI responses to HTTP responses. + +The primary goal of these docs is to familiarize you with the concepts +involved in running a WSGI application using a production WSGI server +and HTTP server. There are many WSGI servers and HTTP servers, with many +configuration possibilities. The pages below discuss the most common +servers, and show the basics of running each one. The next section +discusses platforms that can manage this for you. + +.. toctree:: + :maxdepth: 1 + + gunicorn + waitress + mod_wsgi + uwsgi + gevent + eventlet + asgi + +WSGI servers have HTTP servers built-in. However, a dedicated HTTP +server may be safer, more efficient, or more capable. Putting an HTTP +server in front of the WSGI server is called a "reverse proxy." + +.. toctree:: + :maxdepth: 1 + + proxy_fix + nginx + apache-httpd + +This list is not exhaustive, and you should evaluate these and other +servers based on your application's needs. Different servers will have +different capabilities, configuration, and support. + + +Hosting Platforms +----------------- + +There are many services available for hosting web applications without +needing to maintain your own server, networking, domain, etc. Some +services may have a free tier up to a certain time or bandwidth. Many of +these services use one of the WSGI servers described above, or a similar +interface. The links below are for some of the most common platforms, +which have instructions for Flask, WSGI, or Python. + +- `PythonAnywhere `_ +- `Google App Engine `_ +- `Google Cloud Run `_ +- `AWS Elastic Beanstalk `_ +- `Microsoft Azure `_ + +This list is not exhaustive, and you should evaluate these and other +services based on your application's needs. Different services will have +different capabilities, configuration, pricing, and support. + +You'll probably need to :doc:`proxy_fix` when using most hosting +platforms. diff --git a/_build/_sources/deploying/mod_wsgi.rst.txt b/_build/_sources/deploying/mod_wsgi.rst.txt new file mode 100644 index 00000000..23e82279 --- /dev/null +++ b/_build/_sources/deploying/mod_wsgi.rst.txt @@ -0,0 +1,94 @@ +mod_wsgi +======== + +`mod_wsgi`_ is a WSGI server integrated with the `Apache httpd`_ server. +The modern `mod_wsgi-express`_ command makes it easy to configure and +start the server without needing to write Apache httpd configuration. + +* Tightly integrated with Apache httpd. +* Supports Windows directly. +* Requires a compiler and the Apache development headers to install. +* Does not require a reverse proxy setup. + +This page outlines the basics of running mod_wsgi-express, not the more +complex installation and configuration with httpd. Be sure to read the +`mod_wsgi-express`_, `mod_wsgi`_, and `Apache httpd`_ documentation to +understand what features are available. + +.. _mod_wsgi-express: https://pypi.org/project/mod-wsgi/ +.. _mod_wsgi: https://modwsgi.readthedocs.io/ +.. _Apache httpd: https://httpd.apache.org/ + + +Installing +---------- + +Installing mod_wsgi requires a compiler and the Apache server and +development headers installed. You will get an error if they are not. +How to install them depends on the OS and package manager that you use. + +Create a virtualenv, install your application, then install +``mod_wsgi``. + +.. code-block:: text + + $ cd hello-app + $ python -m venv .venv + $ . .venv/bin/activate + $ pip install . # install your application + $ pip install mod_wsgi + + +Running +------- + +The only argument to ``mod_wsgi-express`` specifies a script containing +your Flask application, which must be called ``application``. You can +write a small script to import your app with this name, or to create it +if using the app factory pattern. + +.. code-block:: python + :caption: ``wsgi.py`` + + from hello import app + + application = app + +.. code-block:: python + :caption: ``wsgi.py`` + + from hello import create_app + + application = create_app() + +Now run the ``mod_wsgi-express start-server`` command. + +.. code-block:: text + + $ mod_wsgi-express start-server wsgi.py --processes 4 + +The ``--processes`` option specifies the number of worker processes to +run; a starting value could be ``CPU * 2``. + +Logs for each request aren't show in the terminal. If an error occurs, +its information is written to the error log file shown when starting the +server. + + +Binding Externally +------------------ + +Unlike the other WSGI servers in these docs, mod_wsgi can be run as +root to bind to privileged ports like 80 and 443. However, it must be +configured to drop permissions to a different user and group for the +worker processes. + +For example, if you created a ``hello`` user and group, you should +install your virtualenv and application as that user, then tell +mod_wsgi to drop to that user after starting. + +.. code-block:: text + + $ sudo /home/hello/.venv/bin/mod_wsgi-express start-server \ + /home/hello/wsgi.py \ + --user hello --group hello --port 80 --processes 4 diff --git a/_build/_sources/deploying/nginx.rst.txt b/_build/_sources/deploying/nginx.rst.txt new file mode 100644 index 00000000..6b25c073 --- /dev/null +++ b/_build/_sources/deploying/nginx.rst.txt @@ -0,0 +1,69 @@ +nginx +===== + +`nginx`_ is a fast, production level HTTP server. When serving your +application with one of the WSGI servers listed in :doc:`index`, it is +often good or necessary to put a dedicated HTTP server in front of it. +This "reverse proxy" can handle incoming requests, TLS, and other +security and performance concerns better than the WSGI server. + +Nginx can be installed using your system package manager, or a pre-built +executable for Windows. Installing and running Nginx itself is outside +the scope of this doc. This page outlines the basics of configuring +Nginx to proxy your application. Be sure to read its documentation to +understand what features are available. + +.. _nginx: https://nginx.org/ + + +Domain Name +----------- + +Acquiring and configuring a domain name is outside the scope of this +doc. In general, you will buy a domain name from a registrar, pay for +server space with a hosting provider, and then point your registrar +at the hosting provider's name servers. + +To simulate this, you can also edit your ``hosts`` file, located at +``/etc/hosts`` on Linux. Add a line that associates a name with the +local IP. + +Modern Linux systems may be configured to treat any domain name that +ends with ``.localhost`` like this without adding it to the ``hosts`` +file. + +.. code-block:: python + :caption: ``/etc/hosts`` + + 127.0.0.1 hello.localhost + + +Configuration +------------- + +The nginx configuration is located at ``/etc/nginx/nginx.conf`` on +Linux. It may be different depending on your operating system. Check the +docs and look for ``nginx.conf``. + +Remove or comment out any existing ``server`` section. Add a ``server`` +section and use the ``proxy_pass`` directive to point to the address the +WSGI server is listening on. We'll assume the WSGI server is listening +locally at ``http://127.0.0.1:8000``. + +.. code-block:: nginx + :caption: ``/etc/nginx.conf`` + + server { + listen 80; + server_name _; + + location / { + proxy_pass http://127.0.0.1:8000/; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-Host $host; + proxy_set_header X-Forwarded-Prefix /; + } + } + +Then :doc:`proxy_fix` so that your application uses these headers. diff --git a/_build/_sources/deploying/proxy_fix.rst.txt b/_build/_sources/deploying/proxy_fix.rst.txt new file mode 100644 index 00000000..e2c42e82 --- /dev/null +++ b/_build/_sources/deploying/proxy_fix.rst.txt @@ -0,0 +1,33 @@ +Tell Flask it is Behind a Proxy +=============================== + +When using a reverse proxy, or many Python hosting platforms, the proxy +will intercept and forward all external requests to the local WSGI +server. + +From the WSGI server and Flask application's perspectives, requests are +now coming from the HTTP server to the local address, rather than from +the remote address to the external server address. + +HTTP servers should set ``X-Forwarded-`` headers to pass on the real +values to the application. The application can then be told to trust and +use those values by wrapping it with the +:doc:`werkzeug:middleware/proxy_fix` middleware provided by Werkzeug. + +This middleware should only be used if the application is actually +behind a proxy, and should be configured with the number of proxies that +are chained in front of it. Not all proxies set all the headers. Since +incoming headers can be faked, you must set how many proxies are setting +each header so the middleware knows what to trust. + +.. code-block:: python + + from werkzeug.middleware.proxy_fix import ProxyFix + + app.wsgi_app = ProxyFix( + app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1 + ) + +Remember, only apply this middleware if you are behind a proxy, and set +the correct number of proxies that set each header. It can be a security +issue if you get this configuration wrong. diff --git a/_build/_sources/deploying/uwsgi.rst.txt b/_build/_sources/deploying/uwsgi.rst.txt new file mode 100644 index 00000000..1f9d5eca --- /dev/null +++ b/_build/_sources/deploying/uwsgi.rst.txt @@ -0,0 +1,145 @@ +uWSGI +===== + +`uWSGI`_ is a fast, compiled server suite with extensive configuration +and capabilities beyond a basic server. + +* It can be very performant due to being a compiled program. +* It is complex to configure beyond the basic application, and has so + many options that it can be difficult for beginners to understand. +* It does not support Windows (but does run on WSL). +* It requires a compiler to install in some cases. + +This page outlines the basics of running uWSGI. Be sure to read its +documentation to understand what features are available. + +.. _uWSGI: https://uwsgi-docs.readthedocs.io/en/latest/ + + +Installing +---------- + +uWSGI has multiple ways to install it. The most straightforward is to +install the ``pyuwsgi`` package, which provides precompiled wheels for +common platforms. However, it does not provide SSL support, which can be +provided with a reverse proxy instead. + +Create a virtualenv, install your application, then install ``pyuwsgi``. + +.. code-block:: text + + $ cd hello-app + $ python -m venv .venv + $ . .venv/bin/activate + $ pip install . # install your application + $ pip install pyuwsgi + +If you have a compiler available, you can install the ``uwsgi`` package +instead. Or install the ``pyuwsgi`` package from sdist instead of wheel. +Either method will include SSL support. + +.. code-block:: text + + $ pip install uwsgi + + # or + $ pip install --no-binary pyuwsgi pyuwsgi + + +Running +------- + +The most basic way to run uWSGI is to tell it to start an HTTP server +and import your application. + +.. code-block:: text + + $ uwsgi --http 127.0.0.1:8000 --master -p 4 -w hello:app + + *** Starting uWSGI 2.0.20 (64bit) on [x] *** + *** Operational MODE: preforking *** + mounting hello:app on / + spawned uWSGI master process (pid: x) + spawned uWSGI worker 1 (pid: x, cores: 1) + spawned uWSGI worker 2 (pid: x, cores: 1) + spawned uWSGI worker 3 (pid: x, cores: 1) + spawned uWSGI worker 4 (pid: x, cores: 1) + spawned uWSGI http 1 (pid: x) + +If you're using the app factory pattern, you'll need to create a small +Python file to create the app, then point uWSGI at that. + +.. code-block:: python + :caption: ``wsgi.py`` + + from hello import create_app + + app = create_app() + +.. code-block:: text + + $ uwsgi --http 127.0.0.1:8000 --master -p 4 -w wsgi:app + +The ``--http`` option starts an HTTP server at 127.0.0.1 port 8000. The +``--master`` option specifies the standard worker manager. The ``-p`` +option starts 4 worker processes; a starting value could be ``CPU * 2``. +The ``-w`` option tells uWSGI how to import your application + + +Binding Externally +------------------ + +uWSGI should not be run as root with the configuration shown in this doc +because it would cause your application code to run as root, which is +not secure. However, this means it will not be possible to bind to port +80 or 443. Instead, a reverse proxy such as :doc:`nginx` or +:doc:`apache-httpd` should be used in front of uWSGI. It is possible to +run uWSGI as root securely, but that is beyond the scope of this doc. + +uWSGI has optimized integration with `Nginx uWSGI`_ and +`Apache mod_proxy_uwsgi`_, and possibly other servers, instead of using +a standard HTTP proxy. That configuration is beyond the scope of this +doc, see the links for more information. + +.. _Nginx uWSGI: https://uwsgi-docs.readthedocs.io/en/latest/Nginx.html +.. _Apache mod_proxy_uwsgi: https://uwsgi-docs.readthedocs.io/en/latest/Apache.html#mod-proxy-uwsgi + +You can bind to all external IPs on a non-privileged port using the +``--http 0.0.0.0:8000`` option. Don't do this when using a reverse proxy +setup, otherwise it will be possible to bypass the proxy. + +.. code-block:: text + + $ uwsgi --http 0.0.0.0:8000 --master -p 4 -w wsgi:app + +``0.0.0.0`` is not a valid address to navigate to, you'd use a specific +IP address in your browser. + + +Async with gevent +----------------- + +The default sync worker is appropriate for many use cases. If you need +asynchronous support, uWSGI provides a `gevent`_ worker. This is not the +same as Python's ``async/await``, or the ASGI server spec. You must +actually use gevent in your own code to see any benefit to using the +worker. + +When using gevent, greenlet>=1.0 is required, otherwise context locals +such as ``request`` will not work as expected. When using PyPy, +PyPy>=7.3.7 is required. + +.. code-block:: text + + $ uwsgi --http 127.0.0.1:8000 --master --gevent 100 -w wsgi:app + + *** Starting uWSGI 2.0.20 (64bit) on [x] *** + *** Operational MODE: async *** + mounting hello:app on / + spawned uWSGI master process (pid: x) + spawned uWSGI worker 1 (pid: x, cores: 100) + spawned uWSGI http 1 (pid: x) + *** running gevent loop engine [addr:x] *** + + +.. _gevent: https://www.gevent.org/ diff --git a/_build/_sources/deploying/waitress.rst.txt b/_build/_sources/deploying/waitress.rst.txt new file mode 100644 index 00000000..7bdd695b --- /dev/null +++ b/_build/_sources/deploying/waitress.rst.txt @@ -0,0 +1,75 @@ +Waitress +======== + +`Waitress`_ is a pure Python WSGI server. + +* It is easy to configure. +* It supports Windows directly. +* It is easy to install as it does not require additional dependencies + or compilation. +* It does not support streaming requests, full request data is always + buffered. +* It uses a single process with multiple thread workers. + +This page outlines the basics of running Waitress. Be sure to read its +documentation and ``waitress-serve --help`` to understand what features +are available. + +.. _Waitress: https://docs.pylonsproject.org/projects/waitress/ + + +Installing +---------- + +Create a virtualenv, install your application, then install +``waitress``. + +.. code-block:: text + + $ cd hello-app + $ python -m venv .venv + $ . .venv/bin/activate + $ pip install . # install your application + $ pip install waitress + + +Running +------- + +The only required argument to ``waitress-serve`` tells it how to load +your Flask application. The syntax is ``{module}:{app}``. ``module`` is +the dotted import name to the module with your application. ``app`` is +the variable with the application. If you're using the app factory +pattern, use ``--call {module}:{factory}`` instead. + +.. code-block:: text + + # equivalent to 'from hello import app' + $ waitress-serve --host 127.0.0.1 hello:app + + # equivalent to 'from hello import create_app; create_app()' + $ waitress-serve --host 127.0.0.1 --call hello:create_app + + Serving on http://127.0.0.1:8080 + +The ``--host`` option binds the server to local ``127.0.0.1`` only. + +Logs for each request aren't shown, only errors are shown. Logging can +be configured through the Python interface instead of the command line. + + +Binding Externally +------------------ + +Waitress should not be run as root because it would cause your +application code to run as root, which is not secure. However, this +means it will not be possible to bind to port 80 or 443. Instead, a +reverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used +in front of Waitress. + +You can bind to all external IPs on a non-privileged port by not +specifying the ``--host`` option. Don't do this when using a reverse +proxy setup, otherwise it will be possible to bypass the proxy. + +``0.0.0.0`` is not a valid address to navigate to, you'd use a specific +IP address in your browser. diff --git a/_build/_sources/design.rst.txt b/_build/_sources/design.rst.txt new file mode 100644 index 00000000..066cf107 --- /dev/null +++ b/_build/_sources/design.rst.txt @@ -0,0 +1,228 @@ +Design Decisions in Flask +========================= + +If you are curious why Flask does certain things the way it does and not +differently, this section is for you. This should give you an idea about +some of the design decisions that may appear arbitrary and surprising at +first, especially in direct comparison with other frameworks. + + +The Explicit Application Object +------------------------------- + +A Python web application based on WSGI has to have one central callable +object that implements the actual application. In Flask this is an +instance of the :class:`~flask.Flask` class. Each Flask application has +to create an instance of this class itself and pass it the name of the +module, but why can't Flask do that itself? + +Without such an explicit application object the following code:: + + from flask import Flask + app = Flask(__name__) + + @app.route('/') + def index(): + return 'Hello World!' + +Would look like this instead:: + + from hypothetical_flask import route + + @route('/') + def index(): + return 'Hello World!' + +There are three major reasons for this. The most important one is that +implicit application objects require that there may only be one instance at +the time. There are ways to fake multiple applications with a single +application object, like maintaining a stack of applications, but this +causes some problems I won't outline here in detail. Now the question is: +when does a microframework need more than one application at the same +time? A good example for this is unit testing. When you want to test +something it can be very helpful to create a minimal application to test +specific behavior. When the application object is deleted everything it +allocated will be freed again. + +Another thing that becomes possible when you have an explicit object lying +around in your code is that you can subclass the base class +(:class:`~flask.Flask`) to alter specific behavior. This would not be +possible without hacks if the object were created ahead of time for you +based on a class that is not exposed to you. + +But there is another very important reason why Flask depends on an +explicit instantiation of that class: the package name. Whenever you +create a Flask instance you usually pass it `__name__` as package name. +Flask depends on that information to properly load resources relative +to your module. With Python's outstanding support for reflection it can +then access the package to figure out where the templates and static files +are stored (see :meth:`~flask.Flask.open_resource`). Now obviously there +are frameworks around that do not need any configuration and will still be +able to load templates relative to your application module. But they have +to use the current working directory for that, which is a very unreliable +way to determine where the application is. The current working directory +is process-wide and if you are running multiple applications in one +process (which could happen in a webserver without you knowing) the paths +will be off. Worse: many webservers do not set the working directory to +the directory of your application but to the document root which does not +have to be the same folder. + +The third reason is "explicit is better than implicit". That object is +your WSGI application, you don't have to remember anything else. If you +want to apply a WSGI middleware, just wrap it and you're done (though +there are better ways to do that so that you do not lose the reference +to the application object :meth:`~flask.Flask.wsgi_app`). + +Furthermore this design makes it possible to use a factory function to +create the application which is very helpful for unit testing and similar +things (:doc:`/patterns/appfactories`). + +The Routing System +------------------ + +Flask uses the Werkzeug routing system which was designed to +automatically order routes by complexity. This means that you can declare +routes in arbitrary order and they will still work as expected. This is a +requirement if you want to properly implement decorator based routing +since decorators could be fired in undefined order when the application is +split into multiple modules. + +Another design decision with the Werkzeug routing system is that routes +in Werkzeug try to ensure that URLs are unique. Werkzeug will go quite far +with that in that it will automatically redirect to a canonical URL if a route +is ambiguous. + + +One Template Engine +------------------- + +Flask decides on one template engine: Jinja2. Why doesn't Flask have a +pluggable template engine interface? You can obviously use a different +template engine, but Flask will still configure Jinja2 for you. While +that limitation that Jinja2 is *always* configured will probably go away, +the decision to bundle one template engine and use that will not. + +Template engines are like programming languages and each of those engines +has a certain understanding about how things work. On the surface they +all work the same: you tell the engine to evaluate a template with a set +of variables and take the return value as string. + +But that's about where similarities end. Jinja2 for example has an +extensive filter system, a certain way to do template inheritance, +support for reusable blocks (macros) that can be used from inside +templates and also from Python code, supports iterative template +rendering, configurable syntax and more. On the other hand an engine +like Genshi is based on XML stream evaluation, template inheritance by +taking the availability of XPath into account and more. Mako on the +other hand treats templates similar to Python modules. + +When it comes to connecting a template engine with an application or +framework there is more than just rendering templates. For instance, +Flask uses Jinja2's extensive autoescaping support. Also it provides +ways to access macros from Jinja2 templates. + +A template abstraction layer that would not take the unique features of +the template engines away is a science on its own and a too large +undertaking for a microframework like Flask. + +Furthermore extensions can then easily depend on one template language +being present. You can easily use your own templating language, but an +extension could still depend on Jinja itself. + + +What does "micro" mean? +----------------------- + +“Micro” does not mean that your whole web application has to fit into a single +Python file (although it certainly can), nor does it mean that Flask is lacking +in functionality. The "micro" in microframework means Flask aims to keep the +core simple but extensible. Flask won't make many decisions for you, such as +what database to use. Those decisions that it does make, such as what +templating engine to use, are easy to change. Everything else is up to you, so +that Flask can be everything you need and nothing you don't. + +By default, Flask does not include a database abstraction layer, form +validation or anything else where different libraries already exist that can +handle that. Instead, Flask supports extensions to add such functionality to +your application as if it was implemented in Flask itself. Numerous extensions +provide database integration, form validation, upload handling, various open +authentication technologies, and more. Flask may be "micro", but it's ready for +production use on a variety of needs. + +Why does Flask call itself a microframework and yet it depends on two +libraries (namely Werkzeug and Jinja2). Why shouldn't it? If we look +over to the Ruby side of web development there we have a protocol very +similar to WSGI. Just that it's called Rack there, but besides that it +looks very much like a WSGI rendition for Ruby. But nearly all +applications in Ruby land do not work with Rack directly, but on top of a +library with the same name. This Rack library has two equivalents in +Python: WebOb (formerly Paste) and Werkzeug. Paste is still around but +from my understanding it's sort of deprecated in favour of WebOb. The +development of WebOb and Werkzeug started side by side with similar ideas +in mind: be a good implementation of WSGI for other applications to take +advantage. + +Flask is a framework that takes advantage of the work already done by +Werkzeug to properly interface WSGI (which can be a complex task at +times). Thanks to recent developments in the Python package +infrastructure, packages with dependencies are no longer an issue and +there are very few reasons against having libraries that depend on others. + + +Thread Locals +------------- + +Flask uses thread local objects (context local objects in fact, they +support greenlet contexts as well) for request, session and an extra +object you can put your own things on (:data:`~flask.g`). Why is that and +isn't that a bad idea? + +Yes it is usually not such a bright idea to use thread locals. They cause +troubles for servers that are not based on the concept of threads and make +large applications harder to maintain. However Flask is just not designed +for large applications or asynchronous servers. Flask wants to make it +quick and easy to write a traditional web application. + + +Async/await and ASGI support +---------------------------- + +Flask supports ``async`` coroutines for view functions by executing the +coroutine on a separate thread instead of using an event loop on the +main thread as an async-first (ASGI) framework would. This is necessary +for Flask to remain backwards compatible with extensions and code built +before ``async`` was introduced into Python. This compromise introduces +a performance cost compared with the ASGI frameworks, due to the +overhead of the threads. + +Due to how tied to WSGI Flask's code is, it's not clear if it's possible +to make the ``Flask`` class support ASGI and WSGI at the same time. Work +is currently being done in Werkzeug to work with ASGI, which may +eventually enable support in Flask as well. + +See :doc:`/async-await` for more discussion. + + +What Flask is, What Flask is Not +-------------------------------- + +Flask will never have a database layer. It will not have a form library +or anything else in that direction. Flask itself just bridges to Werkzeug +to implement a proper WSGI application and to Jinja2 to handle templating. +It also binds to a few common standard library packages such as logging. +Everything else is up for extensions. + +Why is this the case? Because people have different preferences and +requirements and Flask could not meet those if it would force any of this +into the core. The majority of web applications will need a template +engine in some sort. However not every application needs a SQL database. + +As your codebase grows, you are free to make the design decisions appropriate +for your project. Flask will continue to provide a very simple glue layer to +the best that Python has to offer. You can implement advanced patterns in +SQLAlchemy or another database tool, introduce non-relational data persistence +as appropriate, and take advantage of framework-agnostic tools built for WSGI, +the Python web interface. + +The idea of Flask is to build a good foundation for all applications. +Everything else is up to you or extensions. diff --git a/_build/_sources/errorhandling.rst.txt b/_build/_sources/errorhandling.rst.txt new file mode 100644 index 00000000..faca58c2 --- /dev/null +++ b/_build/_sources/errorhandling.rst.txt @@ -0,0 +1,523 @@ +Handling Application Errors +=========================== + +Applications fail, servers fail. Sooner or later you will see an exception +in production. Even if your code is 100% correct, you will still see +exceptions from time to time. Why? Because everything else involved will +fail. Here are some situations where perfectly fine code can lead to server +errors: + +- the client terminated the request early and the application was still + reading from the incoming data +- the database server was overloaded and could not handle the query +- a filesystem is full +- a harddrive crashed +- a backend server overloaded +- a programming error in a library you are using +- network connection of the server to another system failed + +And that's just a small sample of issues you could be facing. So how do we +deal with that sort of problem? By default if your application runs in +production mode, and an exception is raised Flask will display a very simple +page for you and log the exception to the :attr:`~flask.Flask.logger`. + +But there is more you can do, and we will cover some better setups to deal +with errors including custom exceptions and 3rd party tools. + + +.. _error-logging-tools: + +Error Logging Tools +------------------- + +Sending error mails, even if just for critical ones, can become +overwhelming if enough users are hitting the error and log files are +typically never looked at. This is why we recommend using `Sentry +`_ for dealing with application errors. It's +available as a source-available project `on GitHub +`_ and is also available as a `hosted version +`_ which you can try for free. Sentry +aggregates duplicate errors, captures the full stack trace and local +variables for debugging, and sends you mails based on new errors or +frequency thresholds. + +To use Sentry you need to install the ``sentry-sdk`` client with extra +``flask`` dependencies. + +.. code-block:: text + + $ pip install sentry-sdk[flask] + +And then add this to your Flask app: + +.. code-block:: python + + import sentry_sdk + from sentry_sdk.integrations.flask import FlaskIntegration + + sentry_sdk.init('YOUR_DSN_HERE', integrations=[FlaskIntegration()]) + +The ``YOUR_DSN_HERE`` value needs to be replaced with the DSN value you +get from your Sentry installation. + +After installation, failures leading to an Internal Server Error +are automatically reported to Sentry and from there you can +receive error notifications. + +See also: + +- Sentry also supports catching errors from a worker queue + (RQ, Celery, etc.) in a similar fashion. See the `Python SDK docs + `__ for more information. +- `Flask-specific documentation `__ + + +Error Handlers +-------------- + +When an error occurs in Flask, an appropriate `HTTP status code +`__ will be +returned. 400-499 indicate errors with the client's request data, or +about the data requested. 500-599 indicate errors with the server or +application itself. + +You might want to show custom error pages to the user when an error occurs. +This can be done by registering error handlers. + +An error handler is a function that returns a response when a type of error is +raised, similar to how a view is a function that returns a response when a +request URL is matched. It is passed the instance of the error being handled, +which is most likely a :exc:`~werkzeug.exceptions.HTTPException`. + +The status code of the response will not be set to the handler's code. Make +sure to provide the appropriate HTTP status code when returning a response from +a handler. + + +Registering +``````````` + +Register handlers by decorating a function with +:meth:`~flask.Flask.errorhandler`. Or use +:meth:`~flask.Flask.register_error_handler` to register the function later. +Remember to set the error code when returning the response. + +.. code-block:: python + + @app.errorhandler(werkzeug.exceptions.BadRequest) + def handle_bad_request(e): + return 'bad request!', 400 + + # or, without the decorator + app.register_error_handler(400, handle_bad_request) + +:exc:`werkzeug.exceptions.HTTPException` subclasses like +:exc:`~werkzeug.exceptions.BadRequest` and their HTTP codes are interchangeable +when registering handlers. (``BadRequest.code == 400``) + +Non-standard HTTP codes cannot be registered by code because they are not known +by Werkzeug. Instead, define a subclass of +:class:`~werkzeug.exceptions.HTTPException` with the appropriate code and +register and raise that exception class. + +.. code-block:: python + + class InsufficientStorage(werkzeug.exceptions.HTTPException): + code = 507 + description = 'Not enough storage space.' + + app.register_error_handler(InsufficientStorage, handle_507) + + raise InsufficientStorage() + +Handlers can be registered for any exception class, not just +:exc:`~werkzeug.exceptions.HTTPException` subclasses or HTTP status +codes. Handlers can be registered for a specific class, or for all subclasses +of a parent class. + + +Handling +```````` + +When building a Flask application you *will* run into exceptions. If some part +of your code breaks while handling a request (and you have no error handlers +registered), a "500 Internal Server Error" +(:exc:`~werkzeug.exceptions.InternalServerError`) will be returned by default. +Similarly, "404 Not Found" +(:exc:`~werkzeug.exceptions.NotFound`) error will occur if a request is sent to an unregistered route. +If a route receives an unallowed request method, a "405 Method Not Allowed" +(:exc:`~werkzeug.exceptions.MethodNotAllowed`) will be raised. These are all +subclasses of :class:`~werkzeug.exceptions.HTTPException` and are provided by +default in Flask. + +Flask gives you the ability to raise any HTTP exception registered by +Werkzeug. However, the default HTTP exceptions return simple exception +pages. You might want to show custom error pages to the user when an error occurs. +This can be done by registering error handlers. + +When Flask catches an exception while handling a request, it is first looked up by code. +If no handler is registered for the code, Flask looks up the error by its class hierarchy; the most specific handler is chosen. +If no handler is registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a +generic message about their code, while other exceptions are converted to a +generic "500 Internal Server Error". + +For example, if an instance of :exc:`ConnectionRefusedError` is raised, +and a handler is registered for :exc:`ConnectionError` and +:exc:`ConnectionRefusedError`, the more specific :exc:`ConnectionRefusedError` +handler is called with the exception instance to generate the response. + +Handlers registered on the blueprint take precedence over those registered +globally on the application, assuming a blueprint is handling the request that +raises the exception. However, the blueprint cannot handle 404 routing errors +because the 404 occurs at the routing level before the blueprint can be +determined. + + +Generic Exception Handlers +`````````````````````````` + +It is possible to register error handlers for very generic base classes +such as ``HTTPException`` or even ``Exception``. However, be aware that +these will catch more than you might expect. + +For example, an error handler for ``HTTPException`` might be useful for turning +the default HTML errors pages into JSON. However, this +handler will trigger for things you don't cause directly, such as 404 +and 405 errors during routing. Be sure to craft your handler carefully +so you don't lose information about the HTTP error. + +.. code-block:: python + + from flask import json + from werkzeug.exceptions import HTTPException + + @app.errorhandler(HTTPException) + def handle_exception(e): + """Return JSON instead of HTML for HTTP errors.""" + # start with the correct headers and status code from the error + response = e.get_response() + # replace the body with JSON + response.data = json.dumps({ + "code": e.code, + "name": e.name, + "description": e.description, + }) + response.content_type = "application/json" + return response + +An error handler for ``Exception`` might seem useful for changing how +all errors, even unhandled ones, are presented to the user. However, +this is similar to doing ``except Exception:`` in Python, it will +capture *all* otherwise unhandled errors, including all HTTP status +codes. + +In most cases it will be safer to register handlers for more +specific exceptions. Since ``HTTPException`` instances are valid WSGI +responses, you could also pass them through directly. + +.. code-block:: python + + from werkzeug.exceptions import HTTPException + + @app.errorhandler(Exception) + def handle_exception(e): + # pass through HTTP errors + if isinstance(e, HTTPException): + return e + + # now you're handling non-HTTP exceptions only + return render_template("500_generic.html", e=e), 500 + +Error handlers still respect the exception class hierarchy. If you +register handlers for both ``HTTPException`` and ``Exception``, the +``Exception`` handler will not handle ``HTTPException`` subclasses +because the ``HTTPException`` handler is more specific. + + +Unhandled Exceptions +```````````````````` + +When there is no error handler registered for an exception, a 500 +Internal Server Error will be returned instead. See +:meth:`flask.Flask.handle_exception` for information about this +behavior. + +If there is an error handler registered for ``InternalServerError``, +this will be invoked. As of Flask 1.1.0, this error handler will always +be passed an instance of ``InternalServerError``, not the original +unhandled error. + +The original error is available as ``e.original_exception``. + +An error handler for "500 Internal Server Error" will be passed uncaught +exceptions in addition to explicit 500 errors. In debug mode, a handler +for "500 Internal Server Error" will not be used. Instead, the +interactive debugger will be shown. + + +Custom Error Pages +------------------ + +Sometimes when building a Flask application, you might want to raise a +:exc:`~werkzeug.exceptions.HTTPException` to signal to the user that +something is wrong with the request. Fortunately, Flask comes with a handy +:func:`~flask.abort` function that aborts a request with a HTTP error from +werkzeug as desired. It will also provide a plain black and white error page +for you with a basic description, but nothing fancy. + +Depending on the error code it is less or more likely for the user to +actually see such an error. + +Consider the code below, we might have a user profile route, and if the user +fails to pass a username we can raise a "400 Bad Request". If the user passes a +username and we can't find it, we raise a "404 Not Found". + +.. code-block:: python + + from flask import abort, render_template, request + + # a username needs to be supplied in the query args + # a successful request would be like /profile?username=jack + @app.route("/profile") + def user_profile(): + username = request.arg.get("username") + # if a username isn't supplied in the request, return a 400 bad request + if username is None: + abort(400) + + user = get_user(username=username) + # if a user can't be found by their username, return 404 not found + if user is None: + abort(404) + + return render_template("profile.html", user=user) + +Here is another example implementation for a "404 Page Not Found" exception: + +.. code-block:: python + + from flask import render_template + + @app.errorhandler(404) + def page_not_found(e): + # note that we set the 404 status explicitly + return render_template('404.html'), 404 + +When using :doc:`/patterns/appfactories`: + +.. code-block:: python + + from flask import Flask, render_template + + def page_not_found(e): + return render_template('404.html'), 404 + + def create_app(config_filename): + app = Flask(__name__) + app.register_error_handler(404, page_not_found) + return app + +An example template might be this: + +.. code-block:: html+jinja + + {% extends "layout.html" %} + {% block title %}Page Not Found{% endblock %} + {% block body %} +

Page Not Found

+

What you were looking for is just not there. +

go somewhere nice + {% endblock %} + + +Further Examples +```````````````` + +The above examples wouldn't actually be an improvement on the default +exception pages. We can create a custom 500.html template like this: + +.. code-block:: html+jinja + + {% extends "layout.html" %} + {% block title %}Internal Server Error{% endblock %} + {% block body %} +

Internal Server Error

+

Oops... we seem to have made a mistake, sorry!

+

Go somewhere nice instead + {% endblock %} + +It can be implemented by rendering the template on "500 Internal Server Error": + +.. code-block:: python + + from flask import render_template + + @app.errorhandler(500) + def internal_server_error(e): + # note that we set the 500 status explicitly + return render_template('500.html'), 500 + +When using :doc:`/patterns/appfactories`: + +.. code-block:: python + + from flask import Flask, render_template + + def internal_server_error(e): + return render_template('500.html'), 500 + + def create_app(): + app = Flask(__name__) + app.register_error_handler(500, internal_server_error) + return app + +When using :doc:`/blueprints`: + +.. code-block:: python + + from flask import Blueprint + + blog = Blueprint('blog', __name__) + + # as a decorator + @blog.errorhandler(500) + def internal_server_error(e): + return render_template('500.html'), 500 + + # or with register_error_handler + blog.register_error_handler(500, internal_server_error) + + +Blueprint Error Handlers +------------------------ + +In :doc:`/blueprints`, most error handlers will work as expected. +However, there is a caveat concerning handlers for 404 and 405 +exceptions. These error handlers are only invoked from an appropriate +``raise`` statement or a call to ``abort`` in another of the blueprint's +view functions; they are not invoked by, e.g., an invalid URL access. + +This is because the blueprint does not "own" a certain URL space, so +the application instance has no way of knowing which blueprint error +handler it should run if given an invalid URL. If you would like to +execute different handling strategies for these errors based on URL +prefixes, they may be defined at the application level using the +``request`` proxy object. + +.. code-block:: python + + from flask import jsonify, render_template + + # at the application level + # not the blueprint level + @app.errorhandler(404) + def page_not_found(e): + # if a request is in our blog URL space + if request.path.startswith('/blog/'): + # we return a custom blog 404 page + return render_template("blog/404.html"), 404 + else: + # otherwise we return our generic site-wide 404 page + return render_template("404.html"), 404 + + @app.errorhandler(405) + def method_not_allowed(e): + # if a request has the wrong method to our API + if request.path.startswith('/api/'): + # we return a json saying so + return jsonify(message="Method Not Allowed"), 405 + else: + # otherwise we return a generic site-wide 405 page + return render_template("405.html"), 405 + + +Returning API Errors as JSON +---------------------------- + +When building APIs in Flask, some developers realise that the built-in +exceptions are not expressive enough for APIs and that the content type of +:mimetype:`text/html` they are emitting is not very useful for API consumers. + +Using the same techniques as above and :func:`~flask.json.jsonify` we can return JSON +responses to API errors. :func:`~flask.abort` is called +with a ``description`` parameter. The error handler will +use that as the JSON error message, and set the status code to 404. + +.. code-block:: python + + from flask import abort, jsonify + + @app.errorhandler(404) + def resource_not_found(e): + return jsonify(error=str(e)), 404 + + @app.route("/cheese") + def get_one_cheese(): + resource = get_resource() + + if resource is None: + abort(404, description="Resource not found") + + return jsonify(resource) + +We can also create custom exception classes. For instance, we can +introduce a new custom exception for an API that can take a proper human readable message, +a status code for the error and some optional payload to give more context +for the error. + +This is a simple example: + +.. code-block:: python + + from flask import jsonify, request + + class InvalidAPIUsage(Exception): + status_code = 400 + + def __init__(self, message, status_code=None, payload=None): + super().__init__() + self.message = message + if status_code is not None: + self.status_code = status_code + self.payload = payload + + def to_dict(self): + rv = dict(self.payload or ()) + rv['message'] = self.message + return rv + + @app.errorhandler(InvalidAPIUsage) + def invalid_api_usage(e): + return jsonify(e.to_dict()), e.status_code + + # an API app route for getting user information + # a correct request might be /api/user?user_id=420 + @app.route("/api/user") + def user_api(user_id): + user_id = request.arg.get("user_id") + if not user_id: + raise InvalidAPIUsage("No user id provided!") + + user = get_user(user_id=user_id) + if not user: + raise InvalidAPIUsage("No such user!", status_code=404) + + return jsonify(user.to_dict()) + +A view can now raise that exception with an error message. Additionally +some extra payload can be provided as a dictionary through the `payload` +parameter. + + +Logging +------- + +See :doc:`/logging` for information about how to log exceptions, such as +by emailing them to admins. + + +Debugging +--------- + +See :doc:`/debugging` for information about how to debug errors in +development and production. diff --git a/_build/_sources/extensiondev.rst.txt b/_build/_sources/extensiondev.rst.txt new file mode 100644 index 00000000..0c74ad92 --- /dev/null +++ b/_build/_sources/extensiondev.rst.txt @@ -0,0 +1,304 @@ +Flask Extension Development +=========================== + +.. currentmodule:: flask + +Extensions are extra packages that add functionality to a Flask +application. While `PyPI`_ contains many Flask extensions, you may not +find one that fits your need. If this is the case, you can create your +own, and publish it for others to use as well. + +This guide will show how to create a Flask extension, and some of the +common patterns and requirements involved. Since extensions can do +anything, this guide won't be able to cover every possibility. + +The best ways to learn about extensions are to look at how other +extensions you use are written, and discuss with others. Discuss your +design ideas with others on our `Discord Chat`_ or +`GitHub Discussions`_. + +The best extensions share common patterns, so that anyone familiar with +using one extension won't feel completely lost with another. This can +only work if collaboration happens early. + + +Naming +------ + +A Flask extension typically has ``flask`` in its name as a prefix or +suffix. If it wraps another library, it should include the library name +as well. This makes it easy to search for extensions, and makes their +purpose clearer. + +A general Python packaging recommendation is that the install name from +the package index and the name used in ``import`` statements should be +related. The import name is lowercase, with words separated by +underscores (``_``). The install name is either lower case or title +case, with words separated by dashes (``-``). If it wraps another +library, prefer using the same case as that library's name. + +Here are some example install and import names: + +- ``Flask-Name`` imported as ``flask_name`` +- ``flask-name-lower`` imported as ``flask_name_lower`` +- ``Flask-ComboName`` imported as ``flask_comboname`` +- ``Name-Flask`` imported as ``name_flask`` + + +The Extension Class and Initialization +-------------------------------------- + +All extensions will need some entry point that initializes the +extension with the application. The most common pattern is to create a +class that represents the extension's configuration and behavior, with +an ``init_app`` method to apply the extension instance to the given +application instance. + +.. code-block:: python + + class HelloExtension: + def __init__(self, app=None): + if app is not None: + self.init_app(app) + + def init_app(self, app): + app.before_request(...) + +It is important that the app is not stored on the extension, don't do +``self.app = app``. The only time the extension should have direct +access to an app is during ``init_app``, otherwise it should use +:data:`current_app`. + +This allows the extension to support the application factory pattern, +avoids circular import issues when importing the extension instance +elsewhere in a user's code, and makes testing with different +configurations easier. + +.. code-block:: python + + hello = HelloExtension() + + def create_app(): + app = Flask(__name__) + hello.init_app(app) + return app + +Above, the ``hello`` extension instance exists independently of the +application. This means that other modules in a user's project can do +``from project import hello`` and use the extension in blueprints before +the app exists. + +The :attr:`Flask.extensions` dict can be used to store a reference to +the extension on the application, or some other state specific to the +application. Be aware that this is a single namespace, so use a name +unique to your extension, such as the extension's name without the +"flask" prefix. + + +Adding Behavior +--------------- + +There are many ways that an extension can add behavior. Any setup +methods that are available on the :class:`Flask` object can be used +during an extension's ``init_app`` method. + +A common pattern is to use :meth:`~Flask.before_request` to initialize +some data or a connection at the beginning of each request, then +:meth:`~Flask.teardown_request` to clean it up at the end. This can be +stored on :data:`g`, discussed more below. + +A more lazy approach is to provide a method that initializes and caches +the data or connection. For example, a ``ext.get_db`` method could +create a database connection the first time it's called, so that a view +that doesn't use the database doesn't create a connection. + +Besides doing something before and after every view, your extension +might want to add some specific views as well. In this case, you could +define a :class:`Blueprint`, then call :meth:`~Flask.register_blueprint` +during ``init_app`` to add the blueprint to the app. + + +Configuration Techniques +------------------------ + +There can be multiple levels and sources of configuration for an +extension. You should consider what parts of your extension fall into +each one. + +- Configuration per application instance, through ``app.config`` + values. This is configuration that could reasonably change for each + deployment of an application. A common example is a URL to an + external resource, such as a database. Configuration keys should + start with the extension's name so that they don't interfere with + other extensions. +- Configuration per extension instance, through ``__init__`` + arguments. This configuration usually affects how the extension + is used, such that it wouldn't make sense to change it per + deployment. +- Configuration per extension instance, through instance attributes + and decorator methods. It might be more ergonomic to assign to + ``ext.value``, or use a ``@ext.register`` decorator to register a + function, after the extension instance has been created. +- Global configuration through class attributes. Changing a class + attribute like ``Ext.connection_class`` can customize default + behavior without making a subclass. This could be combined + per-extension configuration to override defaults. +- Subclassing and overriding methods and attributes. Making the API of + the extension itself something that can be overridden provides a + very powerful tool for advanced customization. + +The :class:`~flask.Flask` object itself uses all of these techniques. + +It's up to you to decide what configuration is appropriate for your +extension, based on what you need and what you want to support. + +Configuration should not be changed after the application setup phase is +complete and the server begins handling requests. Configuration is +global, any changes to it are not guaranteed to be visible to other +workers. + + +Data During a Request +--------------------- + +When writing a Flask application, the :data:`~flask.g` object is used to +store information during a request. For example the +:doc:`tutorial ` stores a connection to a SQLite +database as ``g.db``. Extensions can also use this, with some care. +Since ``g`` is a single global namespace, extensions must use unique +names that won't collide with user data. For example, use the extension +name as a prefix, or as a namespace. + +.. code-block:: python + + # an internal prefix with the extension name + g._hello_user_id = 2 + + # or an internal prefix as a namespace + from types import SimpleNamespace + g._hello = SimpleNamespace() + g._hello.user_id = 2 + +The data in ``g`` lasts for an application context. An application +context is active when a request context is, or when a CLI command is +run. If you're storing something that should be closed, use +:meth:`~flask.Flask.teardown_appcontext` to ensure that it gets closed +when the application context ends. If it should only be valid during a +request, or would not be used in the CLI outside a request, use +:meth:`~flask.Flask.teardown_request`. + + +Views and Models +---------------- + +Your extension views might want to interact with specific models in your +database, or some other extension or data connected to your application. +For example, let's consider a ``Flask-SimpleBlog`` extension that works +with Flask-SQLAlchemy to provide a ``Post`` model and views to write +and read posts. + +The ``Post`` model needs to subclass the Flask-SQLAlchemy ``db.Model`` +object, but that's only available once you've created an instance of +that extension, not when your extension is defining its views. So how +can the view code, defined before the model exists, access the model? + +One method could be to use :doc:`views`. During ``__init__``, create +the model, then create the views by passing the model to the view +class's :meth:`~views.View.as_view` method. + +.. code-block:: python + + class PostAPI(MethodView): + def __init__(self, model): + self.model = model + + def get(self, id): + post = self.model.query.get(id) + return jsonify(post.to_json()) + + class BlogExtension: + def __init__(self, db): + class Post(db.Model): + id = db.Column(primary_key=True) + title = db.Column(db.String, nullable=False) + + self.post_model = Post + + def init_app(self, app): + api_view = PostAPI.as_view(model=self.post_model) + + db = SQLAlchemy() + blog = BlogExtension(db) + db.init_app(app) + blog.init_app(app) + +Another technique could be to use an attribute on the extension, such as +``self.post_model`` from above. Add the extension to ``app.extensions`` +in ``init_app``, then access +``current_app.extensions["simple_blog"].post_model`` from views. + +You may also want to provide base classes so that users can provide +their own ``Post`` model that conforms to the API your extension +expects. So they could implement ``class Post(blog.BasePost)``, then +set it as ``blog.post_model``. + +As you can see, this can get a bit complex. Unfortunately, there's no +perfect solution here, only different strategies and tradeoffs depending +on your needs and how much customization you want to offer. Luckily, +this sort of resource dependency is not a common need for most +extensions. Remember, if you need help with design, ask on our +`Discord Chat`_ or `GitHub Discussions`_. + + +Recommended Extension Guidelines +-------------------------------- + +Flask previously had the concept of "approved extensions", where the +Flask maintainers evaluated the quality, support, and compatibility of +the extensions before listing them. While the list became too difficult +to maintain over time, the guidelines are still relevant to all +extensions maintained and developed today, as they help the Flask +ecosystem remain consistent and compatible. + +1. An extension requires a maintainer. In the event an extension author + would like to move beyond the project, the project should find a new + maintainer and transfer access to the repository, documentation, + PyPI, and any other services. The `Pallets-Eco`_ organization on + GitHub allows for community maintenance with oversight from the + Pallets maintainers. +2. The naming scheme is *Flask-ExtensionName* or *ExtensionName-Flask*. + It must provide exactly one package or module named + ``flask_extension_name``. +3. The extension must use an open source license. The Python web + ecosystem tends to prefer BSD or MIT. It must be open source and + publicly available. +4. The extension's API must have the following characteristics: + + - It must support multiple applications running in the same Python + process. Use ``current_app`` instead of ``self.app``, store + configuration and state per application instance. + - It must be possible to use the factory pattern for creating + applications. Use the ``ext.init_app()`` pattern. + +5. From a clone of the repository, an extension with its dependencies + must be installable in editable mode with ``pip install -e .``. +6. It must ship tests that can be invoked with a common tool like + ``tox -e py``, ``nox -s test`` or ``pytest``. If not using ``tox``, + the test dependencies should be specified in a requirements file. + The tests must be part of the sdist distribution. +7. A link to the documentation or project website must be in the PyPI + metadata or the readme. The documentation should use the Flask theme + from the `Official Pallets Themes`_. +8. The extension's dependencies should not use upper bounds or assume + any particular version scheme, but should use lower bounds to + indicate minimum compatibility support. For example, + ``sqlalchemy>=1.4``. +9. Indicate the versions of Python supported using ``python_requires=">=version"``. + Flask itself supports Python >=3.9 as of October 2024, and this will update + over time. + +.. _PyPI: https://pypi.org/search/?c=Framework+%3A%3A+Flask +.. _Discord Chat: https://discord.gg/pallets +.. _GitHub Discussions: https://github.com/pallets/flask/discussions +.. _Official Pallets Themes: https://pypi.org/project/Pallets-Sphinx-Themes/ +.. _Pallets-Eco: https://github.com/pallets-eco diff --git a/_build/_sources/extensions.rst.txt b/_build/_sources/extensions.rst.txt new file mode 100644 index 00000000..4713ec8e --- /dev/null +++ b/_build/_sources/extensions.rst.txt @@ -0,0 +1,48 @@ +Extensions +========== + +Extensions are extra packages that add functionality to a Flask +application. For example, an extension might add support for sending +email or connecting to a database. Some extensions add entire new +frameworks to help build certain types of applications, like a REST API. + + +Finding Extensions +------------------ + +Flask extensions are usually named "Flask-Foo" or "Foo-Flask". You can +search PyPI for packages tagged with `Framework :: Flask `_. + + +Using Extensions +---------------- + +Consult each extension's documentation for installation, configuration, +and usage instructions. Generally, extensions pull their own +configuration from :attr:`app.config ` and are +passed an application instance during initialization. For example, +an extension called "Flask-Foo" might be used like this:: + + from flask_foo import Foo + + foo = Foo() + + app = Flask(__name__) + app.config.update( + FOO_BAR='baz', + FOO_SPAM='eggs', + ) + + foo.init_app(app) + + +Building Extensions +------------------- + +While `PyPI `_ contains many Flask extensions, you may not find +an extension that fits your need. If this is the case, you can create +your own, and publish it for others to use as well. Read +:doc:`extensiondev` to develop your own Flask extension. + + +.. _pypi: https://pypi.org/search/?c=Framework+%3A%3A+Flask diff --git a/_build/_sources/index.rst.txt b/_build/_sources/index.rst.txt new file mode 100644 index 00000000..f9ab9bd9 --- /dev/null +++ b/_build/_sources/index.rst.txt @@ -0,0 +1,88 @@ +.. rst-class:: hide-header + +Welcome to Flask +================ + +.. image:: _static/flask-horizontal.png + :align: center + +Welcome to Flask's documentation. Flask is a lightweight WSGI web application framework. +It is designed to make getting started quick and easy, with the ability to scale up to +complex applications. + +Get started with :doc:`installation` +and then get an overview with the :doc:`quickstart`. There is also a +more detailed :doc:`tutorial/index` that shows how to create a small but +complete application with Flask. Common patterns are described in the +:doc:`patterns/index` section. The rest of the docs describe each +component of Flask in detail, with a full reference in the :doc:`api` +section. + +Flask depends on the `Werkzeug`_ WSGI toolkit, the `Jinja`_ template engine, and the +`Click`_ CLI toolkit. Be sure to check their documentation as well as Flask's when +looking for information. + +.. _Werkzeug: https://werkzeug.palletsprojects.com +.. _Jinja: https://jinja.palletsprojects.com +.. _Click: https://click.palletsprojects.com + + +User's Guide +------------ + +Flask provides configuration and conventions, with sensible defaults, to get started. +This section of the documentation explains the different parts of the Flask framework +and how they can be used, customized, and extended. Beyond Flask itself, look for +community-maintained extensions to add even more functionality. + +.. toctree:: + :maxdepth: 2 + + installation + quickstart + tutorial/index + templating + testing + errorhandling + debugging + logging + config + signals + views + lifecycle + appcontext + reqcontext + blueprints + extensions + cli + server + shell + patterns/index + web-security + deploying/index + async-await + + +API Reference +------------- + +If you are looking for information on a specific function, class or +method, this part of the documentation is for you. + +.. toctree:: + :maxdepth: 2 + + api + + +Additional Notes +---------------- + +.. toctree:: + :maxdepth: 2 + + design + extensiondev + contributing + license + changes diff --git a/_build/_sources/installation.rst.txt b/_build/_sources/installation.rst.txt new file mode 100644 index 00000000..90a314bf --- /dev/null +++ b/_build/_sources/installation.rst.txt @@ -0,0 +1,144 @@ +Installation +============ + + +Python Version +-------------- + +We recommend using the latest version of Python. Flask supports Python 3.9 and newer. + + +Dependencies +------------ + +These distributions will be installed automatically when installing Flask. + +* `Werkzeug`_ implements WSGI, the standard Python interface between + applications and servers. +* `Jinja`_ is a template language that renders the pages your application + serves. +* `MarkupSafe`_ comes with Jinja. It escapes untrusted input when rendering + templates to avoid injection attacks. +* `ItsDangerous`_ securely signs data to ensure its integrity. This is used + to protect Flask's session cookie. +* `Click`_ is a framework for writing command line applications. It provides + the ``flask`` command and allows adding custom management commands. +* `Blinker`_ provides support for :doc:`signals`. + +.. _Werkzeug: https://palletsprojects.com/p/werkzeug/ +.. _Jinja: https://palletsprojects.com/p/jinja/ +.. _MarkupSafe: https://palletsprojects.com/p/markupsafe/ +.. _ItsDangerous: https://palletsprojects.com/p/itsdangerous/ +.. _Click: https://palletsprojects.com/p/click/ +.. _Blinker: https://blinker.readthedocs.io/ + + +Optional dependencies +~~~~~~~~~~~~~~~~~~~~~ + +These distributions will not be installed automatically. Flask will detect and +use them if you install them. + +* `python-dotenv`_ enables support for :ref:`dotenv` when running ``flask`` + commands. +* `Watchdog`_ provides a faster, more efficient reloader for the development + server. + +.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme +.. _watchdog: https://pythonhosted.org/watchdog/ + + +greenlet +~~~~~~~~ + +You may choose to use gevent or eventlet with your application. In this +case, greenlet>=1.0 is required. When using PyPy, PyPy>=7.3.7 is +required. + +These are not minimum supported versions, they only indicate the first +versions that added necessary features. You should use the latest +versions of each. + + +Virtual environments +-------------------- + +Use a virtual environment to manage the dependencies for your project, both in +development and in production. + +What problem does a virtual environment solve? The more Python projects you +have, the more likely it is that you need to work with different versions of +Python libraries, or even Python itself. Newer versions of libraries for one +project can break compatibility in another project. + +Virtual environments are independent groups of Python libraries, one for each +project. Packages installed for one project will not affect other projects or +the operating system's packages. + +Python comes bundled with the :mod:`venv` module to create virtual +environments. + + +.. _install-create-env: + +Create an environment +~~~~~~~~~~~~~~~~~~~~~ + +Create a project folder and a :file:`.venv` folder within: + +.. tabs:: + + .. group-tab:: macOS/Linux + + .. code-block:: text + + $ mkdir myproject + $ cd myproject + $ python3 -m venv .venv + + .. group-tab:: Windows + + .. code-block:: text + + > mkdir myproject + > cd myproject + > py -3 -m venv .venv + + +.. _install-activate-env: + +Activate the environment +~~~~~~~~~~~~~~~~~~~~~~~~ + +Before you work on your project, activate the corresponding environment: + +.. tabs:: + + .. group-tab:: macOS/Linux + + .. code-block:: text + + $ . .venv/bin/activate + + .. group-tab:: Windows + + .. code-block:: text + + > .venv\Scripts\activate + +Your shell prompt will change to show the name of the activated +environment. + + +Install Flask +------------- + +Within the activated environment, use the following command to install +Flask: + +.. code-block:: sh + + $ pip install Flask + +Flask is now installed. Check out the :doc:`/quickstart` or go to the +:doc:`Documentation Overview `. diff --git a/_build/_sources/license.rst.txt b/_build/_sources/license.rst.txt new file mode 100644 index 00000000..2a445f9c --- /dev/null +++ b/_build/_sources/license.rst.txt @@ -0,0 +1,5 @@ +BSD-3-Clause License +==================== + +.. literalinclude:: ../LICENSE.txt + :language: text diff --git a/_build/_sources/lifecycle.rst.txt b/_build/_sources/lifecycle.rst.txt new file mode 100644 index 00000000..2344d98a --- /dev/null +++ b/_build/_sources/lifecycle.rst.txt @@ -0,0 +1,168 @@ +Application Structure and Lifecycle +=================================== + +Flask makes it pretty easy to write a web application. But there are quite a few +different parts to an application and to each request it handles. Knowing what happens +during application setup, serving, and handling requests will help you know what's +possible in Flask and how to structure your application. + + +Application Setup +----------------- + +The first step in creating a Flask application is creating the application object. Each +Flask application is an instance of the :class:`.Flask` class, which collects all +configuration, extensions, and views. + +.. code-block:: python + + from flask import Flask + + app = Flask(__name__) + app.config.from_mapping( + SECRET_KEY="dev", + ) + app.config.from_prefixed_env() + + @app.route("/") + def index(): + return "Hello, World!" + +This is known as the "application setup phase", it's the code you write that's outside +any view functions or other handlers. It can be split up between different modules and +sub-packages, but all code that you want to be part of your application must be imported +in order for it to be registered. + +All application setup must be completed before you start serving your application and +handling requests. This is because WSGI servers divide work between multiple workers, or +can be distributed across multiple machines. If the configuration changed in one worker, +there's no way for Flask to ensure consistency between other workers. + +Flask tries to help developers catch some of these setup ordering issues by showing an +error if setup-related methods are called after requests are handled. In that case +you'll see this error: + + The setup method 'route' can no longer be called on the application. It has already + handled its first request, any changes will not be applied consistently. + Make sure all imports, decorators, functions, etc. needed to set up the application + are done before running it. + +However, it is not possible for Flask to detect all cases of out-of-order setup. In +general, don't do anything to modify the ``Flask`` app object and ``Blueprint`` objects +from within view functions that run during requests. This includes: + +- Adding routes, view functions, and other request handlers with ``@app.route``, + ``@app.errorhandler``, ``@app.before_request``, etc. +- Registering blueprints. +- Loading configuration with ``app.config``. +- Setting up the Jinja template environment with ``app.jinja_env``. +- Setting a session interface, instead of the default itsdangerous cookie. +- Setting a JSON provider with ``app.json``, instead of the default provider. +- Creating and initializing Flask extensions. + + +Serving the Application +----------------------- + +Flask is a WSGI application framework. The other half of WSGI is the WSGI server. During +development, Flask, through Werkzeug, provides a development WSGI server with the +``flask run`` CLI command. When you are done with development, use a production server +to serve your application, see :doc:`deploying/index`. + +Regardless of what server you're using, it will follow the :pep:`3333` WSGI spec. The +WSGI server will be told how to access your Flask application object, which is the WSGI +application. Then it will start listening for HTTP requests, translate the request data +into a WSGI environ, and call the WSGI application with that data. The WSGI application +will return data that is translated into an HTTP response. + +#. Browser or other client makes HTTP request. +#. WSGI server receives request. +#. WSGI server converts HTTP data to WSGI ``environ`` dict. +#. WSGI server calls WSGI application with the ``environ``. +#. Flask, the WSGI application, does all its internal processing to route the request + to a view function, handle errors, etc. +#. Flask translates View function return into WSGI response data, passes it to WSGI + server. +#. WSGI server creates and send an HTTP response. +#. Client receives the HTTP response. + + +Middleware +~~~~~~~~~~ + +The WSGI application above is a callable that behaves in a certain way. Middleware +is a WSGI application that wraps another WSGI application. It's a similar concept to +Python decorators. The outermost middleware will be called by the server. It can modify +the data passed to it, then call the WSGI application (or further middleware) that it +wraps, and so on. And it can take the return value of that call and modify it further. + +From the WSGI server's perspective, there is one WSGI application, the one it calls +directly. Typically, Flask is the "real" application at the end of the chain of +middleware. But even Flask can call further WSGI applications, although that's an +advanced, uncommon use case. + +A common middleware you'll see used with Flask is Werkzeug's +:class:`~werkzeug.middleware.proxy_fix.ProxyFix`, which modifies the request to look +like it came directly from a client even if it passed through HTTP proxies on the way. +There are other middleware that can handle serving static files, authentication, etc. + + +How a Request is Handled +------------------------ + +For us, the interesting part of the steps above is when Flask gets called by the WSGI +server (or middleware). At that point, it will do quite a lot to handle the request and +generate the response. At the most basic, it will match the URL to a view function, call +the view function, and pass the return value back to the server. But there are many more +parts that you can use to customize its behavior. + +#. WSGI server calls the Flask object, which calls :meth:`.Flask.wsgi_app`. +#. A :class:`.RequestContext` object is created. This converts the WSGI ``environ`` + dict into a :class:`.Request` object. It also creates an :class:`AppContext` object. +#. The :doc:`app context ` is pushed, which makes :data:`.current_app` and + :data:`.g` available. +#. The :data:`.appcontext_pushed` signal is sent. +#. The :doc:`request context ` is pushed, which makes :attr:`.request` and + :class:`.session` available. +#. The session is opened, loading any existing session data using the app's + :attr:`~.Flask.session_interface`, an instance of :class:`.SessionInterface`. +#. The URL is matched against the URL rules registered with the :meth:`~.Flask.route` + decorator during application setup. If there is no match, the error - usually a 404, + 405, or redirect - is stored to be handled later. +#. The :data:`.request_started` signal is sent. +#. Any :meth:`~.Flask.url_value_preprocessor` decorated functions are called. +#. Any :meth:`~.Flask.before_request` decorated functions are called. If any of + these function returns a value it is treated as the response immediately. +#. If the URL didn't match a route a few steps ago, that error is raised now. +#. The :meth:`~.Flask.route` decorated view function associated with the matched URL + is called and returns a value to be used as the response. +#. If any step so far raised an exception, and there is an :meth:`~.Flask.errorhandler` + decorated function that matches the exception class or HTTP error code, it is + called to handle the error and return a response. +#. Whatever returned a response value - a before request function, the view, or an + error handler, that value is converted to a :class:`.Response` object. +#. Any :func:`~.after_this_request` decorated functions are called, then cleared. +#. Any :meth:`~.Flask.after_request` decorated functions are called, which can modify + the response object. +#. The session is saved, persisting any modified session data using the app's + :attr:`~.Flask.session_interface`. +#. The :data:`.request_finished` signal is sent. +#. If any step so far raised an exception, and it was not handled by an error handler + function, it is handled now. HTTP exceptions are treated as responses with their + corresponding status code, other exceptions are converted to a generic 500 response. + The :data:`.got_request_exception` signal is sent. +#. The response object's status, headers, and body are returned to the WSGI server. +#. Any :meth:`~.Flask.teardown_request` decorated functions are called. +#. The :data:`.request_tearing_down` signal is sent. +#. The request context is popped, :attr:`.request` and :class:`.session` are no longer + available. +#. Any :meth:`~.Flask.teardown_appcontext` decorated functions are called. +#. The :data:`.appcontext_tearing_down` signal is sent. +#. The app context is popped, :data:`.current_app` and :data:`.g` are no longer + available. +#. The :data:`.appcontext_popped` signal is sent. + +There are even more decorators and customization points than this, but that aren't part +of every request lifecycle. They're more specific to certain things you might use during +a request, such as templates, building URLs, or handling JSON data. See the rest of this +documentation, as well as the :doc:`api` to explore further. diff --git a/_build/_sources/logging.rst.txt b/_build/_sources/logging.rst.txt new file mode 100644 index 00000000..39588242 --- /dev/null +++ b/_build/_sources/logging.rst.txt @@ -0,0 +1,183 @@ +Logging +======= + +Flask uses standard Python :mod:`logging`. Messages about your Flask +application are logged with :meth:`app.logger `, +which takes the same name as :attr:`app.name `. This +logger can also be used to log your own messages. + +.. code-block:: python + + @app.route('/login', methods=['POST']) + def login(): + user = get_user(request.form['username']) + + if user.check_password(request.form['password']): + login_user(user) + app.logger.info('%s logged in successfully', user.username) + return redirect(url_for('index')) + else: + app.logger.info('%s failed to log in', user.username) + abort(401) + +If you don't configure logging, Python's default log level is usually +'warning'. Nothing below the configured level will be visible. + + +Basic Configuration +------------------- + +When you want to configure logging for your project, you should do it as soon +as possible when the program starts. If :meth:`app.logger ` +is accessed before logging is configured, it will add a default handler. If +possible, configure logging before creating the application object. + +This example uses :func:`~logging.config.dictConfig` to create a logging +configuration similar to Flask's default, except for all logs:: + + from logging.config import dictConfig + + dictConfig({ + 'version': 1, + 'formatters': {'default': { + 'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s', + }}, + 'handlers': {'wsgi': { + 'class': 'logging.StreamHandler', + 'stream': 'ext://flask.logging.wsgi_errors_stream', + 'formatter': 'default' + }}, + 'root': { + 'level': 'INFO', + 'handlers': ['wsgi'] + } + }) + + app = Flask(__name__) + + +Default Configuration +````````````````````` + +If you do not configure logging yourself, Flask will add a +:class:`~logging.StreamHandler` to :meth:`app.logger ` +automatically. During requests, it will write to the stream specified by the +WSGI server in ``environ['wsgi.errors']`` (which is usually +:data:`sys.stderr`). Outside a request, it will log to :data:`sys.stderr`. + + +Removing the Default Handler +```````````````````````````` + +If you configured logging after accessing +:meth:`app.logger `, and need to remove the default +handler, you can import and remove it:: + + from flask.logging import default_handler + + app.logger.removeHandler(default_handler) + + +Email Errors to Admins +---------------------- + +When running the application on a remote server for production, you probably +won't be looking at the log messages very often. The WSGI server will probably +send log messages to a file, and you'll only check that file if a user tells +you something went wrong. + +To be proactive about discovering and fixing bugs, you can configure a +:class:`logging.handlers.SMTPHandler` to send an email when errors and higher +are logged. :: + + import logging + from logging.handlers import SMTPHandler + + mail_handler = SMTPHandler( + mailhost='127.0.0.1', + fromaddr='server-error@example.com', + toaddrs=['admin@example.com'], + subject='Application Error' + ) + mail_handler.setLevel(logging.ERROR) + mail_handler.setFormatter(logging.Formatter( + '[%(asctime)s] %(levelname)s in %(module)s: %(message)s' + )) + + if not app.debug: + app.logger.addHandler(mail_handler) + +This requires that you have an SMTP server set up on the same server. See the +Python docs for more information about configuring the handler. + + +Injecting Request Information +----------------------------- + +Seeing more information about the request, such as the IP address, may help +debugging some errors. You can subclass :class:`logging.Formatter` to inject +your own fields that can be used in messages. You can change the formatter for +Flask's default handler, the mail handler defined above, or any other +handler. :: + + from flask import has_request_context, request + from flask.logging import default_handler + + class RequestFormatter(logging.Formatter): + def format(self, record): + if has_request_context(): + record.url = request.url + record.remote_addr = request.remote_addr + else: + record.url = None + record.remote_addr = None + + return super().format(record) + + formatter = RequestFormatter( + '[%(asctime)s] %(remote_addr)s requested %(url)s\n' + '%(levelname)s in %(module)s: %(message)s' + ) + default_handler.setFormatter(formatter) + mail_handler.setFormatter(formatter) + + +Other Libraries +--------------- + +Other libraries may use logging extensively, and you want to see relevant +messages from those logs too. The simplest way to do this is to add handlers +to the root logger instead of only the app logger. :: + + from flask.logging import default_handler + + root = logging.getLogger() + root.addHandler(default_handler) + root.addHandler(mail_handler) + +Depending on your project, it may be more useful to configure each logger you +care about separately, instead of configuring only the root logger. :: + + for logger in ( + logging.getLogger(app.name), + logging.getLogger('sqlalchemy'), + logging.getLogger('other_package'), + ): + logger.addHandler(default_handler) + logger.addHandler(mail_handler) + + +Werkzeug +```````` + +Werkzeug logs basic request/response information to the ``'werkzeug'`` logger. +If the root logger has no handlers configured, Werkzeug adds a +:class:`~logging.StreamHandler` to its logger. + + +Flask Extensions +```````````````` + +Depending on the situation, an extension may choose to log to +:meth:`app.logger ` or its own named logger. Consult each +extension's documentation for details. diff --git a/_build/_sources/patterns/appdispatch.rst.txt b/_build/_sources/patterns/appdispatch.rst.txt new file mode 100644 index 00000000..f22c8060 --- /dev/null +++ b/_build/_sources/patterns/appdispatch.rst.txt @@ -0,0 +1,189 @@ +Application Dispatching +======================= + +Application dispatching is the process of combining multiple Flask +applications on the WSGI level. You can combine not only Flask +applications but any WSGI application. This would allow you to run a +Django and a Flask application in the same interpreter side by side if +you want. The usefulness of this depends on how the applications work +internally. + +The fundamental difference from :doc:`packages` is that in this case you +are running the same or different Flask applications that are entirely +isolated from each other. They run different configurations and are +dispatched on the WSGI level. + + +Working with this Document +-------------------------- + +Each of the techniques and examples below results in an ``application`` +object that can be run with any WSGI server. For development, use the +``flask run`` command to start a development server. For production, see +:doc:`/deploying/index`. + +.. code-block:: python + + from flask import Flask + + app = Flask(__name__) + + @app.route('/') + def hello_world(): + return 'Hello World!' + + +Combining Applications +---------------------- + +If you have entirely separated applications and you want them to work next +to each other in the same Python interpreter process you can take +advantage of the :class:`werkzeug.wsgi.DispatcherMiddleware`. The idea +here is that each Flask application is a valid WSGI application and they +are combined by the dispatcher middleware into a larger one that is +dispatched based on prefix. + +For example you could have your main application run on ``/`` and your +backend interface on ``/backend``. + +.. code-block:: python + + from werkzeug.middleware.dispatcher import DispatcherMiddleware + from frontend_app import application as frontend + from backend_app import application as backend + + application = DispatcherMiddleware(frontend, { + '/backend': backend + }) + + +Dispatch by Subdomain +--------------------- + +Sometimes you might want to use multiple instances of the same application +with different configurations. Assuming the application is created inside +a function and you can call that function to instantiate it, that is +really easy to implement. In order to develop your application to support +creating new instances in functions have a look at the +:doc:`appfactories` pattern. + +A very common example would be creating applications per subdomain. For +instance you configure your webserver to dispatch all requests for all +subdomains to your application and you then use the subdomain information +to create user-specific instances. Once you have your server set up to +listen on all subdomains you can use a very simple WSGI application to do +the dynamic application creation. + +The perfect level for abstraction in that regard is the WSGI layer. You +write your own WSGI application that looks at the request that comes and +delegates it to your Flask application. If that application does not +exist yet, it is dynamically created and remembered. + +.. code-block:: python + + from threading import Lock + + class SubdomainDispatcher: + + def __init__(self, domain, create_app): + self.domain = domain + self.create_app = create_app + self.lock = Lock() + self.instances = {} + + def get_application(self, host): + host = host.split(':')[0] + assert host.endswith(self.domain), 'Configuration error' + subdomain = host[:-len(self.domain)].rstrip('.') + with self.lock: + app = self.instances.get(subdomain) + if app is None: + app = self.create_app(subdomain) + self.instances[subdomain] = app + return app + + def __call__(self, environ, start_response): + app = self.get_application(environ['HTTP_HOST']) + return app(environ, start_response) + + +This dispatcher can then be used like this: + +.. code-block:: python + + from myapplication import create_app, get_user_for_subdomain + from werkzeug.exceptions import NotFound + + def make_app(subdomain): + user = get_user_for_subdomain(subdomain) + if user is None: + # if there is no user for that subdomain we still have + # to return a WSGI application that handles that request. + # We can then just return the NotFound() exception as + # application which will render a default 404 page. + # You might also redirect the user to the main page then + return NotFound() + + # otherwise create the application for the specific user + return create_app(user) + + application = SubdomainDispatcher('example.com', make_app) + + +Dispatch by Path +---------------- + +Dispatching by a path on the URL is very similar. Instead of looking at +the ``Host`` header to figure out the subdomain one simply looks at the +request path up to the first slash. + +.. code-block:: python + + from threading import Lock + from wsgiref.util import shift_path_info + + class PathDispatcher: + + def __init__(self, default_app, create_app): + self.default_app = default_app + self.create_app = create_app + self.lock = Lock() + self.instances = {} + + def get_application(self, prefix): + with self.lock: + app = self.instances.get(prefix) + if app is None: + app = self.create_app(prefix) + if app is not None: + self.instances[prefix] = app + return app + + def __call__(self, environ, start_response): + app = self.get_application(_peek_path_info(environ)) + if app is not None: + shift_path_info(environ) + else: + app = self.default_app + return app(environ, start_response) + + def _peek_path_info(environ): + segments = environ.get("PATH_INFO", "").lstrip("/").split("/", 1) + if segments: + return segments[0] + + return None + +The big difference between this and the subdomain one is that this one +falls back to another application if the creator function returns ``None``. + +.. code-block:: python + + from myapplication import create_app, default_app, get_user_for_prefix + + def make_app(prefix): + user = get_user_for_prefix(prefix) + if user is not None: + return create_app(user) + + application = PathDispatcher(default_app, make_app) diff --git a/_build/_sources/patterns/appfactories.rst.txt b/_build/_sources/patterns/appfactories.rst.txt new file mode 100644 index 00000000..32fd062b --- /dev/null +++ b/_build/_sources/patterns/appfactories.rst.txt @@ -0,0 +1,118 @@ +Application Factories +===================== + +If you are already using packages and blueprints for your application +(:doc:`/blueprints`) there are a couple of really nice ways to further improve +the experience. A common pattern is creating the application object when +the blueprint is imported. But if you move the creation of this object +into a function, you can then create multiple instances of this app later. + +So why would you want to do this? + +1. Testing. You can have instances of the application with different + settings to test every case. +2. Multiple instances. Imagine you want to run different versions of the + same application. Of course you could have multiple instances with + different configs set up in your webserver, but if you use factories, + you can have multiple instances of the same application running in the + same application process which can be handy. + +So how would you then actually implement that? + +Basic Factories +--------------- + +The idea is to set up the application in a function. Like this:: + + def create_app(config_filename): + app = Flask(__name__) + app.config.from_pyfile(config_filename) + + from yourapplication.model import db + db.init_app(app) + + from yourapplication.views.admin import admin + from yourapplication.views.frontend import frontend + app.register_blueprint(admin) + app.register_blueprint(frontend) + + return app + +The downside is that you cannot use the application object in the blueprints +at import time. You can however use it from within a request. How do you +get access to the application with the config? Use +:data:`~flask.current_app`:: + + from flask import current_app, Blueprint, render_template + admin = Blueprint('admin', __name__, url_prefix='/admin') + + @admin.route('/') + def index(): + return render_template(current_app.config['INDEX_TEMPLATE']) + +Here we look up the name of a template in the config. + +Factories & Extensions +---------------------- + +It's preferable to create your extensions and app factories so that the +extension object does not initially get bound to the application. + +Using `Flask-SQLAlchemy `_, +as an example, you should not do something along those lines:: + + def create_app(config_filename): + app = Flask(__name__) + app.config.from_pyfile(config_filename) + + db = SQLAlchemy(app) + +But, rather, in model.py (or equivalent):: + + db = SQLAlchemy() + +and in your application.py (or equivalent):: + + def create_app(config_filename): + app = Flask(__name__) + app.config.from_pyfile(config_filename) + + from yourapplication.model import db + db.init_app(app) + +Using this design pattern, no application-specific state is stored on the +extension object, so one extension object can be used for multiple apps. +For more information about the design of extensions refer to :doc:`/extensiondev`. + +Using Applications +------------------ + +To run such an application, you can use the :command:`flask` command: + +.. code-block:: text + + $ flask --app hello run + +Flask will automatically detect the factory if it is named +``create_app`` or ``make_app`` in ``hello``. You can also pass arguments +to the factory like this: + +.. code-block:: text + + $ flask --app hello:create_app(local_auth=True) run + +Then the ``create_app`` factory in ``myapp`` is called with the keyword +argument ``local_auth=True``. See :doc:`/cli` for more detail. + +Factory Improvements +-------------------- + +The factory function above is not very clever, but you can improve it. +The following changes are straightforward to implement: + +1. Make it possible to pass in configuration values for unit tests so that + you don't have to create config files on the filesystem. +2. Call a function from a blueprint when the application is setting up so + that you have a place to modify attributes of the application (like + hooking in before/after request handlers etc.) +3. Add in WSGI middlewares when the application is being created if necessary. diff --git a/_build/_sources/patterns/caching.rst.txt b/_build/_sources/patterns/caching.rst.txt new file mode 100644 index 00000000..9bf7b72a --- /dev/null +++ b/_build/_sources/patterns/caching.rst.txt @@ -0,0 +1,16 @@ +Caching +======= + +When your application runs slow, throw some caches in. Well, at least +it's the easiest way to speed up things. What does a cache do? Say you +have a function that takes some time to complete but the results would +still be good enough if they were 5 minutes old. So then the idea is that +you actually put the result of that calculation into a cache for some +time. + +Flask itself does not provide caching for you, but `Flask-Caching`_, an +extension for Flask does. Flask-Caching supports various backends, and it is +even possible to develop your own caching backend. + + +.. _Flask-Caching: https://flask-caching.readthedocs.io/en/latest/ diff --git a/_build/_sources/patterns/celery.rst.txt b/_build/_sources/patterns/celery.rst.txt new file mode 100644 index 00000000..2e9a43a7 --- /dev/null +++ b/_build/_sources/patterns/celery.rst.txt @@ -0,0 +1,242 @@ +Background Tasks with Celery +============================ + +If your application has a long running task, such as processing some uploaded data or +sending email, you don't want to wait for it to finish during a request. Instead, use a +task queue to send the necessary data to another process that will run the task in the +background while the request returns immediately. + +`Celery`_ is a powerful task queue that can be used for simple background tasks as well +as complex multi-stage programs and schedules. This guide will show you how to configure +Celery using Flask. Read Celery's `First Steps with Celery`_ guide to learn how to use +Celery itself. + +.. _Celery: https://celery.readthedocs.io +.. _First Steps with Celery: https://celery.readthedocs.io/en/latest/getting-started/first-steps-with-celery.html + +The Flask repository contains `an example `_ +based on the information on this page, which also shows how to use JavaScript to submit +tasks and poll for progress and results. + + +Install +------- + +Install Celery from PyPI, for example using pip: + +.. code-block:: text + + $ pip install celery + + +Integrate Celery with Flask +--------------------------- + +You can use Celery without any integration with Flask, but it's convenient to configure +it through Flask's config, and to let tasks access the Flask application. + +Celery uses similar ideas to Flask, with a ``Celery`` app object that has configuration +and registers tasks. While creating a Flask app, use the following code to create and +configure a Celery app as well. + +.. code-block:: python + + from celery import Celery, Task + + def celery_init_app(app: Flask) -> Celery: + class FlaskTask(Task): + def __call__(self, *args: object, **kwargs: object) -> object: + with app.app_context(): + return self.run(*args, **kwargs) + + celery_app = Celery(app.name, task_cls=FlaskTask) + celery_app.config_from_object(app.config["CELERY"]) + celery_app.set_default() + app.extensions["celery"] = celery_app + return celery_app + +This creates and returns a ``Celery`` app object. Celery `configuration`_ is taken from +the ``CELERY`` key in the Flask configuration. The Celery app is set as the default, so +that it is seen during each request. The ``Task`` subclass automatically runs task +functions with a Flask app context active, so that services like your database +connections are available. + +.. _configuration: https://celery.readthedocs.io/en/stable/userguide/configuration.html + +Here's a basic ``example.py`` that configures Celery to use Redis for communication. We +enable a result backend, but ignore results by default. This allows us to store results +only for tasks where we care about the result. + +.. code-block:: python + + from flask import Flask + + app = Flask(__name__) + app.config.from_mapping( + CELERY=dict( + broker_url="redis://localhost", + result_backend="redis://localhost", + task_ignore_result=True, + ), + ) + celery_app = celery_init_app(app) + +Point the ``celery worker`` command at this and it will find the ``celery_app`` object. + +.. code-block:: text + + $ celery -A example worker --loglevel INFO + +You can also run the ``celery beat`` command to run tasks on a schedule. See Celery's +docs for more information about defining schedules. + +.. code-block:: text + + $ celery -A example beat --loglevel INFO + + +Application Factory +------------------- + +When using the Flask application factory pattern, call the ``celery_init_app`` function +inside the factory. It sets ``app.extensions["celery"]`` to the Celery app object, which +can be used to get the Celery app from the Flask app returned by the factory. + +.. code-block:: python + + def create_app() -> Flask: + app = Flask(__name__) + app.config.from_mapping( + CELERY=dict( + broker_url="redis://localhost", + result_backend="redis://localhost", + task_ignore_result=True, + ), + ) + app.config.from_prefixed_env() + celery_init_app(app) + return app + +To use ``celery`` commands, Celery needs an app object, but that's no longer directly +available. Create a ``make_celery.py`` file that calls the Flask app factory and gets +the Celery app from the returned Flask app. + +.. code-block:: python + + from example import create_app + + flask_app = create_app() + celery_app = flask_app.extensions["celery"] + +Point the ``celery`` command to this file. + +.. code-block:: text + + $ celery -A make_celery worker --loglevel INFO + $ celery -A make_celery beat --loglevel INFO + + +Defining Tasks +-------------- + +Using ``@celery_app.task`` to decorate task functions requires access to the +``celery_app`` object, which won't be available when using the factory pattern. It also +means that the decorated tasks are tied to the specific Flask and Celery app instances, +which could be an issue during testing if you change configuration for a test. + +Instead, use Celery's ``@shared_task`` decorator. This creates task objects that will +access whatever the "current app" is, which is a similar concept to Flask's blueprints +and app context. This is why we called ``celery_app.set_default()`` above. + +Here's an example task that adds two numbers together and returns the result. + +.. code-block:: python + + from celery import shared_task + + @shared_task(ignore_result=False) + def add_together(a: int, b: int) -> int: + return a + b + +Earlier, we configured Celery to ignore task results by default. Since we want to know +the return value of this task, we set ``ignore_result=False``. On the other hand, a task +that didn't need a result, such as sending an email, wouldn't set this. + + +Calling Tasks +------------- + +The decorated function becomes a task object with methods to call it in the background. +The simplest way is to use the ``delay(*args, **kwargs)`` method. See Celery's docs for +more methods. + +A Celery worker must be running to run the task. Starting a worker is shown in the +previous sections. + +.. code-block:: python + + from flask import request + + @app.post("/add") + def start_add() -> dict[str, object]: + a = request.form.get("a", type=int) + b = request.form.get("b", type=int) + result = add_together.delay(a, b) + return {"result_id": result.id} + +The route doesn't get the task's result immediately. That would defeat the purpose by +blocking the response. Instead, we return the running task's result id, which we can use +later to get the result. + + +Getting Results +--------------- + +To fetch the result of the task we started above, we'll add another route that takes the +result id we returned before. We return whether the task is finished (ready), whether it +finished successfully, and what the return value (or error) was if it is finished. + +.. code-block:: python + + from celery.result import AsyncResult + + @app.get("/result/") + def task_result(id: str) -> dict[str, object]: + result = AsyncResult(id) + return { + "ready": result.ready(), + "successful": result.successful(), + "value": result.result if result.ready() else None, + } + +Now you can start the task using the first route, then poll for the result using the +second route. This keeps the Flask request workers from being blocked waiting for tasks +to finish. + +The Flask repository contains `an example `_ +using JavaScript to submit tasks and poll for progress and results. + + +Passing Data to Tasks +--------------------- + +The "add" task above took two integers as arguments. To pass arguments to tasks, Celery +has to serialize them to a format that it can pass to other processes. Therefore, +passing complex objects is not recommended. For example, it would be impossible to pass +a SQLAlchemy model object, since that object is probably not serializable and is tied to +the session that queried it. + +Pass the minimal amount of data necessary to fetch or recreate any complex data within +the task. Consider a task that will run when the logged in user asks for an archive of +their data. The Flask request knows the logged in user, and has the user object queried +from the database. It got that by querying the database for a given id, so the task can +do the same thing. Pass the user's id rather than the user object. + +.. code-block:: python + + @shared_task + def generate_user_archive(user_id: str) -> None: + user = db.session.get(User, user_id) + ... + + generate_user_archive.delay(current_user.id) diff --git a/_build/_sources/patterns/deferredcallbacks.rst.txt b/_build/_sources/patterns/deferredcallbacks.rst.txt new file mode 100644 index 00000000..4ff8814b --- /dev/null +++ b/_build/_sources/patterns/deferredcallbacks.rst.txt @@ -0,0 +1,44 @@ +Deferred Request Callbacks +========================== + +One of the design principles of Flask is that response objects are created and +passed down a chain of potential callbacks that can modify them or replace +them. When the request handling starts, there is no response object yet. It is +created as necessary either by a view function or by some other component in +the system. + +What happens if you want to modify the response at a point where the response +does not exist yet? A common example for that would be a +:meth:`~flask.Flask.before_request` callback that wants to set a cookie on the +response object. + +One way is to avoid the situation. Very often that is possible. For instance +you can try to move that logic into a :meth:`~flask.Flask.after_request` +callback instead. However, sometimes moving code there makes it +more complicated or awkward to reason about. + +As an alternative, you can use :func:`~flask.after_this_request` to register +callbacks that will execute after only the current request. This way you can +defer code execution from anywhere in the application, based on the current +request. + +At any time during a request, we can register a function to be called at the +end of the request. For example you can remember the current language of the +user in a cookie in a :meth:`~flask.Flask.before_request` callback:: + + from flask import request, after_this_request + + @app.before_request + def detect_user_language(): + language = request.cookies.get('user_lang') + + if language is None: + language = guess_language_from_request() + + # when the response exists, set a cookie with the language + @after_this_request + def remember_language(response): + response.set_cookie('user_lang', language) + return response + + g.language = language diff --git a/_build/_sources/patterns/favicon.rst.txt b/_build/_sources/patterns/favicon.rst.txt new file mode 100644 index 00000000..21ea767f --- /dev/null +++ b/_build/_sources/patterns/favicon.rst.txt @@ -0,0 +1,53 @@ +Adding a favicon +================ + +A "favicon" is an icon used by browsers for tabs and bookmarks. This helps +to distinguish your website and to give it a unique brand. + +A common question is how to add a favicon to a Flask application. First, of +course, you need an icon. It should be 16 × 16 pixels and in the ICO file +format. This is not a requirement but a de-facto standard supported by all +relevant browsers. Put the icon in your static directory as +:file:`favicon.ico`. + +Now, to get browsers to find your icon, the correct way is to add a link +tag in your HTML. So, for example: + +.. sourcecode:: html+jinja + + + +That's all you need for most browsers, however some really old ones do not +support this standard. The old de-facto standard is to serve this file, +with this name, at the website root. If your application is not mounted at +the root path of the domain you either need to configure the web server to +serve the icon at the root or if you can't do that you're out of luck. If +however your application is the root you can simply route a redirect:: + + app.add_url_rule('/favicon.ico', + redirect_to=url_for('static', filename='favicon.ico')) + +If you want to save the extra redirect request you can also write a view +using :func:`~flask.send_from_directory`:: + + import os + from flask import send_from_directory + + @app.route('/favicon.ico') + def favicon(): + return send_from_directory(os.path.join(app.root_path, 'static'), + 'favicon.ico', mimetype='image/vnd.microsoft.icon') + +We can leave out the explicit mimetype and it will be guessed, but we may +as well specify it to avoid the extra guessing, as it will always be the +same. + +The above will serve the icon via your application and if possible it's +better to configure your dedicated web server to serve it; refer to the +web server's documentation. + +See also +-------- + +* The `Favicon `_ article on + Wikipedia diff --git a/_build/_sources/patterns/fileuploads.rst.txt b/_build/_sources/patterns/fileuploads.rst.txt new file mode 100644 index 00000000..304f57dc --- /dev/null +++ b/_build/_sources/patterns/fileuploads.rst.txt @@ -0,0 +1,182 @@ +Uploading Files +=============== + +Ah yes, the good old problem of file uploads. The basic idea of file +uploads is actually quite simple. It basically works like this: + +1. A ``

`` tag is marked with ``enctype=multipart/form-data`` + and an ```` is placed in that form. +2. The application accesses the file from the :attr:`~flask.request.files` + dictionary on the request object. +3. use the :meth:`~werkzeug.datastructures.FileStorage.save` method of the file to save + the file permanently somewhere on the filesystem. + +A Gentle Introduction +--------------------- + +Let's start with a very basic application that uploads a file to a +specific upload folder and displays a file to the user. Let's look at the +bootstrapping code for our application:: + + import os + from flask import Flask, flash, request, redirect, url_for + from werkzeug.utils import secure_filename + + UPLOAD_FOLDER = '/path/to/the/uploads' + ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'} + + app = Flask(__name__) + app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER + +So first we need a couple of imports. Most should be straightforward, the +:func:`werkzeug.secure_filename` is explained a little bit later. The +``UPLOAD_FOLDER`` is where we will store the uploaded files and the +``ALLOWED_EXTENSIONS`` is the set of allowed file extensions. + +Why do we limit the extensions that are allowed? You probably don't want +your users to be able to upload everything there if the server is directly +sending out the data to the client. That way you can make sure that users +are not able to upload HTML files that would cause XSS problems (see +:ref:`security-xss`). Also make sure to disallow ``.php`` files if the server +executes them, but who has PHP installed on their server, right? :) + +Next the functions that check if an extension is valid and that uploads +the file and redirects the user to the URL for the uploaded file:: + + def allowed_file(filename): + return '.' in filename and \ + filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS + + @app.route('/', methods=['GET', 'POST']) + def upload_file(): + if request.method == 'POST': + # check if the post request has the file part + if 'file' not in request.files: + flash('No file part') + return redirect(request.url) + file = request.files['file'] + # If the user does not select a file, the browser submits an + # empty file without a filename. + if file.filename == '': + flash('No selected file') + return redirect(request.url) + if file and allowed_file(file.filename): + filename = secure_filename(file.filename) + file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) + return redirect(url_for('download_file', name=filename)) + return ''' + + Upload new File +

Upload new File

+ + + +
+ ''' + +So what does that :func:`~werkzeug.utils.secure_filename` function actually do? +Now the problem is that there is that principle called "never trust user +input". This is also true for the filename of an uploaded file. All +submitted form data can be forged, and filenames can be dangerous. For +the moment just remember: always use that function to secure a filename +before storing it directly on the filesystem. + +.. admonition:: Information for the Pros + + So you're interested in what that :func:`~werkzeug.utils.secure_filename` + function does and what the problem is if you're not using it? So just + imagine someone would send the following information as `filename` to + your application:: + + filename = "../../../../home/username/.bashrc" + + Assuming the number of ``../`` is correct and you would join this with + the ``UPLOAD_FOLDER`` the user might have the ability to modify a file on + the server's filesystem he or she should not modify. This does require some + knowledge about how the application looks like, but trust me, hackers + are patient :) + + Now let's look how that function works: + + >>> secure_filename('../../../../home/username/.bashrc') + 'home_username_.bashrc' + +We want to be able to serve the uploaded files so they can be downloaded +by users. We'll define a ``download_file`` view to serve files in the +upload folder by name. ``url_for("download_file", name=name)`` generates +download URLs. + +.. code-block:: python + + from flask import send_from_directory + + @app.route('/uploads/') + def download_file(name): + return send_from_directory(app.config["UPLOAD_FOLDER"], name) + +If you're using middleware or the HTTP server to serve files, you can +register the ``download_file`` endpoint as ``build_only`` so ``url_for`` +will work without a view function. + +.. code-block:: python + + app.add_url_rule( + "/uploads/", endpoint="download_file", build_only=True + ) + + +Improving Uploads +----------------- + +.. versionadded:: 0.6 + +So how exactly does Flask handle uploads? Well it will store them in the +webserver's memory if the files are reasonably small, otherwise in a +temporary location (as returned by :func:`tempfile.gettempdir`). But how +do you specify the maximum file size after which an upload is aborted? By +default Flask will happily accept file uploads with an unlimited amount of +memory, but you can limit that by setting the ``MAX_CONTENT_LENGTH`` +config key:: + + from flask import Flask, Request + + app = Flask(__name__) + app.config['MAX_CONTENT_LENGTH'] = 16 * 1000 * 1000 + +The code above will limit the maximum allowed payload to 16 megabytes. +If a larger file is transmitted, Flask will raise a +:exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception. + +.. admonition:: Connection Reset Issue + + When using the local development server, you may get a connection + reset error instead of a 413 response. You will get the correct + status response when running the app with a production WSGI server. + +This feature was added in Flask 0.6 but can be achieved in older versions +as well by subclassing the request object. For more information on that +consult the Werkzeug documentation on file handling. + + +Upload Progress Bars +-------------------- + +A while ago many developers had the idea to read the incoming file in +small chunks and store the upload progress in the database to be able to +poll the progress with JavaScript from the client. The client asks the +server every 5 seconds how much it has transmitted, but this is +something it should already know. + +An Easier Solution +------------------ + +Now there are better solutions that work faster and are more reliable. There +are JavaScript libraries like jQuery_ that have form plugins to ease the +construction of progress bar. + +Because the common pattern for file uploads exists almost unchanged in all +applications dealing with uploads, there are also some Flask extensions that +implement a full fledged upload mechanism that allows controlling which +file extensions are allowed to be uploaded. + +.. _jQuery: https://jquery.com/ diff --git a/_build/_sources/patterns/flashing.rst.txt b/_build/_sources/patterns/flashing.rst.txt new file mode 100644 index 00000000..8eb6b3ac --- /dev/null +++ b/_build/_sources/patterns/flashing.rst.txt @@ -0,0 +1,148 @@ +Message Flashing +================ + +Good applications and user interfaces are all about feedback. If the user +does not get enough feedback they will probably end up hating the +application. Flask provides a really simple way to give feedback to a +user with the flashing system. The flashing system basically makes it +possible to record a message at the end of a request and access it next +request and only next request. This is usually combined with a layout +template that does this. Note that browsers and sometimes web servers enforce +a limit on cookie sizes. This means that flashing messages that are too +large for session cookies causes message flashing to fail silently. + +Simple Flashing +--------------- + +So here is a full example:: + + from flask import Flask, flash, redirect, render_template, \ + request, url_for + + app = Flask(__name__) + app.secret_key = b'_5#y2L"F4Q8z\n\xec]/' + + @app.route('/') + def index(): + return render_template('index.html') + + @app.route('/login', methods=['GET', 'POST']) + def login(): + error = None + if request.method == 'POST': + if request.form['username'] != 'admin' or \ + request.form['password'] != 'secret': + error = 'Invalid credentials' + else: + flash('You were successfully logged in') + return redirect(url_for('index')) + return render_template('login.html', error=error) + +And here is the :file:`layout.html` template which does the magic: + +.. sourcecode:: html+jinja + + + My Application + {% with messages = get_flashed_messages() %} + {% if messages %} +
    + {% for message in messages %} +
  • {{ message }}
  • + {% endfor %} +
+ {% endif %} + {% endwith %} + {% block body %}{% endblock %} + +Here is the :file:`index.html` template which inherits from :file:`layout.html`: + +.. sourcecode:: html+jinja + + {% extends "layout.html" %} + {% block body %} +

Overview

+

Do you want to log in? + {% endblock %} + +And here is the :file:`login.html` template which also inherits from +:file:`layout.html`: + +.. sourcecode:: html+jinja + + {% extends "layout.html" %} + {% block body %} +

Login

+ {% if error %} +

Error: {{ error }} + {% endif %} +

+
+
Username: +
+
Password: +
+
+

+

+ {% endblock %} + +Flashing With Categories +------------------------ + +.. versionadded:: 0.3 + +It is also possible to provide categories when flashing a message. The +default category if nothing is provided is ``'message'``. Alternative +categories can be used to give the user better feedback. For example +error messages could be displayed with a red background. + +To flash a message with a different category, just use the second argument +to the :func:`~flask.flash` function:: + + flash('Invalid password provided', 'error') + +Inside the template you then have to tell the +:func:`~flask.get_flashed_messages` function to also return the +categories. The loop looks slightly different in that situation then: + +.. sourcecode:: html+jinja + + {% with messages = get_flashed_messages(with_categories=true) %} + {% if messages %} +
    + {% for category, message in messages %} +
  • {{ message }}
  • + {% endfor %} +
+ {% endif %} + {% endwith %} + +This is just one example of how to render these flashed messages. One +might also use the category to add a prefix such as +``Error:`` to the message. + +Filtering Flash Messages +------------------------ + +.. versionadded:: 0.9 + +Optionally you can pass a list of categories which filters the results of +:func:`~flask.get_flashed_messages`. This is useful if you wish to +render each category in a separate block. + +.. sourcecode:: html+jinja + + {% with errors = get_flashed_messages(category_filter=["error"]) %} + {% if errors %} +
+ × +
    + {%- for msg in errors %} +
  • {{ msg }}
  • + {% endfor -%} +
+
+ {% endif %} + {% endwith %} diff --git a/_build/_sources/patterns/index.rst.txt b/_build/_sources/patterns/index.rst.txt new file mode 100644 index 00000000..1f2c07dd --- /dev/null +++ b/_build/_sources/patterns/index.rst.txt @@ -0,0 +1,40 @@ +Patterns for Flask +================== + +Certain features and interactions are common enough that you will find +them in most web applications. For example, many applications use a +relational database and user authentication. They will open a database +connection at the beginning of the request and get the information for +the logged in user. At the end of the request, the database connection +is closed. + +These types of patterns may be a bit outside the scope of Flask itself, +but Flask makes it easy to implement them. Some common patterns are +collected in the following pages. + +.. toctree:: + :maxdepth: 2 + + packages + appfactories + appdispatch + urlprocessors + sqlite3 + sqlalchemy + fileuploads + caching + viewdecorators + wtforms + templateinheritance + flashing + javascript + lazyloading + mongoengine + favicon + streaming + deferredcallbacks + methodoverrides + requestchecksum + celery + subclassing + singlepageapplications diff --git a/_build/_sources/patterns/javascript.rst.txt b/_build/_sources/patterns/javascript.rst.txt new file mode 100644 index 00000000..d58a3eb6 --- /dev/null +++ b/_build/_sources/patterns/javascript.rst.txt @@ -0,0 +1,259 @@ +JavaScript, ``fetch``, and JSON +=============================== + +You may want to make your HTML page dynamic, by changing data without +reloading the entire page. Instead of submitting an HTML ``
`` and +performing a redirect to re-render the template, you can add +`JavaScript`_ that calls |fetch|_ and replaces content on the page. + +|fetch|_ is the modern, built-in JavaScript solution to making +requests from a page. You may have heard of other "AJAX" methods and +libraries, such as |XHR|_ or `jQuery`_. These are no longer needed in +modern browsers, although you may choose to use them or another library +depending on your application's requirements. These docs will only focus +on built-in JavaScript features. + +.. _JavaScript: https://developer.mozilla.org/Web/JavaScript +.. |fetch| replace:: ``fetch()`` +.. _fetch: https://developer.mozilla.org/Web/API/Fetch_API +.. |XHR| replace:: ``XMLHttpRequest()`` +.. _XHR: https://developer.mozilla.org/Web/API/XMLHttpRequest +.. _jQuery: https://jquery.com/ + + +Rendering Templates +------------------- + +It is important to understand the difference between templates and +JavaScript. Templates are rendered on the server, before the response is +sent to the user's browser. JavaScript runs in the user's browser, after +the template is rendered and sent. Therefore, it is impossible to use +JavaScript to affect how the Jinja template is rendered, but it is +possible to render data into the JavaScript that will run. + +To provide data to JavaScript when rendering the template, use the +:func:`~jinja-filters.tojson` filter in a `` + +A less common pattern is to add the data to a ``data-`` attribute on an +HTML tag. In this case, you must use single quotes around the value, not +double quotes, otherwise you will produce invalid or unsafe HTML. + +.. code-block:: jinja + +
+ + +Generating URLs +--------------- + +The other way to get data from the server to JavaScript is to make a +request for it. First, you need to know the URL to request. + +The simplest way to generate URLs is to continue to use +:func:`~flask.url_for` when rendering the template. For example: + +.. code-block:: javascript + + const user_url = {{ url_for("user", id=current_user.id)|tojson }} + fetch(user_url).then(...) + +However, you might need to generate a URL based on information you only +know in JavaScript. As discussed above, JavaScript runs in the user's +browser, not as part of the template rendering, so you can't use +``url_for`` at that point. + +In this case, you need to know the "root URL" under which your +application is served. In simple setups, this is ``/``, but it might +also be something else, like ``https://example.com/myapp/``. + +A simple way to tell your JavaScript code about this root is to set it +as a global variable when rendering the template. Then you can use it +when generating URLs from JavaScript. + +.. code-block:: javascript + + const SCRIPT_ROOT = {{ request.script_root|tojson }} + let user_id = ... // do something to get a user id from the page + let user_url = `${SCRIPT_ROOT}/user/${user_id}` + fetch(user_url).then(...) + + +Making a Request with ``fetch`` +------------------------------- + +|fetch|_ takes two arguments, a URL and an object with other options, +and returns a |Promise|_. We won't cover all the available options, and +will only use ``then()`` on the promise, not other callbacks or +``await`` syntax. Read the linked MDN docs for more information about +those features. + +By default, the GET method is used. If the response contains JSON, it +can be used with a ``then()`` callback chain. + +.. code-block:: javascript + + const room_url = {{ url_for("room_detail", id=room.id)|tojson }} + fetch(room_url) + .then(response => response.json()) + .then(data => { + // data is a parsed JSON object + }) + +To send data, use a data method such as POST, and pass the ``body`` +option. The most common types for data are form data or JSON data. + +To send form data, pass a populated |FormData|_ object. This uses the +same format as an HTML form, and would be accessed with ``request.form`` +in a Flask view. + +.. code-block:: javascript + + let data = new FormData() + data.append("name", "Flask Room") + data.append("description", "Talk about Flask here.") + fetch(room_url, { + "method": "POST", + "body": data, + }).then(...) + +In general, prefer sending request data as form data, as would be used +when submitting an HTML form. JSON can represent more complex data, but +unless you need that it's better to stick with the simpler format. When +sending JSON data, the ``Content-Type: application/json`` header must be +sent as well, otherwise Flask will return a 400 error. + +.. code-block:: javascript + + let data = { + "name": "Flask Room", + "description": "Talk about Flask here.", + } + fetch(room_url, { + "method": "POST", + "headers": {"Content-Type": "application/json"}, + "body": JSON.stringify(data), + }).then(...) + +.. |Promise| replace:: ``Promise`` +.. _Promise: https://developer.mozilla.org/Web/JavaScript/Reference/Global_Objects/Promise +.. |FormData| replace:: ``FormData`` +.. _FormData: https://developer.mozilla.org/en-US/docs/Web/API/FormData + + +Following Redirects +------------------- + +A response might be a redirect, for example if you logged in with +JavaScript instead of a traditional HTML form, and your view returned +a redirect instead of JSON. JavaScript requests do follow redirects, but +they don't change the page. If you want to make the page change you can +inspect the response and apply the redirect manually. + +.. code-block:: javascript + + fetch("/login", {"body": ...}).then( + response => { + if (response.redirected) { + window.location = response.url + } else { + showLoginError() + } + } + ) + + +Replacing Content +----------------- + +A response might be new HTML, either a new section of the page to add or +replace, or an entirely new page. In general, if you're returning the +entire page, it would be better to handle that with a redirect as shown +in the previous section. The following example shows how to replace a +``
`` with the HTML returned by a request. + +.. code-block:: html + +
+ {{ include "geology_fact.html" }} +
+ + + +Return JSON from Views +---------------------- + +To return a JSON object from your API view, you can directly return a +dict from the view. It will be serialized to JSON automatically. + +.. code-block:: python + + @app.route("/user/") + def user_detail(id): + user = User.query.get_or_404(id) + return { + "username": User.username, + "email": User.email, + "picture": url_for("static", filename=f"users/{id}/profile.png"), + } + +If you want to return another JSON type, use the +:func:`~flask.json.jsonify` function, which creates a response object +with the given data serialized to JSON. + +.. code-block:: python + + from flask import jsonify + + @app.route("/users") + def user_list(): + users = User.query.order_by(User.name).all() + return jsonify([u.to_json() for u in users]) + +It is usually not a good idea to return file data in a JSON response. +JSON cannot represent binary data directly, so it must be base64 +encoded, which can be slow, takes more bandwidth to send, and is not as +easy to cache. Instead, serve files using one view, and generate a URL +to the desired file to include in the JSON. Then the client can make a +separate request to get the linked resource after getting the JSON. + + +Receiving JSON in Views +----------------------- + +Use the :attr:`~flask.Request.json` property of the +:data:`~flask.request` object to decode the request's body as JSON. If +the body is not valid JSON, or the ``Content-Type`` header is not set to +``application/json``, a 400 Bad Request error will be raised. + +.. code-block:: python + + from flask import request + + @app.post("/user/") + def user_update(id): + user = User.query.get_or_404(id) + user.update_from_json(request.json) + db.session.commit() + return user.to_json() diff --git a/_build/_sources/patterns/jquery.rst.txt b/_build/_sources/patterns/jquery.rst.txt new file mode 100644 index 00000000..7ac6856e --- /dev/null +++ b/_build/_sources/patterns/jquery.rst.txt @@ -0,0 +1,6 @@ +:orphan: + +AJAX with jQuery +================ + +Obsolete, see :doc:`/patterns/javascript` instead. diff --git a/_build/_sources/patterns/lazyloading.rst.txt b/_build/_sources/patterns/lazyloading.rst.txt new file mode 100644 index 00000000..658a1cd4 --- /dev/null +++ b/_build/_sources/patterns/lazyloading.rst.txt @@ -0,0 +1,109 @@ +Lazily Loading Views +==================== + +Flask is usually used with the decorators. Decorators are simple and you +have the URL right next to the function that is called for that specific +URL. However there is a downside to this approach: it means all your code +that uses decorators has to be imported upfront or Flask will never +actually find your function. + +This can be a problem if your application has to import quick. It might +have to do that on systems like Google's App Engine or other systems. So +if you suddenly notice that your application outgrows this approach you +can fall back to a centralized URL mapping. + +The system that enables having a central URL map is the +:meth:`~flask.Flask.add_url_rule` function. Instead of using decorators, +you have a file that sets up the application with all URLs. + +Converting to Centralized URL Map +--------------------------------- + +Imagine the current application looks somewhat like this:: + + from flask import Flask + app = Flask(__name__) + + @app.route('/') + def index(): + pass + + @app.route('/user/') + def user(username): + pass + +Then, with the centralized approach you would have one file with the views +(:file:`views.py`) but without any decorator:: + + def index(): + pass + + def user(username): + pass + +And then a file that sets up an application which maps the functions to +URLs:: + + from flask import Flask + from yourapplication import views + app = Flask(__name__) + app.add_url_rule('/', view_func=views.index) + app.add_url_rule('/user/', view_func=views.user) + +Loading Late +------------ + +So far we only split up the views and the routing, but the module is still +loaded upfront. The trick is to actually load the view function as needed. +This can be accomplished with a helper class that behaves just like a +function but internally imports the real function on first use:: + + from werkzeug.utils import import_string, cached_property + + class LazyView(object): + + def __init__(self, import_name): + self.__module__, self.__name__ = import_name.rsplit('.', 1) + self.import_name = import_name + + @cached_property + def view(self): + return import_string(self.import_name) + + def __call__(self, *args, **kwargs): + return self.view(*args, **kwargs) + +What's important here is is that `__module__` and `__name__` are properly +set. This is used by Flask internally to figure out how to name the +URL rules in case you don't provide a name for the rule yourself. + +Then you can define your central place to combine the views like this:: + + from flask import Flask + from yourapplication.helpers import LazyView + app = Flask(__name__) + app.add_url_rule('/', + view_func=LazyView('yourapplication.views.index')) + app.add_url_rule('/user/', + view_func=LazyView('yourapplication.views.user')) + +You can further optimize this in terms of amount of keystrokes needed to +write this by having a function that calls into +:meth:`~flask.Flask.add_url_rule` by prefixing a string with the project +name and a dot, and by wrapping `view_func` in a `LazyView` as needed. :: + + def url(import_name, url_rules=[], **options): + view = LazyView(f"yourapplication.{import_name}") + for url_rule in url_rules: + app.add_url_rule(url_rule, view_func=view, **options) + + # add a single route to the index view + url('views.index', ['/']) + + # add two routes to a single function endpoint + url_rules = ['/user/','/user/'] + url('views.user', url_rules) + +One thing to keep in mind is that before and after request handlers have +to be in a file that is imported upfront to work properly on the first +request. The same goes for any kind of remaining decorator. diff --git a/_build/_sources/patterns/methodoverrides.rst.txt b/_build/_sources/patterns/methodoverrides.rst.txt new file mode 100644 index 00000000..45dbb87e --- /dev/null +++ b/_build/_sources/patterns/methodoverrides.rst.txt @@ -0,0 +1,42 @@ +Adding HTTP Method Overrides +============================ + +Some HTTP proxies do not support arbitrary HTTP methods or newer HTTP +methods (such as PATCH). In that case it's possible to "proxy" HTTP +methods through another HTTP method in total violation of the protocol. + +The way this works is by letting the client do an HTTP POST request and +set the ``X-HTTP-Method-Override`` header. Then the method is replaced +with the header value before being passed to Flask. + +This can be accomplished with an HTTP middleware:: + + class HTTPMethodOverrideMiddleware(object): + allowed_methods = frozenset([ + 'GET', + 'HEAD', + 'POST', + 'DELETE', + 'PUT', + 'PATCH', + 'OPTIONS' + ]) + bodyless_methods = frozenset(['GET', 'HEAD', 'OPTIONS', 'DELETE']) + + def __init__(self, app): + self.app = app + + def __call__(self, environ, start_response): + method = environ.get('HTTP_X_HTTP_METHOD_OVERRIDE', '').upper() + if method in self.allowed_methods: + environ['REQUEST_METHOD'] = method + if method in self.bodyless_methods: + environ['CONTENT_LENGTH'] = '0' + return self.app(environ, start_response) + +To use this with Flask, wrap the app object with the middleware:: + + from flask import Flask + + app = Flask(__name__) + app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app) diff --git a/_build/_sources/patterns/mongoengine.rst.txt b/_build/_sources/patterns/mongoengine.rst.txt new file mode 100644 index 00000000..015e7b61 --- /dev/null +++ b/_build/_sources/patterns/mongoengine.rst.txt @@ -0,0 +1,103 @@ +MongoDB with MongoEngine +======================== + +Using a document database like MongoDB is a common alternative to +relational SQL databases. This pattern shows how to use +`MongoEngine`_, a document mapper library, to integrate with MongoDB. + +A running MongoDB server and `Flask-MongoEngine`_ are required. :: + + pip install flask-mongoengine + +.. _MongoEngine: http://mongoengine.org +.. _Flask-MongoEngine: https://flask-mongoengine.readthedocs.io + + +Configuration +------------- + +Basic setup can be done by defining ``MONGODB_SETTINGS`` on +``app.config`` and creating a ``MongoEngine`` instance. :: + + from flask import Flask + from flask_mongoengine import MongoEngine + + app = Flask(__name__) + app.config['MONGODB_SETTINGS'] = { + "db": "myapp", + } + db = MongoEngine(app) + + +Mapping Documents +----------------- + +To declare a model that represents a Mongo document, create a class that +inherits from ``Document`` and declare each of the fields. :: + + import mongoengine as me + + class Movie(me.Document): + title = me.StringField(required=True) + year = me.IntField() + rated = me.StringField() + director = me.StringField() + actors = me.ListField() + +If the document has nested fields, use ``EmbeddedDocument`` to +defined the fields of the embedded document and +``EmbeddedDocumentField`` to declare it on the parent document. :: + + class Imdb(me.EmbeddedDocument): + imdb_id = me.StringField() + rating = me.DecimalField() + votes = me.IntField() + + class Movie(me.Document): + ... + imdb = me.EmbeddedDocumentField(Imdb) + + +Creating Data +------------- + +Instantiate your document class with keyword arguments for the fields. +You can also assign values to the field attributes after instantiation. +Then call ``doc.save()``. :: + + bttf = Movie(title="Back To The Future", year=1985) + bttf.actors = [ + "Michael J. Fox", + "Christopher Lloyd" + ] + bttf.imdb = Imdb(imdb_id="tt0088763", rating=8.5) + bttf.save() + + +Queries +------- + +Use the class ``objects`` attribute to make queries. A keyword argument +looks for an equal value on the field. :: + + bttf = Movies.objects(title="Back To The Future").get_or_404() + +Query operators may be used by concatenating them with the field name +using a double-underscore. ``objects``, and queries returned by +calling it, are iterable. :: + + some_theron_movie = Movie.objects(actors__in=["Charlize Theron"]).first() + + for recents in Movie.objects(year__gte=2017): + print(recents.title) + + +Documentation +------------- + +There are many more ways to define and query documents with MongoEngine. +For more information, check out the `official documentation +`_. + +Flask-MongoEngine adds helpful utilities on top of MongoEngine. Check +out their `documentation `_ as well. diff --git a/_build/_sources/patterns/packages.rst.txt b/_build/_sources/patterns/packages.rst.txt new file mode 100644 index 00000000..90fa8a8f --- /dev/null +++ b/_build/_sources/patterns/packages.rst.txt @@ -0,0 +1,133 @@ +Large Applications as Packages +============================== + +Imagine a simple flask application structure that looks like this:: + + /yourapplication + yourapplication.py + /static + style.css + /templates + layout.html + index.html + login.html + ... + +While this is fine for small applications, for larger applications +it's a good idea to use a package instead of a module. +The :doc:`/tutorial/index` is structured to use the package pattern, +see the :gh:`example code `. + +Simple Packages +--------------- + +To convert that into a larger one, just create a new folder +:file:`yourapplication` inside the existing one and move everything below it. +Then rename :file:`yourapplication.py` to :file:`__init__.py`. (Make sure to delete +all ``.pyc`` files first, otherwise things would most likely break) + +You should then end up with something like that:: + + /yourapplication + /yourapplication + __init__.py + /static + style.css + /templates + layout.html + index.html + login.html + ... + +But how do you run your application now? The naive ``python +yourapplication/__init__.py`` will not work. Let's just say that Python +does not want modules in packages to be the startup file. But that is not +a big problem, just add a new file called :file:`pyproject.toml` next to the inner +:file:`yourapplication` folder with the following contents: + +.. code-block:: toml + + [project] + name = "yourapplication" + dependencies = [ + "flask", + ] + + [build-system] + requires = ["flit_core<4"] + build-backend = "flit_core.buildapi" + +Install your application so it is importable: + +.. code-block:: text + + $ pip install -e . + +To use the ``flask`` command and run your application you need to set +the ``--app`` option that tells Flask where to find the application +instance: + +.. code-block:: text + + $ flask --app yourapplication run + +What did we gain from this? Now we can restructure the application a bit +into multiple modules. The only thing you have to remember is the +following quick checklist: + +1. the `Flask` application object creation has to be in the + :file:`__init__.py` file. That way each module can import it safely and the + `__name__` variable will resolve to the correct package. +2. all the view functions (the ones with a :meth:`~flask.Flask.route` + decorator on top) have to be imported in the :file:`__init__.py` file. + Not the object itself, but the module it is in. Import the view module + **after the application object is created**. + +Here's an example :file:`__init__.py`:: + + from flask import Flask + app = Flask(__name__) + + import yourapplication.views + +And this is what :file:`views.py` would look like:: + + from yourapplication import app + + @app.route('/') + def index(): + return 'Hello World!' + +You should then end up with something like that:: + + /yourapplication + pyproject.toml + /yourapplication + __init__.py + views.py + /static + style.css + /templates + layout.html + index.html + login.html + ... + +.. admonition:: Circular Imports + + Every Python programmer hates them, and yet we just added some: + circular imports (That's when two modules depend on each other. In this + case :file:`views.py` depends on :file:`__init__.py`). Be advised that this is a + bad idea in general but here it is actually fine. The reason for this is + that we are not actually using the views in :file:`__init__.py` and just + ensuring the module is imported and we are doing that at the bottom of + the file. + + +Working with Blueprints +----------------------- + +If you have larger applications it's recommended to divide them into +smaller groups where each group is implemented with the help of a +blueprint. For a gentle introduction into this topic refer to the +:doc:`/blueprints` chapter of the documentation. diff --git a/_build/_sources/patterns/requestchecksum.rst.txt b/_build/_sources/patterns/requestchecksum.rst.txt new file mode 100644 index 00000000..25bc38b2 --- /dev/null +++ b/_build/_sources/patterns/requestchecksum.rst.txt @@ -0,0 +1,55 @@ +Request Content Checksums +========================= + +Various pieces of code can consume the request data and preprocess it. +For instance JSON data ends up on the request object already read and +processed, form data ends up there as well but goes through a different +code path. This seems inconvenient when you want to calculate the +checksum of the incoming request data. This is necessary sometimes for +some APIs. + +Fortunately this is however very simple to change by wrapping the input +stream. + +The following example calculates the SHA1 checksum of the incoming data as +it gets read and stores it in the WSGI environment:: + + import hashlib + + class ChecksumCalcStream(object): + + def __init__(self, stream): + self._stream = stream + self._hash = hashlib.sha1() + + def read(self, bytes): + rv = self._stream.read(bytes) + self._hash.update(rv) + return rv + + def readline(self, size_hint): + rv = self._stream.readline(size_hint) + self._hash.update(rv) + return rv + + def generate_checksum(request): + env = request.environ + stream = ChecksumCalcStream(env['wsgi.input']) + env['wsgi.input'] = stream + return stream._hash + +To use this, all you need to do is to hook the calculating stream in +before the request starts consuming data. (Eg: be careful accessing +``request.form`` or anything of that nature. ``before_request_handlers`` +for instance should be careful not to access it). + +Example usage:: + + @app.route('/special-api', methods=['POST']) + def special_api(): + hash = generate_checksum(request) + # Accessing this parses the input stream + files = request.files + # At this point the hash is fully constructed. + checksum = hash.hexdigest() + return f"Hash was: {checksum}" diff --git a/_build/_sources/patterns/singlepageapplications.rst.txt b/_build/_sources/patterns/singlepageapplications.rst.txt new file mode 100644 index 00000000..1cb779b3 --- /dev/null +++ b/_build/_sources/patterns/singlepageapplications.rst.txt @@ -0,0 +1,24 @@ +Single-Page Applications +======================== + +Flask can be used to serve Single-Page Applications (SPA) by placing static +files produced by your frontend framework in a subfolder inside of your +project. You will also need to create a catch-all endpoint that routes all +requests to your SPA. + +The following example demonstrates how to serve an SPA along with an API:: + + from flask import Flask, jsonify + + app = Flask(__name__, static_folder='app', static_url_path="/app") + + + @app.route("/heartbeat") + def heartbeat(): + return jsonify({"status": "healthy"}) + + + @app.route('/', defaults={'path': ''}) + @app.route('/') + def catch_all(path): + return app.send_static_file("index.html") diff --git a/_build/_sources/patterns/sqlalchemy.rst.txt b/_build/_sources/patterns/sqlalchemy.rst.txt new file mode 100644 index 00000000..7e4108d0 --- /dev/null +++ b/_build/_sources/patterns/sqlalchemy.rst.txt @@ -0,0 +1,214 @@ +SQLAlchemy in Flask +=================== + +Many people prefer `SQLAlchemy`_ for database access. In this case it's +encouraged to use a package instead of a module for your flask application +and drop the models into a separate module (:doc:`packages`). While that +is not necessary, it makes a lot of sense. + +There are four very common ways to use SQLAlchemy. I will outline each +of them here: + +Flask-SQLAlchemy Extension +-------------------------- + +Because SQLAlchemy is a common database abstraction layer and object +relational mapper that requires a little bit of configuration effort, +there is a Flask extension that handles that for you. This is recommended +if you want to get started quickly. + +You can download `Flask-SQLAlchemy`_ from `PyPI +`_. + +.. _Flask-SQLAlchemy: https://flask-sqlalchemy.palletsprojects.com/ + + +Declarative +----------- + +The declarative extension in SQLAlchemy is the most recent method of using +SQLAlchemy. It allows you to define tables and models in one go, similar +to how Django works. In addition to the following text I recommend the +official documentation on the `declarative`_ extension. + +Here's the example :file:`database.py` module for your application:: + + from sqlalchemy import create_engine + from sqlalchemy.orm import scoped_session, sessionmaker, declarative_base + + engine = create_engine('sqlite:////tmp/test.db') + db_session = scoped_session(sessionmaker(autocommit=False, + autoflush=False, + bind=engine)) + Base = declarative_base() + Base.query = db_session.query_property() + + def init_db(): + # import all modules here that might define models so that + # they will be registered properly on the metadata. Otherwise + # you will have to import them first before calling init_db() + import yourapplication.models + Base.metadata.create_all(bind=engine) + +To define your models, just subclass the `Base` class that was created by +the code above. If you are wondering why we don't have to care about +threads here (like we did in the SQLite3 example above with the +:data:`~flask.g` object): that's because SQLAlchemy does that for us +already with the :class:`~sqlalchemy.orm.scoped_session`. + +To use SQLAlchemy in a declarative way with your application, you just +have to put the following code into your application module. Flask will +automatically remove database sessions at the end of the request or +when the application shuts down:: + + from yourapplication.database import db_session + + @app.teardown_appcontext + def shutdown_session(exception=None): + db_session.remove() + +Here is an example model (put this into :file:`models.py`, e.g.):: + + from sqlalchemy import Column, Integer, String + from yourapplication.database import Base + + class User(Base): + __tablename__ = 'users' + id = Column(Integer, primary_key=True) + name = Column(String(50), unique=True) + email = Column(String(120), unique=True) + + def __init__(self, name=None, email=None): + self.name = name + self.email = email + + def __repr__(self): + return f'' + +To create the database you can use the `init_db` function: + +>>> from yourapplication.database import init_db +>>> init_db() + +You can insert entries into the database like this: + +>>> from yourapplication.database import db_session +>>> from yourapplication.models import User +>>> u = User('admin', 'admin@localhost') +>>> db_session.add(u) +>>> db_session.commit() + +Querying is simple as well: + +>>> User.query.all() +[] +>>> User.query.filter(User.name == 'admin').first() + + +.. _SQLAlchemy: https://www.sqlalchemy.org/ +.. _declarative: https://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/ + +Manual Object Relational Mapping +-------------------------------- + +Manual object relational mapping has a few upsides and a few downsides +versus the declarative approach from above. The main difference is that +you define tables and classes separately and map them together. It's more +flexible but a little more to type. In general it works like the +declarative approach, so make sure to also split up your application into +multiple modules in a package. + +Here is an example :file:`database.py` module for your application:: + + from sqlalchemy import create_engine, MetaData + from sqlalchemy.orm import scoped_session, sessionmaker + + engine = create_engine('sqlite:////tmp/test.db') + metadata = MetaData() + db_session = scoped_session(sessionmaker(autocommit=False, + autoflush=False, + bind=engine)) + def init_db(): + metadata.create_all(bind=engine) + +As in the declarative approach, you need to close the session after +each request or application context shutdown. Put this into your +application module:: + + from yourapplication.database import db_session + + @app.teardown_appcontext + def shutdown_session(exception=None): + db_session.remove() + +Here is an example table and model (put this into :file:`models.py`):: + + from sqlalchemy import Table, Column, Integer, String + from sqlalchemy.orm import mapper + from yourapplication.database import metadata, db_session + + class User(object): + query = db_session.query_property() + + def __init__(self, name=None, email=None): + self.name = name + self.email = email + + def __repr__(self): + return f'' + + users = Table('users', metadata, + Column('id', Integer, primary_key=True), + Column('name', String(50), unique=True), + Column('email', String(120), unique=True) + ) + mapper(User, users) + +Querying and inserting works exactly the same as in the example above. + + +SQL Abstraction Layer +--------------------- + +If you just want to use the database system (and SQL) abstraction layer +you basically only need the engine:: + + from sqlalchemy import create_engine, MetaData, Table + + engine = create_engine('sqlite:////tmp/test.db') + metadata = MetaData(bind=engine) + +Then you can either declare the tables in your code like in the examples +above, or automatically load them:: + + from sqlalchemy import Table + + users = Table('users', metadata, autoload=True) + +To insert data you can use the `insert` method. We have to get a +connection first so that we can use a transaction: + +>>> con = engine.connect() +>>> con.execute(users.insert(), name='admin', email='admin@localhost') + +SQLAlchemy will automatically commit for us. + +To query your database, you use the engine directly or use a connection: + +>>> users.select(users.c.id == 1).execute().first() +(1, 'admin', 'admin@localhost') + +These results are also dict-like tuples: + +>>> r = users.select(users.c.id == 1).execute().first() +>>> r['name'] +'admin' + +You can also pass strings of SQL statements to the +:meth:`~sqlalchemy.engine.base.Connection.execute` method: + +>>> engine.execute('select * from users where id = :1', [1]).first() +(1, 'admin', 'admin@localhost') + +For more information about SQLAlchemy, head over to the +`website `_. diff --git a/_build/_sources/patterns/sqlite3.rst.txt b/_build/_sources/patterns/sqlite3.rst.txt new file mode 100644 index 00000000..5932589f --- /dev/null +++ b/_build/_sources/patterns/sqlite3.rst.txt @@ -0,0 +1,147 @@ +Using SQLite 3 with Flask +========================= + +In Flask you can easily implement the opening of database connections on +demand and closing them when the context dies (usually at the end of the +request). + +Here is a simple example of how you can use SQLite 3 with Flask:: + + import sqlite3 + from flask import g + + DATABASE = '/path/to/database.db' + + def get_db(): + db = getattr(g, '_database', None) + if db is None: + db = g._database = sqlite3.connect(DATABASE) + return db + + @app.teardown_appcontext + def close_connection(exception): + db = getattr(g, '_database', None) + if db is not None: + db.close() + +Now, to use the database, the application must either have an active +application context (which is always true if there is a request in flight) +or create an application context itself. At that point the ``get_db`` +function can be used to get the current database connection. Whenever the +context is destroyed the database connection will be terminated. + +Example:: + + @app.route('/') + def index(): + cur = get_db().cursor() + ... + + +.. note:: + + Please keep in mind that the teardown request and appcontext functions + are always executed, even if a before-request handler failed or was + never executed. Because of this we have to make sure here that the + database is there before we close it. + +Connect on Demand +----------------- + +The upside of this approach (connecting on first use) is that this will +only open the connection if truly necessary. If you want to use this +code outside a request context you can use it in a Python shell by opening +the application context by hand:: + + with app.app_context(): + # now you can use get_db() + + +Easy Querying +------------- + +Now in each request handling function you can access `get_db()` to get the +current open database connection. To simplify working with SQLite, a +row factory function is useful. It is executed for every result returned +from the database to convert the result. For instance, in order to get +dictionaries instead of tuples, this could be inserted into the ``get_db`` +function we created above:: + + def make_dicts(cursor, row): + return dict((cursor.description[idx][0], value) + for idx, value in enumerate(row)) + + db.row_factory = make_dicts + +This will make the sqlite3 module return dicts for this database connection, which are much nicer to deal with. Even more simply, we could place this in ``get_db`` instead:: + + db.row_factory = sqlite3.Row + +This would use Row objects rather than dicts to return the results of queries. These are ``namedtuple`` s, so we can access them either by index or by key. For example, assuming we have a ``sqlite3.Row`` called ``r`` for the rows ``id``, ``FirstName``, ``LastName``, and ``MiddleInitial``:: + + >>> # You can get values based on the row's name + >>> r['FirstName'] + John + >>> # Or, you can get them based on index + >>> r[1] + John + # Row objects are also iterable: + >>> for value in r: + ... print(value) + 1 + John + Doe + M + +Additionally, it is a good idea to provide a query function that combines +getting the cursor, executing and fetching the results:: + + def query_db(query, args=(), one=False): + cur = get_db().execute(query, args) + rv = cur.fetchall() + cur.close() + return (rv[0] if rv else None) if one else rv + +This handy little function, in combination with a row factory, makes +working with the database much more pleasant than it is by just using the +raw cursor and connection objects. + +Here is how you can use it:: + + for user in query_db('select * from users'): + print(user['username'], 'has the id', user['user_id']) + +Or if you just want a single result:: + + user = query_db('select * from users where username = ?', + [the_username], one=True) + if user is None: + print('No such user') + else: + print(the_username, 'has the id', user['user_id']) + +To pass variable parts to the SQL statement, use a question mark in the +statement and pass in the arguments as a list. Never directly add them to +the SQL statement with string formatting because this makes it possible +to attack the application using `SQL Injections +`_. + +Initial Schemas +--------------- + +Relational databases need schemas, so applications often ship a +`schema.sql` file that creates the database. It's a good idea to provide +a function that creates the database based on that schema. This function +can do that for you:: + + def init_db(): + with app.app_context(): + db = get_db() + with app.open_resource('schema.sql', mode='r') as f: + db.cursor().executescript(f.read()) + db.commit() + +You can then create such a database from the Python shell: + +>>> from yourapplication import init_db +>>> init_db() diff --git a/_build/_sources/patterns/streaming.rst.txt b/_build/_sources/patterns/streaming.rst.txt new file mode 100644 index 00000000..c9e6ef22 --- /dev/null +++ b/_build/_sources/patterns/streaming.rst.txt @@ -0,0 +1,85 @@ +Streaming Contents +================== + +Sometimes you want to send an enormous amount of data to the client, much +more than you want to keep in memory. When you are generating the data on +the fly though, how do you send that back to the client without the +roundtrip to the filesystem? + +The answer is by using generators and direct responses. + +Basic Usage +----------- + +This is a basic view function that generates a lot of CSV data on the fly. +The trick is to have an inner function that uses a generator to generate +data and to then invoke that function and pass it to a response object:: + + @app.route('/large.csv') + def generate_large_csv(): + def generate(): + for row in iter_all_rows(): + yield f"{','.join(row)}\n" + return generate(), {"Content-Type": "text/csv"} + +Each ``yield`` expression is directly sent to the browser. Note though +that some WSGI middlewares might break streaming, so be careful there in +debug environments with profilers and other things you might have enabled. + +Streaming from Templates +------------------------ + +The Jinja2 template engine supports rendering a template piece by +piece, returning an iterator of strings. Flask provides the +:func:`~flask.stream_template` and :func:`~flask.stream_template_string` +functions to make this easier to use. + +.. code-block:: python + + from flask import stream_template + + @app.get("/timeline") + def timeline(): + return stream_template("timeline.html") + +The parts yielded by the render stream tend to match statement blocks in +the template. + + +Streaming with Context +---------------------- + +The :data:`~flask.request` will not be active while the generator is +running, because the view has already returned at that point. If you try +to access ``request``, you'll get a ``RuntimeError``. + +If your generator function relies on data in ``request``, use the +:func:`~flask.stream_with_context` wrapper. This will keep the request +context active during the generator. + +.. code-block:: python + + from flask import stream_with_context, request + from markupsafe import escape + + @app.route('/stream') + def streamed_response(): + def generate(): + yield '

Hello ' + yield escape(request.args['name']) + yield '!

' + return stream_with_context(generate()) + +It can also be used as a decorator. + +.. code-block:: python + + @stream_with_context + def generate(): + ... + + return generate() + +The :func:`~flask.stream_template` and +:func:`~flask.stream_template_string` functions automatically +use :func:`~flask.stream_with_context` if a request is active. diff --git a/_build/_sources/patterns/subclassing.rst.txt b/_build/_sources/patterns/subclassing.rst.txt new file mode 100644 index 00000000..d8de2335 --- /dev/null +++ b/_build/_sources/patterns/subclassing.rst.txt @@ -0,0 +1,17 @@ +Subclassing Flask +================= + +The :class:`~flask.Flask` class is designed for subclassing. + +For example, you may want to override how request parameters are handled to preserve their order:: + + from flask import Flask, Request + from werkzeug.datastructures import ImmutableOrderedMultiDict + class MyRequest(Request): + """Request subclass to override request parameter storage""" + parameter_storage_class = ImmutableOrderedMultiDict + class MyFlask(Flask): + """Flask subclass using the custom request class""" + request_class = MyRequest + +This is the recommended approach for overriding or augmenting Flask's internal functionality. diff --git a/_build/_sources/patterns/templateinheritance.rst.txt b/_build/_sources/patterns/templateinheritance.rst.txt new file mode 100644 index 00000000..bb5cba27 --- /dev/null +++ b/_build/_sources/patterns/templateinheritance.rst.txt @@ -0,0 +1,68 @@ +Template Inheritance +==================== + +The most powerful part of Jinja is template inheritance. Template inheritance +allows you to build a base "skeleton" template that contains all the common +elements of your site and defines **blocks** that child templates can override. + +Sounds complicated but is very basic. It's easiest to understand it by starting +with an example. + + +Base Template +------------- + +This template, which we'll call :file:`layout.html`, defines a simple HTML skeleton +document that you might use for a simple two-column page. It's the job of +"child" templates to fill the empty blocks with content: + +.. sourcecode:: html+jinja + + + + + {% block head %} + + {% block title %}{% endblock %} - My Webpage + {% endblock %} + + +
{% block content %}{% endblock %}
+ + + + +In this example, the ``{% block %}`` tags define four blocks that child templates +can fill in. All the `block` tag does is tell the template engine that a +child template may override those portions of the template. + +Child Template +-------------- + +A child template might look like this: + +.. sourcecode:: html+jinja + + {% extends "layout.html" %} + {% block title %}Index{% endblock %} + {% block head %} + {{ super() }} + + {% endblock %} + {% block content %} +

Index

+

+ Welcome on my awesome homepage. + {% endblock %} + +The ``{% extends %}`` tag is the key here. It tells the template engine that +this template "extends" another template. When the template system evaluates +this template, first it locates the parent. The extends tag must be the +first tag in the template. To render the contents of a block defined in +the parent template, use ``{{ super() }}``. diff --git a/_build/_sources/patterns/urlprocessors.rst.txt b/_build/_sources/patterns/urlprocessors.rst.txt new file mode 100644 index 00000000..0d743205 --- /dev/null +++ b/_build/_sources/patterns/urlprocessors.rst.txt @@ -0,0 +1,126 @@ +Using URL Processors +==================== + +.. versionadded:: 0.7 + +Flask 0.7 introduces the concept of URL processors. The idea is that you +might have a bunch of resources with common parts in the URL that you +don't always explicitly want to provide. For instance you might have a +bunch of URLs that have the language code in it but you don't want to have +to handle it in every single function yourself. + +URL processors are especially helpful when combined with blueprints. We +will handle both application specific URL processors here as well as +blueprint specifics. + +Internationalized Application URLs +---------------------------------- + +Consider an application like this:: + + from flask import Flask, g + + app = Flask(__name__) + + @app.route('//') + def index(lang_code): + g.lang_code = lang_code + ... + + @app.route('//about') + def about(lang_code): + g.lang_code = lang_code + ... + +This is an awful lot of repetition as you have to handle the language code +setting on the :data:`~flask.g` object yourself in every single function. +Sure, a decorator could be used to simplify this, but if you want to +generate URLs from one function to another you would have to still provide +the language code explicitly which can be annoying. + +For the latter, this is where :func:`~flask.Flask.url_defaults` functions +come in. They can automatically inject values into a call to +:func:`~flask.url_for`. The code below checks if the +language code is not yet in the dictionary of URL values and if the +endpoint wants a value named ``'lang_code'``:: + + @app.url_defaults + def add_language_code(endpoint, values): + if 'lang_code' in values or not g.lang_code: + return + if app.url_map.is_endpoint_expecting(endpoint, 'lang_code'): + values['lang_code'] = g.lang_code + +The method :meth:`~werkzeug.routing.Map.is_endpoint_expecting` of the URL +map can be used to figure out if it would make sense to provide a language +code for the given endpoint. + +The reverse of that function are +:meth:`~flask.Flask.url_value_preprocessor`\s. They are executed right +after the request was matched and can execute code based on the URL +values. The idea is that they pull information out of the values +dictionary and put it somewhere else:: + + @app.url_value_preprocessor + def pull_lang_code(endpoint, values): + g.lang_code = values.pop('lang_code', None) + +That way you no longer have to do the `lang_code` assignment to +:data:`~flask.g` in every function. You can further improve that by +writing your own decorator that prefixes URLs with the language code, but +the more beautiful solution is using a blueprint. Once the +``'lang_code'`` is popped from the values dictionary and it will no longer +be forwarded to the view function reducing the code to this:: + + from flask import Flask, g + + app = Flask(__name__) + + @app.url_defaults + def add_language_code(endpoint, values): + if 'lang_code' in values or not g.lang_code: + return + if app.url_map.is_endpoint_expecting(endpoint, 'lang_code'): + values['lang_code'] = g.lang_code + + @app.url_value_preprocessor + def pull_lang_code(endpoint, values): + g.lang_code = values.pop('lang_code', None) + + @app.route('//') + def index(): + ... + + @app.route('//about') + def about(): + ... + +Internationalized Blueprint URLs +-------------------------------- + +Because blueprints can automatically prefix all URLs with a common string +it's easy to automatically do that for every function. Furthermore +blueprints can have per-blueprint URL processors which removes a whole lot +of logic from the :meth:`~flask.Flask.url_defaults` function because it no +longer has to check if the URL is really interested in a ``'lang_code'`` +parameter:: + + from flask import Blueprint, g + + bp = Blueprint('frontend', __name__, url_prefix='/') + + @bp.url_defaults + def add_language_code(endpoint, values): + values.setdefault('lang_code', g.lang_code) + + @bp.url_value_preprocessor + def pull_lang_code(endpoint, values): + g.lang_code = values.pop('lang_code') + + @bp.route('/') + def index(): + ... + + @bp.route('/about') + def about(): + ... diff --git a/_build/_sources/patterns/viewdecorators.rst.txt b/_build/_sources/patterns/viewdecorators.rst.txt new file mode 100644 index 00000000..0b0479ef --- /dev/null +++ b/_build/_sources/patterns/viewdecorators.rst.txt @@ -0,0 +1,171 @@ +View Decorators +=============== + +Python has a really interesting feature called function decorators. This +allows some really neat things for web applications. Because each view in +Flask is a function, decorators can be used to inject additional +functionality to one or more functions. The :meth:`~flask.Flask.route` +decorator is the one you probably used already. But there are use cases +for implementing your own decorator. For instance, imagine you have a +view that should only be used by people that are logged in. If a user +goes to the site and is not logged in, they should be redirected to the +login page. This is a good example of a use case where a decorator is an +excellent solution. + +Login Required Decorator +------------------------ + +So let's implement such a decorator. A decorator is a function that +wraps and replaces another function. Since the original function is +replaced, you need to remember to copy the original function's information +to the new function. Use :func:`functools.wraps` to handle this for you. + +This example assumes that the login page is called ``'login'`` and that +the current user is stored in ``g.user`` and is ``None`` if there is no-one +logged in. :: + + from functools import wraps + from flask import g, request, redirect, url_for + + def login_required(f): + @wraps(f) + def decorated_function(*args, **kwargs): + if g.user is None: + return redirect(url_for('login', next=request.url)) + return f(*args, **kwargs) + return decorated_function + +To use the decorator, apply it as innermost decorator to a view function. +When applying further decorators, always remember +that the :meth:`~flask.Flask.route` decorator is the outermost. :: + + @app.route('/secret_page') + @login_required + def secret_page(): + pass + +.. note:: + The ``next`` value will exist in ``request.args`` after a ``GET`` request for + the login page. You'll have to pass it along when sending the ``POST`` request + from the login form. You can do this with a hidden input tag, then retrieve it + from ``request.form`` when logging the user in. :: + + + + +Caching Decorator +----------------- + +Imagine you have a view function that does an expensive calculation and +because of that you would like to cache the generated results for a +certain amount of time. A decorator would be nice for that. We're +assuming you have set up a cache like mentioned in :doc:`caching`. + +Here is an example cache function. It generates the cache key from a +specific prefix (actually a format string) and the current path of the +request. Notice that we are using a function that first creates the +decorator that then decorates the function. Sounds awful? Unfortunately +it is a little bit more complex, but the code should still be +straightforward to read. + +The decorated function will then work as follows + +1. get the unique cache key for the current request based on the current + path. +2. get the value for that key from the cache. If the cache returned + something we will return that value. +3. otherwise the original function is called and the return value is + stored in the cache for the timeout provided (by default 5 minutes). + +Here the code:: + + from functools import wraps + from flask import request + + def cached(timeout=5 * 60, key='view/{}'): + def decorator(f): + @wraps(f) + def decorated_function(*args, **kwargs): + cache_key = key.format(request.path) + rv = cache.get(cache_key) + if rv is not None: + return rv + rv = f(*args, **kwargs) + cache.set(cache_key, rv, timeout=timeout) + return rv + return decorated_function + return decorator + +Notice that this assumes an instantiated ``cache`` object is available, see +:doc:`caching`. + + +Templating Decorator +-------------------- + +A common pattern invented by the TurboGears guys a while back is a +templating decorator. The idea of that decorator is that you return a +dictionary with the values passed to the template from the view function +and the template is automatically rendered. With that, the following +three examples do exactly the same:: + + @app.route('/') + def index(): + return render_template('index.html', value=42) + + @app.route('/') + @templated('index.html') + def index(): + return dict(value=42) + + @app.route('/') + @templated() + def index(): + return dict(value=42) + +As you can see, if no template name is provided it will use the endpoint +of the URL map with dots converted to slashes + ``'.html'``. Otherwise +the provided template name is used. When the decorated function returns, +the dictionary returned is passed to the template rendering function. If +``None`` is returned, an empty dictionary is assumed, if something else than +a dictionary is returned we return it from the function unchanged. That +way you can still use the redirect function or return simple strings. + +Here is the code for that decorator:: + + from functools import wraps + from flask import request, render_template + + def templated(template=None): + def decorator(f): + @wraps(f) + def decorated_function(*args, **kwargs): + template_name = template + if template_name is None: + template_name = f"{request.endpoint.replace('.', '/')}.html" + ctx = f(*args, **kwargs) + if ctx is None: + ctx = {} + elif not isinstance(ctx, dict): + return ctx + return render_template(template_name, **ctx) + return decorated_function + return decorator + + +Endpoint Decorator +------------------ + +When you want to use the werkzeug routing system for more flexibility you +need to map the endpoint as defined in the :class:`~werkzeug.routing.Rule` +to a view function. This is possible with this decorator. For example:: + + from flask import Flask + from werkzeug.routing import Rule + + app = Flask(__name__) + app.url_map.add(Rule('/', endpoint='index')) + + @app.endpoint('index') + def my_index(): + return "Hello world" diff --git a/_build/_sources/patterns/wtforms.rst.txt b/_build/_sources/patterns/wtforms.rst.txt new file mode 100644 index 00000000..3d626f50 --- /dev/null +++ b/_build/_sources/patterns/wtforms.rst.txt @@ -0,0 +1,126 @@ +Form Validation with WTForms +============================ + +When you have to work with form data submitted by a browser view, code +quickly becomes very hard to read. There are libraries out there designed +to make this process easier to manage. One of them is `WTForms`_ which we +will handle here. If you find yourself in the situation of having many +forms, you might want to give it a try. + +When you are working with WTForms you have to define your forms as classes +first. I recommend breaking up the application into multiple modules +(:doc:`packages`) for that and adding a separate module for the +forms. + +.. admonition:: Getting the most out of WTForms with an Extension + + The `Flask-WTF`_ extension expands on this pattern and adds a + few little helpers that make working with forms and Flask more + fun. You can get it from `PyPI + `_. + +.. _Flask-WTF: https://flask-wtf.readthedocs.io/ + +The Forms +--------- + +This is an example form for a typical registration page:: + + from wtforms import Form, BooleanField, StringField, PasswordField, validators + + class RegistrationForm(Form): + username = StringField('Username', [validators.Length(min=4, max=25)]) + email = StringField('Email Address', [validators.Length(min=6, max=35)]) + password = PasswordField('New Password', [ + validators.DataRequired(), + validators.EqualTo('confirm', message='Passwords must match') + ]) + confirm = PasswordField('Repeat Password') + accept_tos = BooleanField('I accept the TOS', [validators.DataRequired()]) + +In the View +----------- + +In the view function, the usage of this form looks like this:: + + @app.route('/register', methods=['GET', 'POST']) + def register(): + form = RegistrationForm(request.form) + if request.method == 'POST' and form.validate(): + user = User(form.username.data, form.email.data, + form.password.data) + db_session.add(user) + flash('Thanks for registering') + return redirect(url_for('login')) + return render_template('register.html', form=form) + +Notice we're implying that the view is using SQLAlchemy here +(:doc:`sqlalchemy`), but that's not a requirement, of course. Adapt +the code as necessary. + +Things to remember: + +1. create the form from the request :attr:`~flask.request.form` value if + the data is submitted via the HTTP ``POST`` method and + :attr:`~flask.request.args` if the data is submitted as ``GET``. +2. to validate the data, call the :func:`~wtforms.form.Form.validate` + method, which will return ``True`` if the data validates, ``False`` + otherwise. +3. to access individual values from the form, access `form..data`. + +Forms in Templates +------------------ + +Now to the template side. When you pass the form to the templates, you can +easily render them there. Look at the following example template to see +how easy this is. WTForms does half the form generation for us already. +To make it even nicer, we can write a macro that renders a field with +label and a list of errors if there are any. + +Here's an example :file:`_formhelpers.html` template with such a macro: + +.. sourcecode:: html+jinja + + {% macro render_field(field) %} +

{{ field.label }} +
{{ field(**kwargs)|safe }} + {% if field.errors %} +
    + {% for error in field.errors %} +
  • {{ error }}
  • + {% endfor %} +
+ {% endif %} +
+ {% endmacro %} + +This macro accepts a couple of keyword arguments that are forwarded to +WTForm's field function, which renders the field for us. The keyword +arguments will be inserted as HTML attributes. So, for example, you can +call ``render_field(form.username, class='username')`` to add a class to +the input element. Note that WTForms returns standard Python strings, +so we have to tell Jinja2 that this data is already HTML-escaped with +the ``|safe`` filter. + +Here is the :file:`register.html` template for the function we used above, which +takes advantage of the :file:`_formhelpers.html` template: + +.. sourcecode:: html+jinja + + {% from "_formhelpers.html" import render_field %} + +
+ {{ render_field(form.username) }} + {{ render_field(form.email) }} + {{ render_field(form.password) }} + {{ render_field(form.confirm) }} + {{ render_field(form.accept_tos) }} +
+

+

+ +For more information about WTForms, head over to the `WTForms +website`_. + +.. _WTForms: https://wtforms.readthedocs.io/ +.. _WTForms website: https://wtforms.readthedocs.io/ diff --git a/_build/_sources/quickstart.rst.txt b/_build/_sources/quickstart.rst.txt new file mode 100644 index 00000000..f763bb1e --- /dev/null +++ b/_build/_sources/quickstart.rst.txt @@ -0,0 +1,907 @@ +Quickstart +========== + +Eager to get started? This page gives a good introduction to Flask. +Follow :doc:`installation` to set up a project and install Flask first. + + +A Minimal Application +--------------------- + +A minimal Flask application looks something like this: + +.. code-block:: python + + from flask import Flask + + app = Flask(__name__) + + @app.route("/") + def hello_world(): + return "

Hello, World!

" + +So what did that code do? + +1. First we imported the :class:`~flask.Flask` class. An instance of + this class will be our WSGI application. +2. Next we create an instance of this class. The first argument is the + name of the application's module or package. ``__name__`` is a + convenient shortcut for this that is appropriate for most cases. + This is needed so that Flask knows where to look for resources such + as templates and static files. +3. We then use the :meth:`~flask.Flask.route` decorator to tell Flask + what URL should trigger our function. +4. The function returns the message we want to display in the user's + browser. The default content type is HTML, so HTML in the string + will be rendered by the browser. + +Save it as :file:`hello.py` or something similar. Make sure to not call +your application :file:`flask.py` because this would conflict with Flask +itself. + +To run the application, use the ``flask`` command or +``python -m flask``. You need to tell the Flask where your application +is with the ``--app`` option. + +.. code-block:: text + + $ flask --app hello run + * Serving Flask app 'hello' + * Running on http://127.0.0.1:5000 (Press CTRL+C to quit) + +.. admonition:: Application Discovery Behavior + + As a shortcut, if the file is named ``app.py`` or ``wsgi.py``, you + don't have to use ``--app``. See :doc:`/cli` for more details. + +This launches a very simple builtin server, which is good enough for +testing but probably not what you want to use in production. For +deployment options see :doc:`deploying/index`. + +Now head over to http://127.0.0.1:5000/, and you should see your hello +world greeting. + +If another program is already using port 5000, you'll see +``OSError: [Errno 98]`` or ``OSError: [WinError 10013]`` when the +server tries to start. See :ref:`address-already-in-use` for how to +handle that. + +.. _public-server: + +.. admonition:: Externally Visible Server + + If you run the server you will notice that the server is only accessible + from your own computer, not from any other in the network. This is the + default because in debugging mode a user of the application can execute + arbitrary Python code on your computer. + + If you have the debugger disabled or trust the users on your network, + you can make the server publicly available simply by adding + ``--host=0.0.0.0`` to the command line:: + + $ flask run --host=0.0.0.0 + + This tells your operating system to listen on all public IPs. + + +Debug Mode +---------- + +The ``flask run`` command can do more than just start the development +server. By enabling debug mode, the server will automatically reload if +code changes, and will show an interactive debugger in the browser if an +error occurs during a request. + +.. image:: _static/debugger.png + :align: center + :class: screenshot + :alt: The interactive debugger in action. + +.. warning:: + + The debugger allows executing arbitrary Python code from the + browser. It is protected by a pin, but still represents a major + security risk. Do not run the development server or debugger in a + production environment. + +To enable debug mode, use the ``--debug`` option. + +.. code-block:: text + + $ flask --app hello run --debug + * Serving Flask app 'hello' + * Debug mode: on + * Running on http://127.0.0.1:5000 (Press CTRL+C to quit) + * Restarting with stat + * Debugger is active! + * Debugger PIN: nnn-nnn-nnn + +See also: + +- :doc:`/server` and :doc:`/cli` for information about running in debug mode. +- :doc:`/debugging` for information about using the built-in debugger + and other debuggers. +- :doc:`/logging` and :doc:`/errorhandling` to log errors and display + nice error pages. + + +HTML Escaping +------------- + +When returning HTML (the default response type in Flask), any +user-provided values rendered in the output must be escaped to protect +from injection attacks. HTML templates rendered with Jinja, introduced +later, will do this automatically. + +:func:`~markupsafe.escape`, shown here, can be used manually. It is +omitted in most examples for brevity, but you should always be aware of +how you're using untrusted data. + +.. code-block:: python + + from markupsafe import escape + + @app.route("/") + def hello(name): + return f"Hello, {escape(name)}!" + +If a user managed to submit the name ````, +escaping causes it to be rendered as text, rather than running the +script in the user's browser. + +```` in the route captures a value from the URL and passes it to +the view function. These variable rules are explained below. + + +Routing +------- + +Modern web applications use meaningful URLs to help users. Users are more +likely to like a page and come back if the page uses a meaningful URL they can +remember and use to directly visit a page. + +Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. :: + + @app.route('/') + def index(): + return 'Index Page' + + @app.route('/hello') + def hello(): + return 'Hello, World' + +You can do more! You can make parts of the URL dynamic and attach multiple +rules to a function. + +Variable Rules +`````````````` + +You can add variable sections to a URL by marking sections with +````. Your function then receives the ```` +as a keyword argument. Optionally, you can use a converter to specify the type +of the argument like ````. :: + + from markupsafe import escape + + @app.route('/user/') + def show_user_profile(username): + # show the user profile for that user + return f'User {escape(username)}' + + @app.route('/post/') + def show_post(post_id): + # show the post with the given id, the id is an integer + return f'Post {post_id}' + + @app.route('/path/') + def show_subpath(subpath): + # show the subpath after /path/ + return f'Subpath {escape(subpath)}' + +Converter types: + +========== ========================================== +``string`` (default) accepts any text without a slash +``int`` accepts positive integers +``float`` accepts positive floating point values +``path`` like ``string`` but also accepts slashes +``uuid`` accepts UUID strings +========== ========================================== + + +Unique URLs / Redirection Behavior +`````````````````````````````````` + +The following two rules differ in their use of a trailing slash. :: + + @app.route('/projects/') + def projects(): + return 'The project page' + + @app.route('/about') + def about(): + return 'The about page' + +The canonical URL for the ``projects`` endpoint has a trailing slash. +It's similar to a folder in a file system. If you access the URL without +a trailing slash (``/projects``), Flask redirects you to the canonical URL +with the trailing slash (``/projects/``). + +The canonical URL for the ``about`` endpoint does not have a trailing +slash. It's similar to the pathname of a file. Accessing the URL with a +trailing slash (``/about/``) produces a 404 "Not Found" error. This helps +keep URLs unique for these resources, which helps search engines avoid +indexing the same page twice. + + +.. _url-building: + +URL Building +```````````` + +To build a URL to a specific function, use the :func:`~flask.url_for` function. +It accepts the name of the function as its first argument and any number of +keyword arguments, each corresponding to a variable part of the URL rule. +Unknown variable parts are appended to the URL as query parameters. + +Why would you want to build URLs using the URL reversing function +:func:`~flask.url_for` instead of hard-coding them into your templates? + +1. Reversing is often more descriptive than hard-coding the URLs. +2. You can change your URLs in one go instead of needing to remember to + manually change hard-coded URLs. +3. URL building handles escaping of special characters transparently. +4. The generated paths are always absolute, avoiding unexpected behavior + of relative paths in browsers. +5. If your application is placed outside the URL root, for example, in + ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly + handles that for you. + +For example, here we use the :meth:`~flask.Flask.test_request_context` method +to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context` +tells Flask to behave as though it's handling a request even while we use a +Python shell. See :ref:`context-locals`. + +.. code-block:: python + + from flask import url_for + + @app.route('/') + def index(): + return 'index' + + @app.route('/login') + def login(): + return 'login' + + @app.route('/user/') + def profile(username): + return f'{username}\'s profile' + + with app.test_request_context(): + print(url_for('index')) + print(url_for('login')) + print(url_for('login', next='/')) + print(url_for('profile', username='John Doe')) + +.. code-block:: text + + / + /login + /login?next=/ + /user/John%20Doe + + +HTTP Methods +```````````` + +Web applications use different HTTP methods when accessing URLs. You should +familiarize yourself with the HTTP methods as you work with Flask. By default, +a route only answers to ``GET`` requests. You can use the ``methods`` argument +of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods. +:: + + from flask import request + + @app.route('/login', methods=['GET', 'POST']) + def login(): + if request.method == 'POST': + return do_the_login() + else: + return show_the_login_form() + +The example above keeps all methods for the route within one function, +which can be useful if each part uses some common data. + +You can also separate views for different methods into different +functions. Flask provides a shortcut for decorating such routes with +:meth:`~flask.Flask.get`, :meth:`~flask.Flask.post`, etc. for each +common HTTP method. + +.. code-block:: python + + @app.get('/login') + def login_get(): + return show_the_login_form() + + @app.post('/login') + def login_post(): + return do_the_login() + +If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method +and handles ``HEAD`` requests according to the `HTTP RFC`_. Likewise, +``OPTIONS`` is automatically implemented for you. + +.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt + +Static Files +------------ + +Dynamic web applications also need static files. That's usually where +the CSS and JavaScript files are coming from. Ideally your web server is +configured to serve them for you, but during development Flask can do that +as well. Just create a folder called :file:`static` in your package or next to +your module and it will be available at ``/static`` on the application. + +To generate URLs for static files, use the special ``'static'`` endpoint name:: + + url_for('static', filename='style.css') + +The file has to be stored on the filesystem as :file:`static/style.css`. + +Rendering Templates +------------------- + +Generating HTML from within Python is not fun, and actually pretty +cumbersome because you have to do the HTML escaping on your own to keep +the application secure. Because of that Flask configures the `Jinja2 +`_ template engine for you automatically. + +Templates can be used to generate any type of text file. For web applications, you'll +primarily be generating HTML pages, but you can also generate markdown, plain text for +emails, and anything else. + +For a reference to HTML, CSS, and other web APIs, use the `MDN Web Docs`_. + +.. _MDN Web Docs: https://developer.mozilla.org/ + +To render a template you can use the :func:`~flask.render_template` +method. All you have to do is provide the name of the template and the +variables you want to pass to the template engine as keyword arguments. +Here's a simple example of how to render a template:: + + from flask import render_template + + @app.route('/hello/') + @app.route('/hello/') + def hello(name=None): + return render_template('hello.html', person=name) + +Flask will look for templates in the :file:`templates` folder. So if your +application is a module, this folder is next to that module, if it's a +package it's actually inside your package: + +**Case 1**: a module:: + + /application.py + /templates + /hello.html + +**Case 2**: a package:: + + /application + /__init__.py + /templates + /hello.html + +For templates you can use the full power of Jinja2 templates. Head over +to the official `Jinja2 Template Documentation +`_ for more information. + +Here is an example template: + +.. sourcecode:: html+jinja + + + Hello from Flask + {% if person %} +

Hello {{ person }}!

+ {% else %} +

Hello, World!

+ {% endif %} + +Inside templates you also have access to the :data:`~flask.Flask.config`, +:class:`~flask.request`, :class:`~flask.session` and :class:`~flask.g` [#]_ objects +as well as the :func:`~flask.url_for` and :func:`~flask.get_flashed_messages` functions. + +Templates are especially useful if inheritance is used. If you want to +know how that works, see :doc:`patterns/templateinheritance`. Basically +template inheritance makes it possible to keep certain elements on each +page (like header, navigation and footer). + +Automatic escaping is enabled, so if ``person`` contains HTML it will be escaped +automatically. If you can trust a variable and you know that it will be +safe HTML (for example because it came from a module that converts wiki +markup to HTML) you can mark it as safe by using the +:class:`~markupsafe.Markup` class or by using the ``|safe`` filter in the +template. Head over to the Jinja 2 documentation for more examples. + +Here is a basic introduction to how the :class:`~markupsafe.Markup` class works:: + + >>> from markupsafe import Markup + >>> Markup('Hello %s!') % 'hacker' + Markup('Hello <blink>hacker</blink>!') + >>> Markup.escape('hacker') + Markup('<blink>hacker</blink>') + >>> Markup('Marked up » HTML').striptags() + 'Marked up » HTML' + +.. versionchanged:: 0.5 + + Autoescaping is no longer enabled for all templates. The following + extensions for templates trigger autoescaping: ``.html``, ``.htm``, + ``.xml``, ``.xhtml``. Templates loaded from a string will have + autoescaping disabled. + +.. [#] Unsure what that :class:`~flask.g` object is? It's something in which + you can store information for your own needs. See the documentation + for :class:`flask.g` and :doc:`patterns/sqlite3`. + + +Accessing Request Data +---------------------- + +For web applications it's crucial to react to the data a client sends to +the server. In Flask this information is provided by the global +:class:`~flask.request` object. If you have some experience with Python +you might be wondering how that object can be global and how Flask +manages to still be threadsafe. The answer is context locals: + + +.. _context-locals: + +Context Locals +`````````````` + +.. admonition:: Insider Information + + If you want to understand how that works and how you can implement + tests with context locals, read this section, otherwise just skip it. + +Certain objects in Flask are global objects, but not of the usual kind. +These objects are actually proxies to objects that are local to a specific +context. What a mouthful. But that is actually quite easy to understand. + +Imagine the context being the handling thread. A request comes in and the +web server decides to spawn a new thread (or something else, the +underlying object is capable of dealing with concurrency systems other +than threads). When Flask starts its internal request handling it +figures out that the current thread is the active context and binds the +current application and the WSGI environments to that context (thread). +It does that in an intelligent way so that one application can invoke another +application without breaking. + +So what does this mean to you? Basically you can completely ignore that +this is the case unless you are doing something like unit testing. You +will notice that code which depends on a request object will suddenly break +because there is no request object. The solution is creating a request +object yourself and binding it to the context. The easiest solution for +unit testing is to use the :meth:`~flask.Flask.test_request_context` +context manager. In combination with the ``with`` statement it will bind a +test request so that you can interact with it. Here is an example:: + + from flask import request + + with app.test_request_context('/hello', method='POST'): + # now you can do something with the request until the + # end of the with block, such as basic assertions: + assert request.path == '/hello' + assert request.method == 'POST' + +The other possibility is passing a whole WSGI environment to the +:meth:`~flask.Flask.request_context` method:: + + with app.request_context(environ): + assert request.method == 'POST' + +The Request Object +`````````````````` + +The request object is documented in the API section and we will not cover +it here in detail (see :class:`~flask.Request`). Here is a broad overview of +some of the most common operations. First of all you have to import it from +the ``flask`` module:: + + from flask import request + +The current request method is available by using the +:attr:`~flask.Request.method` attribute. To access form data (data +transmitted in a ``POST`` or ``PUT`` request) you can use the +:attr:`~flask.Request.form` attribute. Here is a full example of the two +attributes mentioned above:: + + @app.route('/login', methods=['POST', 'GET']) + def login(): + error = None + if request.method == 'POST': + if valid_login(request.form['username'], + request.form['password']): + return log_the_user_in(request.form['username']) + else: + error = 'Invalid username/password' + # the code below is executed if the request method + # was GET or the credentials were invalid + return render_template('login.html', error=error) + +What happens if the key does not exist in the ``form`` attribute? In that +case a special :exc:`KeyError` is raised. You can catch it like a +standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request +error page is shown instead. So for many situations you don't have to +deal with that problem. + +To access parameters submitted in the URL (``?key=value``) you can use the +:attr:`~flask.Request.args` attribute:: + + searchword = request.args.get('key', '') + +We recommend accessing URL parameters with `get` or by catching the +:exc:`KeyError` because users might change the URL and presenting them a 400 +bad request page in that case is not user friendly. + +For a full list of methods and attributes of the request object, head over +to the :class:`~flask.Request` documentation. + + +File Uploads +```````````` + +You can handle uploaded files with Flask easily. Just make sure not to +forget to set the ``enctype="multipart/form-data"`` attribute on your HTML +form, otherwise the browser will not transmit your files at all. + +Uploaded files are stored in memory or at a temporary location on the +filesystem. You can access those files by looking at the +:attr:`~flask.request.files` attribute on the request object. Each +uploaded file is stored in that dictionary. It behaves just like a +standard Python :class:`file` object, but it also has a +:meth:`~werkzeug.datastructures.FileStorage.save` method that +allows you to store that file on the filesystem of the server. +Here is a simple example showing how that works:: + + from flask import request + + @app.route('/upload', methods=['GET', 'POST']) + def upload_file(): + if request.method == 'POST': + f = request.files['the_file'] + f.save('/var/www/uploads/uploaded_file.txt') + ... + +If you want to know how the file was named on the client before it was +uploaded to your application, you can access the +:attr:`~werkzeug.datastructures.FileStorage.filename` attribute. +However please keep in mind that this value can be forged +so never ever trust that value. If you want to use the filename +of the client to store the file on the server, pass it through the +:func:`~werkzeug.utils.secure_filename` function that +Werkzeug provides for you:: + + from werkzeug.utils import secure_filename + + @app.route('/upload', methods=['GET', 'POST']) + def upload_file(): + if request.method == 'POST': + file = request.files['the_file'] + file.save(f"/var/www/uploads/{secure_filename(file.filename)}") + ... + +For some better examples, see :doc:`patterns/fileuploads`. + +Cookies +``````` + +To access cookies you can use the :attr:`~flask.Request.cookies` +attribute. To set cookies you can use the +:attr:`~flask.Response.set_cookie` method of response objects. The +:attr:`~flask.Request.cookies` attribute of request objects is a +dictionary with all the cookies the client transmits. If you want to use +sessions, do not use the cookies directly but instead use the +:ref:`sessions` in Flask that add some security on top of cookies for you. + +Reading cookies:: + + from flask import request + + @app.route('/') + def index(): + username = request.cookies.get('username') + # use cookies.get(key) instead of cookies[key] to not get a + # KeyError if the cookie is missing. + +Storing cookies:: + + from flask import make_response + + @app.route('/') + def index(): + resp = make_response(render_template(...)) + resp.set_cookie('username', 'the username') + return resp + +Note that cookies are set on response objects. Since you normally +just return strings from the view functions Flask will convert them into +response objects for you. If you explicitly want to do that you can use +the :meth:`~flask.make_response` function and then modify it. + +Sometimes you might want to set a cookie at a point where the response +object does not exist yet. This is possible by utilizing the +:doc:`patterns/deferredcallbacks` pattern. + +For this also see :ref:`about-responses`. + +Redirects and Errors +-------------------- + +To redirect a user to another endpoint, use the :func:`~flask.redirect` +function; to abort a request early with an error code, use the +:func:`~flask.abort` function:: + + from flask import abort, redirect, url_for + + @app.route('/') + def index(): + return redirect(url_for('login')) + + @app.route('/login') + def login(): + abort(401) + this_is_never_executed() + +This is a rather pointless example because a user will be redirected from +the index to a page they cannot access (401 means access denied) but it +shows how that works. + +By default a black and white error page is shown for each error code. If +you want to customize the error page, you can use the +:meth:`~flask.Flask.errorhandler` decorator:: + + from flask import render_template + + @app.errorhandler(404) + def page_not_found(error): + return render_template('page_not_found.html'), 404 + +Note the ``404`` after the :func:`~flask.render_template` call. This +tells Flask that the status code of that page should be 404 which means +not found. By default 200 is assumed which translates to: all went well. + +See :doc:`errorhandling` for more details. + +.. _about-responses: + +About Responses +--------------- + +The return value from a view function is automatically converted into +a response object for you. If the return value is a string it's +converted into a response object with the string as response body, a +``200 OK`` status code and a :mimetype:`text/html` mimetype. If the +return value is a dict or list, :func:`jsonify` is called to produce a +response. The logic that Flask applies to converting return values into +response objects is as follows: + +1. If a response object of the correct type is returned it's directly + returned from the view. +2. If it's a string, a response object is created with that data and + the default parameters. +3. If it's an iterator or generator returning strings or bytes, it is + treated as a streaming response. +4. If it's a dict or list, a response object is created using + :func:`~flask.json.jsonify`. +5. If a tuple is returned the items in the tuple can provide extra + information. Such tuples have to be in the form + ``(response, status)``, ``(response, headers)``, or + ``(response, status, headers)``. The ``status`` value will override + the status code and ``headers`` can be a list or dictionary of + additional header values. +6. If none of that works, Flask will assume the return value is a + valid WSGI application and convert that into a response object. + +If you want to get hold of the resulting response object inside the view +you can use the :func:`~flask.make_response` function. + +Imagine you have a view like this:: + + from flask import render_template + + @app.errorhandler(404) + def not_found(error): + return render_template('error.html'), 404 + +You just need to wrap the return expression with +:func:`~flask.make_response` and get the response object to modify it, then +return it:: + + from flask import make_response + + @app.errorhandler(404) + def not_found(error): + resp = make_response(render_template('error.html'), 404) + resp.headers['X-Something'] = 'A value' + return resp + + +APIs with JSON +`````````````` + +A common response format when writing an API is JSON. It's easy to get +started writing such an API with Flask. If you return a ``dict`` or +``list`` from a view, it will be converted to a JSON response. + +.. code-block:: python + + @app.route("/me") + def me_api(): + user = get_current_user() + return { + "username": user.username, + "theme": user.theme, + "image": url_for("user_image", filename=user.image), + } + + @app.route("/users") + def users_api(): + users = get_all_users() + return [user.to_json() for user in users] + +This is a shortcut to passing the data to the +:func:`~flask.json.jsonify` function, which will serialize any supported +JSON data type. That means that all the data in the dict or list must be +JSON serializable. + +For complex types such as database models, you'll want to use a +serialization library to convert the data to valid JSON types first. +There are many serialization libraries and Flask API extensions +maintained by the community that support more complex applications. + + +.. _sessions: + +Sessions +-------- + +In addition to the request object there is also a second object called +:class:`~flask.session` which allows you to store information specific to a +user from one request to the next. This is implemented on top of cookies +for you and signs the cookies cryptographically. What this means is that +the user could look at the contents of your cookie but not modify it, +unless they know the secret key used for signing. + +In order to use sessions you have to set a secret key. Here is how +sessions work:: + + from flask import session + + # Set the secret key to some random bytes. Keep this really secret! + app.secret_key = b'_5#y2L"F4Q8z\n\xec]/' + + @app.route('/') + def index(): + if 'username' in session: + return f'Logged in as {session["username"]}' + return 'You are not logged in' + + @app.route('/login', methods=['GET', 'POST']) + def login(): + if request.method == 'POST': + session['username'] = request.form['username'] + return redirect(url_for('index')) + return ''' +
+

+

+

+ ''' + + @app.route('/logout') + def logout(): + # remove the username from the session if it's there + session.pop('username', None) + return redirect(url_for('index')) + +.. admonition:: How to generate good secret keys + + A secret key should be as random as possible. Your operating system has + ways to generate pretty random data based on a cryptographic random + generator. Use the following command to quickly generate a value for + :attr:`Flask.secret_key` (or :data:`SECRET_KEY`):: + + $ python -c 'import secrets; print(secrets.token_hex())' + '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf' + +A note on cookie-based sessions: Flask will take the values you put into the +session object and serialize them into a cookie. If you are finding some +values do not persist across requests, cookies are indeed enabled, and you are +not getting a clear error message, check the size of the cookie in your page +responses compared to the size supported by web browsers. + +Besides the default client-side based sessions, if you want to handle +sessions on the server-side instead, there are several +Flask extensions that support this. + +Message Flashing +---------------- + +Good applications and user interfaces are all about feedback. If the user +does not get enough feedback they will probably end up hating the +application. Flask provides a really simple way to give feedback to a +user with the flashing system. The flashing system basically makes it +possible to record a message at the end of a request and access it on the next +(and only the next) request. This is usually combined with a layout +template to expose the message. + +To flash a message use the :func:`~flask.flash` method, to get hold of the +messages you can use :func:`~flask.get_flashed_messages` which is also +available in the templates. See :doc:`patterns/flashing` for a full +example. + +Logging +------- + +.. versionadded:: 0.3 + +Sometimes you might be in a situation where you deal with data that +should be correct, but actually is not. For example you may have +some client-side code that sends an HTTP request to the server +but it's obviously malformed. This might be caused by a user tampering +with the data, or the client code failing. Most of the time it's okay +to reply with ``400 Bad Request`` in that situation, but sometimes +that won't do and the code has to continue working. + +You may still want to log that something fishy happened. This is where +loggers come in handy. As of Flask 0.3 a logger is preconfigured for you +to use. + +Here are some example log calls:: + + app.logger.debug('A value for debugging') + app.logger.warning('A warning occurred (%d apples)', 42) + app.logger.error('An error occurred') + +The attached :attr:`~flask.Flask.logger` is a standard logging +:class:`~logging.Logger`, so head over to the official :mod:`logging` +docs for more information. + +See :doc:`errorhandling`. + + +Hooking in WSGI Middleware +-------------------------- + +To add WSGI middleware to your Flask application, wrap the application's +``wsgi_app`` attribute. For example, to apply Werkzeug's +:class:`~werkzeug.middleware.proxy_fix.ProxyFix` middleware for running +behind Nginx: + +.. code-block:: python + + from werkzeug.middleware.proxy_fix import ProxyFix + app.wsgi_app = ProxyFix(app.wsgi_app) + +Wrapping ``app.wsgi_app`` instead of ``app`` means that ``app`` still +points at your Flask application, not at the middleware, so you can +continue to use and configure ``app`` directly. + +Using Flask Extensions +---------------------- + +Extensions are packages that help you accomplish common tasks. For +example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple +and easy to use with Flask. + +For more on Flask extensions, see :doc:`extensions`. + +Deploying to a Web Server +------------------------- + +Ready to deploy your new Flask app? See :doc:`deploying/index`. diff --git a/_build/_sources/reqcontext.rst.txt b/_build/_sources/reqcontext.rst.txt new file mode 100644 index 00000000..4f1846a3 --- /dev/null +++ b/_build/_sources/reqcontext.rst.txt @@ -0,0 +1,243 @@ +.. currentmodule:: flask + +The Request Context +=================== + +The request context keeps track of the request-level data during a +request. Rather than passing the request object to each function that +runs during a request, the :data:`request` and :data:`session` proxies +are accessed instead. + +This is similar to :doc:`/appcontext`, which keeps track of the +application-level data independent of a request. A corresponding +application context is pushed when a request context is pushed. + + +Purpose of the Context +---------------------- + +When the :class:`Flask` application handles a request, it creates a +:class:`Request` object based on the environment it received from the +WSGI server. Because a *worker* (thread, process, or coroutine depending +on the server) handles only one request at a time, the request data can +be considered global to that worker during that request. Flask uses the +term *context local* for this. + +Flask automatically *pushes* a request context when handling a request. +View functions, error handlers, and other functions that run during a +request will have access to the :data:`request` proxy, which points to +the request object for the current request. + + +Lifetime of the Context +----------------------- + +When a Flask application begins handling a request, it pushes a request +context, which also pushes an :doc:`app context `. When the +request ends it pops the request context then the application context. + +The context is unique to each thread (or other worker type). +:data:`request` cannot be passed to another thread, the other thread has +a different context space and will not know about the request the parent +thread was pointing to. + +Context locals are implemented using Python's :mod:`contextvars` and +Werkzeug's :class:`~werkzeug.local.LocalProxy`. Python manages the +lifetime of context vars automatically, and local proxy wraps that +low-level interface to make the data easier to work with. + + +Manually Push a Context +----------------------- + +If you try to access :data:`request`, or anything that uses it, outside +a request context, you'll get this error message: + +.. code-block:: pytb + + RuntimeError: Working outside of request context. + + This typically means that you attempted to use functionality that + needed an active HTTP request. Consult the documentation on testing + for information about how to avoid this problem. + +This should typically only happen when testing code that expects an +active request. One option is to use the +:meth:`test client ` to simulate a full request. Or +you can use :meth:`~Flask.test_request_context` in a ``with`` block, and +everything that runs in the block will have access to :data:`request`, +populated with your test data. :: + + def generate_report(year): + format = request.args.get("format") + ... + + with app.test_request_context( + "/make_report/2017", query_string={"format": "short"} + ): + generate_report() + +If you see that error somewhere else in your code not related to +testing, it most likely indicates that you should move that code into a +view function. + +For information on how to use the request context from the interactive +Python shell, see :doc:`/shell`. + + +How the Context Works +--------------------- + +The :meth:`Flask.wsgi_app` method is called to handle each request. It +manages the contexts during the request. Internally, the request and +application contexts work like stacks. When contexts are pushed, the +proxies that depend on them are available and point at information from +the top item. + +When the request starts, a :class:`~ctx.RequestContext` is created and +pushed, which creates and pushes an :class:`~ctx.AppContext` first if +a context for that application is not already the top context. While +these contexts are pushed, the :data:`current_app`, :data:`g`, +:data:`request`, and :data:`session` proxies are available to the +original thread handling the request. + +Other contexts may be pushed to change the proxies during a request. +While this is not a common pattern, it can be used in advanced +applications to, for example, do internal redirects or chain different +applications together. + +After the request is dispatched and a response is generated and sent, +the request context is popped, which then pops the application context. +Immediately before they are popped, the :meth:`~Flask.teardown_request` +and :meth:`~Flask.teardown_appcontext` functions are executed. These +execute even if an unhandled exception occurred during dispatch. + + +.. _callbacks-and-errors: + +Callbacks and Errors +-------------------- + +Flask dispatches a request in multiple stages which can affect the +request, response, and how errors are handled. The contexts are active +during all of these stages. + +A :class:`Blueprint` can add handlers for these events that are specific +to the blueprint. The handlers for a blueprint will run if the blueprint +owns the route that matches the request. + +#. Before each request, :meth:`~Flask.before_request` functions are + called. If one of these functions return a value, the other + functions are skipped. The return value is treated as the response + and the view function is not called. + +#. If the :meth:`~Flask.before_request` functions did not return a + response, the view function for the matched route is called and + returns a response. + +#. The return value of the view is converted into an actual response + object and passed to the :meth:`~Flask.after_request` + functions. Each function returns a modified or new response object. + +#. After the response is returned, the contexts are popped, which calls + the :meth:`~Flask.teardown_request` and + :meth:`~Flask.teardown_appcontext` functions. These functions are + called even if an unhandled exception was raised at any point above. + +If an exception is raised before the teardown functions, Flask tries to +match it with an :meth:`~Flask.errorhandler` function to handle the +exception and return a response. If no error handler is found, or the +handler itself raises an exception, Flask returns a generic +``500 Internal Server Error`` response. The teardown functions are still +called, and are passed the exception object. + +If debug mode is enabled, unhandled exceptions are not converted to a +``500`` response and instead are propagated to the WSGI server. This +allows the development server to present the interactive debugger with +the traceback. + + +Teardown Callbacks +~~~~~~~~~~~~~~~~~~ + +The teardown callbacks are independent of the request dispatch, and are +instead called by the contexts when they are popped. The functions are +called even if there is an unhandled exception during dispatch, and for +manually pushed contexts. This means there is no guarantee that any +other parts of the request dispatch have run first. Be sure to write +these functions in a way that does not depend on other callbacks and +will not fail. + +During testing, it can be useful to defer popping the contexts after the +request ends, so that their data can be accessed in the test function. +Use the :meth:`~Flask.test_client` as a ``with`` block to preserve the +contexts until the ``with`` block exits. + +.. code-block:: python + + from flask import Flask, request + + app = Flask(__name__) + + @app.route('/') + def hello(): + print('during view') + return 'Hello, World!' + + @app.teardown_request + def show_teardown(exception): + print('after with block') + + with app.test_request_context(): + print('during with block') + + # teardown functions are called after the context with block exits + + with app.test_client() as client: + client.get('/') + # the contexts are not popped even though the request ended + print(request.path) + + # the contexts are popped and teardown functions are called after + # the client with block exits + +Signals +~~~~~~~ + +The following signals are sent: + +#. :data:`request_started` is sent before the :meth:`~Flask.before_request` functions + are called. +#. :data:`request_finished` is sent after the :meth:`~Flask.after_request` functions + are called. +#. :data:`got_request_exception` is sent when an exception begins to be handled, but + before an :meth:`~Flask.errorhandler` is looked up or called. +#. :data:`request_tearing_down` is sent after the :meth:`~Flask.teardown_request` + functions are called. + + +.. _notes-on-proxies: + +Notes On Proxies +---------------- + +Some of the objects provided by Flask are proxies to other objects. The +proxies are accessed in the same way for each worker thread, but +point to the unique object bound to each worker behind the scenes as +described on this page. + +Most of the time you don't have to care about that, but there are some +exceptions where it is good to know that this object is actually a proxy: + +- The proxy objects cannot fake their type as the actual object types. + If you want to perform instance checks, you have to do that on the + object being proxied. +- The reference to the proxied object is needed in some situations, + such as sending :doc:`signals` or passing data to a background + thread. + +If you need to access the underlying object that is proxied, use the +:meth:`~werkzeug.local.LocalProxy._get_current_object` method:: + + app = current_app._get_current_object() + my_signal.send(app) diff --git a/_build/_sources/server.rst.txt b/_build/_sources/server.rst.txt new file mode 100644 index 00000000..11e976bc --- /dev/null +++ b/_build/_sources/server.rst.txt @@ -0,0 +1,115 @@ +.. currentmodule:: flask + +Development Server +================== + +Flask provides a ``run`` command to run the application with a development server. In +debug mode, this server provides an interactive debugger and will reload when code is +changed. + +.. warning:: + + Do not use the development server when deploying to production. It + is intended for use only during local development. It is not + designed to be particularly efficient, stable, or secure. + + See :doc:`/deploying/index` for deployment options. + +Command Line +------------ + +The ``flask run`` CLI command is the recommended way to run the development server. Use +the ``--app`` option to point to your application, and the ``--debug`` option to enable +debug mode. + +.. code-block:: text + + $ flask --app hello run --debug + +This enables debug mode, including the interactive debugger and reloader, and then +starts the server on http://localhost:5000/. Use ``flask run --help`` to see the +available options, and :doc:`/cli` for detailed instructions about configuring and using +the CLI. + + +.. _address-already-in-use: + +Address already in use +~~~~~~~~~~~~~~~~~~~~~~ + +If another program is already using port 5000, you'll see an ``OSError`` +when the server tries to start. It may have one of the following +messages: + +- ``OSError: [Errno 98] Address already in use`` +- ``OSError: [WinError 10013] An attempt was made to access a socket + in a way forbidden by its access permissions`` + +Either identify and stop the other program, or use +``flask run --port 5001`` to pick a different port. + +You can use ``netstat`` or ``lsof`` to identify what process id is using +a port, then use other operating system tools stop that process. The +following example shows that process id 6847 is using port 5000. + +.. tabs:: + + .. tab:: ``netstat`` (Linux) + + .. code-block:: text + + $ netstat -nlp | grep 5000 + tcp 0 0 127.0.0.1:5000 0.0.0.0:* LISTEN 6847/python + + .. tab:: ``lsof`` (macOS / Linux) + + .. code-block:: text + + $ lsof -P -i :5000 + Python 6847 IPv4 TCP localhost:5000 (LISTEN) + + .. tab:: ``netstat`` (Windows) + + .. code-block:: text + + > netstat -ano | findstr 5000 + TCP 127.0.0.1:5000 0.0.0.0:0 LISTENING 6847 + +macOS Monterey and later automatically starts a service that uses port +5000. You can choose to disable this service instead of using a different port by +searching for "AirPlay Receiver" in System Preferences and toggling it off. + + +Deferred Errors on Reload +~~~~~~~~~~~~~~~~~~~~~~~~~ + +When using the ``flask run`` command with the reloader, the server will +continue to run even if you introduce syntax errors or other +initialization errors into the code. Accessing the site will show the +interactive debugger for the error, rather than crashing the server. + +If a syntax error is already present when calling ``flask run``, it will +fail immediately and show the traceback rather than waiting until the +site is accessed. This is intended to make errors more visible initially +while still allowing the server to handle errors on reload. + + +In Code +------- + +The development server can also be started from Python with the :meth:`Flask.run` +method. This method takes arguments similar to the CLI options to control the server. +The main difference from the CLI command is that the server will crash if there are +errors when reloading. ``debug=True`` can be passed to enable debug mode. + +Place the call in a main block, otherwise it will interfere when trying to import and +run the application with a production server later. + +.. code-block:: python + + if __name__ == "__main__": + app.run(debug=True) + +.. code-block:: text + + $ python hello.py diff --git a/_build/_sources/shell.rst.txt b/_build/_sources/shell.rst.txt new file mode 100644 index 00000000..7e42e285 --- /dev/null +++ b/_build/_sources/shell.rst.txt @@ -0,0 +1,100 @@ +Working with the Shell +====================== + +.. versionadded:: 0.3 + +One of the reasons everybody loves Python is the interactive shell. It +basically allows you to execute Python commands in real time and +immediately get results back. Flask itself does not come with an +interactive shell, because it does not require any specific setup upfront, +just import your application and start playing around. + +There are however some handy helpers to make playing around in the shell a +more pleasant experience. The main issue with interactive console +sessions is that you're not triggering a request like a browser does which +means that :data:`~flask.g`, :data:`~flask.request` and others are not +available. But the code you want to test might depend on them, so what +can you do? + +This is where some helper functions come in handy. Keep in mind however +that these functions are not only there for interactive shell usage, but +also for unit testing and other situations that require a faked request +context. + +Generally it's recommended that you read :doc:`reqcontext` first. + +Command Line Interface +---------------------- + +Starting with Flask 0.11 the recommended way to work with the shell is the +``flask shell`` command which does a lot of this automatically for you. +For instance the shell is automatically initialized with a loaded +application context. + +For more information see :doc:`/cli`. + +Creating a Request Context +-------------------------- + +The easiest way to create a proper request context from the shell is by +using the :attr:`~flask.Flask.test_request_context` method which creates +us a :class:`~flask.ctx.RequestContext`: + +>>> ctx = app.test_request_context() + +Normally you would use the ``with`` statement to make this request object +active, but in the shell it's easier to use the +:meth:`~flask.ctx.RequestContext.push` and +:meth:`~flask.ctx.RequestContext.pop` methods by hand: + +>>> ctx.push() + +From that point onwards you can work with the request object until you +call `pop`: + +>>> ctx.pop() + +Firing Before/After Request +--------------------------- + +By just creating a request context, you still don't have run the code that +is normally run before a request. This might result in your database +being unavailable if you are connecting to the database in a +before-request callback or the current user not being stored on the +:data:`~flask.g` object etc. + +This however can easily be done yourself. Just call +:meth:`~flask.Flask.preprocess_request`: + +>>> ctx = app.test_request_context() +>>> ctx.push() +>>> app.preprocess_request() + +Keep in mind that the :meth:`~flask.Flask.preprocess_request` function +might return a response object, in that case just ignore it. + +To shutdown a request, you need to trick a bit before the after request +functions (triggered by :meth:`~flask.Flask.process_response`) operate on +a response object: + +>>> app.process_response(app.response_class()) + +>>> ctx.pop() + +The functions registered as :meth:`~flask.Flask.teardown_request` are +automatically called when the context is popped. So this is the perfect +place to automatically tear down resources that were needed by the request +context (such as database connections). + + +Further Improving the Shell Experience +-------------------------------------- + +If you like the idea of experimenting in a shell, create yourself a module +with stuff you want to star import into your interactive session. There +you could also define some more helper methods for common things such as +initializing the database, dropping tables etc. + +Just put them into a module (like `shelltools`) and import from there: + +>>> from shelltools import * diff --git a/_build/_sources/signals.rst.txt b/_build/_sources/signals.rst.txt new file mode 100644 index 00000000..739bb0b5 --- /dev/null +++ b/_build/_sources/signals.rst.txt @@ -0,0 +1,167 @@ +Signals +======= + +Signals are a lightweight way to notify subscribers of certain events during the +lifecycle of the application and each request. When an event occurs, it emits the +signal, which calls each subscriber. + +Signals are implemented by the `Blinker`_ library. See its documentation for detailed +information. Flask provides some built-in signals. Extensions may provide their own. + +Many signals mirror Flask's decorator-based callbacks with similar names. For example, +the :data:`.request_started` signal is similar to the :meth:`~.Flask.before_request` +decorator. The advantage of signals over handlers is that they can be subscribed to +temporarily, and can't directly affect the application. This is useful for testing, +metrics, auditing, and more. For example, if you want to know what templates were +rendered at what parts of what requests, there is a signal that will notify you of that +information. + + +Core Signals +------------ + +See :ref:`core-signals-list` for a list of all built-in signals. The :doc:`lifecycle` +page also describes the order that signals and decorators execute. + + +Subscribing to Signals +---------------------- + +To subscribe to a signal, you can use the +:meth:`~blinker.base.Signal.connect` method of a signal. The first +argument is the function that should be called when the signal is emitted, +the optional second argument specifies a sender. To unsubscribe from a +signal, you can use the :meth:`~blinker.base.Signal.disconnect` method. + +For all core Flask signals, the sender is the application that issued the +signal. When you subscribe to a signal, be sure to also provide a sender +unless you really want to listen for signals from all applications. This is +especially true if you are developing an extension. + +For example, here is a helper context manager that can be used in a unit test +to determine which templates were rendered and what variables were passed +to the template:: + + from flask import template_rendered + from contextlib import contextmanager + + @contextmanager + def captured_templates(app): + recorded = [] + def record(sender, template, context, **extra): + recorded.append((template, context)) + template_rendered.connect(record, app) + try: + yield recorded + finally: + template_rendered.disconnect(record, app) + +This can now easily be paired with a test client:: + + with captured_templates(app) as templates: + rv = app.test_client().get('/') + assert rv.status_code == 200 + assert len(templates) == 1 + template, context = templates[0] + assert template.name == 'index.html' + assert len(context['items']) == 10 + +Make sure to subscribe with an extra ``**extra`` argument so that your +calls don't fail if Flask introduces new arguments to the signals. + +All the template rendering in the code issued by the application `app` +in the body of the ``with`` block will now be recorded in the `templates` +variable. Whenever a template is rendered, the template object as well as +context are appended to it. + +Additionally there is a convenient helper method +(:meth:`~blinker.base.Signal.connected_to`) that allows you to +temporarily subscribe a function to a signal with a context manager on +its own. Because the return value of the context manager cannot be +specified that way, you have to pass the list in as an argument:: + + from flask import template_rendered + + def captured_templates(app, recorded, **extra): + def record(sender, template, context): + recorded.append((template, context)) + return template_rendered.connected_to(record, app) + +The example above would then look like this:: + + templates = [] + with captured_templates(app, templates, **extra): + ... + template, context = templates[0] + +Creating Signals +---------------- + +If you want to use signals in your own application, you can use the +blinker library directly. The most common use case are named signals in a +custom :class:`~blinker.base.Namespace`. This is what is recommended +most of the time:: + + from blinker import Namespace + my_signals = Namespace() + +Now you can create new signals like this:: + + model_saved = my_signals.signal('model-saved') + +The name for the signal here makes it unique and also simplifies +debugging. You can access the name of the signal with the +:attr:`~blinker.base.NamedSignal.name` attribute. + +.. _signals-sending: + +Sending Signals +--------------- + +If you want to emit a signal, you can do so by calling the +:meth:`~blinker.base.Signal.send` method. It accepts a sender as first +argument and optionally some keyword arguments that are forwarded to the +signal subscribers:: + + class Model(object): + ... + + def save(self): + model_saved.send(self) + +Try to always pick a good sender. If you have a class that is emitting a +signal, pass ``self`` as sender. If you are emitting a signal from a random +function, you can pass ``current_app._get_current_object()`` as sender. + +.. admonition:: Passing Proxies as Senders + + Never pass :data:`~flask.current_app` as sender to a signal. Use + ``current_app._get_current_object()`` instead. The reason for this is + that :data:`~flask.current_app` is a proxy and not the real application + object. + + +Signals and Flask's Request Context +----------------------------------- + +Signals fully support :doc:`reqcontext` when receiving signals. +Context-local variables are consistently available between +:data:`~flask.request_started` and :data:`~flask.request_finished`, so you can +rely on :class:`flask.g` and others as needed. Note the limitations described +in :ref:`signals-sending` and the :data:`~flask.request_tearing_down` signal. + + +Decorator Based Signal Subscriptions +------------------------------------ + +You can also easily subscribe to signals by using the +:meth:`~blinker.base.NamedSignal.connect_via` decorator:: + + from flask import template_rendered + + @template_rendered.connect_via(app) + def when_template_rendered(sender, template, context, **extra): + print(f'Template {template.name} is rendered with {context}') + + +.. _blinker: https://pypi.org/project/blinker/ diff --git a/_build/_sources/templating.rst.txt b/_build/_sources/templating.rst.txt new file mode 100644 index 00000000..23cfee4c --- /dev/null +++ b/_build/_sources/templating.rst.txt @@ -0,0 +1,229 @@ +Templates +========= + +Flask leverages Jinja2 as its template engine. You are obviously free to use +a different template engine, but you still have to install Jinja2 to run +Flask itself. This requirement is necessary to enable rich extensions. +An extension can depend on Jinja2 being present. + +This section only gives a very quick introduction into how Jinja2 +is integrated into Flask. If you want information on the template +engine's syntax itself, head over to the official `Jinja2 Template +Documentation `_ for +more information. + +Jinja Setup +----------- + +Unless customized, Jinja2 is configured by Flask as follows: + +- autoescaping is enabled for all templates ending in ``.html``, + ``.htm``, ``.xml``, ``.xhtml``, as well as ``.svg`` when using + :func:`~flask.templating.render_template`. +- autoescaping is enabled for all strings when using + :func:`~flask.templating.render_template_string`. +- a template has the ability to opt in/out autoescaping with the + ``{% autoescape %}`` tag. +- Flask inserts a couple of global functions and helpers into the + Jinja2 context, additionally to the values that are present by + default. + +Standard Context +---------------- + +The following global variables are available within Jinja2 templates +by default: + +.. data:: config + :noindex: + + The current configuration object (:data:`flask.Flask.config`) + + .. versionadded:: 0.6 + + .. versionchanged:: 0.10 + This is now always available, even in imported templates. + +.. data:: request + :noindex: + + The current request object (:class:`flask.request`). This variable is + unavailable if the template was rendered without an active request + context. + +.. data:: session + :noindex: + + The current session object (:class:`flask.session`). This variable + is unavailable if the template was rendered without an active request + context. + +.. data:: g + :noindex: + + The request-bound object for global variables (:data:`flask.g`). This + variable is unavailable if the template was rendered without an active + request context. + +.. function:: url_for + :noindex: + + The :func:`flask.url_for` function. + +.. function:: get_flashed_messages + :noindex: + + The :func:`flask.get_flashed_messages` function. + +.. admonition:: The Jinja Context Behavior + + These variables are added to the context of variables, they are not + global variables. The difference is that by default these will not + show up in the context of imported templates. This is partially caused + by performance considerations, partially to keep things explicit. + + What does this mean for you? If you have a macro you want to import, + that needs to access the request object you have two possibilities: + + 1. you explicitly pass the request to the macro as parameter, or + the attribute of the request object you are interested in. + 2. you import the macro "with context". + + Importing with context looks like this: + + .. sourcecode:: jinja + + {% from '_helpers.html' import my_macro with context %} + + +Controlling Autoescaping +------------------------ + +Autoescaping is the concept of automatically escaping special characters +for you. Special characters in the sense of HTML (or XML, and thus XHTML) +are ``&``, ``>``, ``<``, ``"`` as well as ``'``. Because these characters +carry specific meanings in documents on their own you have to replace them +by so called "entities" if you want to use them for text. Not doing so +would not only cause user frustration by the inability to use these +characters in text, but can also lead to security problems. (see +:ref:`security-xss`) + +Sometimes however you will need to disable autoescaping in templates. +This can be the case if you want to explicitly inject HTML into pages, for +example if they come from a system that generates secure HTML like a +markdown to HTML converter. + +There are three ways to accomplish that: + +- In the Python code, wrap the HTML string in a :class:`~markupsafe.Markup` + object before passing it to the template. This is in general the + recommended way. +- Inside the template, use the ``|safe`` filter to explicitly mark a + string as safe HTML (``{{ myvariable|safe }}``) +- Temporarily disable the autoescape system altogether. + +To disable the autoescape system in templates, you can use the ``{% +autoescape %}`` block: + +.. sourcecode:: html+jinja + + {% autoescape false %} +

autoescaping is disabled here +

{{ will_not_be_escaped }} + {% endautoescape %} + +Whenever you do this, please be very cautious about the variables you are +using in this block. + +.. _registering-filters: + +Registering Filters +------------------- + +If you want to register your own filters in Jinja2 you have two ways to do +that. You can either put them by hand into the +:attr:`~flask.Flask.jinja_env` of the application or use the +:meth:`~flask.Flask.template_filter` decorator. + +The two following examples work the same and both reverse an object:: + + @app.template_filter('reverse') + def reverse_filter(s): + return s[::-1] + + def reverse_filter(s): + return s[::-1] + app.jinja_env.filters['reverse'] = reverse_filter + +In case of the decorator the argument is optional if you want to use the +function name as name of the filter. Once registered, you can use the filter +in your templates in the same way as Jinja2's builtin filters, for example if +you have a Python list in context called `mylist`:: + + {% for x in mylist | reverse %} + {% endfor %} + + +Context Processors +------------------ + +To inject new variables automatically into the context of a template, +context processors exist in Flask. Context processors run before the +template is rendered and have the ability to inject new values into the +template context. A context processor is a function that returns a +dictionary. The keys and values of this dictionary are then merged with +the template context, for all templates in the app:: + + @app.context_processor + def inject_user(): + return dict(user=g.user) + +The context processor above makes a variable called `user` available in +the template with the value of `g.user`. This example is not very +interesting because `g` is available in templates anyways, but it gives an +idea how this works. + +Variables are not limited to values; a context processor can also make +functions available to templates (since Python allows passing around +functions):: + + @app.context_processor + def utility_processor(): + def format_price(amount, currency="€"): + return f"{amount:.2f}{currency}" + return dict(format_price=format_price) + +The context processor above makes the `format_price` function available to all +templates:: + + {{ format_price(0.33) }} + +You could also build `format_price` as a template filter (see +:ref:`registering-filters`), but this demonstrates how to pass functions in a +context processor. + +Streaming +--------- + +It can be useful to not render the whole template as one complete +string, instead render it as a stream, yielding smaller incremental +strings. This can be used for streaming HTML in chunks to speed up +initial page load, or to save memory when rendering a very large +template. + +The Jinja2 template engine supports rendering a template piece +by piece, returning an iterator of strings. Flask provides the +:func:`~flask.stream_template` and :func:`~flask.stream_template_string` +functions to make this easier to use. + +.. code-block:: python + + from flask import stream_template + + @app.get("/timeline") + def timeline(): + return stream_template("timeline.html") + +These functions automatically apply the +:func:`~flask.stream_with_context` wrapper if a request is active, so +that it remains available in the template. diff --git a/_build/_sources/testing.rst.txt b/_build/_sources/testing.rst.txt new file mode 100644 index 00000000..b1d52f9a --- /dev/null +++ b/_build/_sources/testing.rst.txt @@ -0,0 +1,319 @@ +Testing Flask Applications +========================== + +Flask provides utilities for testing an application. This documentation +goes over techniques for working with different parts of the application +in tests. + +We will use the `pytest`_ framework to set up and run our tests. + +.. code-block:: text + + $ pip install pytest + +.. _pytest: https://docs.pytest.org/ + +The :doc:`tutorial ` goes over how to write tests for +100% coverage of the sample Flaskr blog application. See +:doc:`the tutorial on tests ` for a detailed +explanation of specific tests for an application. + + +Identifying Tests +----------------- + +Tests are typically located in the ``tests`` folder. Tests are functions +that start with ``test_``, in Python modules that start with ``test_``. +Tests can also be further grouped in classes that start with ``Test``. + +It can be difficult to know what to test. Generally, try to test the +code that you write, not the code of libraries that you use, since they +are already tested. Try to extract complex behaviors as separate +functions to test individually. + + +Fixtures +-------- + +Pytest *fixtures* allow writing pieces of code that are reusable across +tests. A simple fixture returns a value, but a fixture can also do +setup, yield a value, then do teardown. Fixtures for the application, +test client, and CLI runner are shown below, they can be placed in +``tests/conftest.py``. + +If you're using an +:doc:`application factory `, define an ``app`` +fixture to create and configure an app instance. You can add code before +and after the ``yield`` to set up and tear down other resources, such as +creating and clearing a database. + +If you're not using a factory, you already have an app object you can +import and configure directly. You can still use an ``app`` fixture to +set up and tear down resources. + +.. code-block:: python + + import pytest + from my_project import create_app + + @pytest.fixture() + def app(): + app = create_app() + app.config.update({ + "TESTING": True, + }) + + # other setup can go here + + yield app + + # clean up / reset resources here + + + @pytest.fixture() + def client(app): + return app.test_client() + + + @pytest.fixture() + def runner(app): + return app.test_cli_runner() + + +Sending Requests with the Test Client +------------------------------------- + +The test client makes requests to the application without running a live +server. Flask's client extends +:doc:`Werkzeug's client `, see those docs for additional +information. + +The ``client`` has methods that match the common HTTP request methods, +such as ``client.get()`` and ``client.post()``. They take many arguments +for building the request; you can find the full documentation in +:class:`~werkzeug.test.EnvironBuilder`. Typically you'll use ``path``, +``query_string``, ``headers``, and ``data`` or ``json``. + +To make a request, call the method the request should use with the path +to the route to test. A :class:`~werkzeug.test.TestResponse` is returned +to examine the response data. It has all the usual properties of a +response object. You'll usually look at ``response.data``, which is the +bytes returned by the view. If you want to use text, Werkzeug 2.1 +provides ``response.text``, or use ``response.get_data(as_text=True)``. + +.. code-block:: python + + def test_request_example(client): + response = client.get("/posts") + assert b"

Hello, World!

" in response.data + + +Pass a dict ``query_string={"key": "value", ...}`` to set arguments in +the query string (after the ``?`` in the URL). Pass a dict +``headers={}`` to set request headers. + +To send a request body in a POST or PUT request, pass a value to +``data``. If raw bytes are passed, that exact body is used. Usually, +you'll pass a dict to set form data. + + +Form Data +~~~~~~~~~ + +To send form data, pass a dict to ``data``. The ``Content-Type`` header +will be set to ``multipart/form-data`` or +``application/x-www-form-urlencoded`` automatically. + +If a value is a file object opened for reading bytes (``"rb"`` mode), it +will be treated as an uploaded file. To change the detected filename and +content type, pass a ``(file, filename, content_type)`` tuple. File +objects will be closed after making the request, so they do not need to +use the usual ``with open() as f:`` pattern. + +It can be useful to store files in a ``tests/resources`` folder, then +use ``pathlib.Path`` to get files relative to the current test file. + +.. code-block:: python + + from pathlib import Path + + # get the resources folder in the tests folder + resources = Path(__file__).parent / "resources" + + def test_edit_user(client): + response = client.post("/user/2/edit", data={ + "name": "Flask", + "theme": "dark", + "picture": (resources / "picture.png").open("rb"), + }) + assert response.status_code == 200 + + +JSON Data +~~~~~~~~~ + +To send JSON data, pass an object to ``json``. The ``Content-Type`` +header will be set to ``application/json`` automatically. + +Similarly, if the response contains JSON data, the ``response.json`` +attribute will contain the deserialized object. + +.. code-block:: python + + def test_json_data(client): + response = client.post("/graphql", json={ + "query": """ + query User($id: String!) { + user(id: $id) { + name + theme + picture_url + } + } + """, + variables={"id": 2}, + }) + assert response.json["data"]["user"]["name"] == "Flask" + + +Following Redirects +------------------- + +By default, the client does not make additional requests if the response +is a redirect. By passing ``follow_redirects=True`` to a request method, +the client will continue to make requests until a non-redirect response +is returned. + +:attr:`TestResponse.history ` is +a tuple of the responses that led up to the final response. Each +response has a :attr:`~werkzeug.test.TestResponse.request` attribute +which records the request that produced that response. + +.. code-block:: python + + def test_logout_redirect(client): + response = client.get("/logout", follow_redirects=True) + # Check that there was one redirect response. + assert len(response.history) == 1 + # Check that the second request was to the index page. + assert response.request.path == "/index" + + +Accessing and Modifying the Session +----------------------------------- + +To access Flask's context variables, mainly +:data:`~flask.session`, use the client in a ``with`` statement. +The app and request context will remain active *after* making a request, +until the ``with`` block ends. + +.. code-block:: python + + from flask import session + + def test_access_session(client): + with client: + client.post("/auth/login", data={"username": "flask"}) + # session is still accessible + assert session["user_id"] == 1 + + # session is no longer accessible + +If you want to access or set a value in the session *before* making a +request, use the client's +:meth:`~flask.testing.FlaskClient.session_transaction` method in a +``with`` statement. It returns a session object, and will save the +session once the block ends. + +.. code-block:: python + + from flask import session + + def test_modify_session(client): + with client.session_transaction() as session: + # set a user id without going through the login route + session["user_id"] = 1 + + # session is saved now + + response = client.get("/users/me") + assert response.json["username"] == "flask" + + +.. _testing-cli: + +Running Commands with the CLI Runner +------------------------------------ + +Flask provides :meth:`~flask.Flask.test_cli_runner` to create a +:class:`~flask.testing.FlaskCliRunner`, which runs CLI commands in +isolation and captures the output in a :class:`~click.testing.Result` +object. Flask's runner extends :doc:`Click's runner `, +see those docs for additional information. + +Use the runner's :meth:`~flask.testing.FlaskCliRunner.invoke` method to +call commands in the same way they would be called with the ``flask`` +command from the command line. + +.. code-block:: python + + import click + + @app.cli.command("hello") + @click.option("--name", default="World") + def hello_command(name): + click.echo(f"Hello, {name}!") + + def test_hello_command(runner): + result = runner.invoke(args="hello") + assert "World" in result.output + + result = runner.invoke(args=["hello", "--name", "Flask"]) + assert "Flask" in result.output + + +Tests that depend on an Active Context +-------------------------------------- + +You may have functions that are called from views or commands, that +expect an active :doc:`application context ` or +:doc:`request context ` because they access ``request``, +``session``, or ``current_app``. Rather than testing them by making a +request or invoking the command, you can create and activate a context +directly. + +Use ``with app.app_context()`` to push an application context. For +example, database extensions usually require an active app context to +make queries. + +.. code-block:: python + + def test_db_post_model(app): + with app.app_context(): + post = db.session.query(Post).get(1) + +Use ``with app.test_request_context()`` to push a request context. It +takes the same arguments as the test client's request methods. + +.. code-block:: python + + def test_validate_user_edit(app): + with app.test_request_context( + "/user/2/edit", method="POST", data={"name": ""} + ): + # call a function that accesses `request` + messages = validate_edit_user() + + assert messages["name"][0] == "Name cannot be empty." + +Creating a test request context doesn't run any of the Flask dispatching +code, so ``before_request`` functions are not called. If you need to +call these, usually it's better to make a full request instead. However, +it's possible to call them manually. + +.. code-block:: python + + def test_auth_token(app): + with app.test_request_context("/user/2/edit", headers={"X-Auth-Token": "1"}): + app.preprocess_request() + assert g.user.name == "Flask" diff --git a/_build/_sources/tutorial/blog.rst.txt b/_build/_sources/tutorial/blog.rst.txt new file mode 100644 index 00000000..b06329ea --- /dev/null +++ b/_build/_sources/tutorial/blog.rst.txt @@ -0,0 +1,336 @@ +.. currentmodule:: flask + +Blog Blueprint +============== + +You'll use the same techniques you learned about when writing the +authentication blueprint to write the blog blueprint. The blog should +list all posts, allow logged in users to create posts, and allow the +author of a post to edit or delete it. + +As you implement each view, keep the development server running. As you +save your changes, try going to the URL in your browser and testing them +out. + +The Blueprint +------------- + +Define the blueprint and register it in the application factory. + +.. code-block:: python + :caption: ``flaskr/blog.py`` + + from flask import ( + Blueprint, flash, g, redirect, render_template, request, url_for + ) + from werkzeug.exceptions import abort + + from flaskr.auth import login_required + from flaskr.db import get_db + + bp = Blueprint('blog', __name__) + +Import and register the blueprint from the factory using +:meth:`app.register_blueprint() `. Place the +new code at the end of the factory function before returning the app. + +.. code-block:: python + :caption: ``flaskr/__init__.py`` + + def create_app(): + app = ... + # existing code omitted + + from . import blog + app.register_blueprint(blog.bp) + app.add_url_rule('/', endpoint='index') + + return app + + +Unlike the auth blueprint, the blog blueprint does not have a +``url_prefix``. So the ``index`` view will be at ``/``, the ``create`` +view at ``/create``, and so on. The blog is the main feature of Flaskr, +so it makes sense that the blog index will be the main index. + +However, the endpoint for the ``index`` view defined below will be +``blog.index``. Some of the authentication views referred to a plain +``index`` endpoint. :meth:`app.add_url_rule() ` +associates the endpoint name ``'index'`` with the ``/`` url so that +``url_for('index')`` or ``url_for('blog.index')`` will both work, +generating the same ``/`` URL either way. + +In another application you might give the blog blueprint a +``url_prefix`` and define a separate ``index`` view in the application +factory, similar to the ``hello`` view. Then the ``index`` and +``blog.index`` endpoints and URLs would be different. + + +Index +----- + +The index will show all of the posts, most recent first. A ``JOIN`` is +used so that the author information from the ``user`` table is +available in the result. + +.. code-block:: python + :caption: ``flaskr/blog.py`` + + @bp.route('/') + def index(): + db = get_db() + posts = db.execute( + 'SELECT p.id, title, body, created, author_id, username' + ' FROM post p JOIN user u ON p.author_id = u.id' + ' ORDER BY created DESC' + ).fetchall() + return render_template('blog/index.html', posts=posts) + +.. code-block:: html+jinja + :caption: ``flaskr/templates/blog/index.html`` + + {% extends 'base.html' %} + + {% block header %} +

{% block title %}Posts{% endblock %}

+ {% if g.user %} + New + {% endif %} + {% endblock %} + + {% block content %} + {% for post in posts %} +
+
+
+

{{ post['title'] }}

+
by {{ post['username'] }} on {{ post['created'].strftime('%Y-%m-%d') }}
+
+ {% if g.user['id'] == post['author_id'] %} + Edit + {% endif %} +
+

{{ post['body'] }}

+
+ {% if not loop.last %} +
+ {% endif %} + {% endfor %} + {% endblock %} + +When a user is logged in, the ``header`` block adds a link to the +``create`` view. When the user is the author of a post, they'll see an +"Edit" link to the ``update`` view for that post. ``loop.last`` is a +special variable available inside `Jinja for loops`_. It's used to +display a line after each post except the last one, to visually separate +them. + +.. _Jinja for loops: https://jinja.palletsprojects.com/templates/#for + + +Create +------ + +The ``create`` view works the same as the auth ``register`` view. Either +the form is displayed, or the posted data is validated and the post is +added to the database or an error is shown. + +The ``login_required`` decorator you wrote earlier is used on the blog +views. A user must be logged in to visit these views, otherwise they +will be redirected to the login page. + +.. code-block:: python + :caption: ``flaskr/blog.py`` + + @bp.route('/create', methods=('GET', 'POST')) + @login_required + def create(): + if request.method == 'POST': + title = request.form['title'] + body = request.form['body'] + error = None + + if not title: + error = 'Title is required.' + + if error is not None: + flash(error) + else: + db = get_db() + db.execute( + 'INSERT INTO post (title, body, author_id)' + ' VALUES (?, ?, ?)', + (title, body, g.user['id']) + ) + db.commit() + return redirect(url_for('blog.index')) + + return render_template('blog/create.html') + +.. code-block:: html+jinja + :caption: ``flaskr/templates/blog/create.html`` + + {% extends 'base.html' %} + + {% block header %} +

{% block title %}New Post{% endblock %}

+ {% endblock %} + + {% block content %} +
+ + + + + +
+ {% endblock %} + + +Update +------ + +Both the ``update`` and ``delete`` views will need to fetch a ``post`` +by ``id`` and check if the author matches the logged in user. To avoid +duplicating code, you can write a function to get the ``post`` and call +it from each view. + +.. code-block:: python + :caption: ``flaskr/blog.py`` + + def get_post(id, check_author=True): + post = get_db().execute( + 'SELECT p.id, title, body, created, author_id, username' + ' FROM post p JOIN user u ON p.author_id = u.id' + ' WHERE p.id = ?', + (id,) + ).fetchone() + + if post is None: + abort(404, f"Post id {id} doesn't exist.") + + if check_author and post['author_id'] != g.user['id']: + abort(403) + + return post + +:func:`abort` will raise a special exception that returns an HTTP status +code. It takes an optional message to show with the error, otherwise a +default message is used. ``404`` means "Not Found", and ``403`` means +"Forbidden". (``401`` means "Unauthorized", but you redirect to the +login page instead of returning that status.) + +The ``check_author`` argument is defined so that the function can be +used to get a ``post`` without checking the author. This would be useful +if you wrote a view to show an individual post on a page, where the user +doesn't matter because they're not modifying the post. + +.. code-block:: python + :caption: ``flaskr/blog.py`` + + @bp.route('//update', methods=('GET', 'POST')) + @login_required + def update(id): + post = get_post(id) + + if request.method == 'POST': + title = request.form['title'] + body = request.form['body'] + error = None + + if not title: + error = 'Title is required.' + + if error is not None: + flash(error) + else: + db = get_db() + db.execute( + 'UPDATE post SET title = ?, body = ?' + ' WHERE id = ?', + (title, body, id) + ) + db.commit() + return redirect(url_for('blog.index')) + + return render_template('blog/update.html', post=post) + +Unlike the views you've written so far, the ``update`` function takes +an argument, ``id``. That corresponds to the ```` in the route. +A real URL will look like ``/1/update``. Flask will capture the ``1``, +ensure it's an :class:`int`, and pass it as the ``id`` argument. If you +don't specify ``int:`` and instead do ````, it will be a string. +To generate a URL to the update page, :func:`url_for` needs to be passed +the ``id`` so it knows what to fill in: +``url_for('blog.update', id=post['id'])``. This is also in the +``index.html`` file above. + +The ``create`` and ``update`` views look very similar. The main +difference is that the ``update`` view uses a ``post`` object and an +``UPDATE`` query instead of an ``INSERT``. With some clever refactoring, +you could use one view and template for both actions, but for the +tutorial it's clearer to keep them separate. + +.. code-block:: html+jinja + :caption: ``flaskr/templates/blog/update.html`` + + {% extends 'base.html' %} + + {% block header %} +

{% block title %}Edit "{{ post['title'] }}"{% endblock %}

+ {% endblock %} + + {% block content %} +
+ + + + + +
+
+
+ +
+ {% endblock %} + +This template has two forms. The first posts the edited data to the +current page (``//update``). The other form contains only a button +and specifies an ``action`` attribute that posts to the delete view +instead. The button uses some JavaScript to show a confirmation dialog +before submitting. + +The pattern ``{{ request.form['title'] or post['title'] }}`` is used to +choose what data appears in the form. When the form hasn't been +submitted, the original ``post`` data appears, but if invalid form data +was posted you want to display that so the user can fix the error, so +``request.form`` is used instead. :data:`request` is another variable +that's automatically available in templates. + + +Delete +------ + +The delete view doesn't have its own template, the delete button is part +of ``update.html`` and posts to the ``//delete`` URL. Since there +is no template, it will only handle the ``POST`` method and then redirect +to the ``index`` view. + +.. code-block:: python + :caption: ``flaskr/blog.py`` + + @bp.route('//delete', methods=('POST',)) + @login_required + def delete(id): + get_post(id) + db = get_db() + db.execute('DELETE FROM post WHERE id = ?', (id,)) + db.commit() + return redirect(url_for('blog.index')) + +Congratulations, you've now finished writing your application! Take some +time to try out everything in the browser. However, there's still more +to do before the project is complete. + +Continue to :doc:`install`. diff --git a/_build/_sources/tutorial/database.rst.txt b/_build/_sources/tutorial/database.rst.txt new file mode 100644 index 00000000..93abf93a --- /dev/null +++ b/_build/_sources/tutorial/database.rst.txt @@ -0,0 +1,219 @@ +.. currentmodule:: flask + +Define and Access the Database +============================== + +The application will use a `SQLite`_ database to store users and posts. +Python comes with built-in support for SQLite in the :mod:`sqlite3` +module. + +SQLite is convenient because it doesn't require setting up a separate +database server and is built-in to Python. However, if concurrent +requests try to write to the database at the same time, they will slow +down as each write happens sequentially. Small applications won't notice +this. Once you become big, you may want to switch to a different +database. + +The tutorial doesn't go into detail about SQL. If you are not familiar +with it, the SQLite docs describe the `language`_. + +.. _SQLite: https://sqlite.org/about.html +.. _language: https://sqlite.org/lang.html + + +Connect to the Database +----------------------- + +The first thing to do when working with a SQLite database (and most +other Python database libraries) is to create a connection to it. Any +queries and operations are performed using the connection, which is +closed after the work is finished. + +In web applications this connection is typically tied to the request. It +is created at some point when handling a request, and closed before the +response is sent. + +.. code-block:: python + :caption: ``flaskr/db.py`` + + import sqlite3 + from datetime import datetime + + import click + from flask import current_app, g + + + def get_db(): + if 'db' not in g: + g.db = sqlite3.connect( + current_app.config['DATABASE'], + detect_types=sqlite3.PARSE_DECLTYPES + ) + g.db.row_factory = sqlite3.Row + + return g.db + + + def close_db(e=None): + db = g.pop('db', None) + + if db is not None: + db.close() + +:data:`g` is a special object that is unique for each request. It is +used to store data that might be accessed by multiple functions during +the request. The connection is stored and reused instead of creating a +new connection if ``get_db`` is called a second time in the same +request. + +:data:`current_app` is another special object that points to the Flask +application handling the request. Since you used an application factory, +there is no application object when writing the rest of your code. +``get_db`` will be called when the application has been created and is +handling a request, so :data:`current_app` can be used. + +:func:`sqlite3.connect` establishes a connection to the file pointed at +by the ``DATABASE`` configuration key. This file doesn't have to exist +yet, and won't until you initialize the database later. + +:class:`sqlite3.Row` tells the connection to return rows that behave +like dicts. This allows accessing the columns by name. + +``close_db`` checks if a connection was created by checking if ``g.db`` +was set. If the connection exists, it is closed. Further down you will +tell your application about the ``close_db`` function in the application +factory so that it is called after each request. + + +Create the Tables +----------------- + +In SQLite, data is stored in *tables* and *columns*. These need to be +created before you can store and retrieve data. Flaskr will store users +in the ``user`` table, and posts in the ``post`` table. Create a file +with the SQL commands needed to create empty tables: + +.. code-block:: sql + :caption: ``flaskr/schema.sql`` + + DROP TABLE IF EXISTS user; + DROP TABLE IF EXISTS post; + + CREATE TABLE user ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + username TEXT UNIQUE NOT NULL, + password TEXT NOT NULL + ); + + CREATE TABLE post ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + author_id INTEGER NOT NULL, + created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + title TEXT NOT NULL, + body TEXT NOT NULL, + FOREIGN KEY (author_id) REFERENCES user (id) + ); + +Add the Python functions that will run these SQL commands to the +``db.py`` file: + +.. code-block:: python + :caption: ``flaskr/db.py`` + + def init_db(): + db = get_db() + + with current_app.open_resource('schema.sql') as f: + db.executescript(f.read().decode('utf8')) + + + @click.command('init-db') + def init_db_command(): + """Clear the existing data and create new tables.""" + init_db() + click.echo('Initialized the database.') + + + sqlite3.register_converter( + "timestamp", lambda v: datetime.fromisoformat(v.decode()) + ) + +:meth:`open_resource() ` opens a file relative to +the ``flaskr`` package, which is useful since you won't necessarily know +where that location is when deploying the application later. ``get_db`` +returns a database connection, which is used to execute the commands +read from the file. + +:func:`click.command` defines a command line command called ``init-db`` +that calls the ``init_db`` function and shows a success message to the +user. You can read :doc:`/cli` to learn more about writing commands. + +The call to :func:`sqlite3.register_converter` tells Python how to +interpret timestamp values in the database. We convert the value to a +:class:`datetime.datetime`. + + +Register with the Application +----------------------------- + +The ``close_db`` and ``init_db_command`` functions need to be registered +with the application instance; otherwise, they won't be used by the +application. However, since you're using a factory function, that +instance isn't available when writing the functions. Instead, write a +function that takes an application and does the registration. + +.. code-block:: python + :caption: ``flaskr/db.py`` + + def init_app(app): + app.teardown_appcontext(close_db) + app.cli.add_command(init_db_command) + +:meth:`app.teardown_appcontext() ` tells +Flask to call that function when cleaning up after returning the +response. + +:meth:`app.cli.add_command() ` adds a new +command that can be called with the ``flask`` command. + +Import and call this function from the factory. Place the new code at +the end of the factory function before returning the app. + +.. code-block:: python + :caption: ``flaskr/__init__.py`` + + def create_app(): + app = ... + # existing code omitted + + from . import db + db.init_app(app) + + return app + + +Initialize the Database File +---------------------------- + +Now that ``init-db`` has been registered with the app, it can be called +using the ``flask`` command, similar to the ``run`` command from the +previous page. + +.. note:: + + If you're still running the server from the previous page, you can + either stop the server, or run this command in a new terminal. If + you use a new terminal, remember to change to your project directory + and activate the env as described in :doc:`/installation`. + +Run the ``init-db`` command: + +.. code-block:: none + + $ flask --app flaskr init-db + Initialized the database. + +There will now be a ``flaskr.sqlite`` file in the ``instance`` folder in +your project. + +Continue to :doc:`views`. diff --git a/_build/_sources/tutorial/deploy.rst.txt b/_build/_sources/tutorial/deploy.rst.txt new file mode 100644 index 00000000..eb3a53ac --- /dev/null +++ b/_build/_sources/tutorial/deploy.rst.txt @@ -0,0 +1,111 @@ +Deploy to Production +==================== + +This part of the tutorial assumes you have a server that you want to +deploy your application to. It gives an overview of how to create the +distribution file and install it, but won't go into specifics about +what server or software to use. You can set up a new environment on your +development computer to try out the instructions below, but probably +shouldn't use it for hosting a real public application. See +:doc:`/deploying/index` for a list of many different ways to host your +application. + + +Build and Install +----------------- + +When you want to deploy your application elsewhere, you build a *wheel* +(``.whl``) file. Install and use the ``build`` tool to do this. + +.. code-block:: none + + $ pip install build + $ python -m build --wheel + +You can find the file in ``dist/flaskr-1.0.0-py3-none-any.whl``. The +file name is in the format of {project name}-{version}-{python tag} +-{abi tag}-{platform tag}. + +Copy this file to another machine, +:ref:`set up a new virtualenv `, then install the +file with ``pip``. + +.. code-block:: none + + $ pip install flaskr-1.0.0-py3-none-any.whl + +Pip will install your project along with its dependencies. + +Since this is a different machine, you need to run ``init-db`` again to +create the database in the instance folder. + + .. code-block:: text + + $ flask --app flaskr init-db + +When Flask detects that it's installed (not in editable mode), it uses +a different directory for the instance folder. You can find it at +``.venv/var/flaskr-instance`` instead. + + +Configure the Secret Key +------------------------ + +In the beginning of the tutorial that you gave a default value for +:data:`SECRET_KEY`. This should be changed to some random bytes in +production. Otherwise, attackers could use the public ``'dev'`` key to +modify the session cookie, or anything else that uses the secret key. + +You can use the following command to output a random secret key: + +.. code-block:: none + + $ python -c 'import secrets; print(secrets.token_hex())' + + '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf' + +Create the ``config.py`` file in the instance folder, which the factory +will read from if it exists. Copy the generated value into it. + +.. code-block:: python + :caption: ``.venv/var/flaskr-instance/config.py`` + + SECRET_KEY = '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf' + +You can also set any other necessary configuration here, although +``SECRET_KEY`` is the only one needed for Flaskr. + + +Run with a Production Server +---------------------------- + +When running publicly rather than in development, you should not use the +built-in development server (``flask run``). The development server is +provided by Werkzeug for convenience, but is not designed to be +particularly efficient, stable, or secure. + +Instead, use a production WSGI server. For example, to use `Waitress`_, +first install it in the virtual environment: + +.. code-block:: none + + $ pip install waitress + +You need to tell Waitress about your application, but it doesn't use +``--app`` like ``flask run`` does. You need to tell it to import and +call the application factory to get an application object. + +.. code-block:: none + + $ waitress-serve --call 'flaskr:create_app' + + Serving on http://0.0.0.0:8080 + +See :doc:`/deploying/index` for a list of many different ways to host +your application. Waitress is just an example, chosen for the tutorial +because it supports both Windows and Linux. There are many more WSGI +servers and deployment options that you may choose for your project. + +.. _Waitress: https://docs.pylonsproject.org/projects/waitress/en/stable/ + +Continue to :doc:`next`. diff --git a/_build/_sources/tutorial/factory.rst.txt b/_build/_sources/tutorial/factory.rst.txt new file mode 100644 index 00000000..39febd13 --- /dev/null +++ b/_build/_sources/tutorial/factory.rst.txt @@ -0,0 +1,162 @@ +.. currentmodule:: flask + +Application Setup +================= + +A Flask application is an instance of the :class:`Flask` class. +Everything about the application, such as configuration and URLs, will +be registered with this class. + +The most straightforward way to create a Flask application is to create +a global :class:`Flask` instance directly at the top of your code, like +how the "Hello, World!" example did on the previous page. While this is +simple and useful in some cases, it can cause some tricky issues as the +project grows. + +Instead of creating a :class:`Flask` instance globally, you will create +it inside a function. This function is known as the *application +factory*. Any configuration, registration, and other setup the +application needs will happen inside the function, then the application +will be returned. + + +The Application Factory +----------------------- + +It's time to start coding! Create the ``flaskr`` directory and add the +``__init__.py`` file. The ``__init__.py`` serves double duty: it will +contain the application factory, and it tells Python that the ``flaskr`` +directory should be treated as a package. + +.. code-block:: none + + $ mkdir flaskr + +.. code-block:: python + :caption: ``flaskr/__init__.py`` + + import os + + from flask import Flask + + + def create_app(test_config=None): + # create and configure the app + app = Flask(__name__, instance_relative_config=True) + app.config.from_mapping( + SECRET_KEY='dev', + DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'), + ) + + if test_config is None: + # load the instance config, if it exists, when not testing + app.config.from_pyfile('config.py', silent=True) + else: + # load the test config if passed in + app.config.from_mapping(test_config) + + # ensure the instance folder exists + try: + os.makedirs(app.instance_path) + except OSError: + pass + + # a simple page that says hello + @app.route('/hello') + def hello(): + return 'Hello, World!' + + return app + +``create_app`` is the application factory function. You'll add to it +later in the tutorial, but it already does a lot. + +#. ``app = Flask(__name__, instance_relative_config=True)`` creates the + :class:`Flask` instance. + + * ``__name__`` is the name of the current Python module. The app + needs to know where it's located to set up some paths, and + ``__name__`` is a convenient way to tell it that. + + * ``instance_relative_config=True`` tells the app that + configuration files are relative to the + :ref:`instance folder `. The instance folder + is located outside the ``flaskr`` package and can hold local + data that shouldn't be committed to version control, such as + configuration secrets and the database file. + +#. :meth:`app.config.from_mapping() ` sets + some default configuration that the app will use: + + * :data:`SECRET_KEY` is used by Flask and extensions to keep data + safe. It's set to ``'dev'`` to provide a convenient value + during development, but it should be overridden with a random + value when deploying. + + * ``DATABASE`` is the path where the SQLite database file will be + saved. It's under + :attr:`app.instance_path `, which is the + path that Flask has chosen for the instance folder. You'll learn + more about the database in the next section. + +#. :meth:`app.config.from_pyfile() ` overrides + the default configuration with values taken from the ``config.py`` + file in the instance folder if it exists. For example, when + deploying, this can be used to set a real ``SECRET_KEY``. + + * ``test_config`` can also be passed to the factory, and will be + used instead of the instance configuration. This is so the tests + you'll write later in the tutorial can be configured + independently of any development values you have configured. + +#. :func:`os.makedirs` ensures that + :attr:`app.instance_path ` exists. Flask + doesn't create the instance folder automatically, but it needs to be + created because your project will create the SQLite database file + there. + +#. :meth:`@app.route() ` creates a simple route so you can + see the application working before getting into the rest of the + tutorial. It creates a connection between the URL ``/hello`` and a + function that returns a response, the string ``'Hello, World!'`` in + this case. + + +Run The Application +------------------- + +Now you can run your application using the ``flask`` command. From the +terminal, tell Flask where to find your application, then run it in +debug mode. Remember, you should still be in the top-level +``flask-tutorial`` directory, not the ``flaskr`` package. + +Debug mode shows an interactive debugger whenever a page raises an +exception, and restarts the server whenever you make changes to the +code. You can leave it running and just reload the browser page as you +follow the tutorial. + +.. code-block:: text + + $ flask --app flaskr run --debug + +You'll see output similar to this: + +.. code-block:: text + + * Serving Flask app "flaskr" + * Debug mode: on + * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) + * Restarting with stat + * Debugger is active! + * Debugger PIN: nnn-nnn-nnn + +Visit http://127.0.0.1:5000/hello in a browser and you should see the +"Hello, World!" message. Congratulations, you're now running your Flask +web application! + +If another program is already using port 5000, you'll see +``OSError: [Errno 98]`` or ``OSError: [WinError 10013]`` when the +server tries to start. See :ref:`address-already-in-use` for how to +handle that. + +Continue to :doc:`database`. diff --git a/_build/_sources/tutorial/index.rst.txt b/_build/_sources/tutorial/index.rst.txt new file mode 100644 index 00000000..d5dc5b3c --- /dev/null +++ b/_build/_sources/tutorial/index.rst.txt @@ -0,0 +1,64 @@ +Tutorial +======== + +.. toctree:: + :caption: Contents: + :maxdepth: 1 + + layout + factory + database + views + templates + static + blog + install + tests + deploy + next + +This tutorial will walk you through creating a basic blog application +called Flaskr. Users will be able to register, log in, create posts, +and edit or delete their own posts. You will be able to package and +install the application on other computers. + +.. image:: flaskr_index.png + :align: center + :class: screenshot + :alt: screenshot of index page + +It's assumed that you're already familiar with Python. The `official +tutorial`_ in the Python docs is a great way to learn or review first. + +.. _official tutorial: https://docs.python.org/3/tutorial/ + +While it's designed to give a good starting point, the tutorial doesn't +cover all of Flask's features. Check out the :doc:`/quickstart` for an +overview of what Flask can do, then dive into the docs to find out more. +The tutorial only uses what's provided by Flask and Python. In another +project, you might decide to use :doc:`/extensions` or other libraries +to make some tasks simpler. + +.. image:: flaskr_login.png + :align: center + :class: screenshot + :alt: screenshot of login page + +Flask is flexible. It doesn't require you to use any particular project +or code layout. However, when first starting, it's helpful to use a more +structured approach. This means that the tutorial will require a bit of +boilerplate up front, but it's done to avoid many common pitfalls that +new developers encounter, and it creates a project that's easy to expand +on. Once you become more comfortable with Flask, you can step out of +this structure and take full advantage of Flask's flexibility. + +.. image:: flaskr_edit.png + :align: center + :class: screenshot + :alt: screenshot of edit page + +:gh:`The tutorial project is available as an example in the Flask +repository `, if you want to compare your project +with the final product as you follow the tutorial. + +Continue to :doc:`layout`. diff --git a/_build/_sources/tutorial/install.rst.txt b/_build/_sources/tutorial/install.rst.txt new file mode 100644 index 00000000..db83e106 --- /dev/null +++ b/_build/_sources/tutorial/install.rst.txt @@ -0,0 +1,89 @@ +Make the Project Installable +============================ + +Making your project installable means that you can build a *wheel* file and install that +in another environment, just like you installed Flask in your project's environment. +This makes deploying your project the same as installing any other library, so you're +using all the standard Python tools to manage everything. + +Installing also comes with other benefits that might not be obvious from +the tutorial or as a new Python user, including: + +* Currently, Python and Flask understand how to use the ``flaskr`` + package only because you're running from your project's directory. + Installing means you can import it no matter where you run from. + +* You can manage your project's dependencies just like other packages + do, so ``pip install yourproject.whl`` installs them. + +* Test tools can isolate your test environment from your development + environment. + +.. note:: + This is being introduced late in the tutorial, but in your future + projects you should always start with this. + + +Describe the Project +-------------------- + +The ``pyproject.toml`` file describes your project and how to build it. + +.. code-block:: toml + :caption: ``pyproject.toml`` + + [project] + name = "flaskr" + version = "1.0.0" + description = "The basic blog app built in the Flask tutorial." + dependencies = [ + "flask", + ] + + [build-system] + requires = ["flit_core<4"] + build-backend = "flit_core.buildapi" + +See the official `Packaging tutorial `_ for more +explanation of the files and options used. + +.. _packaging tutorial: https://packaging.python.org/tutorials/packaging-projects/ + + +Install the Project +------------------- + +Use ``pip`` to install your project in the virtual environment. + +.. code-block:: none + + $ pip install -e . + +This tells pip to find ``pyproject.toml`` in the current directory and install the +project in *editable* or *development* mode. Editable mode means that as you make +changes to your local code, you'll only need to re-install if you change the metadata +about the project, such as its dependencies. + +You can observe that the project is now installed with ``pip list``. + +.. code-block:: none + + $ pip list + + Package Version Location + -------------- --------- ---------------------------------- + click 6.7 + Flask 1.0 + flaskr 1.0.0 /home/user/Projects/flask-tutorial + itsdangerous 0.24 + Jinja2 2.10 + MarkupSafe 1.0 + pip 9.0.3 + Werkzeug 0.14.1 + +Nothing changes from how you've been running your project so far. +``--app`` is still set to ``flaskr`` and ``flask run`` still runs +the application, but you can call it from anywhere, not just the +``flask-tutorial`` directory. + +Continue to :doc:`tests`. diff --git a/_build/_sources/tutorial/layout.rst.txt b/_build/_sources/tutorial/layout.rst.txt new file mode 100644 index 00000000..6f8e59f4 --- /dev/null +++ b/_build/_sources/tutorial/layout.rst.txt @@ -0,0 +1,110 @@ +Project Layout +============== + +Create a project directory and enter it: + +.. code-block:: none + + $ mkdir flask-tutorial + $ cd flask-tutorial + +Then follow the :doc:`installation instructions ` to set +up a Python virtual environment and install Flask for your project. + +The tutorial will assume you're working from the ``flask-tutorial`` +directory from now on. The file names at the top of each code block are +relative to this directory. + +---- + +A Flask application can be as simple as a single file. + +.. code-block:: python + :caption: ``hello.py`` + + from flask import Flask + + app = Flask(__name__) + + + @app.route('/') + def hello(): + return 'Hello, World!' + +However, as a project gets bigger, it becomes overwhelming to keep all +the code in one file. Python projects use *packages* to organize code +into multiple modules that can be imported where needed, and the +tutorial will do this as well. + +The project directory will contain: + +* ``flaskr/``, a Python package containing your application code and + files. +* ``tests/``, a directory containing test modules. +* ``.venv/``, a Python virtual environment where Flask and other + dependencies are installed. +* Installation files telling Python how to install your project. +* Version control config, such as `git`_. You should make a habit of + using some type of version control for all your projects, no matter + the size. +* Any other project files you might add in the future. + +.. _git: https://git-scm.com/ + +By the end, your project layout will look like this: + +.. code-block:: none + + /home/user/Projects/flask-tutorial + ├── flaskr/ + │ ├── __init__.py + │ ├── db.py + │ ├── schema.sql + │ ├── auth.py + │ ├── blog.py + │ ├── templates/ + │ │ ├── base.html + │ │ ├── auth/ + │ │ │ ├── login.html + │ │ │ └── register.html + │ │ └── blog/ + │ │ ├── create.html + │ │ ├── index.html + │ │ └── update.html + │ └── static/ + │ └── style.css + ├── tests/ + │ ├── conftest.py + │ ├── data.sql + │ ├── test_factory.py + │ ├── test_db.py + │ ├── test_auth.py + │ └── test_blog.py + ├── .venv/ + ├── pyproject.toml + └── MANIFEST.in + +If you're using version control, the following files that are generated +while running your project should be ignored. There may be other files +based on the editor you use. In general, ignore files that you didn't +write. For example, with git: + +.. code-block:: none + :caption: ``.gitignore`` + + .venv/ + + *.pyc + __pycache__/ + + instance/ + + .pytest_cache/ + .coverage + htmlcov/ + + dist/ + build/ + *.egg-info/ + +Continue to :doc:`factory`. diff --git a/_build/_sources/tutorial/next.rst.txt b/_build/_sources/tutorial/next.rst.txt new file mode 100644 index 00000000..d41e8ef2 --- /dev/null +++ b/_build/_sources/tutorial/next.rst.txt @@ -0,0 +1,38 @@ +Keep Developing! +================ + +You've learned about quite a few Flask and Python concepts throughout +the tutorial. Go back and review the tutorial and compare your code with +the steps you took to get there. Compare your project to the +:gh:`example project `, which might look a bit +different due to the step-by-step nature of the tutorial. + +There's a lot more to Flask than what you've seen so far. Even so, +you're now equipped to start developing your own web applications. Check +out the :doc:`/quickstart` for an overview of what Flask can do, then +dive into the docs to keep learning. Flask uses `Jinja`_, `Click`_, +`Werkzeug`_, and `ItsDangerous`_ behind the scenes, and they all have +their own documentation too. You'll also be interested in +:doc:`/extensions` which make tasks like working with the database or +validating form data easier and more powerful. + +If you want to keep developing your Flaskr project, here are some ideas +for what to try next: + +* A detail view to show a single post. Click a post's title to go to + its page. +* Like / unlike a post. +* Comments. +* Tags. Clicking a tag shows all the posts with that tag. +* A search box that filters the index page by name. +* Paged display. Only show 5 posts per page. +* Upload an image to go along with a post. +* Format posts using Markdown. +* An RSS feed of new posts. + +Have fun and make awesome applications! + +.. _Jinja: https://palletsprojects.com/p/jinja/ +.. _Click: https://palletsprojects.com/p/click/ +.. _Werkzeug: https://palletsprojects.com/p/werkzeug/ +.. _ItsDangerous: https://palletsprojects.com/p/itsdangerous/ diff --git a/_build/_sources/tutorial/static.rst.txt b/_build/_sources/tutorial/static.rst.txt new file mode 100644 index 00000000..8e76c409 --- /dev/null +++ b/_build/_sources/tutorial/static.rst.txt @@ -0,0 +1,72 @@ +Static Files +============ + +The authentication views and templates work, but they look very plain +right now. Some `CSS`_ can be added to add style to the HTML layout you +constructed. The style won't change, so it's a *static* file rather than +a template. + +Flask automatically adds a ``static`` view that takes a path relative +to the ``flaskr/static`` directory and serves it. The ``base.html`` +template already has a link to the ``style.css`` file: + +.. code-block:: html+jinja + + {{ url_for('static', filename='style.css') }} + +Besides CSS, other types of static files might be files with JavaScript +functions, or a logo image. They are all placed under the +``flaskr/static`` directory and referenced with +``url_for('static', filename='...')``. + +This tutorial isn't focused on how to write CSS, so you can just copy +the following into the ``flaskr/static/style.css`` file: + +.. code-block:: css + :caption: ``flaskr/static/style.css`` + + html { font-family: sans-serif; background: #eee; padding: 1rem; } + body { max-width: 960px; margin: 0 auto; background: white; } + h1 { font-family: serif; color: #377ba8; margin: 1rem 0; } + a { color: #377ba8; } + hr { border: none; border-top: 1px solid lightgray; } + nav { background: lightgray; display: flex; align-items: center; padding: 0 0.5rem; } + nav h1 { flex: auto; margin: 0; } + nav h1 a { text-decoration: none; padding: 0.25rem 0.5rem; } + nav ul { display: flex; list-style: none; margin: 0; padding: 0; } + nav ul li a, nav ul li span, header .action { display: block; padding: 0.5rem; } + .content { padding: 0 1rem 1rem; } + .content > header { border-bottom: 1px solid lightgray; display: flex; align-items: flex-end; } + .content > header h1 { flex: auto; margin: 1rem 0 0.25rem 0; } + .flash { margin: 1em 0; padding: 1em; background: #cae6f6; border: 1px solid #377ba8; } + .post > header { display: flex; align-items: flex-end; font-size: 0.85em; } + .post > header > div:first-of-type { flex: auto; } + .post > header h1 { font-size: 1.5em; margin-bottom: 0; } + .post .about { color: slategray; font-style: italic; } + .post .body { white-space: pre-line; } + .content:last-child { margin-bottom: 0; } + .content form { margin: 1em 0; display: flex; flex-direction: column; } + .content label { font-weight: bold; margin-bottom: 0.5em; } + .content input, .content textarea { margin-bottom: 1em; } + .content textarea { min-height: 12em; resize: vertical; } + input.danger { color: #cc2f2e; } + input[type=submit] { align-self: start; min-width: 10em; } + +You can find a less compact version of ``style.css`` in the +:gh:`example code `. + +Go to http://127.0.0.1:5000/auth/login and the page should look like the +screenshot below. + +.. image:: flaskr_login.png + :align: center + :class: screenshot + :alt: screenshot of login page + +You can read more about CSS from `Mozilla's documentation `_. If +you change a static file, refresh the browser page. If the change +doesn't show up, try clearing your browser's cache. + +.. _CSS: https://developer.mozilla.org/docs/Web/CSS + +Continue to :doc:`blog`. diff --git a/_build/_sources/tutorial/templates.rst.txt b/_build/_sources/tutorial/templates.rst.txt new file mode 100644 index 00000000..1a5535cc --- /dev/null +++ b/_build/_sources/tutorial/templates.rst.txt @@ -0,0 +1,187 @@ +.. currentmodule:: flask + +Templates +========= + +You've written the authentication views for your application, but if +you're running the server and try to go to any of the URLs, you'll see a +``TemplateNotFound`` error. That's because the views are calling +:func:`render_template`, but you haven't written the templates yet. +The template files will be stored in the ``templates`` directory inside +the ``flaskr`` package. + +Templates are files that contain static data as well as placeholders +for dynamic data. A template is rendered with specific data to produce a +final document. Flask uses the `Jinja`_ template library to render +templates. + +In your application, you will use templates to render `HTML`_ which +will display in the user's browser. In Flask, Jinja is configured to +*autoescape* any data that is rendered in HTML templates. This means +that it's safe to render user input; any characters they've entered that +could mess with the HTML, such as ``<`` and ``>`` will be *escaped* with +*safe* values that look the same in the browser but don't cause unwanted +effects. + +Jinja looks and behaves mostly like Python. Special delimiters are used +to distinguish Jinja syntax from the static data in the template. +Anything between ``{{`` and ``}}`` is an expression that will be output +to the final document. ``{%`` and ``%}`` denotes a control flow +statement like ``if`` and ``for``. Unlike Python, blocks are denoted +by start and end tags rather than indentation since static text within +a block could change indentation. + +.. _Jinja: https://jinja.palletsprojects.com/templates/ +.. _HTML: https://developer.mozilla.org/docs/Web/HTML + + +The Base Layout +--------------- + +Each page in the application will have the same basic layout around a +different body. Instead of writing the entire HTML structure in each +template, each template will *extend* a base template and override +specific sections. + +.. code-block:: html+jinja + :caption: ``flaskr/templates/base.html`` + + + {% block title %}{% endblock %} - Flaskr + + +
+
+ {% block header %}{% endblock %} +
+ {% for message in get_flashed_messages() %} +
{{ message }}
+ {% endfor %} + {% block content %}{% endblock %} +
+ +:data:`g` is automatically available in templates. Based on if +``g.user`` is set (from ``load_logged_in_user``), either the username +and a log out link are displayed, or links to register and log in +are displayed. :func:`url_for` is also automatically available, and is +used to generate URLs to views instead of writing them out manually. + +After the page title, and before the content, the template loops over +each message returned by :func:`get_flashed_messages`. You used +:func:`flash` in the views to show error messages, and this is the code +that will display them. + +There are three blocks defined here that will be overridden in the other +templates: + +#. ``{% block title %}`` will change the title displayed in the + browser's tab and window title. + +#. ``{% block header %}`` is similar to ``title`` but will change the + title displayed on the page. + +#. ``{% block content %}`` is where the content of each page goes, such + as the login form or a blog post. + +The base template is directly in the ``templates`` directory. To keep +the others organized, the templates for a blueprint will be placed in a +directory with the same name as the blueprint. + + +Register +-------- + +.. code-block:: html+jinja + :caption: ``flaskr/templates/auth/register.html`` + + {% extends 'base.html' %} + + {% block header %} +

{% block title %}Register{% endblock %}

+ {% endblock %} + + {% block content %} +
+ + + + + +
+ {% endblock %} + +``{% extends 'base.html' %}`` tells Jinja that this template should +replace the blocks from the base template. All the rendered content must +appear inside ``{% block %}`` tags that override blocks from the base +template. + +A useful pattern used here is to place ``{% block title %}`` inside +``{% block header %}``. This will set the title block and then output +the value of it into the header block, so that both the window and page +share the same title without writing it twice. + +The ``input`` tags are using the ``required`` attribute here. This tells +the browser not to submit the form until those fields are filled in. If +the user is using an older browser that doesn't support that attribute, +or if they are using something besides a browser to make requests, you +still want to validate the data in the Flask view. It's important to +always fully validate the data on the server, even if the client does +some validation as well. + + +Log In +------ + +This is identical to the register template except for the title and +submit button. + +.. code-block:: html+jinja + :caption: ``flaskr/templates/auth/login.html`` + + {% extends 'base.html' %} + + {% block header %} +

{% block title %}Log In{% endblock %}

+ {% endblock %} + + {% block content %} +
+ + + + + +
+ {% endblock %} + + +Register A User +--------------- + +Now that the authentication templates are written, you can register a +user. Make sure the server is still running (``flask run`` if it's not), +then go to http://127.0.0.1:5000/auth/register. + +Try clicking the "Register" button without filling out the form and see +that the browser shows an error message. Try removing the ``required`` +attributes from the ``register.html`` template and click "Register" +again. Instead of the browser showing an error, the page will reload and +the error from :func:`flash` in the view will be shown. + +Fill out a username and password and you'll be redirected to the login +page. Try entering an incorrect username, or the correct username and +incorrect password. If you log in you'll get an error because there's +no ``index`` view to redirect to yet. + +Continue to :doc:`static`. diff --git a/_build/_sources/tutorial/tests.rst.txt b/_build/_sources/tutorial/tests.rst.txt new file mode 100644 index 00000000..f4744cda --- /dev/null +++ b/_build/_sources/tutorial/tests.rst.txt @@ -0,0 +1,559 @@ +.. currentmodule:: flask + +Test Coverage +============= + +Writing unit tests for your application lets you check that the code +you wrote works the way you expect. Flask provides a test client that +simulates requests to the application and returns the response data. + +You should test as much of your code as possible. Code in functions only +runs when the function is called, and code in branches, such as ``if`` +blocks, only runs when the condition is met. You want to make sure that +each function is tested with data that covers each branch. + +The closer you get to 100% coverage, the more comfortable you can be +that making a change won't unexpectedly change other behavior. However, +100% coverage doesn't guarantee that your application doesn't have bugs. +In particular, it doesn't test how the user interacts with the +application in the browser. Despite this, test coverage is an important +tool to use during development. + +.. note:: + This is being introduced late in the tutorial, but in your future + projects you should test as you develop. + +You'll use `pytest`_ and `coverage`_ to test and measure your code. +Install them both: + +.. code-block:: none + + $ pip install pytest coverage + +.. _pytest: https://pytest.readthedocs.io/ +.. _coverage: https://coverage.readthedocs.io/ + + +Setup and Fixtures +------------------ + +The test code is located in the ``tests`` directory. This directory is +*next to* the ``flaskr`` package, not inside it. The +``tests/conftest.py`` file contains setup functions called *fixtures* +that each test will use. Tests are in Python modules that start with +``test_``, and each test function in those modules also starts with +``test_``. + +Each test will create a new temporary database file and populate some +data that will be used in the tests. Write a SQL file to insert that +data. + +.. code-block:: sql + :caption: ``tests/data.sql`` + + INSERT INTO user (username, password) + VALUES + ('test', 'pbkdf2:sha256:50000$TCI4GzcX$0de171a4f4dac32e3364c7ddc7c14f3e2fa61f2d17574483f7ffbb431b4acb2f'), + ('other', 'pbkdf2:sha256:50000$kJPKsz6N$d2d4784f1b030a9761f5ccaeeaca413f27f2ecb76d6168407af962ddce849f79'); + + INSERT INTO post (title, body, author_id, created) + VALUES + ('test title', 'test' || x'0a' || 'body', 1, '2018-01-01 00:00:00'); + +The ``app`` fixture will call the factory and pass ``test_config`` to +configure the application and database for testing instead of using your +local development configuration. + +.. code-block:: python + :caption: ``tests/conftest.py`` + + import os + import tempfile + + import pytest + from flaskr import create_app + from flaskr.db import get_db, init_db + + with open(os.path.join(os.path.dirname(__file__), 'data.sql'), 'rb') as f: + _data_sql = f.read().decode('utf8') + + + @pytest.fixture + def app(): + db_fd, db_path = tempfile.mkstemp() + + app = create_app({ + 'TESTING': True, + 'DATABASE': db_path, + }) + + with app.app_context(): + init_db() + get_db().executescript(_data_sql) + + yield app + + os.close(db_fd) + os.unlink(db_path) + + + @pytest.fixture + def client(app): + return app.test_client() + + + @pytest.fixture + def runner(app): + return app.test_cli_runner() + +:func:`tempfile.mkstemp` creates and opens a temporary file, returning +the file descriptor and the path to it. The ``DATABASE`` path is +overridden so it points to this temporary path instead of the instance +folder. After setting the path, the database tables are created and the +test data is inserted. After the test is over, the temporary file is +closed and removed. + +:data:`TESTING` tells Flask that the app is in test mode. Flask changes +some internal behavior so it's easier to test, and other extensions can +also use the flag to make testing them easier. + +The ``client`` fixture calls +:meth:`app.test_client() ` with the application +object created by the ``app`` fixture. Tests will use the client to make +requests to the application without running the server. + +The ``runner`` fixture is similar to ``client``. +:meth:`app.test_cli_runner() ` creates a runner +that can call the Click commands registered with the application. + +Pytest uses fixtures by matching their function names with the names +of arguments in the test functions. For example, the ``test_hello`` +function you'll write next takes a ``client`` argument. Pytest matches +that with the ``client`` fixture function, calls it, and passes the +returned value to the test function. + + +Factory +------- + +There's not much to test about the factory itself. Most of the code will +be executed for each test already, so if something fails the other tests +will notice. + +The only behavior that can change is passing test config. If config is +not passed, there should be some default configuration, otherwise the +configuration should be overridden. + +.. code-block:: python + :caption: ``tests/test_factory.py`` + + from flaskr import create_app + + + def test_config(): + assert not create_app().testing + assert create_app({'TESTING': True}).testing + + + def test_hello(client): + response = client.get('/hello') + assert response.data == b'Hello, World!' + +You added the ``hello`` route as an example when writing the factory at +the beginning of the tutorial. It returns "Hello, World!", so the test +checks that the response data matches. + + +Database +-------- + +Within an application context, ``get_db`` should return the same +connection each time it's called. After the context, the connection +should be closed. + +.. code-block:: python + :caption: ``tests/test_db.py`` + + import sqlite3 + + import pytest + from flaskr.db import get_db + + + def test_get_close_db(app): + with app.app_context(): + db = get_db() + assert db is get_db() + + with pytest.raises(sqlite3.ProgrammingError) as e: + db.execute('SELECT 1') + + assert 'closed' in str(e.value) + +The ``init-db`` command should call the ``init_db`` function and output +a message. + +.. code-block:: python + :caption: ``tests/test_db.py`` + + def test_init_db_command(runner, monkeypatch): + class Recorder(object): + called = False + + def fake_init_db(): + Recorder.called = True + + monkeypatch.setattr('flaskr.db.init_db', fake_init_db) + result = runner.invoke(args=['init-db']) + assert 'Initialized' in result.output + assert Recorder.called + +This test uses Pytest's ``monkeypatch`` fixture to replace the +``init_db`` function with one that records that it's been called. The +``runner`` fixture you wrote above is used to call the ``init-db`` +command by name. + + +Authentication +-------------- + +For most of the views, a user needs to be logged in. The easiest way to +do this in tests is to make a ``POST`` request to the ``login`` view +with the client. Rather than writing that out every time, you can write +a class with methods to do that, and use a fixture to pass it the client +for each test. + +.. code-block:: python + :caption: ``tests/conftest.py`` + + class AuthActions(object): + def __init__(self, client): + self._client = client + + def login(self, username='test', password='test'): + return self._client.post( + '/auth/login', + data={'username': username, 'password': password} + ) + + def logout(self): + return self._client.get('/auth/logout') + + + @pytest.fixture + def auth(client): + return AuthActions(client) + +With the ``auth`` fixture, you can call ``auth.login()`` in a test to +log in as the ``test`` user, which was inserted as part of the test +data in the ``app`` fixture. + +The ``register`` view should render successfully on ``GET``. On ``POST`` +with valid form data, it should redirect to the login URL and the user's +data should be in the database. Invalid data should display error +messages. + +.. code-block:: python + :caption: ``tests/test_auth.py`` + + import pytest + from flask import g, session + from flaskr.db import get_db + + + def test_register(client, app): + assert client.get('/auth/register').status_code == 200 + response = client.post( + '/auth/register', data={'username': 'a', 'password': 'a'} + ) + assert response.headers["Location"] == "/auth/login" + + with app.app_context(): + assert get_db().execute( + "SELECT * FROM user WHERE username = 'a'", + ).fetchone() is not None + + + @pytest.mark.parametrize(('username', 'password', 'message'), ( + ('', '', b'Username is required.'), + ('a', '', b'Password is required.'), + ('test', 'test', b'already registered'), + )) + def test_register_validate_input(client, username, password, message): + response = client.post( + '/auth/register', + data={'username': username, 'password': password} + ) + assert message in response.data + +:meth:`client.get() ` makes a ``GET`` request +and returns the :class:`Response` object returned by Flask. Similarly, +:meth:`client.post() ` makes a ``POST`` +request, converting the ``data`` dict into form data. + +To test that the page renders successfully, a simple request is made and +checked for a ``200 OK`` :attr:`~Response.status_code`. If +rendering failed, Flask would return a ``500 Internal Server Error`` +code. + +:attr:`~Response.headers` will have a ``Location`` header with the login +URL when the register view redirects to the login view. + +:attr:`~Response.data` contains the body of the response as bytes. If +you expect a certain value to render on the page, check that it's in +``data``. Bytes must be compared to bytes. If you want to compare text, +use :meth:`get_data(as_text=True) ` +instead. + +``pytest.mark.parametrize`` tells Pytest to run the same test function +with different arguments. You use it here to test different invalid +input and error messages without writing the same code three times. + +The tests for the ``login`` view are very similar to those for +``register``. Rather than testing the data in the database, +:data:`session` should have ``user_id`` set after logging in. + +.. code-block:: python + :caption: ``tests/test_auth.py`` + + def test_login(client, auth): + assert client.get('/auth/login').status_code == 200 + response = auth.login() + assert response.headers["Location"] == "/" + + with client: + client.get('/') + assert session['user_id'] == 1 + assert g.user['username'] == 'test' + + + @pytest.mark.parametrize(('username', 'password', 'message'), ( + ('a', 'test', b'Incorrect username.'), + ('test', 'a', b'Incorrect password.'), + )) + def test_login_validate_input(auth, username, password, message): + response = auth.login(username, password) + assert message in response.data + +Using ``client`` in a ``with`` block allows accessing context variables +such as :data:`session` after the response is returned. Normally, +accessing ``session`` outside of a request would raise an error. + +Testing ``logout`` is the opposite of ``login``. :data:`session` should +not contain ``user_id`` after logging out. + +.. code-block:: python + :caption: ``tests/test_auth.py`` + + def test_logout(client, auth): + auth.login() + + with client: + auth.logout() + assert 'user_id' not in session + + +Blog +---- + +All the blog views use the ``auth`` fixture you wrote earlier. Call +``auth.login()`` and subsequent requests from the client will be logged +in as the ``test`` user. + +The ``index`` view should display information about the post that was +added with the test data. When logged in as the author, there should be +a link to edit the post. + +You can also test some more authentication behavior while testing the +``index`` view. When not logged in, each page shows links to log in or +register. When logged in, there's a link to log out. + +.. code-block:: python + :caption: ``tests/test_blog.py`` + + import pytest + from flaskr.db import get_db + + + def test_index(client, auth): + response = client.get('/') + assert b"Log In" in response.data + assert b"Register" in response.data + + auth.login() + response = client.get('/') + assert b'Log Out' in response.data + assert b'test title' in response.data + assert b'by test on 2018-01-01' in response.data + assert b'test\nbody' in response.data + assert b'href="/1/update"' in response.data + +A user must be logged in to access the ``create``, ``update``, and +``delete`` views. The logged in user must be the author of the post to +access ``update`` and ``delete``, otherwise a ``403 Forbidden`` status +is returned. If a ``post`` with the given ``id`` doesn't exist, +``update`` and ``delete`` should return ``404 Not Found``. + +.. code-block:: python + :caption: ``tests/test_blog.py`` + + @pytest.mark.parametrize('path', ( + '/create', + '/1/update', + '/1/delete', + )) + def test_login_required(client, path): + response = client.post(path) + assert response.headers["Location"] == "/auth/login" + + + def test_author_required(app, client, auth): + # change the post author to another user + with app.app_context(): + db = get_db() + db.execute('UPDATE post SET author_id = 2 WHERE id = 1') + db.commit() + + auth.login() + # current user can't modify other user's post + assert client.post('/1/update').status_code == 403 + assert client.post('/1/delete').status_code == 403 + # current user doesn't see edit link + assert b'href="/1/update"' not in client.get('/').data + + + @pytest.mark.parametrize('path', ( + '/2/update', + '/2/delete', + )) + def test_exists_required(client, auth, path): + auth.login() + assert client.post(path).status_code == 404 + +The ``create`` and ``update`` views should render and return a +``200 OK`` status for a ``GET`` request. When valid data is sent in a +``POST`` request, ``create`` should insert the new post data into the +database, and ``update`` should modify the existing data. Both pages +should show an error message on invalid data. + +.. code-block:: python + :caption: ``tests/test_blog.py`` + + def test_create(client, auth, app): + auth.login() + assert client.get('/create').status_code == 200 + client.post('/create', data={'title': 'created', 'body': ''}) + + with app.app_context(): + db = get_db() + count = db.execute('SELECT COUNT(id) FROM post').fetchone()[0] + assert count == 2 + + + def test_update(client, auth, app): + auth.login() + assert client.get('/1/update').status_code == 200 + client.post('/1/update', data={'title': 'updated', 'body': ''}) + + with app.app_context(): + db = get_db() + post = db.execute('SELECT * FROM post WHERE id = 1').fetchone() + assert post['title'] == 'updated' + + + @pytest.mark.parametrize('path', ( + '/create', + '/1/update', + )) + def test_create_update_validate(client, auth, path): + auth.login() + response = client.post(path, data={'title': '', 'body': ''}) + assert b'Title is required.' in response.data + +The ``delete`` view should redirect to the index URL and the post should +no longer exist in the database. + +.. code-block:: python + :caption: ``tests/test_blog.py`` + + def test_delete(client, auth, app): + auth.login() + response = client.post('/1/delete') + assert response.headers["Location"] == "/" + + with app.app_context(): + db = get_db() + post = db.execute('SELECT * FROM post WHERE id = 1').fetchone() + assert post is None + + +Running the Tests +----------------- + +Some extra configuration, which is not required but makes running tests with coverage +less verbose, can be added to the project's ``pyproject.toml`` file. + +.. code-block:: toml + :caption: ``pyproject.toml`` + + [tool.pytest.ini_options] + testpaths = ["tests"] + + [tool.coverage.run] + branch = true + source = ["flaskr"] + +To run the tests, use the ``pytest`` command. It will find and run all +the test functions you've written. + +.. code-block:: none + + $ pytest + + ========================= test session starts ========================== + platform linux -- Python 3.6.4, pytest-3.5.0, py-1.5.3, pluggy-0.6.0 + rootdir: /home/user/Projects/flask-tutorial + collected 23 items + + tests/test_auth.py ........ [ 34%] + tests/test_blog.py ............ [ 86%] + tests/test_db.py .. [ 95%] + tests/test_factory.py .. [100%] + + ====================== 24 passed in 0.64 seconds ======================= + +If any tests fail, pytest will show the error that was raised. You can +run ``pytest -v`` to get a list of each test function rather than dots. + +To measure the code coverage of your tests, use the ``coverage`` command +to run pytest instead of running it directly. + +.. code-block:: none + + $ coverage run -m pytest + +You can either view a simple coverage report in the terminal: + +.. code-block:: none + + $ coverage report + + Name Stmts Miss Branch BrPart Cover + ------------------------------------------------------ + flaskr/__init__.py 21 0 2 0 100% + flaskr/auth.py 54 0 22 0 100% + flaskr/blog.py 54 0 16 0 100% + flaskr/db.py 24 0 4 0 100% + ------------------------------------------------------ + TOTAL 153 0 44 0 100% + +An HTML report allows you to see which lines were covered in each file: + +.. code-block:: none + + $ coverage html + +This generates files in the ``htmlcov`` directory. Open +``htmlcov/index.html`` in your browser to see the report. + +Continue to :doc:`deploy`. diff --git a/_build/_sources/tutorial/views.rst.txt b/_build/_sources/tutorial/views.rst.txt new file mode 100644 index 00000000..7092dbc2 --- /dev/null +++ b/_build/_sources/tutorial/views.rst.txt @@ -0,0 +1,305 @@ +.. currentmodule:: flask + +Blueprints and Views +==================== + +A view function is the code you write to respond to requests to your +application. Flask uses patterns to match the incoming request URL to +the view that should handle it. The view returns data that Flask turns +into an outgoing response. Flask can also go the other direction and +generate a URL to a view based on its name and arguments. + + +Create a Blueprint +------------------ + +A :class:`Blueprint` is a way to organize a group of related views and +other code. Rather than registering views and other code directly with +an application, they are registered with a blueprint. Then the blueprint +is registered with the application when it is available in the factory +function. + +Flaskr will have two blueprints, one for authentication functions and +one for the blog posts functions. The code for each blueprint will go +in a separate module. Since the blog needs to know about authentication, +you'll write the authentication one first. + +.. code-block:: python + :caption: ``flaskr/auth.py`` + + import functools + + from flask import ( + Blueprint, flash, g, redirect, render_template, request, session, url_for + ) + from werkzeug.security import check_password_hash, generate_password_hash + + from flaskr.db import get_db + + bp = Blueprint('auth', __name__, url_prefix='/auth') + +This creates a :class:`Blueprint` named ``'auth'``. Like the application +object, the blueprint needs to know where it's defined, so ``__name__`` +is passed as the second argument. The ``url_prefix`` will be prepended +to all the URLs associated with the blueprint. + +Import and register the blueprint from the factory using +:meth:`app.register_blueprint() `. Place the +new code at the end of the factory function before returning the app. + +.. code-block:: python + :caption: ``flaskr/__init__.py`` + + def create_app(): + app = ... + # existing code omitted + + from . import auth + app.register_blueprint(auth.bp) + + return app + +The authentication blueprint will have views to register new users and +to log in and log out. + + +The First View: Register +------------------------ + +When the user visits the ``/auth/register`` URL, the ``register`` view +will return `HTML`_ with a form for them to fill out. When they submit +the form, it will validate their input and either show the form again +with an error message or create the new user and go to the login page. + +.. _HTML: https://developer.mozilla.org/docs/Web/HTML + +For now you will just write the view code. On the next page, you'll +write templates to generate the HTML form. + +.. code-block:: python + :caption: ``flaskr/auth.py`` + + @bp.route('/register', methods=('GET', 'POST')) + def register(): + if request.method == 'POST': + username = request.form['username'] + password = request.form['password'] + db = get_db() + error = None + + if not username: + error = 'Username is required.' + elif not password: + error = 'Password is required.' + + if error is None: + try: + db.execute( + "INSERT INTO user (username, password) VALUES (?, ?)", + (username, generate_password_hash(password)), + ) + db.commit() + except db.IntegrityError: + error = f"User {username} is already registered." + else: + return redirect(url_for("auth.login")) + + flash(error) + + return render_template('auth/register.html') + +Here's what the ``register`` view function is doing: + +#. :meth:`@bp.route ` associates the URL ``/register`` + with the ``register`` view function. When Flask receives a request + to ``/auth/register``, it will call the ``register`` view and use + the return value as the response. + +#. If the user submitted the form, + :attr:`request.method ` will be ``'POST'``. In this + case, start validating the input. + +#. :attr:`request.form ` is a special type of + :class:`dict` mapping submitted form keys and values. The user will + input their ``username`` and ``password``. + +#. Validate that ``username`` and ``password`` are not empty. + +#. If validation succeeds, insert the new user data into the database. + + - :meth:`db.execute ` takes a SQL + query with ``?`` placeholders for any user input, and a tuple of + values to replace the placeholders with. The database library + will take care of escaping the values so you are not vulnerable + to a *SQL injection attack*. + + - For security, passwords should never be stored in the database + directly. Instead, + :func:`~werkzeug.security.generate_password_hash` is used to + securely hash the password, and that hash is stored. Since this + query modifies data, + :meth:`db.commit() ` needs to be + called afterwards to save the changes. + + - An :exc:`sqlite3.IntegrityError` will occur if the username + already exists, which should be shown to the user as another + validation error. + +#. After storing the user, they are redirected to the login page. + :func:`url_for` generates the URL for the login view based on its + name. This is preferable to writing the URL directly as it allows + you to change the URL later without changing all code that links to + it. :func:`redirect` generates a redirect response to the generated + URL. + +#. If validation fails, the error is shown to the user. :func:`flash` + stores messages that can be retrieved when rendering the template. + +#. When the user initially navigates to ``auth/register``, or + there was a validation error, an HTML page with the registration + form should be shown. :func:`render_template` will render a template + containing the HTML, which you'll write in the next step of the + tutorial. + + +Login +----- + +This view follows the same pattern as the ``register`` view above. + +.. code-block:: python + :caption: ``flaskr/auth.py`` + + @bp.route('/login', methods=('GET', 'POST')) + def login(): + if request.method == 'POST': + username = request.form['username'] + password = request.form['password'] + db = get_db() + error = None + user = db.execute( + 'SELECT * FROM user WHERE username = ?', (username,) + ).fetchone() + + if user is None: + error = 'Incorrect username.' + elif not check_password_hash(user['password'], password): + error = 'Incorrect password.' + + if error is None: + session.clear() + session['user_id'] = user['id'] + return redirect(url_for('index')) + + flash(error) + + return render_template('auth/login.html') + +There are a few differences from the ``register`` view: + +#. The user is queried first and stored in a variable for later use. + + :meth:`~sqlite3.Cursor.fetchone` returns one row from the query. + If the query returned no results, it returns ``None``. Later, + :meth:`~sqlite3.Cursor.fetchall` will be used, which returns a list + of all results. + +#. :func:`~werkzeug.security.check_password_hash` hashes the submitted + password in the same way as the stored hash and securely compares + them. If they match, the password is valid. + +#. :data:`session` is a :class:`dict` that stores data across requests. + When validation succeeds, the user's ``id`` is stored in a new + session. The data is stored in a *cookie* that is sent to the + browser, and the browser then sends it back with subsequent requests. + Flask securely *signs* the data so that it can't be tampered with. + +Now that the user's ``id`` is stored in the :data:`session`, it will be +available on subsequent requests. At the beginning of each request, if +a user is logged in their information should be loaded and made +available to other views. + +.. code-block:: python + :caption: ``flaskr/auth.py`` + + @bp.before_app_request + def load_logged_in_user(): + user_id = session.get('user_id') + + if user_id is None: + g.user = None + else: + g.user = get_db().execute( + 'SELECT * FROM user WHERE id = ?', (user_id,) + ).fetchone() + +:meth:`bp.before_app_request() ` registers +a function that runs before the view function, no matter what URL is +requested. ``load_logged_in_user`` checks if a user id is stored in the +:data:`session` and gets that user's data from the database, storing it +on :data:`g.user `, which lasts for the length of the request. If +there is no user id, or if the id doesn't exist, ``g.user`` will be +``None``. + + +Logout +------ + +To log out, you need to remove the user id from the :data:`session`. +Then ``load_logged_in_user`` won't load a user on subsequent requests. + +.. code-block:: python + :caption: ``flaskr/auth.py`` + + @bp.route('/logout') + def logout(): + session.clear() + return redirect(url_for('index')) + + +Require Authentication in Other Views +------------------------------------- + +Creating, editing, and deleting blog posts will require a user to be +logged in. A *decorator* can be used to check this for each view it's +applied to. + +.. code-block:: python + :caption: ``flaskr/auth.py`` + + def login_required(view): + @functools.wraps(view) + def wrapped_view(**kwargs): + if g.user is None: + return redirect(url_for('auth.login')) + + return view(**kwargs) + + return wrapped_view + +This decorator returns a new view function that wraps the original view +it's applied to. The new function checks if a user is loaded and +redirects to the login page otherwise. If a user is loaded the original +view is called and continues normally. You'll use this decorator when +writing the blog views. + +Endpoints and URLs +------------------ + +The :func:`url_for` function generates the URL to a view based on a name +and arguments. The name associated with a view is also called the +*endpoint*, and by default it's the same as the name of the view +function. + +For example, the ``hello()`` view that was added to the app +factory earlier in the tutorial has the name ``'hello'`` and can be +linked to with ``url_for('hello')``. If it took an argument, which +you'll see later, it would be linked to using +``url_for('hello', who='World')``. + +When using a blueprint, the name of the blueprint is prepended to the +name of the function, so the endpoint for the ``login`` function you +wrote above is ``'auth.login'`` because you added it to the ``'auth'`` +blueprint. + +Continue to :doc:`templates`. diff --git a/_build/_sources/views.rst.txt b/_build/_sources/views.rst.txt new file mode 100644 index 00000000..f2210270 --- /dev/null +++ b/_build/_sources/views.rst.txt @@ -0,0 +1,324 @@ +Class-based Views +================= + +.. currentmodule:: flask.views + +This page introduces using the :class:`View` and :class:`MethodView` +classes to write class-based views. + +A class-based view is a class that acts as a view function. Because it +is a class, different instances of the class can be created with +different arguments, to change the behavior of the view. This is also +known as generic, reusable, or pluggable views. + +An example of where this is useful is defining a class that creates an +API based on the database model it is initialized with. + +For more complex API behavior and customization, look into the various +API extensions for Flask. + + +Basic Reusable View +------------------- + +Let's walk through an example converting a view function to a view +class. We start with a view function that queries a list of users then +renders a template to show the list. + +.. code-block:: python + + @app.route("/users/") + def user_list(): + users = User.query.all() + return render_template("users.html", users=users) + +This works for the user model, but let's say you also had more models +that needed list pages. You'd need to write another view function for +each model, even though the only thing that would change is the model +and template name. + +Instead, you can write a :class:`View` subclass that will query a model +and render a template. As the first step, we'll convert the view to a +class without any customization. + +.. code-block:: python + + from flask.views import View + + class UserList(View): + def dispatch_request(self): + users = User.query.all() + return render_template("users.html", objects=users) + + app.add_url_rule("/users/", view_func=UserList.as_view("user_list")) + +The :meth:`View.dispatch_request` method is the equivalent of the view +function. Calling :meth:`View.as_view` method will create a view +function that can be registered on the app with its +:meth:`~flask.Flask.add_url_rule` method. The first argument to +``as_view`` is the name to use to refer to the view with +:func:`~flask.url_for`. + +.. note:: + + You can't decorate the class with ``@app.route()`` the way you'd + do with a basic view function. + +Next, we need to be able to register the same view class for different +models and templates, to make it more useful than the original function. +The class will take two arguments, the model and template, and store +them on ``self``. Then ``dispatch_request`` can reference these instead +of hard-coded values. + +.. code-block:: python + + class ListView(View): + def __init__(self, model, template): + self.model = model + self.template = template + + def dispatch_request(self): + items = self.model.query.all() + return render_template(self.template, items=items) + +Remember, we create the view function with ``View.as_view()`` instead of +creating the class directly. Any extra arguments passed to ``as_view`` +are then passed when creating the class. Now we can register the same +view to handle multiple models. + +.. code-block:: python + + app.add_url_rule( + "/users/", + view_func=ListView.as_view("user_list", User, "users.html"), + ) + app.add_url_rule( + "/stories/", + view_func=ListView.as_view("story_list", Story, "stories.html"), + ) + + +URL Variables +------------- + +Any variables captured by the URL are passed as keyword arguments to the +``dispatch_request`` method, as they would be for a regular view +function. + +.. code-block:: python + + class DetailView(View): + def __init__(self, model): + self.model = model + self.template = f"{model.__name__.lower()}/detail.html" + + def dispatch_request(self, id) + item = self.model.query.get_or_404(id) + return render_template(self.template, item=item) + + app.add_url_rule( + "/users/", + view_func=DetailView.as_view("user_detail", User) + ) + + +View Lifetime and ``self`` +-------------------------- + +By default, a new instance of the view class is created every time a +request is handled. This means that it is safe to write other data to +``self`` during the request, since the next request will not see it, +unlike other forms of global state. + +However, if your view class needs to do a lot of complex initialization, +doing it for every request is unnecessary and can be inefficient. To +avoid this, set :attr:`View.init_every_request` to ``False``, which will +only create one instance of the class and use it for every request. In +this case, writing to ``self`` is not safe. If you need to store data +during the request, use :data:`~flask.g` instead. + +In the ``ListView`` example, nothing writes to ``self`` during the +request, so it is more efficient to create a single instance. + +.. code-block:: python + + class ListView(View): + init_every_request = False + + def __init__(self, model, template): + self.model = model + self.template = template + + def dispatch_request(self): + items = self.model.query.all() + return render_template(self.template, items=items) + +Different instances will still be created each for each ``as_view`` +call, but not for each request to those views. + + +View Decorators +--------------- + +The view class itself is not the view function. View decorators need to +be applied to the view function returned by ``as_view``, not the class +itself. Set :attr:`View.decorators` to a list of decorators to apply. + +.. code-block:: python + + class UserList(View): + decorators = [cache(minutes=2), login_required] + + app.add_url_rule('/users/', view_func=UserList.as_view()) + +If you didn't set ``decorators``, you could apply them manually instead. +This is equivalent to: + +.. code-block:: python + + view = UserList.as_view("users_list") + view = cache(minutes=2)(view) + view = login_required(view) + app.add_url_rule('/users/', view_func=view) + +Keep in mind that order matters. If you're used to ``@decorator`` style, +this is equivalent to: + +.. code-block:: python + + @app.route("/users/") + @login_required + @cache(minutes=2) + def user_list(): + ... + + +Method Hints +------------ + +A common pattern is to register a view with ``methods=["GET", "POST"]``, +then check ``request.method == "POST"`` to decide what to do. Setting +:attr:`View.methods` is equivalent to passing the list of methods to +``add_url_rule`` or ``route``. + +.. code-block:: python + + class MyView(View): + methods = ["GET", "POST"] + + def dispatch_request(self): + if request.method == "POST": + ... + ... + + app.add_url_rule('/my-view', view_func=MyView.as_view('my-view')) + +This is equivalent to the following, except further subclasses can +inherit or change the methods. + +.. code-block:: python + + app.add_url_rule( + "/my-view", + view_func=MyView.as_view("my-view"), + methods=["GET", "POST"], + ) + + +Method Dispatching and APIs +--------------------------- + +For APIs it can be helpful to use a different function for each HTTP +method. :class:`MethodView` extends the basic :class:`View` to dispatch +to different methods of the class based on the request method. Each HTTP +method maps to a method of the class with the same (lowercase) name. + +:class:`MethodView` automatically sets :attr:`View.methods` based on the +methods defined by the class. It even knows how to handle subclasses +that override or define other methods. + +We can make a generic ``ItemAPI`` class that provides get (detail), +patch (edit), and delete methods for a given model. A ``GroupAPI`` can +provide get (list) and post (create) methods. + +.. code-block:: python + + from flask.views import MethodView + + class ItemAPI(MethodView): + init_every_request = False + + def __init__(self, model): + self.model = model + self.validator = generate_validator(model) + + def _get_item(self, id): + return self.model.query.get_or_404(id) + + def get(self, id): + item = self._get_item(id) + return jsonify(item.to_json()) + + def patch(self, id): + item = self._get_item(id) + errors = self.validator.validate(item, request.json) + + if errors: + return jsonify(errors), 400 + + item.update_from_json(request.json) + db.session.commit() + return jsonify(item.to_json()) + + def delete(self, id): + item = self._get_item(id) + db.session.delete(item) + db.session.commit() + return "", 204 + + class GroupAPI(MethodView): + init_every_request = False + + def __init__(self, model): + self.model = model + self.validator = generate_validator(model, create=True) + + def get(self): + items = self.model.query.all() + return jsonify([item.to_json() for item in items]) + + def post(self): + errors = self.validator.validate(request.json) + + if errors: + return jsonify(errors), 400 + + db.session.add(self.model.from_json(request.json)) + db.session.commit() + return jsonify(item.to_json()) + + def register_api(app, model, name): + item = ItemAPI.as_view(f"{name}-item", model) + group = GroupAPI.as_view(f"{name}-group", model) + app.add_url_rule(f"/{name}/", view_func=item) + app.add_url_rule(f"/{name}/", view_func=group) + + register_api(app, User, "users") + register_api(app, Story, "stories") + +This produces the following views, a standard REST API! + +================= ========== =================== +URL Method Description +----------------- ---------- ------------------- +``/users/`` ``GET`` List all users +``/users/`` ``POST`` Create a new user +``/users/`` ``GET`` Show a single user +``/users/`` ``PATCH`` Update a user +``/users/`` ``DELETE`` Delete a user +``/stories/`` ``GET`` List all stories +``/stories/`` ``POST`` Create a new story +``/stories/`` ``GET`` Show a single story +``/stories/`` ``PATCH`` Update a story +``/stories/`` ``DELETE`` Delete a story +================= ========== =================== diff --git a/_build/_sources/web-security.rst.txt b/_build/_sources/web-security.rst.txt new file mode 100644 index 00000000..f13bb7b8 --- /dev/null +++ b/_build/_sources/web-security.rst.txt @@ -0,0 +1,308 @@ +Security Considerations +======================= + +Web applications face many types of potential security problems, and it can be +hard to get everything right, or even to know what "right" is in general. Flask +tries to solve a few of these things by default, but there are other parts you +may have to take care of yourself. Many of these solutions are tradeoffs, and +will depend on each application's specific needs and threat model. Many hosting +platforms may take care of certain types of problems without the need for the +Flask application to handle them. + +Resource Use +------------ + +A common category of attacks is "Denial of Service" (DoS or DDoS). This is a +very broad category, and different variants target different layers in a +deployed application. In general, something is done to increase how much +processing time or memory is used to handle each request, to the point where +there are not enough resources to handle legitimate requests. + +Flask provides a few configuration options to handle resource use. They can +also be set on individual requests to customize only that request. The +documentation for each goes into more detail. + +- :data:`MAX_CONTENT_LENGTH` or :attr:`.Request.max_content_length` controls + how much data will be read from a request. It is not set by default, + although it will still block truly unlimited streams unless the WSGI server + indicates support. +- :data:`MAX_FORM_MEMORY_SIZE` or :attr:`.Request.max_form_memory_size` + controls how large any non-file ``multipart/form-data`` field can be. It is + set to 500kB by default. +- :data:`MAX_FORM_PARTS` or :attr:`.Request.max_form_parts` controls how many + ``multipart/form-data`` fields can be parsed. It is set to 1000 by default. + Combined with the default `max_form_memory_size`, this means that a form + will occupy at most 500MB of memory. + +Regardless of these settings, you should also review what settings are available +from your operating system, container deployment (Docker etc), WSGI server, HTTP +server, and hosting platform. They typically have ways to set process resource +limits, timeouts, and other checks regardless of how Flask is configured. + +.. _security-xss: + +Cross-Site Scripting (XSS) +-------------------------- + +Cross site scripting is the concept of injecting arbitrary HTML (and with +it JavaScript) into the context of a website. To remedy this, developers +have to properly escape text so that it cannot include arbitrary HTML +tags. For more information on that have a look at the Wikipedia article +on `Cross-Site Scripting +`_. + +Flask configures Jinja2 to automatically escape all values unless +explicitly told otherwise. This should rule out all XSS problems caused +in templates, but there are still other places where you have to be +careful: + +- generating HTML without the help of Jinja2 +- calling :class:`~markupsafe.Markup` on data submitted by users +- sending out HTML from uploaded files, never do that, use the + ``Content-Disposition: attachment`` header to prevent that problem. +- sending out textfiles from uploaded files. Some browsers are using + content-type guessing based on the first few bytes so users could + trick a browser to execute HTML. + +Another thing that is very important are unquoted attributes. While +Jinja2 can protect you from XSS issues by escaping HTML, there is one +thing it cannot protect you from: XSS by attribute injection. To counter +this possible attack vector, be sure to always quote your attributes with +either double or single quotes when using Jinja expressions in them: + +.. sourcecode:: html+jinja + + + +Why is this necessary? Because if you would not be doing that, an +attacker could easily inject custom JavaScript handlers. For example an +attacker could inject this piece of HTML+JavaScript: + +.. sourcecode:: html + + onmouseover=alert(document.cookie) + +When the user would then move with the mouse over the input, the cookie +would be presented to the user in an alert window. But instead of showing +the cookie to the user, a good attacker might also execute any other +JavaScript code. In combination with CSS injections the attacker might +even make the element fill out the entire page so that the user would +just have to have the mouse anywhere on the page to trigger the attack. + +There is one class of XSS issues that Jinja's escaping does not protect +against. The ``a`` tag's ``href`` attribute can contain a `javascript:` URI, +which the browser will execute when clicked if not secured properly. + +.. sourcecode:: html + + click here + click here + +To prevent this, you'll need to set the :ref:`security-csp` response header. + +Cross-Site Request Forgery (CSRF) +--------------------------------- + +Another big problem is CSRF. This is a very complex topic and I won't +outline it here in detail just mention what it is and how to theoretically +prevent it. + +If your authentication information is stored in cookies, you have implicit +state management. The state of "being logged in" is controlled by a +cookie, and that cookie is sent with each request to a page. +Unfortunately that includes requests triggered by 3rd party sites. If you +don't keep that in mind, some people might be able to trick your +application's users with social engineering to do stupid things without +them knowing. + +Say you have a specific URL that, when you sent ``POST`` requests to will +delete a user's profile (say ``http://example.com/user/delete``). If an +attacker now creates a page that sends a post request to that page with +some JavaScript they just have to trick some users to load that page and +their profiles will end up being deleted. + +Imagine you were to run Facebook with millions of concurrent users and +someone would send out links to images of little kittens. When users +would go to that page, their profiles would get deleted while they are +looking at images of fluffy cats. + +How can you prevent that? Basically for each request that modifies +content on the server you would have to either use a one-time token and +store that in the cookie **and** also transmit it with the form data. +After receiving the data on the server again, you would then have to +compare the two tokens and ensure they are equal. + +Why does Flask not do that for you? The ideal place for this to happen is +the form validation framework, which does not exist in Flask. + +.. _security-json: + +JSON Security +------------- + +In Flask 0.10 and lower, :func:`~flask.jsonify` did not serialize top-level +arrays to JSON. This was because of a security vulnerability in ECMAScript 4. + +ECMAScript 5 closed this vulnerability, so only extremely old browsers are +still vulnerable. All of these browsers have `other more serious +vulnerabilities +`_, so +this behavior was changed and :func:`~flask.jsonify` now supports serializing +arrays. + +Security Headers +---------------- + +Browsers recognize various response headers in order to control security. We +recommend reviewing each of the headers below for use in your application. +The `Flask-Talisman`_ extension can be used to manage HTTPS and the security +headers for you. + +.. _Flask-Talisman: https://github.com/GoogleCloudPlatform/flask-talisman + +HTTP Strict Transport Security (HSTS) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Tells the browser to convert all HTTP requests to HTTPS, preventing +man-in-the-middle (MITM) attacks. :: + + response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains' + +- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security + +.. _security-csp: + +Content Security Policy (CSP) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Tell the browser where it can load various types of resource from. This header +should be used whenever possible, but requires some work to define the correct +policy for your site. A very strict policy would be:: + + response.headers['Content-Security-Policy'] = "default-src 'self'" + +- https://csp.withgoogle.com/docs/index.html +- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy + +X-Content-Type-Options +~~~~~~~~~~~~~~~~~~~~~~ + +Forces the browser to honor the response content type instead of trying to +detect it, which can be abused to generate a cross-site scripting (XSS) +attack. :: + + response.headers['X-Content-Type-Options'] = 'nosniff' + +- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options + +X-Frame-Options +~~~~~~~~~~~~~~~ + +Prevents external sites from embedding your site in an ``iframe``. This +prevents a class of attacks where clicks in the outer frame can be translated +invisibly to clicks on your page's elements. This is also known as +"clickjacking". :: + + response.headers['X-Frame-Options'] = 'SAMEORIGIN' + +- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options + +.. _security-cookie: + +Set-Cookie options +~~~~~~~~~~~~~~~~~~ + +These options can be added to a ``Set-Cookie`` header to improve their +security. Flask has configuration options to set these on the session cookie. +They can be set on other cookies too. + +- ``Secure`` limits cookies to HTTPS traffic only. +- ``HttpOnly`` protects the contents of cookies from being read with + JavaScript. +- ``SameSite`` restricts how cookies are sent with requests from + external sites. Can be set to ``'Lax'`` (recommended) or ``'Strict'``. + ``Lax`` prevents sending cookies with CSRF-prone requests from + external sites, such as submitting a form. ``Strict`` prevents sending + cookies with all external requests, including following regular links. + +:: + + app.config.update( + SESSION_COOKIE_SECURE=True, + SESSION_COOKIE_HTTPONLY=True, + SESSION_COOKIE_SAMESITE='Lax', + ) + + response.set_cookie('username', 'flask', secure=True, httponly=True, samesite='Lax') + +Specifying ``Expires`` or ``Max-Age`` options, will remove the cookie after +the given time, or the current time plus the age, respectively. If neither +option is set, the cookie will be removed when the browser is closed. :: + + # cookie expires after 10 minutes + response.set_cookie('snakes', '3', max_age=600) + +For the session cookie, if :attr:`session.permanent ` +is set, then :data:`PERMANENT_SESSION_LIFETIME` is used to set the expiration. +Flask's default cookie implementation validates that the cryptographic +signature is not older than this value. Lowering this value may help mitigate +replay attacks, where intercepted cookies can be sent at a later time. :: + + app.config.update( + PERMANENT_SESSION_LIFETIME=600 + ) + + @app.route('/login', methods=['POST']) + def login(): + ... + session.clear() + session['user_id'] = user.id + session.permanent = True + ... + +Use :class:`itsdangerous.TimedSerializer` to sign and validate other cookie +values (or any values that need secure signatures). + +- https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies +- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie + +.. _samesite_support: https://caniuse.com/#feat=same-site-cookie-attribute + + +HTTP Public Key Pinning (HPKP) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This tells the browser to authenticate with the server using only the specific +certificate key to prevent MITM attacks. + +.. warning:: + Be careful when enabling this, as it is very difficult to undo if you set up + or upgrade your key incorrectly. + +- https://developer.mozilla.org/en-US/docs/Web/HTTP/Public_Key_Pinning + + +Copy/Paste to Terminal +---------------------- + +Hidden characters such as the backspace character (``\b``, ``^H``) can +cause text to render differently in HTML than how it is interpreted if +`pasted into a terminal `__. + +For example, ``import y\bose\bm\bi\bt\be\b`` renders as +``import yosemite`` in HTML, but the backspaces are applied when pasted +into a terminal, and it becomes ``import os``. + +If you expect users to copy and paste untrusted code from your site, +such as from comments posted by users on a technical blog, consider +applying extra filtering, such as replacing all ``\b`` characters. + +.. code-block:: python + + body = body.replace("\b", "") + +Most modern terminals will warn about and remove hidden characters when +pasting, so this isn't strictly necessary. It's also possible to craft +dangerous commands in other ways that aren't possible to filter. +Depending on your site's use case, it may be good to show a warning +about copying code in general. diff --git a/_build/_static/basic.css b/_build/_static/basic.css new file mode 100644 index 00000000..93a4776b --- /dev/null +++ b/_build/_static/basic.css @@ -0,0 +1,914 @@ +/* + * Sphinx stylesheet -- basic theme. + */ + +/* -- main layout ----------------------------------------------------------- */ + +div.clearer { + clear: both; +} + +div.section::after { + display: block; + content: ''; + clear: left; +} + +/* -- relbar ---------------------------------------------------------------- */ + +div.related { + width: 100%; + font-size: 90%; +} + +div.related h3 { + display: none; +} + +div.related ul { + margin: 0; + padding: 0 0 0 10px; + list-style: none; +} + +div.related li { + display: inline; +} + +div.related li.right { + float: right; + margin-right: 5px; +} + +/* -- sidebar --------------------------------------------------------------- */ + +div.sphinxsidebarwrapper { + padding: 10px 5px 0 10px; +} + +div.sphinxsidebar { + float: left; + width: 230px; + margin-left: -100%; + font-size: 90%; + word-wrap: break-word; + overflow-wrap : break-word; +} + +div.sphinxsidebar ul { + list-style: none; +} + +div.sphinxsidebar ul ul, +div.sphinxsidebar ul.want-points { + margin-left: 20px; + list-style: square; +} + +div.sphinxsidebar ul ul { + margin-top: 0; + margin-bottom: 0; +} + +div.sphinxsidebar form { + margin-top: 10px; +} + +div.sphinxsidebar input { + border: 1px solid #98dbcc; + font-family: sans-serif; + font-size: 1em; +} + +div.sphinxsidebar #searchbox form.search { + overflow: hidden; +} + +div.sphinxsidebar #searchbox input[type="text"] { + float: left; + width: 80%; + padding: 0.25em; + box-sizing: border-box; +} + +div.sphinxsidebar #searchbox input[type="submit"] { + float: left; + width: 20%; + border-left: none; + padding: 0.25em; + box-sizing: border-box; +} + + +img { + border: 0; + max-width: 100%; +} + +/* -- search page ----------------------------------------------------------- */ + +ul.search { + margin-top: 10px; +} + +ul.search li { + padding: 5px 0; +} + +ul.search li a { + font-weight: bold; +} + +ul.search li p.context { + color: #888; + margin: 2px 0 0 30px; + text-align: left; +} + +ul.keywordmatches li.goodmatch a { + font-weight: bold; +} + +/* -- index page ------------------------------------------------------------ */ + +table.contentstable { + width: 90%; + margin-left: auto; + margin-right: auto; +} + +table.contentstable p.biglink { + line-height: 150%; +} + +a.biglink { + font-size: 1.3em; +} + +span.linkdescr { + font-style: italic; + padding-top: 5px; + font-size: 90%; +} + +/* -- general index --------------------------------------------------------- */ + +table.indextable { + width: 100%; +} + +table.indextable td { + text-align: left; + vertical-align: top; +} + +table.indextable ul { + margin-top: 0; + margin-bottom: 0; + list-style-type: none; +} + +table.indextable > tbody > tr > td > ul { + padding-left: 0em; +} + +table.indextable tr.pcap { + height: 10px; +} + +table.indextable tr.cap { + margin-top: 10px; + background-color: #f2f2f2; +} + +img.toggler { + margin-right: 3px; + margin-top: 3px; + cursor: pointer; +} + +div.modindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +div.genindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +/* -- domain module index --------------------------------------------------- */ + +table.modindextable td { + padding: 2px; + border-collapse: collapse; +} + +/* -- general body styles --------------------------------------------------- */ + +div.body { + min-width: 360px; + max-width: 800px; +} + +div.body p, div.body dd, div.body li, div.body blockquote { + -moz-hyphens: auto; + -ms-hyphens: auto; + -webkit-hyphens: auto; + hyphens: auto; +} + +a.headerlink { + visibility: hidden; +} + +a:visited { + color: #551A8B; +} + +h1:hover > a.headerlink, +h2:hover > a.headerlink, +h3:hover > a.headerlink, +h4:hover > a.headerlink, +h5:hover > a.headerlink, +h6:hover > a.headerlink, +dt:hover > a.headerlink, +caption:hover > a.headerlink, +p.caption:hover > a.headerlink, +div.code-block-caption:hover > a.headerlink { + visibility: visible; +} + +div.body p.caption { + text-align: inherit; +} + +div.body td { + text-align: left; +} + +.first { + margin-top: 0 !important; +} + +p.rubric { + margin-top: 30px; + font-weight: bold; +} + +img.align-left, figure.align-left, .figure.align-left, object.align-left { + clear: left; + float: left; + margin-right: 1em; +} + +img.align-right, figure.align-right, .figure.align-right, object.align-right { + clear: right; + float: right; + margin-left: 1em; +} + +img.align-center, figure.align-center, .figure.align-center, object.align-center { + display: block; + margin-left: auto; + margin-right: auto; +} + +img.align-default, figure.align-default, .figure.align-default { + display: block; + margin-left: auto; + margin-right: auto; +} + +.align-left { + text-align: left; +} + +.align-center { + text-align: center; +} + +.align-default { + text-align: center; +} + +.align-right { + text-align: right; +} + +/* -- sidebars -------------------------------------------------------------- */ + +div.sidebar, +aside.sidebar { + margin: 0 0 0.5em 1em; + border: 1px solid #ddb; + padding: 7px; + background-color: #ffe; + width: 40%; + float: right; + clear: right; + overflow-x: auto; +} + +p.sidebar-title { + font-weight: bold; +} + +nav.contents, +aside.topic, +div.admonition, div.topic, blockquote { + clear: left; +} + +/* -- topics ---------------------------------------------------------------- */ + +nav.contents, +aside.topic, +div.topic { + border: 1px solid #ccc; + padding: 7px; + margin: 10px 0 10px 0; +} + +p.topic-title { + font-size: 1.1em; + font-weight: bold; + margin-top: 10px; +} + +/* -- admonitions ----------------------------------------------------------- */ + +div.admonition { + margin-top: 10px; + margin-bottom: 10px; + padding: 7px; +} + +div.admonition dt { + font-weight: bold; +} + +p.admonition-title { + margin: 0px 10px 5px 0px; + font-weight: bold; +} + +div.body p.centered { + text-align: center; + margin-top: 25px; +} + +/* -- content of sidebars/topics/admonitions -------------------------------- */ + +div.sidebar > :last-child, +aside.sidebar > :last-child, +nav.contents > :last-child, +aside.topic > :last-child, +div.topic > :last-child, +div.admonition > :last-child { + margin-bottom: 0; +} + +div.sidebar::after, +aside.sidebar::after, +nav.contents::after, +aside.topic::after, +div.topic::after, +div.admonition::after, +blockquote::after { + display: block; + content: ''; + clear: both; +} + +/* -- tables ---------------------------------------------------------------- */ + +table.docutils { + margin-top: 10px; + margin-bottom: 10px; + border: 0; + border-collapse: collapse; +} + +table.align-center { + margin-left: auto; + margin-right: auto; +} + +table.align-default { + margin-left: auto; + margin-right: auto; +} + +table caption span.caption-number { + font-style: italic; +} + +table caption span.caption-text { +} + +table.docutils td, table.docutils th { + padding: 1px 8px 1px 5px; + border-top: 0; + border-left: 0; + border-right: 0; + border-bottom: 1px solid #aaa; +} + +th { + text-align: left; + padding-right: 5px; +} + +table.citation { + border-left: solid 1px gray; + margin-left: 1px; +} + +table.citation td { + border-bottom: none; +} + +th > :first-child, +td > :first-child { + margin-top: 0px; +} + +th > :last-child, +td > :last-child { + margin-bottom: 0px; +} + +/* -- figures --------------------------------------------------------------- */ + +div.figure, figure { + margin: 0.5em; + padding: 0.5em; +} + +div.figure p.caption, figcaption { + padding: 0.3em; +} + +div.figure p.caption span.caption-number, +figcaption span.caption-number { + font-style: italic; +} + +div.figure p.caption span.caption-text, +figcaption span.caption-text { +} + +/* -- field list styles ----------------------------------------------------- */ + +table.field-list td, table.field-list th { + border: 0 !important; +} + +.field-list ul { + margin: 0; + padding-left: 1em; +} + +.field-list p { + margin: 0; +} + +.field-name { + -moz-hyphens: manual; + -ms-hyphens: manual; + -webkit-hyphens: manual; + hyphens: manual; +} + +/* -- hlist styles ---------------------------------------------------------- */ + +table.hlist { + margin: 1em 0; +} + +table.hlist td { + vertical-align: top; +} + +/* -- object description styles --------------------------------------------- */ + +.sig { + font-family: 'Consolas', 'Menlo', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', monospace; +} + +.sig-name, code.descname { + background-color: transparent; + font-weight: bold; +} + +.sig-name { + font-size: 1.1em; +} + +code.descname { + font-size: 1.2em; +} + +.sig-prename, code.descclassname { + background-color: transparent; +} + +.optional { + font-size: 1.3em; +} + +.sig-paren { + font-size: larger; +} + +.sig-param.n { + font-style: italic; +} + +/* C++ specific styling */ + +.sig-inline.c-texpr, +.sig-inline.cpp-texpr { + font-family: unset; +} + +.sig.c .k, .sig.c .kt, +.sig.cpp .k, .sig.cpp .kt { + color: #0033B3; +} + +.sig.c .m, +.sig.cpp .m { + color: #1750EB; +} + +.sig.c .s, .sig.c .sc, +.sig.cpp .s, .sig.cpp .sc { + color: #067D17; +} + + +/* -- other body styles ----------------------------------------------------- */ + +ol.arabic { + list-style: decimal; +} + +ol.loweralpha { + list-style: lower-alpha; +} + +ol.upperalpha { + list-style: upper-alpha; +} + +ol.lowerroman { + list-style: lower-roman; +} + +ol.upperroman { + list-style: upper-roman; +} + +:not(li) > ol > li:first-child > :first-child, +:not(li) > ul > li:first-child > :first-child { + margin-top: 0px; +} + +:not(li) > ol > li:last-child > :last-child, +:not(li) > ul > li:last-child > :last-child { + margin-bottom: 0px; +} + +ol.simple ol p, +ol.simple ul p, +ul.simple ol p, +ul.simple ul p { + margin-top: 0; +} + +ol.simple > li:not(:first-child) > p, +ul.simple > li:not(:first-child) > p { + margin-top: 0; +} + +ol.simple p, +ul.simple p { + margin-bottom: 0; +} + +aside.footnote > span, +div.citation > span { + float: left; +} +aside.footnote > span:last-of-type, +div.citation > span:last-of-type { + padding-right: 0.5em; +} +aside.footnote > p { + margin-left: 2em; +} +div.citation > p { + margin-left: 4em; +} +aside.footnote > p:last-of-type, +div.citation > p:last-of-type { + margin-bottom: 0em; +} +aside.footnote > p:last-of-type:after, +div.citation > p:last-of-type:after { + content: ""; + clear: both; +} + +dl.field-list { + display: grid; + grid-template-columns: fit-content(30%) auto; +} + +dl.field-list > dt { + font-weight: bold; + word-break: break-word; + padding-left: 0.5em; + padding-right: 5px; +} + +dl.field-list > dd { + padding-left: 0.5em; + margin-top: 0em; + margin-left: 0em; + margin-bottom: 0em; +} + +dl { + margin-bottom: 15px; +} + +dd > :first-child { + margin-top: 0px; +} + +dd ul, dd table { + margin-bottom: 10px; +} + +dd { + margin-top: 3px; + margin-bottom: 10px; + margin-left: 30px; +} + +.sig dd { + margin-top: 0px; + margin-bottom: 0px; +} + +.sig dl { + margin-top: 0px; + margin-bottom: 0px; +} + +dl > dd:last-child, +dl > dd:last-child > :last-child { + margin-bottom: 0; +} + +dt:target, span.highlighted { + background-color: #fbe54e; +} + +rect.highlighted { + fill: #fbe54e; +} + +dl.glossary dt { + font-weight: bold; + font-size: 1.1em; +} + +.versionmodified { + font-style: italic; +} + +.system-message { + background-color: #fda; + padding: 5px; + border: 3px solid red; +} + +.footnote:target { + background-color: #ffa; +} + +.line-block { + display: block; + margin-top: 1em; + margin-bottom: 1em; +} + +.line-block .line-block { + margin-top: 0; + margin-bottom: 0; + margin-left: 1.5em; +} + +.guilabel, .menuselection { + font-family: sans-serif; +} + +.accelerator { + text-decoration: underline; +} + +.classifier { + font-style: oblique; +} + +.classifier:before { + font-style: normal; + margin: 0 0.5em; + content: ":"; + display: inline-block; +} + +abbr, acronym { + border-bottom: dotted 1px; + cursor: help; +} + +.translated { + background-color: rgba(207, 255, 207, 0.2) +} + +.untranslated { + background-color: rgba(255, 207, 207, 0.2) +} + +/* -- code displays --------------------------------------------------------- */ + +pre { + overflow: auto; + overflow-y: hidden; /* fixes display issues on Chrome browsers */ +} + +pre, div[class*="highlight-"] { + clear: both; +} + +span.pre { + -moz-hyphens: none; + -ms-hyphens: none; + -webkit-hyphens: none; + hyphens: none; + white-space: nowrap; +} + +div[class*="highlight-"] { + margin: 1em 0; +} + +td.linenos pre { + border: 0; + background-color: transparent; + color: #aaa; +} + +table.highlighttable { + display: block; +} + +table.highlighttable tbody { + display: block; +} + +table.highlighttable tr { + display: flex; +} + +table.highlighttable td { + margin: 0; + padding: 0; +} + +table.highlighttable td.linenos { + padding-right: 0.5em; +} + +table.highlighttable td.code { + flex: 1; + overflow: hidden; +} + +.highlight .hll { + display: block; +} + +div.highlight pre, +table.highlighttable pre { + margin: 0; +} + +div.code-block-caption + div { + margin-top: 0; +} + +div.code-block-caption { + margin-top: 1em; + padding: 2px 5px; + font-size: small; +} + +div.code-block-caption code { + background-color: transparent; +} + +table.highlighttable td.linenos, +span.linenos, +div.highlight span.gp { /* gp: Generic.Prompt */ + user-select: none; + -webkit-user-select: text; /* Safari fallback only */ + -webkit-user-select: none; /* Chrome/Safari */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* IE10+ */ +} + +div.code-block-caption span.caption-number { + padding: 0.1em 0.3em; + font-style: italic; +} + +div.code-block-caption span.caption-text { +} + +div.literal-block-wrapper { + margin: 1em 0; +} + +code.xref, a code { + background-color: transparent; + font-weight: bold; +} + +h1 code, h2 code, h3 code, h4 code, h5 code, h6 code { + background-color: transparent; +} + +.viewcode-link { + float: right; +} + +.viewcode-back { + float: right; + font-family: sans-serif; +} + +div.viewcode-block:target { + margin: -1px -10px; + padding: 0 10px; +} + +/* -- math display ---------------------------------------------------------- */ + +img.math { + vertical-align: middle; +} + +div.body div.math p { + text-align: center; +} + +span.eqno { + float: right; +} + +span.eqno a.headerlink { + position: absolute; + z-index: 1; +} + +div.math:hover a.headerlink { + visibility: visible; +} + +/* -- printout stylesheet --------------------------------------------------- */ + +@media print { + div.document, + div.documentwrapper, + div.bodywrapper { + margin: 0 !important; + width: 100%; + } + + div.sphinxsidebar, + div.related, + div.footer, + #top-link { + display: none; + } +} diff --git a/_build/_static/debugger.png b/_build/_static/debugger.png new file mode 100644 index 00000000..7d4181f6 Binary files /dev/null and b/_build/_static/debugger.png differ diff --git a/_build/_static/describe_version.js b/_build/_static/describe_version.js new file mode 100644 index 00000000..19cd8d41 --- /dev/null +++ b/_build/_static/describe_version.js @@ -0,0 +1,198 @@ +/** + * Match a PEP 440 version string. The full regex given in PEP 440 is not used. + * This subset covers what we expect to encounter in our projects. + */ +const versionRe = new RegExp([ + "^", + "(?:(?[1-9][0-9]*)!)?", + "(?(?:0|[1-9][0-9]*)(?:\\.(?:0|[1-9][0-9]*))*)", + "(?:(?a|b|rc)(?0|[1-9][0-9]*))?", + "(?:\\.post(?0|[1-9][0-9]*))?", + "(?:\\.dev(?0|[1-9][0-9]*))?", + "$", +].join("")) + +/** + * Parse a PEP 440 version string into an object. + * + * @param {string} value + * @returns {Object} parsed version information + */ +function parseVersion(value) { + let {groups: {epoch, version, preL, preN, postN, devN}} = versionRe.exec(value) + return { + value: value, + parts: [ + parseInt(epoch) || 0, ...version.split(".").map(p => parseInt(p)) + ], + isPre: Boolean(preL), + preL: preL || "", + preN: parseInt(preN) || 0, + isPost: Boolean(postN), + postN: parseInt(postN) || 0, + isDev: Boolean(devN), + devN: parseInt(devN) || 0, + } +} + +/** + * Compare two version objects. + * + * @param {Object} a left side of comparison + * @param {Object} b right side of comparison + * @returns {number} -1 less than, 0 equal to, 1 greater than + */ +function compareVersions(a, b) { + for (let [i, an] of a.parts.entries()) { + let bn = i < b.parts.length ? b.parts[i] : 0 + + if (an < bn) { + return -1 + } else if (an > bn) { + return 1 + } + } + + if (a.parts.length < b.parts.length) { + return -1 + } + + return 0 +} + +/** + * Get the list of released versions for the project from PyPI. Prerelease and + * development versions are discarded. The list is sorted in descending order, + * highest version first. + * + * This will be called on every page load. To avoid making excessive requests to + * PyPI, the result is cached for 1 day. PyPI also sends cache headers, so a + * subsequent request may still be more efficient, but it only specifies caching + * the full response for 5 minutes. + * + * @param {string} name The normalized PyPI project name to query. + * @returns {Promise} A sorted list of version objects. + */ +async function getReleasedVersions(name) { + // The response from PyPI is only cached for 5 minutes. Extend that to 1 day. + let cacheTime = localStorage.getItem("describeVersion-time") + let cacheResult = localStorage.getItem("describeVersion-result") + + // if there is a cached value + if (cacheTime && cacheResult) { + // if the cache is younger than 1 day + if (Number(cacheTime) >= Date.now() - 86400000) { + // Use the cached value instead of making another request. + return JSON.parse(cacheResult) + } + } + + let response = await fetch( + `https://pypi.org/simple/${name}/`, + {"headers": {"Accept": "application/vnd.pypi.simple.v1+json"}} + ) + let data = await response.json() + let result = data["versions"] + .map(parseVersion) + .filter(v => !(v.isPre || v.isDev)) + .sort(compareVersions) + .reverse() + localStorage.setItem("describeVersion-time", Date.now().toString()) + localStorage.setItem("describeVersion-result", JSON.stringify(result)) + return result +} + +/** + * Get the highest released version of the project from PyPI, and compare the + * version being documented. Returns a list of two values, the comparison + * result and the highest version. + * + * @param name The normalized PyPI project name. + * @param value The version being documented. + * @returns {Promise<[number, Object|null]>} + */ +async function describeVersion(name, value) { + if (value.endsWith(".x")) { + value = value.slice(0, -2) + } + + let currentVersion = parseVersion(value) + let releasedVersions = await getReleasedVersions(name) + + if (releasedVersions.length === 0) { + return [1, null] + } + + let highestVersion = releasedVersions[0] + let compared = compareVersions(currentVersion, highestVersion) + + if (compared === 1) { + return [1, highestVersion] + } + + // If the current version including trailing zeros is a prefix of the highest + // version, then these are the stable docs. For example, 2.0.x becomes 2.0, + // which is a prefix of 2.0.3. If we were just looking at the compare result, + // it would incorrectly be marked as an old version. + if (currentVersion.parts.every((n, i) => n === highestVersion.parts[i])) { + return [0, highestVersion] + } + + return [-1, highestVersion] +} + +/** + * Compare the version being documented to the highest released version, and + * display a warning banner if it is not the highest version. + * + * @param project The normalized PyPI project name. + * @param version The version being documented. + * @returns {Promise} + */ +async function createBanner(project, version) { + let [compared, stable] = await describeVersion(project, version) + + // No banner if this is the highest version or there are no other versions. + if (compared === 0 || stable === null) { + return + } + + let banner = document.createElement("p") + banner.className = "version-warning" + + if (compared === 1) { + banner.textContent = "This is the development version. The stable version is " + } else if (compared === -1) { + banner.textContent = "This is an old version. The current version is " + } + + let canonical = document.querySelector('link[rel="canonical"]') + + if (canonical !== null) { + // If a canonical URL is available, the version is a link to it. + let link = document.createElement("a") + link.href = canonical.href + link.textContent = stable.value + banner.append(link, ".") + } else { + // Otherwise, the version is text only. + banner.append(stable.value, ".") + } + + document.getElementsByClassName("document")[0].prepend(banner) + // Set scroll-padding-top to prevent the banner from overlapping anchors. + // It's also set in CSS assuming the banner text is only 1 line. + let bannerStyle = window.getComputedStyle(banner) + let bannerMarginTop = parseFloat(bannerStyle["margin-top"]) + let bannerMarginBottom = parseFloat(bannerStyle["margin-bottom"]) + let height = banner.offsetHeight + bannerMarginTop + bannerMarginBottom + document.documentElement.style["scroll-padding-top"] = `${height}px` +} + +(() => { + // currentScript is only available during init, not during callbacks. + let {project, version} = document.currentScript.dataset + document.addEventListener("DOMContentLoaded", async () => { + await createBanner(project, version) + }) +})() diff --git a/_build/_static/doctools.js b/_build/_static/doctools.js new file mode 100644 index 00000000..0398ebb9 --- /dev/null +++ b/_build/_static/doctools.js @@ -0,0 +1,149 @@ +/* + * Base JavaScript utilities for all Sphinx HTML documentation. + */ +"use strict"; + +const BLACKLISTED_KEY_CONTROL_ELEMENTS = new Set([ + "TEXTAREA", + "INPUT", + "SELECT", + "BUTTON", +]); + +const _ready = (callback) => { + if (document.readyState !== "loading") { + callback(); + } else { + document.addEventListener("DOMContentLoaded", callback); + } +}; + +/** + * Small JavaScript module for the documentation. + */ +const Documentation = { + init: () => { + Documentation.initDomainIndexTable(); + Documentation.initOnKeyListeners(); + }, + + /** + * i18n support + */ + TRANSLATIONS: {}, + PLURAL_EXPR: (n) => (n === 1 ? 0 : 1), + LOCALE: "unknown", + + // gettext and ngettext don't access this so that the functions + // can safely bound to a different name (_ = Documentation.gettext) + gettext: (string) => { + const translated = Documentation.TRANSLATIONS[string]; + switch (typeof translated) { + case "undefined": + return string; // no translation + case "string": + return translated; // translation exists + default: + return translated[0]; // (singular, plural) translation tuple exists + } + }, + + ngettext: (singular, plural, n) => { + const translated = Documentation.TRANSLATIONS[singular]; + if (typeof translated !== "undefined") + return translated[Documentation.PLURAL_EXPR(n)]; + return n === 1 ? singular : plural; + }, + + addTranslations: (catalog) => { + Object.assign(Documentation.TRANSLATIONS, catalog.messages); + Documentation.PLURAL_EXPR = new Function( + "n", + `return (${catalog.plural_expr})` + ); + Documentation.LOCALE = catalog.locale; + }, + + /** + * helper function to focus on search bar + */ + focusSearchBar: () => { + document.querySelectorAll("input[name=q]")[0]?.focus(); + }, + + /** + * Initialise the domain index toggle buttons + */ + initDomainIndexTable: () => { + const toggler = (el) => { + const idNumber = el.id.substr(7); + const toggledRows = document.querySelectorAll(`tr.cg-${idNumber}`); + if (el.src.substr(-9) === "minus.png") { + el.src = `${el.src.substr(0, el.src.length - 9)}plus.png`; + toggledRows.forEach((el) => (el.style.display = "none")); + } else { + el.src = `${el.src.substr(0, el.src.length - 8)}minus.png`; + toggledRows.forEach((el) => (el.style.display = "")); + } + }; + + const togglerElements = document.querySelectorAll("img.toggler"); + togglerElements.forEach((el) => + el.addEventListener("click", (event) => toggler(event.currentTarget)) + ); + togglerElements.forEach((el) => (el.style.display = "")); + if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) togglerElements.forEach(toggler); + }, + + initOnKeyListeners: () => { + // only install a listener if it is really needed + if ( + !DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS && + !DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS + ) + return; + + document.addEventListener("keydown", (event) => { + // bail for input elements + if (BLACKLISTED_KEY_CONTROL_ELEMENTS.has(document.activeElement.tagName)) return; + // bail with special keys + if (event.altKey || event.ctrlKey || event.metaKey) return; + + if (!event.shiftKey) { + switch (event.key) { + case "ArrowLeft": + if (!DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) break; + + const prevLink = document.querySelector('link[rel="prev"]'); + if (prevLink && prevLink.href) { + window.location.href = prevLink.href; + event.preventDefault(); + } + break; + case "ArrowRight": + if (!DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) break; + + const nextLink = document.querySelector('link[rel="next"]'); + if (nextLink && nextLink.href) { + window.location.href = nextLink.href; + event.preventDefault(); + } + break; + } + } + + // some keyboard layouts may need Shift to get / + switch (event.key) { + case "/": + if (!DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS) break; + Documentation.focusSearchBar(); + event.preventDefault(); + } + }); + }, +}; + +// quick alias for translations +const _ = Documentation.gettext; + +_ready(Documentation.init); diff --git a/_build/_static/documentation_options.js b/_build/_static/documentation_options.js new file mode 100644 index 00000000..59bfa93b --- /dev/null +++ b/_build/_static/documentation_options.js @@ -0,0 +1,13 @@ +const DOCUMENTATION_OPTIONS = { + VERSION: '3.1.1.dev0', + LANGUAGE: 'en', + COLLAPSE_INDEX: false, + BUILDER: 'dirhtml', + FILE_SUFFIX: '.html', + LINK_SUFFIX: '.html', + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt', + NAVIGATION_WITH_KEYS: false, + SHOW_SEARCH_SUMMARY: true, + ENABLE_SEARCH_SHORTCUTS: true, +}; diff --git a/_build/_static/file.png b/_build/_static/file.png new file mode 100644 index 00000000..a858a410 Binary files /dev/null and b/_build/_static/file.png differ diff --git a/_build/_static/flask-horizontal.png b/_build/_static/flask-horizontal.png new file mode 100644 index 00000000..a0df2c61 Binary files /dev/null and b/_build/_static/flask-horizontal.png differ diff --git a/_build/_static/flask-vertical.png b/_build/_static/flask-vertical.png new file mode 100644 index 00000000..d1fd1499 Binary files /dev/null and b/_build/_static/flask-vertical.png differ diff --git a/_build/_static/flask.css b/_build/_static/flask.css new file mode 100644 index 00000000..e37830da --- /dev/null +++ b/_build/_static/flask.css @@ -0,0 +1,15 @@ +@import url("pocoo.css"); + +a, a.reference, a.footnote-reference { + color: #004b6b; + text-decoration-color: #004b6b; +} + +a:hover { + color: #6d4100; + text-decoration-color: #6d4100; +} + +p.version-warning { + background-color: #004b6b; +} diff --git a/_build/_static/language_data.js b/_build/_static/language_data.js new file mode 100644 index 00000000..a5ea78e1 --- /dev/null +++ b/_build/_static/language_data.js @@ -0,0 +1,191 @@ +/* + * This script contains the language-specific data used by searchtools.js, + * namely the list of stopwords, stemmer, scorer and splitter. + */ + +var stopwords = ["a", "and", "are", "as", "at", "be", "but", "by", "for", "if", "in", "into", "is", "it", "near", "no", "not", "of", "on", "or", "such", "that", "the", "their", "then", "there", "these", "they", "this", "to", "was", "will", "with"]; + + +/* Non-minified version is copied as a separate JS file, if available */ + +/** + * Porter Stemmer + */ +var Stemmer = function() { + + var step2list = { + ational: 'ate', + tional: 'tion', + enci: 'ence', + anci: 'ance', + izer: 'ize', + bli: 'ble', + alli: 'al', + entli: 'ent', + eli: 'e', + ousli: 'ous', + ization: 'ize', + ation: 'ate', + ator: 'ate', + alism: 'al', + iveness: 'ive', + fulness: 'ful', + ousness: 'ous', + aliti: 'al', + iviti: 'ive', + biliti: 'ble', + logi: 'log' + }; + + var step3list = { + icate: 'ic', + ative: '', + alize: 'al', + iciti: 'ic', + ical: 'ic', + ful: '', + ness: '' + }; + + var c = "[^aeiou]"; // consonant + var v = "[aeiouy]"; // vowel + var C = c + "[^aeiouy]*"; // consonant sequence + var V = v + "[aeiou]*"; // vowel sequence + + var mgr0 = "^(" + C + ")?" + V + C; // [C]VC... is m>0 + var meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$"; // [C]VC[V] is m=1 + var mgr1 = "^(" + C + ")?" + V + C + V + C; // [C]VCVC... is m>1 + var s_v = "^(" + C + ")?" + v; // vowel in stem + + this.stemWord = function (w) { + var stem; + var suffix; + var firstch; + var origword = w; + + if (w.length < 3) + return w; + + var re; + var re2; + var re3; + var re4; + + firstch = w.substr(0,1); + if (firstch == "y") + w = firstch.toUpperCase() + w.substr(1); + + // Step 1a + re = /^(.+?)(ss|i)es$/; + re2 = /^(.+?)([^s])s$/; + + if (re.test(w)) + w = w.replace(re,"$1$2"); + else if (re2.test(w)) + w = w.replace(re2,"$1$2"); + + // Step 1b + re = /^(.+?)eed$/; + re2 = /^(.+?)(ed|ing)$/; + if (re.test(w)) { + var fp = re.exec(w); + re = new RegExp(mgr0); + if (re.test(fp[1])) { + re = /.$/; + w = w.replace(re,""); + } + } + else if (re2.test(w)) { + var fp = re2.exec(w); + stem = fp[1]; + re2 = new RegExp(s_v); + if (re2.test(stem)) { + w = stem; + re2 = /(at|bl|iz)$/; + re3 = new RegExp("([^aeiouylsz])\\1$"); + re4 = new RegExp("^" + C + v + "[^aeiouwxy]$"); + if (re2.test(w)) + w = w + "e"; + else if (re3.test(w)) { + re = /.$/; + w = w.replace(re,""); + } + else if (re4.test(w)) + w = w + "e"; + } + } + + // Step 1c + re = /^(.+?)y$/; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + re = new RegExp(s_v); + if (re.test(stem)) + w = stem + "i"; + } + + // Step 2 + re = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + suffix = fp[2]; + re = new RegExp(mgr0); + if (re.test(stem)) + w = stem + step2list[suffix]; + } + + // Step 3 + re = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + suffix = fp[2]; + re = new RegExp(mgr0); + if (re.test(stem)) + w = stem + step3list[suffix]; + } + + // Step 4 + re = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/; + re2 = /^(.+?)(s|t)(ion)$/; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + re = new RegExp(mgr1); + if (re.test(stem)) + w = stem; + } + else if (re2.test(w)) { + var fp = re2.exec(w); + stem = fp[1] + fp[2]; + re2 = new RegExp(mgr1); + if (re2.test(stem)) + w = stem; + } + + // Step 5 + re = /^(.+?)e$/; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + re = new RegExp(mgr1); + re2 = new RegExp(meq1); + re3 = new RegExp("^" + C + v + "[^aeiouwxy]$"); + if (re.test(stem) || (re2.test(stem) && !(re3.test(stem)))) + w = stem; + } + re = /ll$/; + re2 = new RegExp(mgr1); + if (re.test(w) && re2.test(w)) { + re = /.$/; + w = w.replace(re,""); + } + + // and turn initial Y back to y + if (firstch == "y") + w = firstch.toLowerCase() + w.substr(1); + return w; + } +} diff --git a/_build/_static/minus.png b/_build/_static/minus.png new file mode 100644 index 00000000..d96755fd Binary files /dev/null and b/_build/_static/minus.png differ diff --git a/_build/_static/plus.png b/_build/_static/plus.png new file mode 100644 index 00000000..7107cec9 Binary files /dev/null and b/_build/_static/plus.png differ diff --git a/_build/_static/pocoo.css b/_build/_static/pocoo.css new file mode 100644 index 00000000..7a01d1d5 --- /dev/null +++ b/_build/_static/pocoo.css @@ -0,0 +1,515 @@ +@import url("basic.css"); + +/* -- page layout --------------------------------------------------- */ + +html { + scroll-padding-top: calc(30px + 1em); + /* see .version-warning selector for banner positioning */ +} + +body { + font-family: 'Garamond', 'Georgia', serif; + font-size: 17px; + background-color: #fff; + color: #3e4349; + margin: 0; + padding: 0; +} + +div.related { + max-width: 1140px; + margin: 10px auto; + + /* displayed on mobile */ + display: none; +} + +div.document { + max-width: 1140px; + margin: 10px auto; +} + +div.documentwrapper { + float: left; + width: 100%; +} + +div.bodywrapper { + margin: 0 0 0 220px; +} + +div.body { + min-width: initial; + max-width: initial; + padding: 0 30px; +} + +div.sphinxsidebarwrapper { + padding: 10px; +} + +div.sphinxsidebar { + width: 220px; + font-size: 14px; + line-height: 1.5; + color: #444; +} + +div.sphinxsidebar li { + overflow: hidden; + text-overflow: ellipsis; +} + +div.sphinxsidebar li:hover { + overflow: visible; +} + +div.sphinxsidebar a, +div.sphinxsidebar a code { + color: #444; + border-color: #444; +} + +div.sphinxsidebar a:hover { + background-color:#fff; +} + +div.sphinxsidebar p.logo { + margin: 0; + text-align: center; +} + +div.sphinxsidebar h3, +div.sphinxsidebar h4 { + font-size: 24px; + color: #444; +} + +div.sphinxsidebar p.logo a, +div.sphinxsidebar h3 a, +div.sphinxsidebar p.logo a:hover, +div.sphinxsidebar h3 a:hover { + border: none; +} + +div.sphinxsidebar p, +div.sphinxsidebar h3, +div.sphinxsidebar h4 { + margin: 10px 0; +} + +div.sphinxsidebar ul { + margin: 10px 0; + padding: 0; +} + +div.sphinxsidebar input { + border: 1px solid #999; + font-size: 1em; +} + +div.footer { + max-width: 1140px; + margin: 20px auto; + font-size: 14px; + text-align: right; + color: #888; +} + +div.footer a { + color: #888; + border-color: #888; +} + +/* -- quick search -------------------------------------------------- */ + +div.sphinxsidebar #searchbox form { + display: flex; +} + +div.sphinxsidebar #searchbox form > div { + display: flex; + flex: 1 1 auto; +} + +div.sphinxsidebar #searchbox input[type=text] { + flex: 1 1 auto; + width: 1% !important; +} + +div.sphinxsidebar #searchbox input[type=submit] { + border-left-width: 0; +} + +/* -- version warning ----------------------------------------------- */ + +/* see html selector for scroll offset */ + +p.version-warning { + top: 10px; + position: sticky; + + margin: 10px 0; + padding: 5px 10px; + border-radius: 4px; + + letter-spacing: 1px; + color: #fff; + text-shadow: 0 0 2px #000; + text-align: center; + + background: #d40 repeating-linear-gradient( + 135deg, + transparent, + transparent 56px, + rgba(255, 255, 255, 0.2) 56px, + rgba(255, 255, 255, 0.2) 112px + ); +} + +p.version-warning a { + color: #fff; + border-color: #fff; +} + +/* -- body styles --------------------------------------------------- */ + +a { + text-decoration: underline; + text-decoration-style: dotted; + text-decoration-color: #000; + text-decoration-thickness: 1px; +} + +a:hover { + text-decoration-style: solid; +} + +h1, h2, h3, h4, h5, h6 { + font-weight: normal; + margin: 30px 0 10px; + padding: 0; + color: black; +} + +div.body h1 { + font-size: 240%; +} + +div.body h2 { + font-size: 180%; +} + +div.body h3 { + font-size: 150%; +} + +div.body h4 { + font-size: 130%; +} + +div.body h5 { + font-size: 100%; +} + +div.body h6 { + font-size: 100%; +} + +div.body h1:first-of-type { + margin-top: 0; +} + +a.headerlink { + color: #ddd; + margin: 0 0.2em; + padding: 0 0.2em; + border: none; +} + +a.headerlink:hover { + color: #444; +} + +div.body p, +div.body dd, +div.body li { + line-height: 1.4; +} + +img.screenshot { + box-shadow: 2px 2px 4px #eee; +} + +hr { + border: 1px solid #999; +} + +blockquote { + margin: 0 0 0 30px; + padding: 0; +} + +ul, ol { + margin: 10px 0 10px 30px; + padding: 0; +} + +a.footnote-reference { + font-size: 0.7em; + vertical-align: top; +} + +/* -- admonitions --------------------------------------------------- */ + +div.admonition, +div.topic { + background-color: #fafafa; + margin: 10px -10px; + padding: 10px; + border-top: 1px solid #ccc; + border-right: none; + border-bottom: 1px solid #ccc; + border-left: none; +} + +div.admonition p.admonition-title, +div.topic p.topic-title { + font-weight: normal; + font-size: 24px; + margin: 0 0 10px 0; + padding: 0; + line-height: 1; + display: inline; +} + +p.admonition-title::after { + content: ":"; +} + +div.admonition p.last, +div.topic p:last-child { + margin-bottom: 0; +} + +div.danger, div.error { + background-color: #fff0f0; + border-color: #ffb0b0; +} + +div.seealso { + background-color: #fffff0; + border-color: #f0f0a8; +} + +/* -- changelog ----------------------------------------------------- */ + +details.changelog summary { + cursor: pointer; + font-style: italic; + margin-bottom: 10px; +} + +/* -- search highlight ---------------------------------------------- */ + +dt:target, +.footnote:target, +span.highlighted { + background-color: #ffdf80; +} + +rect.highlighted { + fill: #ffdf80; +} + +/* -- code displays ------------------------------------------------- */ + +pre, code { + font-family: 'Consolas', 'Menlo', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', monospace; + font-size: 0.9em; +} + +pre { + margin: 0; + padding: 0; + line-height: 1.3; +} + +div.literal-block-wrapper { + padding: 10px 0 0; +} + +div.code-block-caption { + padding: 0; +} + +div.highlight, div.literal-block-wrapper div.highlight { + margin: 10px -10px; + padding: 10px; +} + +code { + color: #222; + background: #e8eff0; +} + +/* -- tables -------------------------------------------------------- */ + +table.docutils { + border: 1px solid #888; + box-shadow: 2px 2px 4px #eee; +} + +table.docutils td, +table.docutils th { + border: 1px solid #888; + padding: 0.25em 0.7em; +} + +table.field-list, +table.footnote { + border: none; + box-shadow: none; +} + +table.footnote { + margin: 15px 0; + width: 100%; + border: 1px solid #eee; + background-color: #fafafa; + font-size: 0.9em; +} + +table.footnote + table.footnote { + margin-top: -15px; + border-top: none; +} + +table.field-list th { + padding: 0 0.8em 0 0; +} + +table.field-list td { + padding: 0; +} + +table.footnote td.label { + width: 0; + padding: 0.3em 0 0.3em 0.5em; +} + +table.footnote td { + padding: 0.3em 0.5em; +} + +/* -- responsive screen --------------------------------------------- */ + +@media screen and (max-width: 1139px) { + p.version-warning { + margin: 10px; + } + + div.footer { + margin: 20px 10px; + } +} + +/* -- small screen -------------------------------------------------- */ + +@media screen and (max-width: 767px) { + body { + padding: 0 20px; + } + + div.related { + display: block; + } + + p.version-warning { + margin: 10px 0; + } + + div.documentwrapper { + float: none; + } + + div.bodywrapper { + margin: 0; + } + + div.body { + min-height: 0; + padding: 0; + } + + div.sphinxsidebar { + float: none; + width: 100%; + margin: 0 -20px -10px; + padding: 0 20px; + background-color: #333; + color: #ccc; + } + + div.sphinxsidebar a, + div.sphinxsidebar a code, + div.sphinxsidebar h3, + div.sphinxsidebar h4, + div.footer a { + color: #ccc; + border-color: #ccc; + } + + div.sphinxsidebar p.logo { + display: none; + } + + div.footer { + text-align: left; + margin: 0 -20px; + padding: 20px; + background-color: #333; + color: #ccc; + } +} + +/* https://github.com/twbs/bootstrap/blob + /0e8831505ac845f3102fa2c5996a7141c9ab01ee + /scss/mixins/_screen-reader.scss */ +.hide-header > h1:first-child { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} + +/* -- sphinx-tabs -------------------------------------------------- */ + +.sphinx-tabs { + margin-bottom: 0; +} + +.sphinx-tabs .ui.menu { + font-family: 'Garamond', 'Georgia', serif !important; +} + +.sphinx-tabs .ui.attached.menu { + border-bottom: none +} + +.sphinx-tabs .ui.tabular.menu .item { + border-bottom: 2px solid transparent; + border-left: none; + border-right: none; + border-top: none; + padding: .3em 0.6em; +} + +.sphinx-tabs .ui.attached.segment, .ui.segment { + border: 0; + padding: 0; +} diff --git a/_build/_static/pycharm-run-config.png b/_build/_static/pycharm-run-config.png new file mode 100644 index 00000000..ad025545 Binary files /dev/null and b/_build/_static/pycharm-run-config.png differ diff --git a/_build/_static/pygments.css b/_build/_static/pygments.css new file mode 100644 index 00000000..809cf3f0 --- /dev/null +++ b/_build/_static/pygments.css @@ -0,0 +1,84 @@ +pre { line-height: 125%; } +td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; } +span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; } +td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; } +span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; } +.highlight .hll { background-color: #ffffcc } +.highlight { background: #f8f8f8; } +.highlight .c { color: #8f5902; font-style: italic } /* Comment */ +.highlight .err { color: #a40000; border: 1px solid #ef2929 } /* Error */ +.highlight .g { color: #000000 } /* Generic */ +.highlight .k { color: #004461; font-weight: bold } /* Keyword */ +.highlight .l { color: #000000 } /* Literal */ +.highlight .n { color: #000000 } /* Name */ +.highlight .o { color: #582800 } /* Operator */ +.highlight .x { color: #000000 } /* Other */ +.highlight .p { color: #000000; font-weight: bold } /* Punctuation */ +.highlight .ch { color: #8f5902; font-style: italic } /* Comment.Hashbang */ +.highlight .cm { color: #8f5902; font-style: italic } /* Comment.Multiline */ +.highlight .cp { color: #8f5902 } /* Comment.Preproc */ +.highlight .cpf { color: #8f5902; font-style: italic } /* Comment.PreprocFile */ +.highlight .c1 { color: #8f5902; font-style: italic } /* Comment.Single */ +.highlight .cs { color: #8f5902; font-style: italic } /* Comment.Special */ +.highlight .gd { color: #a40000 } /* Generic.Deleted */ +.highlight .ge { color: #000000; font-style: italic } /* Generic.Emph */ +.highlight .ges { color: #000000 } /* Generic.EmphStrong */ +.highlight .gr { color: #ef2929 } /* Generic.Error */ +.highlight .gh { color: #000080; font-weight: bold } /* Generic.Heading */ +.highlight .gi { color: #00A000 } /* Generic.Inserted */ +.highlight .go { color: #888888 } /* Generic.Output */ +.highlight .gp { color: #745334 } /* Generic.Prompt */ +.highlight .gs { color: #000000; font-weight: bold } /* Generic.Strong */ +.highlight .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ +.highlight .gt { color: #a40000; font-weight: bold } /* Generic.Traceback */ +.highlight .kc { color: #004461; font-weight: bold } /* Keyword.Constant */ +.highlight .kd { color: #004461; font-weight: bold } /* Keyword.Declaration */ +.highlight .kn { color: #004461; font-weight: bold } /* Keyword.Namespace */ +.highlight .kp { color: #004461; font-weight: bold } /* Keyword.Pseudo */ +.highlight .kr { color: #004461; font-weight: bold } /* Keyword.Reserved */ +.highlight .kt { color: #004461; font-weight: bold } /* Keyword.Type */ +.highlight .ld { color: #000000 } /* Literal.Date */ +.highlight .m { color: #990000 } /* Literal.Number */ +.highlight .s { color: #4e9a06 } /* Literal.String */ +.highlight .na { color: #c4a000 } /* Name.Attribute */ +.highlight .nb { color: #004461 } /* Name.Builtin */ +.highlight .nc { color: #000000 } /* Name.Class */ +.highlight .no { color: #000000 } /* Name.Constant */ +.highlight .nd { color: #888888 } /* Name.Decorator */ +.highlight .ni { color: #ce5c00 } /* Name.Entity */ +.highlight .ne { color: #cc0000; font-weight: bold } /* Name.Exception */ +.highlight .nf { color: #000000 } /* Name.Function */ +.highlight .nl { color: #f57900 } /* Name.Label */ +.highlight .nn { color: #000000 } /* Name.Namespace */ +.highlight .nx { color: #000000 } /* Name.Other */ +.highlight .py { color: #000000 } /* Name.Property */ +.highlight .nt { color: #004461; font-weight: bold } /* Name.Tag */ +.highlight .nv { color: #000000 } /* Name.Variable */ +.highlight .ow { color: #004461; font-weight: bold } /* Operator.Word */ +.highlight .pm { color: #000000; font-weight: bold } /* Punctuation.Marker */ +.highlight .w { color: #f8f8f8; text-decoration: underline } /* Text.Whitespace */ +.highlight .mb { color: #990000 } /* Literal.Number.Bin */ +.highlight .mf { color: #990000 } /* Literal.Number.Float */ +.highlight .mh { color: #990000 } /* Literal.Number.Hex */ +.highlight .mi { color: #990000 } /* Literal.Number.Integer */ +.highlight .mo { color: #990000 } /* Literal.Number.Oct */ +.highlight .sa { color: #4e9a06 } /* Literal.String.Affix */ +.highlight .sb { color: #4e9a06 } /* Literal.String.Backtick */ +.highlight .sc { color: #4e9a06 } /* Literal.String.Char */ +.highlight .dl { color: #4e9a06 } /* Literal.String.Delimiter */ +.highlight .sd { color: #8f5902; font-style: italic } /* Literal.String.Doc */ +.highlight .s2 { color: #4e9a06 } /* Literal.String.Double */ +.highlight .se { color: #4e9a06 } /* Literal.String.Escape */ +.highlight .sh { color: #4e9a06 } /* Literal.String.Heredoc */ +.highlight .si { color: #4e9a06 } /* Literal.String.Interpol */ +.highlight .sx { color: #4e9a06 } /* Literal.String.Other */ +.highlight .sr { color: #4e9a06 } /* Literal.String.Regex */ +.highlight .s1 { color: #4e9a06 } /* Literal.String.Single */ +.highlight .ss { color: #4e9a06 } /* Literal.String.Symbol */ +.highlight .bp { color: #3465a4 } /* Name.Builtin.Pseudo */ +.highlight .fm { color: #000000 } /* Name.Function.Magic */ +.highlight .vc { color: #000000 } /* Name.Variable.Class */ +.highlight .vg { color: #000000 } /* Name.Variable.Global */ +.highlight .vi { color: #000000 } /* Name.Variable.Instance */ +.highlight .vm { color: #000000 } /* Name.Variable.Magic */ +.highlight .il { color: #990000 } /* Literal.Number.Integer.Long */ diff --git a/_build/_static/searchtools.js b/_build/_static/searchtools.js new file mode 100644 index 00000000..2c774d17 --- /dev/null +++ b/_build/_static/searchtools.js @@ -0,0 +1,632 @@ +/* + * Sphinx JavaScript utilities for the full-text search. + */ +"use strict"; + +/** + * Simple result scoring code. + */ +if (typeof Scorer === "undefined") { + var Scorer = { + // Implement the following function to further tweak the score for each result + // The function takes a result array [docname, title, anchor, descr, score, filename] + // and returns the new score. + /* + score: result => { + const [docname, title, anchor, descr, score, filename, kind] = result + return score + }, + */ + + // query matches the full name of an object + objNameMatch: 11, + // or matches in the last dotted part of the object name + objPartialMatch: 6, + // Additive scores depending on the priority of the object + objPrio: { + 0: 15, // used to be importantResults + 1: 5, // used to be objectResults + 2: -5, // used to be unimportantResults + }, + // Used when the priority is not in the mapping. + objPrioDefault: 0, + + // query found in title + title: 15, + partialTitle: 7, + // query found in terms + term: 5, + partialTerm: 2, + }; +} + +// Global search result kind enum, used by themes to style search results. +class SearchResultKind { + static get index() { return "index"; } + static get object() { return "object"; } + static get text() { return "text"; } + static get title() { return "title"; } +} + +const _removeChildren = (element) => { + while (element && element.lastChild) element.removeChild(element.lastChild); +}; + +/** + * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping + */ +const _escapeRegExp = (string) => + string.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string + +const _displayItem = (item, searchTerms, highlightTerms) => { + const docBuilder = DOCUMENTATION_OPTIONS.BUILDER; + const docFileSuffix = DOCUMENTATION_OPTIONS.FILE_SUFFIX; + const docLinkSuffix = DOCUMENTATION_OPTIONS.LINK_SUFFIX; + const showSearchSummary = DOCUMENTATION_OPTIONS.SHOW_SEARCH_SUMMARY; + const contentRoot = document.documentElement.dataset.content_root; + + const [docName, title, anchor, descr, score, _filename, kind] = item; + + let listItem = document.createElement("li"); + // Add a class representing the item's type: + // can be used by a theme's CSS selector for styling + // See SearchResultKind for the class names. + listItem.classList.add(`kind-${kind}`); + let requestUrl; + let linkUrl; + if (docBuilder === "dirhtml") { + // dirhtml builder + let dirname = docName + "/"; + if (dirname.match(/\/index\/$/)) + dirname = dirname.substring(0, dirname.length - 6); + else if (dirname === "index/") dirname = ""; + requestUrl = contentRoot + dirname; + linkUrl = requestUrl; + } else { + // normal html builders + requestUrl = contentRoot + docName + docFileSuffix; + linkUrl = docName + docLinkSuffix; + } + let linkEl = listItem.appendChild(document.createElement("a")); + linkEl.href = linkUrl + anchor; + linkEl.dataset.score = score; + linkEl.innerHTML = title; + if (descr) { + listItem.appendChild(document.createElement("span")).innerHTML = + " (" + descr + ")"; + // highlight search terms in the description + if (SPHINX_HIGHLIGHT_ENABLED) // set in sphinx_highlight.js + highlightTerms.forEach((term) => _highlightText(listItem, term, "highlighted")); + } + else if (showSearchSummary) + fetch(requestUrl) + .then((responseData) => responseData.text()) + .then((data) => { + if (data) + listItem.appendChild( + Search.makeSearchSummary(data, searchTerms, anchor) + ); + // highlight search terms in the summary + if (SPHINX_HIGHLIGHT_ENABLED) // set in sphinx_highlight.js + highlightTerms.forEach((term) => _highlightText(listItem, term, "highlighted")); + }); + Search.output.appendChild(listItem); +}; +const _finishSearch = (resultCount) => { + Search.stopPulse(); + Search.title.innerText = _("Search Results"); + if (!resultCount) + Search.status.innerText = Documentation.gettext( + "Your search did not match any documents. Please make sure that all words are spelled correctly and that you've selected enough categories." + ); + else + Search.status.innerText = Documentation.ngettext( + "Search finished, found one page matching the search query.", + "Search finished, found ${resultCount} pages matching the search query.", + resultCount, + ).replace('${resultCount}', resultCount); +}; +const _displayNextItem = ( + results, + resultCount, + searchTerms, + highlightTerms, +) => { + // results left, load the summary and display it + // this is intended to be dynamic (don't sub resultsCount) + if (results.length) { + _displayItem(results.pop(), searchTerms, highlightTerms); + setTimeout( + () => _displayNextItem(results, resultCount, searchTerms, highlightTerms), + 5 + ); + } + // search finished, update title and status message + else _finishSearch(resultCount); +}; +// Helper function used by query() to order search results. +// Each input is an array of [docname, title, anchor, descr, score, filename, kind]. +// Order the results by score (in opposite order of appearance, since the +// `_displayNextItem` function uses pop() to retrieve items) and then alphabetically. +const _orderResultsByScoreThenName = (a, b) => { + const leftScore = a[4]; + const rightScore = b[4]; + if (leftScore === rightScore) { + // same score: sort alphabetically + const leftTitle = a[1].toLowerCase(); + const rightTitle = b[1].toLowerCase(); + if (leftTitle === rightTitle) return 0; + return leftTitle > rightTitle ? -1 : 1; // inverted is intentional + } + return leftScore > rightScore ? 1 : -1; +}; + +/** + * Default splitQuery function. Can be overridden in ``sphinx.search`` with a + * custom function per language. + * + * The regular expression works by splitting the string on consecutive characters + * that are not Unicode letters, numbers, underscores, or emoji characters. + * This is the same as ``\W+`` in Python, preserving the surrogate pair area. + */ +if (typeof splitQuery === "undefined") { + var splitQuery = (query) => query + .split(/[^\p{Letter}\p{Number}_\p{Emoji_Presentation}]+/gu) + .filter(term => term) // remove remaining empty strings +} + +/** + * Search Module + */ +const Search = { + _index: null, + _queued_query: null, + _pulse_status: -1, + + htmlToText: (htmlString, anchor) => { + const htmlElement = new DOMParser().parseFromString(htmlString, 'text/html'); + for (const removalQuery of [".headerlink", "script", "style"]) { + htmlElement.querySelectorAll(removalQuery).forEach((el) => { el.remove() }); + } + if (anchor) { + const anchorContent = htmlElement.querySelector(`[role="main"] ${anchor}`); + if (anchorContent) return anchorContent.textContent; + + console.warn( + `Anchored content block not found. Sphinx search tries to obtain it via DOM query '[role=main] ${anchor}'. Check your theme or template.` + ); + } + + // if anchor not specified or not found, fall back to main content + const docContent = htmlElement.querySelector('[role="main"]'); + if (docContent) return docContent.textContent; + + console.warn( + "Content block not found. Sphinx search tries to obtain it via DOM query '[role=main]'. Check your theme or template." + ); + return ""; + }, + + init: () => { + const query = new URLSearchParams(window.location.search).get("q"); + document + .querySelectorAll('input[name="q"]') + .forEach((el) => (el.value = query)); + if (query) Search.performSearch(query); + }, + + loadIndex: (url) => + (document.body.appendChild(document.createElement("script")).src = url), + + setIndex: (index) => { + Search._index = index; + if (Search._queued_query !== null) { + const query = Search._queued_query; + Search._queued_query = null; + Search.query(query); + } + }, + + hasIndex: () => Search._index !== null, + + deferQuery: (query) => (Search._queued_query = query), + + stopPulse: () => (Search._pulse_status = -1), + + startPulse: () => { + if (Search._pulse_status >= 0) return; + + const pulse = () => { + Search._pulse_status = (Search._pulse_status + 1) % 4; + Search.dots.innerText = ".".repeat(Search._pulse_status); + if (Search._pulse_status >= 0) window.setTimeout(pulse, 500); + }; + pulse(); + }, + + /** + * perform a search for something (or wait until index is loaded) + */ + performSearch: (query) => { + // create the required interface elements + const searchText = document.createElement("h2"); + searchText.textContent = _("Searching"); + const searchSummary = document.createElement("p"); + searchSummary.classList.add("search-summary"); + searchSummary.innerText = ""; + const searchList = document.createElement("ul"); + searchList.setAttribute("role", "list"); + searchList.classList.add("search"); + + const out = document.getElementById("search-results"); + Search.title = out.appendChild(searchText); + Search.dots = Search.title.appendChild(document.createElement("span")); + Search.status = out.appendChild(searchSummary); + Search.output = out.appendChild(searchList); + + const searchProgress = document.getElementById("search-progress"); + // Some themes don't use the search progress node + if (searchProgress) { + searchProgress.innerText = _("Preparing search..."); + } + Search.startPulse(); + + // index already loaded, the browser was quick! + if (Search.hasIndex()) Search.query(query); + else Search.deferQuery(query); + }, + + _parseQuery: (query) => { + // stem the search terms and add them to the correct list + const stemmer = new Stemmer(); + const searchTerms = new Set(); + const excludedTerms = new Set(); + const highlightTerms = new Set(); + const objectTerms = new Set(splitQuery(query.toLowerCase().trim())); + splitQuery(query.trim()).forEach((queryTerm) => { + const queryTermLower = queryTerm.toLowerCase(); + + // maybe skip this "word" + // stopwords array is from language_data.js + if ( + stopwords.indexOf(queryTermLower) !== -1 || + queryTerm.match(/^\d+$/) + ) + return; + + // stem the word + let word = stemmer.stemWord(queryTermLower); + // select the correct list + if (word[0] === "-") excludedTerms.add(word.substr(1)); + else { + searchTerms.add(word); + highlightTerms.add(queryTermLower); + } + }); + + if (SPHINX_HIGHLIGHT_ENABLED) { // set in sphinx_highlight.js + localStorage.setItem("sphinx_highlight_terms", [...highlightTerms].join(" ")) + } + + // console.debug("SEARCH: searching for:"); + // console.info("required: ", [...searchTerms]); + // console.info("excluded: ", [...excludedTerms]); + + return [query, searchTerms, excludedTerms, highlightTerms, objectTerms]; + }, + + /** + * execute search (requires search index to be loaded) + */ + _performSearch: (query, searchTerms, excludedTerms, highlightTerms, objectTerms) => { + const filenames = Search._index.filenames; + const docNames = Search._index.docnames; + const titles = Search._index.titles; + const allTitles = Search._index.alltitles; + const indexEntries = Search._index.indexentries; + + // Collect multiple result groups to be sorted separately and then ordered. + // Each is an array of [docname, title, anchor, descr, score, filename, kind]. + const normalResults = []; + const nonMainIndexResults = []; + + _removeChildren(document.getElementById("search-progress")); + + const queryLower = query.toLowerCase().trim(); + for (const [title, foundTitles] of Object.entries(allTitles)) { + if (title.toLowerCase().trim().includes(queryLower) && (queryLower.length >= title.length/2)) { + for (const [file, id] of foundTitles) { + const score = Math.round(Scorer.title * queryLower.length / title.length); + const boost = titles[file] === title ? 1 : 0; // add a boost for document titles + normalResults.push([ + docNames[file], + titles[file] !== title ? `${titles[file]} > ${title}` : title, + id !== null ? "#" + id : "", + null, + score + boost, + filenames[file], + SearchResultKind.title, + ]); + } + } + } + + // search for explicit entries in index directives + for (const [entry, foundEntries] of Object.entries(indexEntries)) { + if (entry.includes(queryLower) && (queryLower.length >= entry.length/2)) { + for (const [file, id, isMain] of foundEntries) { + const score = Math.round(100 * queryLower.length / entry.length); + const result = [ + docNames[file], + titles[file], + id ? "#" + id : "", + null, + score, + filenames[file], + SearchResultKind.index, + ]; + if (isMain) { + normalResults.push(result); + } else { + nonMainIndexResults.push(result); + } + } + } + } + + // lookup as object + objectTerms.forEach((term) => + normalResults.push(...Search.performObjectSearch(term, objectTerms)) + ); + + // lookup as search terms in fulltext + normalResults.push(...Search.performTermsSearch(searchTerms, excludedTerms)); + + // let the scorer override scores with a custom scoring function + if (Scorer.score) { + normalResults.forEach((item) => (item[4] = Scorer.score(item))); + nonMainIndexResults.forEach((item) => (item[4] = Scorer.score(item))); + } + + // Sort each group of results by score and then alphabetically by name. + normalResults.sort(_orderResultsByScoreThenName); + nonMainIndexResults.sort(_orderResultsByScoreThenName); + + // Combine the result groups in (reverse) order. + // Non-main index entries are typically arbitrary cross-references, + // so display them after other results. + let results = [...nonMainIndexResults, ...normalResults]; + + // remove duplicate search results + // note the reversing of results, so that in the case of duplicates, the highest-scoring entry is kept + let seen = new Set(); + results = results.reverse().reduce((acc, result) => { + let resultStr = result.slice(0, 4).concat([result[5]]).map(v => String(v)).join(','); + if (!seen.has(resultStr)) { + acc.push(result); + seen.add(resultStr); + } + return acc; + }, []); + + return results.reverse(); + }, + + query: (query) => { + const [searchQuery, searchTerms, excludedTerms, highlightTerms, objectTerms] = Search._parseQuery(query); + const results = Search._performSearch(searchQuery, searchTerms, excludedTerms, highlightTerms, objectTerms); + + // for debugging + //Search.lastresults = results.slice(); // a copy + // console.info("search results:", Search.lastresults); + + // print the results + _displayNextItem(results, results.length, searchTerms, highlightTerms); + }, + + /** + * search for object names + */ + performObjectSearch: (object, objectTerms) => { + const filenames = Search._index.filenames; + const docNames = Search._index.docnames; + const objects = Search._index.objects; + const objNames = Search._index.objnames; + const titles = Search._index.titles; + + const results = []; + + const objectSearchCallback = (prefix, match) => { + const name = match[4] + const fullname = (prefix ? prefix + "." : "") + name; + const fullnameLower = fullname.toLowerCase(); + if (fullnameLower.indexOf(object) < 0) return; + + let score = 0; + const parts = fullnameLower.split("."); + + // check for different match types: exact matches of full name or + // "last name" (i.e. last dotted part) + if (fullnameLower === object || parts.slice(-1)[0] === object) + score += Scorer.objNameMatch; + else if (parts.slice(-1)[0].indexOf(object) > -1) + score += Scorer.objPartialMatch; // matches in last name + + const objName = objNames[match[1]][2]; + const title = titles[match[0]]; + + // If more than one term searched for, we require other words to be + // found in the name/title/description + const otherTerms = new Set(objectTerms); + otherTerms.delete(object); + if (otherTerms.size > 0) { + const haystack = `${prefix} ${name} ${objName} ${title}`.toLowerCase(); + if ( + [...otherTerms].some((otherTerm) => haystack.indexOf(otherTerm) < 0) + ) + return; + } + + let anchor = match[3]; + if (anchor === "") anchor = fullname; + else if (anchor === "-") anchor = objNames[match[1]][1] + "-" + fullname; + + const descr = objName + _(", in ") + title; + + // add custom score for some objects according to scorer + if (Scorer.objPrio.hasOwnProperty(match[2])) + score += Scorer.objPrio[match[2]]; + else score += Scorer.objPrioDefault; + + results.push([ + docNames[match[0]], + fullname, + "#" + anchor, + descr, + score, + filenames[match[0]], + SearchResultKind.object, + ]); + }; + Object.keys(objects).forEach((prefix) => + objects[prefix].forEach((array) => + objectSearchCallback(prefix, array) + ) + ); + return results; + }, + + /** + * search for full-text terms in the index + */ + performTermsSearch: (searchTerms, excludedTerms) => { + // prepare search + const terms = Search._index.terms; + const titleTerms = Search._index.titleterms; + const filenames = Search._index.filenames; + const docNames = Search._index.docnames; + const titles = Search._index.titles; + + const scoreMap = new Map(); + const fileMap = new Map(); + + // perform the search on the required terms + searchTerms.forEach((word) => { + const files = []; + const arr = [ + { files: terms[word], score: Scorer.term }, + { files: titleTerms[word], score: Scorer.title }, + ]; + // add support for partial matches + if (word.length > 2) { + const escapedWord = _escapeRegExp(word); + if (!terms.hasOwnProperty(word)) { + Object.keys(terms).forEach((term) => { + if (term.match(escapedWord)) + arr.push({ files: terms[term], score: Scorer.partialTerm }); + }); + } + if (!titleTerms.hasOwnProperty(word)) { + Object.keys(titleTerms).forEach((term) => { + if (term.match(escapedWord)) + arr.push({ files: titleTerms[term], score: Scorer.partialTitle }); + }); + } + } + + // no match but word was a required one + if (arr.every((record) => record.files === undefined)) return; + + // found search word in contents + arr.forEach((record) => { + if (record.files === undefined) return; + + let recordFiles = record.files; + if (recordFiles.length === undefined) recordFiles = [recordFiles]; + files.push(...recordFiles); + + // set score for the word in each file + recordFiles.forEach((file) => { + if (!scoreMap.has(file)) scoreMap.set(file, {}); + scoreMap.get(file)[word] = record.score; + }); + }); + + // create the mapping + files.forEach((file) => { + if (!fileMap.has(file)) fileMap.set(file, [word]); + else if (fileMap.get(file).indexOf(word) === -1) fileMap.get(file).push(word); + }); + }); + + // now check if the files don't contain excluded terms + const results = []; + for (const [file, wordList] of fileMap) { + // check if all requirements are matched + + // as search terms with length < 3 are discarded + const filteredTermCount = [...searchTerms].filter( + (term) => term.length > 2 + ).length; + if ( + wordList.length !== searchTerms.size && + wordList.length !== filteredTermCount + ) + continue; + + // ensure that none of the excluded terms is in the search result + if ( + [...excludedTerms].some( + (term) => + terms[term] === file || + titleTerms[term] === file || + (terms[term] || []).includes(file) || + (titleTerms[term] || []).includes(file) + ) + ) + break; + + // select one (max) score for the file. + const score = Math.max(...wordList.map((w) => scoreMap.get(file)[w])); + // add result to the result list + results.push([ + docNames[file], + titles[file], + "", + null, + score, + filenames[file], + SearchResultKind.text, + ]); + } + return results; + }, + + /** + * helper function to return a node containing the + * search summary for a given text. keywords is a list + * of stemmed words. + */ + makeSearchSummary: (htmlText, keywords, anchor) => { + const text = Search.htmlToText(htmlText, anchor); + if (text === "") return null; + + const textLower = text.toLowerCase(); + const actualStartPosition = [...keywords] + .map((k) => textLower.indexOf(k.toLowerCase())) + .filter((i) => i > -1) + .slice(-1)[0]; + const startWithContext = Math.max(actualStartPosition - 120, 0); + + const top = startWithContext === 0 ? "" : "..."; + const tail = startWithContext + 240 < text.length ? "..." : ""; + + let summary = document.createElement("p"); + summary.classList.add("context"); + summary.textContent = top + text.substr(startWithContext, 240).trim() + tail; + + return summary; + }, +}; + +_ready(Search.init); diff --git a/_build/_static/shortcut-icon.png b/_build/_static/shortcut-icon.png new file mode 100644 index 00000000..4d3e6c37 Binary files /dev/null and b/_build/_static/shortcut-icon.png differ diff --git a/_build/_static/sphinx_highlight.js b/_build/_static/sphinx_highlight.js new file mode 100644 index 00000000..8a96c69a --- /dev/null +++ b/_build/_static/sphinx_highlight.js @@ -0,0 +1,154 @@ +/* Highlighting utilities for Sphinx HTML documentation. */ +"use strict"; + +const SPHINX_HIGHLIGHT_ENABLED = true + +/** + * highlight a given string on a node by wrapping it in + * span elements with the given class name. + */ +const _highlight = (node, addItems, text, className) => { + if (node.nodeType === Node.TEXT_NODE) { + const val = node.nodeValue; + const parent = node.parentNode; + const pos = val.toLowerCase().indexOf(text); + if ( + pos >= 0 && + !parent.classList.contains(className) && + !parent.classList.contains("nohighlight") + ) { + let span; + + const closestNode = parent.closest("body, svg, foreignObject"); + const isInSVG = closestNode && closestNode.matches("svg"); + if (isInSVG) { + span = document.createElementNS("http://www.w3.org/2000/svg", "tspan"); + } else { + span = document.createElement("span"); + span.classList.add(className); + } + + span.appendChild(document.createTextNode(val.substr(pos, text.length))); + const rest = document.createTextNode(val.substr(pos + text.length)); + parent.insertBefore( + span, + parent.insertBefore( + rest, + node.nextSibling + ) + ); + node.nodeValue = val.substr(0, pos); + /* There may be more occurrences of search term in this node. So call this + * function recursively on the remaining fragment. + */ + _highlight(rest, addItems, text, className); + + if (isInSVG) { + const rect = document.createElementNS( + "http://www.w3.org/2000/svg", + "rect" + ); + const bbox = parent.getBBox(); + rect.x.baseVal.value = bbox.x; + rect.y.baseVal.value = bbox.y; + rect.width.baseVal.value = bbox.width; + rect.height.baseVal.value = bbox.height; + rect.setAttribute("class", className); + addItems.push({ parent: parent, target: rect }); + } + } + } else if (node.matches && !node.matches("button, select, textarea")) { + node.childNodes.forEach((el) => _highlight(el, addItems, text, className)); + } +}; +const _highlightText = (thisNode, text, className) => { + let addItems = []; + _highlight(thisNode, addItems, text, className); + addItems.forEach((obj) => + obj.parent.insertAdjacentElement("beforebegin", obj.target) + ); +}; + +/** + * Small JavaScript module for the documentation. + */ +const SphinxHighlight = { + + /** + * highlight the search words provided in localstorage in the text + */ + highlightSearchWords: () => { + if (!SPHINX_HIGHLIGHT_ENABLED) return; // bail if no highlight + + // get and clear terms from localstorage + const url = new URL(window.location); + const highlight = + localStorage.getItem("sphinx_highlight_terms") + || url.searchParams.get("highlight") + || ""; + localStorage.removeItem("sphinx_highlight_terms") + url.searchParams.delete("highlight"); + window.history.replaceState({}, "", url); + + // get individual terms from highlight string + const terms = highlight.toLowerCase().split(/\s+/).filter(x => x); + if (terms.length === 0) return; // nothing to do + + // There should never be more than one element matching "div.body" + const divBody = document.querySelectorAll("div.body"); + const body = divBody.length ? divBody[0] : document.querySelector("body"); + window.setTimeout(() => { + terms.forEach((term) => _highlightText(body, term, "highlighted")); + }, 10); + + const searchBox = document.getElementById("searchbox"); + if (searchBox === null) return; + searchBox.appendChild( + document + .createRange() + .createContextualFragment( + '" + ) + ); + }, + + /** + * helper function to hide the search marks again + */ + hideSearchWords: () => { + document + .querySelectorAll("#searchbox .highlight-link") + .forEach((el) => el.remove()); + document + .querySelectorAll("span.highlighted") + .forEach((el) => el.classList.remove("highlighted")); + localStorage.removeItem("sphinx_highlight_terms") + }, + + initEscapeListener: () => { + // only install a listener if it is really needed + if (!DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS) return; + + document.addEventListener("keydown", (event) => { + // bail for input elements + if (BLACKLISTED_KEY_CONTROL_ELEMENTS.has(document.activeElement.tagName)) return; + // bail with special keys + if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return; + if (DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS && (event.key === "Escape")) { + SphinxHighlight.hideSearchWords(); + event.preventDefault(); + } + }); + }, +}; + +_ready(() => { + /* Do not call highlightSearchWords() when we are on the search page. + * It will highlight words from the *previous* search query. + */ + if (typeof Search === "undefined") SphinxHighlight.highlightSearchWords(); + SphinxHighlight.initEscapeListener(); +}); diff --git a/_build/_static/tabs.css b/_build/_static/tabs.css new file mode 100644 index 00000000..957ba60d --- /dev/null +++ b/_build/_static/tabs.css @@ -0,0 +1,89 @@ +.sphinx-tabs { + margin-bottom: 1rem; +} + +[role="tablist"] { + border-bottom: 1px solid #a0b3bf; +} + +.sphinx-tabs-tab { + position: relative; + font-family: Lato,'Helvetica Neue',Arial,Helvetica,sans-serif; + color: #1D5C87; + line-height: 24px; + margin: 0; + font-size: 16px; + font-weight: 400; + background-color: rgba(255, 255, 255, 0); + border-radius: 5px 5px 0 0; + border: 0; + padding: 1rem 1.5rem; + margin-bottom: 0; +} + +.sphinx-tabs-tab[aria-selected="true"] { + font-weight: 700; + border: 1px solid #a0b3bf; + border-bottom: 1px solid white; + margin: -1px; + background-color: white; +} + +.sphinx-tabs-tab:focus { + z-index: 1; + outline-offset: 1px; +} + +.sphinx-tabs-panel { + position: relative; + padding: 1rem; + border: 1px solid #a0b3bf; + margin: 0px -1px -1px -1px; + border-radius: 0 0 5px 5px; + border-top: 0; + background: white; +} + +.sphinx-tabs-panel.code-tab { + padding: 0.4rem; +} + +.sphinx-tab img { + margin-bottom: 24 px; +} + +/* Dark theme preference styling */ + +@media (prefers-color-scheme: dark) { + body[data-theme="auto"] .sphinx-tabs-panel { + color: white; + background-color: rgb(50, 50, 50); + } + + body[data-theme="auto"] .sphinx-tabs-tab { + color: white; + background-color: rgba(255, 255, 255, 0.05); + } + + body[data-theme="auto"] .sphinx-tabs-tab[aria-selected="true"] { + border-bottom: 1px solid rgb(50, 50, 50); + background-color: rgb(50, 50, 50); + } +} + +/* Explicit dark theme styling */ + +body[data-theme="dark"] .sphinx-tabs-panel { + color: white; + background-color: rgb(50, 50, 50); +} + +body[data-theme="dark"] .sphinx-tabs-tab { + color: white; + background-color: rgba(255, 255, 255, 0.05); +} + +body[data-theme="dark"] .sphinx-tabs-tab[aria-selected="true"] { + border-bottom: 2px solid rgb(50, 50, 50); + background-color: rgb(50, 50, 50); +} diff --git a/_build/_static/tabs.js b/_build/_static/tabs.js new file mode 100644 index 00000000..48dc303c --- /dev/null +++ b/_build/_static/tabs.js @@ -0,0 +1,145 @@ +try { + var session = window.sessionStorage || {}; +} catch (e) { + var session = {}; +} + +window.addEventListener("DOMContentLoaded", () => { + const allTabs = document.querySelectorAll('.sphinx-tabs-tab'); + const tabLists = document.querySelectorAll('[role="tablist"]'); + + allTabs.forEach(tab => { + tab.addEventListener("click", changeTabs); + }); + + tabLists.forEach(tabList => { + tabList.addEventListener("keydown", keyTabs); + }); + + // Restore group tab selection from session + const lastSelected = session.getItem('sphinx-tabs-last-selected'); + if (lastSelected != null) selectNamedTabs(lastSelected); +}); + +/** + * Key focus left and right between sibling elements using arrows + * @param {Node} e the element in focus when key was pressed + */ +function keyTabs(e) { + const tab = e.target; + let nextTab = null; + if (e.keyCode === 39 || e.keyCode === 37) { + tab.setAttribute("tabindex", -1); + // Move right + if (e.keyCode === 39) { + nextTab = tab.nextElementSibling; + if (nextTab === null) { + nextTab = tab.parentNode.firstElementChild; + } + // Move left + } else if (e.keyCode === 37) { + nextTab = tab.previousElementSibling; + if (nextTab === null) { + nextTab = tab.parentNode.lastElementChild; + } + } + } + + if (nextTab !== null) { + nextTab.setAttribute("tabindex", 0); + nextTab.focus(); + } +} + +/** + * Select or deselect clicked tab. If a group tab + * is selected, also select tab in other tabLists. + * @param {Node} e the element that was clicked + */ +function changeTabs(e) { + // Use this instead of the element that was clicked, in case it's a child + const notSelected = this.getAttribute("aria-selected") === "false"; + const positionBefore = this.parentNode.getBoundingClientRect().top; + const notClosable = !this.parentNode.classList.contains("closeable"); + + deselectTabList(this); + + if (notSelected || notClosable) { + selectTab(this); + const name = this.getAttribute("name"); + selectNamedTabs(name, this.id); + + if (this.classList.contains("group-tab")) { + // Persist during session + session.setItem('sphinx-tabs-last-selected', name); + } + } + + const positionAfter = this.parentNode.getBoundingClientRect().top; + const positionDelta = positionAfter - positionBefore; + // Scroll to offset content resizing + window.scrollTo(0, window.scrollY + positionDelta); +} + +/** + * Select tab and show associated panel. + * @param {Node} tab tab to select + */ +function selectTab(tab) { + tab.setAttribute("aria-selected", true); + + // Show the associated panel + document + .getElementById(tab.getAttribute("aria-controls")) + .removeAttribute("hidden"); +} + +/** + * Hide the panels associated with all tabs within the + * tablist containing this tab. + * @param {Node} tab a tab within the tablist to deselect + */ +function deselectTabList(tab) { + const parent = tab.parentNode; + const grandparent = parent.parentNode; + + Array.from(parent.children) + .forEach(t => t.setAttribute("aria-selected", false)); + + Array.from(grandparent.children) + .slice(1) // Skip tablist + .forEach(panel => panel.setAttribute("hidden", true)); +} + +/** + * Select grouped tabs with the same name, but no the tab + * with the given id. + * @param {Node} name name of grouped tab to be selected + * @param {Node} clickedId id of clicked tab + */ +function selectNamedTabs(name, clickedId=null) { + const groupedTabs = document.querySelectorAll(`.sphinx-tabs-tab[name="${name}"]`); + const tabLists = Array.from(groupedTabs).map(tab => tab.parentNode); + + tabLists + .forEach(tabList => { + // Don't want to change the tabList containing the clicked tab + const clickedTab = tabList.querySelector(`[id="${clickedId}"]`); + if (clickedTab === null ) { + // Select first tab with matching name + const tab = tabList.querySelector(`.sphinx-tabs-tab[name="${name}"]`); + deselectTabList(tab); + selectTab(tab); + } + }) +} + +if (typeof exports === 'undefined') { + exports = {}; +} + +exports.keyTabs = keyTabs; +exports.changeTabs = changeTabs; +exports.selectTab = selectTab; +exports.deselectTabList = deselectTabList; +exports.selectNamedTabs = selectNamedTabs; diff --git a/_build/api/index.html b/_build/api/index.html new file mode 100644 index 00000000..19ada33b --- /dev/null +++ b/_build/api/index.html @@ -0,0 +1,9831 @@ + + + + + + + + API — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

API

+

This part of the documentation covers all the interfaces of Flask. For +parts where Flask depends on external libraries, we document the most +important right here and provide links to the canonical documentation.

+
+

Application Object

+
+
+class flask.Flask(import_name, static_url_path=None, static_folder='static', static_host=None, host_matching=False, subdomain_matching=False, template_folder='templates', instance_path=None, instance_relative_config=False, root_path=None)
+

The flask object implements a WSGI application and acts as the central +object. It is passed the name of the module or package of the +application. Once it is created it will act as a central registry for +the view functions, the URL rules, template configuration and much more.

+

The name of the package is used to resolve resources from inside the +package or the folder the module is contained in depending on if the +package parameter resolves to an actual python package (a folder with +an __init__.py file inside) or a standard module (just a .py file).

+

For more information about resource loading, see open_resource().

+

Usually you create a Flask instance in your main module or +in the __init__.py file of your package like this:

+
from flask import Flask
+app = Flask(__name__)
+
+
+
+

About the First Parameter

+

The idea of the first parameter is to give Flask an idea of what +belongs to your application. This name is used to find resources +on the filesystem, can be used by extensions to improve debugging +information and a lot more.

+

So it’s important what you provide there. If you are using a single +module, __name__ is always the correct value. If you however are +using a package, it’s usually recommended to hardcode the name of +your package there.

+

For example if your application is defined in yourapplication/app.py +you should create it with one of the two versions below:

+
app = Flask('yourapplication')
+app = Flask(__name__.split('.')[0])
+
+
+

Why is that? The application will work even with __name__, thanks +to how resources are looked up. However it will make debugging more +painful. Certain extensions can make assumptions based on the +import name of your application. For example the Flask-SQLAlchemy +extension will look for the code in your application that triggered +an SQL query in debug mode. If the import name is not properly set +up, that debugging information is lost. (For example it would only +pick up SQL queries in yourapplication.app and not +yourapplication.views.frontend)

+
+
+Changelog
+

Added in version 1.0: The host_matching and static_host parameters were added.

+
+
+

Added in version 1.0: The subdomain_matching parameter was added. Subdomain +matching needs to be enabled manually now. Setting +SERVER_NAME does not implicitly enable it.

+
+
+

Added in version 0.11: The root_path parameter was added.

+
+
+

Added in version 0.8: The instance_path and instance_relative_config parameters were +added.

+
+
+

Added in version 0.7: The static_url_path, static_folder, and template_folder +parameters were added.

+
+
+
Parameters:
+
    +
  • import_name (str) – the name of the application package

  • +
  • static_url_path (str | None) – can be used to specify a different path for the +static files on the web. Defaults to the name +of the static_folder folder.

  • +
  • static_folder (str | os.PathLike[str] | None) – The folder with static files that is served at +static_url_path. Relative to the application root_path +or an absolute path. Defaults to 'static'.

  • +
  • static_host (str | None) – the host to use when adding the static route. +Defaults to None. Required when using host_matching=True +with a static_folder configured.

  • +
  • host_matching (bool) – set url_map.host_matching attribute. +Defaults to False.

  • +
  • subdomain_matching (bool) – consider the subdomain relative to +SERVER_NAME when matching routes. Defaults to False.

  • +
  • template_folder (str | os.PathLike[str] | None) – the folder that contains the templates that should +be used by the application. Defaults to +'templates' folder in the root path of the +application.

  • +
  • instance_path (str | None) – An alternative instance path for the application. +By default the folder 'instance' next to the +package or module is assumed to be the instance +path.

  • +
  • instance_relative_config (bool) – if set to True relative filenames +for loading the config are assumed to +be relative to the instance path instead +of the application root.

  • +
  • root_path (str | None) – The path to the root of the application files. +This should only be set manually when it can’t be detected +automatically, such as for namespace packages.

  • +
+
+
+
+
+request_class
+

alias of Request

+
+ +
+
+response_class
+

alias of Response

+
+ +
+
+session_interface: SessionInterface = <flask.sessions.SecureCookieSessionInterface object>
+

the session interface to use. By default an instance of +SecureCookieSessionInterface is used here.

+
+Changelog
+

Added in version 0.8.

+
+
+ +
+
+cli: Group
+

The Click command group for registering CLI commands for this +object. The commands are available from the flask command +once the application has been discovered and blueprints have +been registered.

+
+ +
+
+get_send_file_max_age(filename)
+

Used by send_file() to determine the max_age cache +value for a given file path if it wasn’t passed.

+

By default, this returns SEND_FILE_MAX_AGE_DEFAULT from +the configuration of current_app. This defaults +to None, which tells the browser to use conditional requests +instead of a timed cache, which is usually preferable.

+

Note this is a duplicate of the same method in the Flask +class.

+
+Changelog
+

Changed in version 2.0: The default configuration is None instead of 12 hours.

+
+
+

Added in version 0.9.

+
+
+
Parameters:
+

filename (str | None)

+
+
Return type:
+

int | None

+
+
+
+ +
+
+send_static_file(filename)
+

The view function used to serve files from +static_folder. A route is automatically registered for +this view at static_url_path if static_folder is +set.

+

Note this is a duplicate of the same method in the Flask +class.

+
+Changelog
+

Added in version 0.5.

+
+
+
Parameters:
+

filename (str)

+
+
Return type:
+

Response

+
+
+
+ +
+
+open_resource(resource, mode='rb', encoding=None)
+

Open a resource file relative to root_path for reading.

+

For example, if the file schema.sql is next to the file +app.py where the Flask app is defined, it can be opened +with:

+
with app.open_resource("schema.sql") as f:
+    conn.executescript(f.read())
+
+
+
+
Parameters:
+
    +
  • resource (str) – Path to the resource relative to root_path.

  • +
  • mode (str) – Open the file in this mode. Only reading is supported, +valid values are "r" (or "rt") and "rb".

  • +
  • encoding (str | None) – Open the file with this encoding when opening in text +mode. This is ignored when opening in binary mode.

  • +
+
+
Return type:
+

IO

+
+
+
+

Changed in version 3.1: Added the encoding parameter.

+
+
+ +
+
+open_instance_resource(resource, mode='rb', encoding='utf-8')
+

Open a resource file relative to the application’s instance folder +instance_path. Unlike open_resource(), files in the +instance folder can be opened for writing.

+
+
Parameters:
+
    +
  • resource (str) – Path to the resource relative to instance_path.

  • +
  • mode (str) – Open the file in this mode.

  • +
  • encoding (str | None) – Open the file with this encoding when opening in text +mode. This is ignored when opening in binary mode.

  • +
+
+
Return type:
+

IO

+
+
+
+

Changed in version 3.1: Added the encoding parameter.

+
+
+ +
+
+create_jinja_environment()
+

Create the Jinja environment based on jinja_options +and the various Jinja-related methods of the app. Changing +jinja_options after this will have no effect. Also adds +Flask-related globals and filters to the environment.

+
+Changelog
+

Changed in version 0.11: Environment.auto_reload set in accordance with +TEMPLATES_AUTO_RELOAD configuration option.

+
+
+

Added in version 0.5.

+
+
+
Return type:
+

Environment

+
+
+
+ +
+
+create_url_adapter(request)
+

Creates a URL adapter for the given request. The URL adapter +is created at a point where the request context is not yet set +up so the request is passed explicitly.

+
+

Changed in version 3.1: If SERVER_NAME is set, it does not restrict requests to +only that domain, for both subdomain_matching and +host_matching.

+
+
+Changelog
+

Changed in version 1.0: SERVER_NAME no longer implicitly enables subdomain +matching. Use subdomain_matching instead.

+
+
+

Changed in version 0.9: This can be called outside a request when the URL adapter is created +for an application context.

+
+
+

Added in version 0.6.

+
+
+
Parameters:
+

request (Request | None)

+
+
Return type:
+

MapAdapter | None

+
+
+
+ +
+
+update_template_context(context)
+

Update the template context with some commonly used variables. +This injects request, session, config and g into the template +context as well as everything template context processors want +to inject. Note that the as of Flask 0.6, the original values +in the context will not be overridden if a context processor +decides to return a value with the same key.

+
+
Parameters:
+

context (dict[str, Any]) – the context as a dictionary that is updated in place +to add extra variables.

+
+
Return type:
+

None

+
+
+
+ +
+
+make_shell_context()
+

Returns the shell context for an interactive shell for this +application. This runs all the registered shell context +processors.

+
+Changelog
+

Added in version 0.11.

+
+
+
Return type:
+

dict[str, Any]

+
+
+
+ +
+
+run(host=None, port=None, debug=None, load_dotenv=True, **options)
+

Runs the application on a local development server.

+

Do not use run() in a production setting. It is not intended to +meet security and performance requirements for a production server. +Instead, see Deploying to Production for WSGI server recommendations.

+

If the debug flag is set the server will automatically reload +for code changes and show a debugger in case an exception happened.

+

If you want to run the application in debug mode, but disable the +code execution on the interactive debugger, you can pass +use_evalex=False as parameter. This will keep the debugger’s +traceback screen active, but disable code execution.

+

It is not recommended to use this function for development with +automatic reloading as this is badly supported. Instead you should +be using the flask command line script’s run support.

+
+

Keep in Mind

+

Flask will suppress any server error with a generic error page +unless it is in debug mode. As such to enable just the +interactive debugger without the code reloading, you have to +invoke run() with debug=True and use_reloader=False. +Setting use_debugger to True without being in debug mode +won’t catch any exceptions because there won’t be any to +catch.

+
+
+
Parameters:
+
    +
  • host (str | None) – the hostname to listen on. Set this to '0.0.0.0' to +have the server available externally as well. Defaults to +'127.0.0.1' or the host in the SERVER_NAME config variable +if present.

  • +
  • port (int | None) – the port of the webserver. Defaults to 5000 or the +port defined in the SERVER_NAME config variable if present.

  • +
  • debug (bool | None) – if given, enable or disable debug mode. See +debug.

  • +
  • load_dotenv (bool) – Load the nearest .env and .flaskenv +files to set environment variables. Will also change the working +directory to the directory containing the first file found.

  • +
  • options (Any) – the options to be forwarded to the underlying Werkzeug +server. See werkzeug.serving.run_simple() for more +information.

  • +
+
+
Return type:
+

None

+
+
+
+Changelog
+

Changed in version 1.0: If installed, python-dotenv will be used to load environment +variables from .env and .flaskenv files.

+

The FLASK_DEBUG environment variable will override debug.

+

Threaded mode is enabled by default.

+
+
+

Changed in version 0.10: The default port is now picked from the SERVER_NAME +variable.

+
+
+ +
+
+test_client(use_cookies=True, **kwargs)
+

Creates a test client for this application. For information +about unit testing head over to Testing Flask Applications.

+

Note that if you are testing for assertions or exceptions in your +application code, you must set app.testing = True in order for the +exceptions to propagate to the test client. Otherwise, the exception +will be handled by the application (not visible to the test client) and +the only indication of an AssertionError or other exception will be a +500 status code response to the test client. See the testing +attribute. For example:

+
app.testing = True
+client = app.test_client()
+
+
+

The test client can be used in a with block to defer the closing down +of the context until the end of the with block. This is useful if +you want to access the context locals for testing:

+
with app.test_client() as c:
+    rv = c.get('/?vodka=42')
+    assert request.args['vodka'] == '42'
+
+
+

Additionally, you may pass optional keyword arguments that will then +be passed to the application’s test_client_class constructor. +For example:

+
from flask.testing import FlaskClient
+
+class CustomClient(FlaskClient):
+    def __init__(self, *args, **kwargs):
+        self._authentication = kwargs.pop("authentication")
+        super(CustomClient,self).__init__( *args, **kwargs)
+
+app.test_client_class = CustomClient
+client = app.test_client(authentication='Basic ....')
+
+
+

See FlaskClient for more information.

+
+Changelog
+

Changed in version 0.11: Added **kwargs to support passing additional keyword arguments to +the constructor of test_client_class.

+
+
+

Added in version 0.7: The use_cookies parameter was added as well as the ability +to override the client to be used by setting the +test_client_class attribute.

+
+
+

Changed in version 0.4: added support for with block usage for the client.

+
+
+
Parameters:
+
    +
  • use_cookies (bool)

  • +
  • kwargs (t.Any)

  • +
+
+
Return type:
+

FlaskClient

+
+
+
+ +
+
+test_cli_runner(**kwargs)
+

Create a CLI runner for testing CLI commands. +See Running Commands with the CLI Runner.

+

Returns an instance of test_cli_runner_class, by default +FlaskCliRunner. The Flask app object is +passed as the first argument.

+
+Changelog
+

Added in version 1.0.

+
+
+
Parameters:
+

kwargs (t.Any)

+
+
Return type:
+

FlaskCliRunner

+
+
+
+ +
+
+handle_http_exception(e)
+

Handles an HTTP exception. By default this will invoke the +registered error handlers and fall back to returning the +exception as response.

+
+Changelog
+

Changed in version 1.0.3: RoutingException, used internally for actions such as + slash redirects during routing, is not passed to error + handlers.

+
+
+

Changed in version 1.0: Exceptions are looked up by code and by MRO, so +HTTPException subclasses can be handled with a catch-all +handler for the base HTTPException.

+
+
+

Added in version 0.3.

+
+
+
Parameters:
+

e (HTTPException)

+
+
Return type:
+

HTTPException | ft.ResponseReturnValue

+
+
+
+ +
+
+handle_user_exception(e)
+

This method is called whenever an exception occurs that +should be handled. A special case is HTTPException which is forwarded to the +handle_http_exception() method. This function will either +return a response value or reraise the exception with the same +traceback.

+
+Changelog
+

Changed in version 1.0: Key errors raised from request data like form show the +bad key in debug mode rather than a generic bad request +message.

+
+
+

Added in version 0.7.

+
+
+
Parameters:
+

e (Exception)

+
+
Return type:
+

HTTPException | ft.ResponseReturnValue

+
+
+
+ +
+
+handle_exception(e)
+

Handle an exception that did not have an error handler +associated with it, or that was raised from an error handler. +This always causes a 500 InternalServerError.

+

Always sends the got_request_exception signal.

+

If PROPAGATE_EXCEPTIONS is True, such as in debug +mode, the error will be re-raised so that the debugger can +display it. Otherwise, the original exception is logged, and +an InternalServerError is returned.

+

If an error handler is registered for InternalServerError or +500, it will be used. For consistency, the handler will +always receive the InternalServerError. The original +unhandled exception is available as e.original_exception.

+
+Changelog
+

Changed in version 1.1.0: Always passes the InternalServerError instance to the +handler, setting original_exception to the unhandled +error.

+
+
+

Changed in version 1.1.0: after_request functions and other finalization is done +even for the default 500 response when there is no handler.

+
+
+

Added in version 0.3.

+
+
+
Parameters:
+

e (Exception)

+
+
Return type:
+

Response

+
+
+
+ +
+
+log_exception(exc_info)
+

Logs an exception. This is called by handle_exception() +if debugging is disabled and right before the handler is called. +The default implementation logs the exception as error on the +logger.

+
+Changelog
+

Added in version 0.8.

+
+
+
Parameters:
+

exc_info (tuple[type, BaseException, TracebackType] | tuple[None, None, None])

+
+
Return type:
+

None

+
+
+
+ +
+
+dispatch_request()
+

Does the request dispatching. Matches the URL and returns the +return value of the view or error handler. This does not have to +be a response object. In order to convert the return value to a +proper response object, call make_response().

+
+Changelog
+

Changed in version 0.7: This no longer does the exception handling, this code was +moved to the new full_dispatch_request().

+
+
+
Return type:
+

ft.ResponseReturnValue

+
+
+
+ +
+
+full_dispatch_request()
+

Dispatches the request and on top of that performs request +pre and postprocessing as well as HTTP exception catching and +error handling.

+
+Changelog
+

Added in version 0.7.

+
+
+
Return type:
+

Response

+
+
+
+ +
+
+make_default_options_response()
+

This method is called to create the default OPTIONS response. +This can be changed through subclassing to change the default +behavior of OPTIONS responses.

+
+Changelog
+

Added in version 0.7.

+
+
+
Return type:
+

Response

+
+
+
+ +
+
+ensure_sync(func)
+

Ensure that the function is synchronous for WSGI workers. +Plain def functions are returned as-is. async def +functions are wrapped to run and wait for the response.

+

Override this method to change how the app runs async views.

+
+Changelog
+

Added in version 2.0.

+
+
+
Parameters:
+

func (Callable[[...], Any])

+
+
Return type:
+

Callable[[…], Any]

+
+
+
+ +
+
+async_to_sync(func)
+

Return a sync function that will run the coroutine function.

+
result = app.async_to_sync(func)(*args, **kwargs)
+
+
+

Override this method to change how the app converts async code +to be synchronously callable.

+
+Changelog
+

Added in version 2.0.

+
+
+
Parameters:
+

func (Callable[[...], Coroutine[Any, Any, Any]])

+
+
Return type:
+

Callable[[…], Any]

+
+
+
+ +
+
+url_for(endpoint, *, _anchor=None, _method=None, _scheme=None, _external=None, **values)
+

Generate a URL to the given endpoint with the given values.

+

This is called by flask.url_for(), and can be called +directly as well.

+

An endpoint is the name of a URL rule, usually added with +@app.route(), and usually the same name as the +view function. A route defined in a Blueprint +will prepend the blueprint’s name separated by a . to the +endpoint.

+

In some cases, such as email messages, you want URLs to include +the scheme and domain, like https://example.com/hello. When +not in an active request, URLs will be external by default, but +this requires setting SERVER_NAME so Flask knows what +domain to use. APPLICATION_ROOT and +PREFERRED_URL_SCHEME should also be configured as +needed. This config is only used when not in an active request.

+

Functions can be decorated with url_defaults() to modify +keyword arguments before the URL is built.

+

If building fails for some reason, such as an unknown endpoint +or incorrect values, the app’s handle_url_build_error() +method is called. If that returns a string, that is returned, +otherwise a BuildError is raised.

+
+
Parameters:
+
    +
  • endpoint (str) – The endpoint name associated with the URL to +generate. If this starts with a ., the current blueprint +name (if any) will be used.

  • +
  • _anchor (str | None) – If given, append this as #anchor to the URL.

  • +
  • _method (str | None) – If given, generate the URL associated with this +method for the endpoint.

  • +
  • _scheme (str | None) – If given, the URL will have this scheme if it +is external.

  • +
  • _external (bool | None) – If given, prefer the URL to be internal +(False) or require it to be external (True). External URLs +include the scheme and domain. When not in an active +request, URLs are external by default.

  • +
  • values (Any) – Values to use for the variable parts of the URL +rule. Unknown keys are appended as query string arguments, +like ?a=b&c=d.

  • +
+
+
Return type:
+

str

+
+
+
+Changelog
+

Added in version 2.2: Moved from flask.url_for, which calls this method.

+
+
+ +
+
+make_response(rv)
+

Convert the return value from a view function to an instance of +response_class.

+
+
Parameters:
+

rv (ft.ResponseReturnValue) –

the return value from the view function. The view function +must return a response. Returning None, or the view ending +without returning, is not allowed. The following types are allowed +for view_rv:

+
+
str

A response object is created with the string encoded to UTF-8 +as the body.

+
+
bytes

A response object is created with the bytes as the body.

+
+
dict

A dictionary that will be jsonify’d before being returned.

+
+
list

A list that will be jsonify’d before being returned.

+
+
generator or iterator

A generator that returns str or bytes to be +streamed as the response.

+
+
tuple

Either (body, status, headers), (body, status), or +(body, headers), where body is any of the other types +allowed here, status is a string or an integer, and +headers is a dictionary or a list of (key, value) +tuples. If body is a response_class instance, +status overwrites the exiting value and headers are +extended.

+
+
response_class

The object is returned unchanged.

+
+
other Response class

The object is coerced to response_class.

+
+
callable()

The function is called as a WSGI application. The result is +used to create a response object.

+
+
+

+
+
Return type:
+

Response

+
+
+
+Changelog
+

Changed in version 2.2: A generator will be converted to a streaming response. +A list will be converted to a JSON response.

+
+
+

Changed in version 1.1: A dict will be converted to a JSON response.

+
+
+

Changed in version 0.9: Previously a tuple was interpreted as the arguments for the +response object.

+
+
+ +
+
+preprocess_request()
+

Called before the request is dispatched. Calls +url_value_preprocessors registered with the app and the +current blueprint (if any). Then calls before_request_funcs +registered with the app and the blueprint.

+

If any before_request() handler returns a non-None value, the +value is handled as if it was the return value from the view, and +further request handling is stopped.

+
+
Return type:
+

ft.ResponseReturnValue | None

+
+
+
+ +
+
+process_response(response)
+

Can be overridden in order to modify the response object +before it’s sent to the WSGI server. By default this will +call all the after_request() decorated functions.

+
+Changelog
+

Changed in version 0.5: As of Flask 0.5 the functions registered for after request +execution are called in reverse order of registration.

+
+
+
Parameters:
+

response (Response) – a response_class object.

+
+
Returns:
+

a new response object or the same, has to be an +instance of response_class.

+
+
Return type:
+

Response

+
+
+
+ +
+
+do_teardown_request(exc=_sentinel)
+

Called after the request is dispatched and the response is +returned, right before the request context is popped.

+

This calls all functions decorated with +teardown_request(), and Blueprint.teardown_request() +if a blueprint handled the request. Finally, the +request_tearing_down signal is sent.

+

This is called by +RequestContext.pop(), +which may be delayed during testing to maintain access to +resources.

+
+
Parameters:
+

exc (BaseException | None) – An unhandled exception raised while dispatching the +request. Detected from the current exception information if +not passed. Passed to each teardown function.

+
+
Return type:
+

None

+
+
+
+Changelog
+

Changed in version 0.9: Added the exc argument.

+
+
+ +
+
+do_teardown_appcontext(exc=_sentinel)
+

Called right before the application context is popped.

+

When handling a request, the application context is popped +after the request context. See do_teardown_request().

+

This calls all functions decorated with +teardown_appcontext(). Then the +appcontext_tearing_down signal is sent.

+

This is called by +AppContext.pop().

+
+Changelog
+

Added in version 0.9.

+
+
+
Parameters:
+

exc (BaseException | None)

+
+
Return type:
+

None

+
+
+
+ +
+
+app_context()
+

Create an AppContext. Use as a with +block to push the context, which will make current_app +point at this application.

+

An application context is automatically pushed by +RequestContext.push() +when handling a request, and when running a CLI command. Use +this to manually create a context outside of these situations.

+
with app.app_context():
+    init_db()
+
+
+

See The Application Context.

+
+Changelog
+

Added in version 0.9.

+
+
+
Return type:
+

AppContext

+
+
+
+ +
+
+request_context(environ)
+

Create a RequestContext representing a +WSGI environment. Use a with block to push the context, +which will make request point at this request.

+

See The Request Context.

+

Typically you should not call this from your own code. A request +context is automatically pushed by the wsgi_app() when +handling a request. Use test_request_context() to create +an environment and context instead of this method.

+
+
Parameters:
+

environ (WSGIEnvironment) – a WSGI environment

+
+
Return type:
+

RequestContext

+
+
+
+ +
+
+test_request_context(*args, **kwargs)
+

Create a RequestContext for a WSGI +environment created from the given values. This is mostly useful +during testing, where you may want to run a function that uses +request data without dispatching a full request.

+

See The Request Context.

+

Use a with block to push the context, which will make +request point at the request for the created +environment.

+
with app.test_request_context(...):
+    generate_report()
+
+
+

When using the shell, it may be easier to push and pop the +context manually to avoid indentation.

+
ctx = app.test_request_context(...)
+ctx.push()
+...
+ctx.pop()
+
+
+

Takes the same arguments as Werkzeug’s +EnvironBuilder, with some defaults from +the application. See the linked Werkzeug docs for most of the +available arguments. Flask-specific behavior is listed here.

+
+
Parameters:
+
    +
  • path – URL path being requested.

  • +
  • base_url – Base URL where the app is being served, which +path is relative to. If not given, built from +PREFERRED_URL_SCHEME, subdomain, +SERVER_NAME, and APPLICATION_ROOT.

  • +
  • subdomain – Subdomain name to append to +SERVER_NAME.

  • +
  • url_scheme – Scheme to use instead of +PREFERRED_URL_SCHEME.

  • +
  • data – The request body, either as a string or a dict of +form keys and values.

  • +
  • json – If given, this is serialized as JSON and passed as +data. Also defaults content_type to +application/json.

  • +
  • args (Any) – other positional arguments passed to +EnvironBuilder.

  • +
  • kwargs (Any) – other keyword arguments passed to +EnvironBuilder.

  • +
+
+
Return type:
+

RequestContext

+
+
+
+ +
+
+wsgi_app(environ, start_response)
+

The actual WSGI application. This is not implemented in +__call__() so that middlewares can be applied without +losing a reference to the app object. Instead of doing this:

+
app = MyMiddleware(app)
+
+
+

It’s a better idea to do this instead:

+
app.wsgi_app = MyMiddleware(app.wsgi_app)
+
+
+

Then you still have the original application object around and +can continue to call methods on it.

+
+Changelog
+

Changed in version 0.7: Teardown events for the request and app contexts are called +even if an unhandled error occurs. Other events may not be +called depending on when an error occurs during dispatch. +See Callbacks and Errors.

+
+
+
Parameters:
+
    +
  • environ (WSGIEnvironment) – A WSGI environment.

  • +
  • start_response (StartResponse) – A callable accepting a status code, +a list of headers, and an optional exception context to +start the response.

  • +
+
+
Return type:
+

cabc.Iterable[bytes]

+
+
+
+ +
+
+aborter_class
+

alias of Aborter

+
+ +
+
+add_template_filter(f, name=None)
+

Register a custom template filter. Works exactly like the +template_filter() decorator.

+
+
Parameters:
+
    +
  • name (str | None) – the optional name of the filter, otherwise the +function name will be used.

  • +
  • f (Callable[[...], Any])

  • +
+
+
Return type:
+

None

+
+
+
+ +
+
+add_template_global(f, name=None)
+

Register a custom template global function. Works exactly like the +template_global() decorator.

+
+Changelog
+

Added in version 0.10.

+
+
+
Parameters:
+
    +
  • name (str | None) – the optional name of the global function, otherwise the +function name will be used.

  • +
  • f (Callable[[...], Any])

  • +
+
+
Return type:
+

None

+
+
+
+ +
+
+add_template_test(f, name=None)
+

Register a custom template test. Works exactly like the +template_test() decorator.

+
+Changelog
+

Added in version 0.10.

+
+
+
Parameters:
+
    +
  • name (str | None) – the optional name of the test, otherwise the +function name will be used.

  • +
  • f (Callable[[...], bool])

  • +
+
+
Return type:
+

None

+
+
+
+ +
+
+add_url_rule(rule, endpoint=None, view_func=None, provide_automatic_options=None, **options)
+

Register a rule for routing incoming requests and building +URLs. The route() decorator is a shortcut to call this +with the view_func argument. These are equivalent:

+
@app.route("/")
+def index():
+    ...
+
+
+
def index():
+    ...
+
+app.add_url_rule("/", view_func=index)
+
+
+

See URL Route Registrations.

+

The endpoint name for the route defaults to the name of the view +function if the endpoint parameter isn’t passed. An error +will be raised if a function has already been registered for the +endpoint.

+

The methods parameter defaults to ["GET"]. HEAD is +always added automatically, and OPTIONS is added +automatically by default.

+

view_func does not necessarily need to be passed, but if the +rule should participate in routing an endpoint name must be +associated with a view function at some point with the +endpoint() decorator.

+
app.add_url_rule("/", endpoint="index")
+
+@app.endpoint("index")
+def index():
+    ...
+
+
+

If view_func has a required_methods attribute, those +methods are added to the passed and automatic methods. If it +has a provide_automatic_methods attribute, it is used as the +default if the parameter is not passed.

+
+
Parameters:
+
    +
  • rule (str) – The URL rule string.

  • +
  • endpoint (str | None) – The endpoint name to associate with the rule +and view function. Used when routing and building URLs. +Defaults to view_func.__name__.

  • +
  • view_func (ft.RouteCallable | None) – The view function to associate with the +endpoint name.

  • +
  • provide_automatic_options (bool | None) – Add the OPTIONS method and +respond to OPTIONS requests automatically.

  • +
  • options (t.Any) – Extra options passed to the +Rule object.

  • +
+
+
Return type:
+

None

+
+
+
+ +
+
+after_request(f)
+

Register a function to run after each request to this object.

+

The function is called with the response object, and must return +a response object. This allows the functions to modify or +replace the response before it is sent.

+

If a function raises an exception, any remaining +after_request functions will not be called. Therefore, this +should not be used for actions that must execute, such as to +close resources. Use teardown_request() for that.

+

This is available on both app and blueprint objects. When used on an app, this +executes after every request. When used on a blueprint, this executes after +every request that the blueprint handles. To register with a blueprint and +execute after every request, use Blueprint.after_app_request().

+
+
Parameters:
+

f (T_after_request)

+
+
Return type:
+

T_after_request

+
+
+
+ +
+
+app_ctx_globals_class
+

alias of _AppCtxGlobals

+
+ +
+
+auto_find_instance_path()
+

Tries to locate the instance path if it was not provided to the +constructor of the application class. It will basically calculate +the path to a folder named instance next to your main file or +the package.

+
+Changelog
+

Added in version 0.8.

+
+
+
Return type:
+

str

+
+
+
+ +
+
+before_request(f)
+

Register a function to run before each request.

+

For example, this can be used to open a database connection, or +to load the logged in user from the session.

+
@app.before_request
+def load_user():
+    if "user_id" in session:
+        g.user = db.session.get(session["user_id"])
+
+
+

The function will be called without any arguments. If it returns +a non-None value, the value is handled as if it was the +return value from the view, and further request handling is +stopped.

+

This is available on both app and blueprint objects. When used on an app, this +executes before every request. When used on a blueprint, this executes before +every request that the blueprint handles. To register with a blueprint and +execute before every request, use Blueprint.before_app_request().

+
+
Parameters:
+

f (T_before_request)

+
+
Return type:
+

T_before_request

+
+
+
+ +
+
+config_class
+

alias of Config

+
+ +
+
+context_processor(f)
+

Registers a template context processor function. These functions run before +rendering a template. The keys of the returned dict are added as variables +available in the template.

+

This is available on both app and blueprint objects. When used on an app, this +is called for every rendered template. When used on a blueprint, this is called +for templates rendered from the blueprint’s views. To register with a blueprint +and affect every template, use Blueprint.app_context_processor().

+
+
Parameters:
+

f (T_template_context_processor)

+
+
Return type:
+

T_template_context_processor

+
+
+
+ +
+
+create_global_jinja_loader()
+

Creates the loader for the Jinja2 environment. Can be used to +override just the loader and keeping the rest unchanged. It’s +discouraged to override this function. Instead one should override +the jinja_loader() function instead.

+

The global loader dispatches between the loaders of the application +and the individual blueprints.

+
+Changelog
+

Added in version 0.7.

+
+
+
Return type:
+

DispatchingJinjaLoader

+
+
+
+ +
+
+property debug: bool
+

Whether debug mode is enabled. When using flask run to start the +development server, an interactive debugger will be shown for unhandled +exceptions, and the server will be reloaded when code changes. This maps to the +DEBUG config key. It may not behave as expected if set late.

+

Do not enable debug mode when deploying in production.

+

Default: False

+
+ +
+
+delete(rule, **options)
+

Shortcut for route() with methods=["DELETE"].

+
+Changelog
+

Added in version 2.0.

+
+
+
Parameters:
+
+
+
Return type:
+

Callable[[T_route], T_route]

+
+
+
+ +
+
+endpoint(endpoint)
+

Decorate a view function to register it for the given +endpoint. Used if a rule is added without a view_func with +add_url_rule().

+
app.add_url_rule("/ex", endpoint="example")
+
+@app.endpoint("example")
+def example():
+    ...
+
+
+
+
Parameters:
+

endpoint (str) – The endpoint name to associate with the view +function.

+
+
Return type:
+

Callable[[F], F]

+
+
+
+ +
+
+errorhandler(code_or_exception)
+

Register a function to handle errors by code or exception class.

+

A decorator that is used to register a function given an +error code. Example:

+
@app.errorhandler(404)
+def page_not_found(error):
+    return 'This page does not exist', 404
+
+
+

You can also register handlers for arbitrary exceptions:

+
@app.errorhandler(DatabaseError)
+def special_exception_handler(error):
+    return 'Database connection failed', 500
+
+
+

This is available on both app and blueprint objects. When used on an app, this +can handle errors from every request. When used on a blueprint, this can handle +errors from requests that the blueprint handles. To register with a blueprint +and affect every request, use Blueprint.app_errorhandler().

+
+Changelog
+

Added in version 0.7: Use register_error_handler() instead of modifying +error_handler_spec directly, for application wide error +handlers.

+
+
+

Added in version 0.7: One can now additionally also register custom exception types +that do not necessarily have to be a subclass of the +HTTPException class.

+
+
+
Parameters:
+

code_or_exception (type[Exception] | int) – the code as integer for the handler, or +an arbitrary exception

+
+
Return type:
+

Callable[[T_error_handler], T_error_handler]

+
+
+
+ +
+
+get(rule, **options)
+

Shortcut for route() with methods=["GET"].

+
+Changelog
+

Added in version 2.0.

+
+
+
Parameters:
+
+
+
Return type:
+

Callable[[T_route], T_route]

+
+
+
+ +
+
+handle_url_build_error(error, endpoint, values)
+

Called by url_for() if a +BuildError was raised. If this returns +a value, it will be returned by url_for, otherwise the error +will be re-raised.

+

Each function in url_build_error_handlers is called with +error, endpoint and values. If a function returns +None or raises a BuildError, it is skipped. Otherwise, +its return value is returned by url_for.

+
+
Parameters:
+
    +
  • error (BuildError) – The active BuildError being handled.

  • +
  • endpoint (str) – The endpoint being built.

  • +
  • values (dict[str, Any]) – The keyword arguments passed to url_for.

  • +
+
+
Return type:
+

str

+
+
+
+ +
+
+property has_static_folder: bool
+

True if static_folder is set.

+
+Changelog
+

Added in version 0.5.

+
+
+ +
+
+inject_url_defaults(endpoint, values)
+

Injects the URL defaults for the given endpoint directly into +the values dictionary passed. This is used internally and +automatically called on URL building.

+
+Changelog
+

Added in version 0.7.

+
+
+
Parameters:
+
+
+
Return type:
+

None

+
+
+
+ +
+
+iter_blueprints()
+

Iterates over all blueprints by the order they were registered.

+
+Changelog
+

Added in version 0.11.

+
+
+
Return type:
+

t.ValuesView[Blueprint]

+
+
+
+ +
+
+property jinja_env: Environment
+

The Jinja environment used to load templates.

+

The environment is created the first time this property is +accessed. Changing jinja_options after that will have no +effect.

+
+ +
+
+jinja_environment
+

alias of Environment

+
+ +
+
+property jinja_loader: BaseLoader | None
+

The Jinja loader for this object’s templates. By default this +is a class jinja2.loaders.FileSystemLoader to +template_folder if it is set.

+
+Changelog
+

Added in version 0.5.

+
+
+ +
+
+jinja_options: dict[str, t.Any] = {}
+

Options that are passed to the Jinja environment in +create_jinja_environment(). Changing these options after +the environment is created (accessing jinja_env) will +have no effect.

+
+Changelog
+

Changed in version 1.1.0: This is a dict instead of an ImmutableDict to allow +easier configuration.

+
+
+ +
+
+json_provider_class
+

alias of DefaultJSONProvider

+
+ +
+
+property logger: Logger
+

A standard Python Logger for the app, with +the same name as name.

+

In debug mode, the logger’s level will +be set to DEBUG.

+

If there are no handlers configured, a default handler will be +added. See Logging for more information.

+
+Changelog
+

Changed in version 1.1.0: The logger takes the same name as name rather than +hard-coding "flask.app".

+
+
+

Changed in version 1.0.0: Behavior was simplified. The logger is always named +"flask.app". The level is only set during configuration, +it doesn’t check app.debug each time. Only one format is +used, not different ones depending on app.debug. No +handlers are removed, and a handler is only added if no +handlers are already configured.

+
+
+

Added in version 0.3.

+
+
+ +
+
+make_aborter()
+

Create the object to assign to aborter. That object +is called by flask.abort() to raise HTTP errors, and can +be called directly as well.

+

By default, this creates an instance of aborter_class, +which defaults to werkzeug.exceptions.Aborter.

+
+Changelog
+

Added in version 2.2.

+
+
+
Return type:
+

Aborter

+
+
+
+ +
+
+make_config(instance_relative=False)
+

Used to create the config attribute by the Flask constructor. +The instance_relative parameter is passed in from the constructor +of Flask (there named instance_relative_config) and indicates if +the config should be relative to the instance path or the root path +of the application.

+
+Changelog
+

Added in version 0.8.

+
+
+
Parameters:
+

instance_relative (bool)

+
+
Return type:
+

Config

+
+
+
+ +
+
+property name: str
+

The name of the application. This is usually the import name +with the difference that it’s guessed from the run file if the +import name is main. This name is used as a display name when +Flask needs the name of the application. It can be set and overridden +to change the value.

+
+Changelog
+

Added in version 0.8.

+
+
+ +
+
+patch(rule, **options)
+

Shortcut for route() with methods=["PATCH"].

+
+Changelog
+

Added in version 2.0.

+
+
+
Parameters:
+
+
+
Return type:
+

Callable[[T_route], T_route]

+
+
+
+ +
+
+permanent_session_lifetime
+

A timedelta which is used to set the expiration +date of a permanent session. The default is 31 days which makes a +permanent session survive for roughly one month.

+

This attribute can also be configured from the config with the +PERMANENT_SESSION_LIFETIME configuration key. Defaults to +timedelta(days=31)

+
+ +
+
+post(rule, **options)
+

Shortcut for route() with methods=["POST"].

+
+Changelog
+

Added in version 2.0.

+
+
+
Parameters:
+
+
+
Return type:
+

Callable[[T_route], T_route]

+
+
+
+ +
+
+put(rule, **options)
+

Shortcut for route() with methods=["PUT"].

+
+Changelog
+

Added in version 2.0.

+
+
+
Parameters:
+
+
+
Return type:
+

Callable[[T_route], T_route]

+
+
+
+ +
+
+redirect(location, code=302)
+

Create a redirect response object.

+

This is called by flask.redirect(), and can be called +directly as well.

+
+
Parameters:
+
    +
  • location (str) – The URL to redirect to.

  • +
  • code (int) – The status code for the redirect.

  • +
+
+
Return type:
+

BaseResponse

+
+
+
+Changelog
+

Added in version 2.2: Moved from flask.redirect, which calls this method.

+
+
+ +
+
+register_blueprint(blueprint, **options)
+

Register a Blueprint on the application. Keyword +arguments passed to this method will override the defaults set on the +blueprint.

+

Calls the blueprint’s register() method after +recording the blueprint in the application’s blueprints.

+
+
Parameters:
+
    +
  • blueprint (Blueprint) – The blueprint to register.

  • +
  • url_prefix – Blueprint routes will be prefixed with this.

  • +
  • subdomain – Blueprint routes will match on this subdomain.

  • +
  • url_defaults – Blueprint routes will use these default values for +view arguments.

  • +
  • options (t.Any) – Additional keyword arguments are passed to +BlueprintSetupState. They can be +accessed in record() callbacks.

  • +
+
+
Return type:
+

None

+
+
+
+Changelog
+

Changed in version 2.0.1: The name option can be used to change the (pre-dotted) +name the blueprint is registered with. This allows the same +blueprint to be registered multiple times with unique names +for url_for.

+
+
+

Added in version 0.7.

+
+
+ +
+
+register_error_handler(code_or_exception, f)
+

Alternative error attach function to the errorhandler() +decorator that is more straightforward to use for non decorator +usage.

+
+Changelog
+

Added in version 0.7.

+
+
+
Parameters:
+
+
+
Return type:
+

None

+
+
+
+ +
+
+route(rule, **options)
+

Decorate a view function to register it with the given URL +rule and options. Calls add_url_rule(), which has more +details about the implementation.

+
@app.route("/")
+def index():
+    return "Hello, World!"
+
+
+

See URL Route Registrations.

+

The endpoint name for the route defaults to the name of the view +function if the endpoint parameter isn’t passed.

+

The methods parameter defaults to ["GET"]. HEAD and +OPTIONS are added automatically.

+
+
Parameters:
+
    +
  • rule (str) – The URL rule string.

  • +
  • options (Any) – Extra options passed to the +Rule object.

  • +
+
+
Return type:
+

Callable[[T_route], T_route]

+
+
+
+ +
+
+secret_key
+

If a secret key is set, cryptographic components can use this to +sign cookies and other things. Set this to a complex random value +when you want to use the secure cookie for instance.

+

This attribute can also be configured from the config with the +SECRET_KEY configuration key. Defaults to None.

+
+ +
+
+select_jinja_autoescape(filename)
+

Returns True if autoescaping should be active for the given +template name. If no template name is given, returns True.

+
+Changelog
+

Changed in version 2.2: Autoescaping is now enabled by default for .svg files.

+
+
+

Added in version 0.5.

+
+
+
Parameters:
+

filename (str)

+
+
Return type:
+

bool

+
+
+
+ +
+
+shell_context_processor(f)
+

Registers a shell context processor function.

+
+Changelog
+

Added in version 0.11.

+
+
+
Parameters:
+

f (T_shell_context_processor)

+
+
Return type:
+

T_shell_context_processor

+
+
+
+ +
+
+should_ignore_error(error)
+

This is called to figure out if an error should be ignored +or not as far as the teardown system is concerned. If this +function returns True then the teardown handlers will not be +passed the error.

+
+Changelog
+

Added in version 0.10.

+
+
+
Parameters:
+

error (BaseException | None)

+
+
Return type:
+

bool

+
+
+
+ +
+
+property static_folder: str | None
+

The absolute path to the configured static folder. None +if no static folder is set.

+
+ +
+
+property static_url_path: str | None
+

The URL prefix that the static route will be accessible from.

+

If it was not configured during init, it is derived from +static_folder.

+
+ +
+
+teardown_appcontext(f)
+

Registers a function to be called when the application +context is popped. The application context is typically popped +after the request context for each request, at the end of CLI +commands, or after a manually pushed context ends.

+
with app.app_context():
+    ...
+
+
+

When the with block exits (or ctx.pop() is called), the +teardown functions are called just before the app context is +made inactive. Since a request context typically also manages an +application context it would also be called when you pop a +request context.

+

When a teardown function was called because of an unhandled +exception it will be passed an error object. If an +errorhandler() is registered, it will handle the exception +and the teardown will not receive it.

+

Teardown functions must avoid raising exceptions. If they +execute code that might fail they must surround that code with a +try/except block and log any errors.

+

The return values of teardown functions are ignored.

+
+Changelog
+

Added in version 0.9.

+
+
+
Parameters:
+

f (T_teardown)

+
+
Return type:
+

T_teardown

+
+
+
+ +
+
+teardown_request(f)
+

Register a function to be called when the request context is +popped. Typically this happens at the end of each request, but +contexts may be pushed manually as well during testing.

+
with app.test_request_context():
+    ...
+
+
+

When the with block exits (or ctx.pop() is called), the +teardown functions are called just before the request context is +made inactive.

+

When a teardown function was called because of an unhandled +exception it will be passed an error object. If an +errorhandler() is registered, it will handle the exception +and the teardown will not receive it.

+

Teardown functions must avoid raising exceptions. If they +execute code that might fail they must surround that code with a +try/except block and log any errors.

+

The return values of teardown functions are ignored.

+

This is available on both app and blueprint objects. When used on an app, this +executes after every request. When used on a blueprint, this executes after +every request that the blueprint handles. To register with a blueprint and +execute after every request, use Blueprint.teardown_app_request().

+
+
Parameters:
+

f (T_teardown)

+
+
Return type:
+

T_teardown

+
+
+
+ +
+
+template_filter(name=None)
+

A decorator that is used to register custom template filter. +You can specify a name for the filter, otherwise the function +name will be used. Example:

+
@app.template_filter()
+def reverse(s):
+    return s[::-1]
+
+
+
+
Parameters:
+

name (str | None) – the optional name of the filter, otherwise the +function name will be used.

+
+
Return type:
+

Callable[[T_template_filter], T_template_filter]

+
+
+
+ +
+
+template_global(name=None)
+

A decorator that is used to register a custom template global function. +You can specify a name for the global function, otherwise the function +name will be used. Example:

+
@app.template_global()
+def double(n):
+    return 2 * n
+
+
+
+Changelog
+

Added in version 0.10.

+
+
+
Parameters:
+

name (str | None) – the optional name of the global function, otherwise the +function name will be used.

+
+
Return type:
+

Callable[[T_template_global], T_template_global]

+
+
+
+ +
+
+template_test(name=None)
+

A decorator that is used to register custom template test. +You can specify a name for the test, otherwise the function +name will be used. Example:

+
@app.template_test()
+def is_prime(n):
+    if n == 2:
+        return True
+    for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
+        if n % i == 0:
+            return False
+    return True
+
+
+
+Changelog
+

Added in version 0.10.

+
+
+
Parameters:
+

name (str | None) – the optional name of the test, otherwise the +function name will be used.

+
+
Return type:
+

Callable[[T_template_test], T_template_test]

+
+
+
+ +
+
+test_cli_runner_class: type[FlaskCliRunner] | None = None
+

The CliRunner subclass, by default +FlaskCliRunner that is used by +test_cli_runner(). Its __init__ method should take a +Flask app object as the first argument.

+
+Changelog
+

Added in version 1.0.

+
+
+ +
+
+test_client_class: type[FlaskClient] | None = None
+

The test_client() method creates an instance of this test +client class. Defaults to FlaskClient.

+
+Changelog
+

Added in version 0.7.

+
+
+ +
+
+testing
+

The testing flag. Set this to True to enable the test mode of +Flask extensions (and in the future probably also Flask itself). +For example this might activate test helpers that have an +additional runtime cost which should not be enabled by default.

+

If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the +default it’s implicitly enabled.

+

This attribute can also be configured from the config with the +TESTING configuration key. Defaults to False.

+
+ +
+
+trap_http_exception(e)
+

Checks if an HTTP exception should be trapped or not. By default +this will return False for all exceptions except for a bad request +key error if TRAP_BAD_REQUEST_ERRORS is set to True. It +also returns True if TRAP_HTTP_EXCEPTIONS is set to True.

+

This is called for all HTTP exceptions raised by a view function. +If it returns True for any exception the error handler for this +exception is not called and it shows up as regular exception in the +traceback. This is helpful for debugging implicitly raised HTTP +exceptions.

+
+Changelog
+

Changed in version 1.0: Bad request errors are not trapped by default in debug mode.

+
+
+

Added in version 0.8.

+
+
+
Parameters:
+

e (Exception)

+
+
Return type:
+

bool

+
+
+
+ +
+
+url_defaults(f)
+

Callback function for URL defaults for all view functions of the +application. It’s called with the endpoint and values and should +update the values passed in place.

+

This is available on both app and blueprint objects. When used on an app, this +is called for every request. When used on a blueprint, this is called for +requests that the blueprint handles. To register with a blueprint and affect +every request, use Blueprint.app_url_defaults().

+
+
Parameters:
+

f (T_url_defaults)

+
+
Return type:
+

T_url_defaults

+
+
+
+ +
+
+url_map_class
+

alias of Map

+
+ +
+
+url_rule_class
+

alias of Rule

+
+ +
+
+url_value_preprocessor(f)
+

Register a URL value preprocessor function for all view +functions in the application. These functions will be called before the +before_request() functions.

+

The function can modify the values captured from the matched url before +they are passed to the view. For example, this can be used to pop a +common language code value and place it in g rather than pass it to +every view.

+

The function is passed the endpoint name and values dict. The return +value is ignored.

+

This is available on both app and blueprint objects. When used on an app, this +is called for every request. When used on a blueprint, this is called for +requests that the blueprint handles. To register with a blueprint and affect +every request, use Blueprint.app_url_value_preprocessor().

+
+
Parameters:
+

f (T_url_value_preprocessor)

+
+
Return type:
+

T_url_value_preprocessor

+
+
+
+ +
+
+instance_path
+

Holds the path to the instance folder.

+
+Changelog
+

Added in version 0.8.

+
+
+ +
+
+config
+

The configuration dictionary as Config. This behaves +exactly like a regular dictionary but supports additional methods +to load a config from files.

+
+ +
+
+aborter
+

An instance of aborter_class created by +make_aborter(). This is called by flask.abort() +to raise HTTP errors, and can be called directly as well.

+
+Changelog
+

Added in version 2.2: Moved from flask.abort, which calls this object.

+
+
+ +
+
+json: JSONProvider
+

Provides access to JSON methods. Functions in flask.json +will call methods on this provider when the application context +is active. Used for handling JSON requests and responses.

+

An instance of json_provider_class. Can be customized by +changing that attribute on a subclass, or by assigning to this +attribute afterwards.

+

The default, DefaultJSONProvider, +uses Python’s built-in json library. A different provider +can use a different JSON library.

+
+Changelog
+

Added in version 2.2.

+
+
+ +
+
+url_build_error_handlers: list[t.Callable[[Exception, str, dict[str, t.Any]], str]]
+

A list of functions that are called by +handle_url_build_error() when url_for() raises a +BuildError. Each function is called +with error, endpoint and values. If a function +returns None or raises a BuildError, it is skipped. +Otherwise, its return value is returned by url_for.

+
+Changelog
+

Added in version 0.9.

+
+
+ +
+
+teardown_appcontext_funcs: list[ft.TeardownCallable]
+

A list of functions that are called when the application context +is destroyed. Since the application context is also torn down +if the request ends this is the place to store code that disconnects +from databases.

+
+Changelog
+

Added in version 0.9.

+
+
+ +
+
+shell_context_processors: list[ft.ShellContextProcessorCallable]
+

A list of shell context processor functions that should be run +when a shell context is created.

+
+Changelog
+

Added in version 0.11.

+
+
+ +
+
+blueprints: dict[str, Blueprint]
+

Maps registered blueprint names to blueprint objects. The +dict retains the order the blueprints were registered in. +Blueprints can be registered multiple times, this dict does +not track how often they were attached.

+
+Changelog
+

Added in version 0.7.

+
+
+ +
+
+extensions: dict[str, t.Any]
+

a place where extensions can store application specific state. For +example this is where an extension could store database engines and +similar things.

+

The key must match the name of the extension module. For example in +case of a “Flask-Foo” extension in flask_foo, the key would be +'foo'.

+
+Changelog
+

Added in version 0.7.

+
+
+ +
+
+url_map
+

The Map for this instance. You can use +this to change the routing converters after the class was created +but before any routes are connected. Example:

+
from werkzeug.routing import BaseConverter
+
+class ListConverter(BaseConverter):
+    def to_python(self, value):
+        return value.split(',')
+    def to_url(self, values):
+        return ','.join(super(ListConverter, self).to_url(value)
+                        for value in values)
+
+app = Flask(__name__)
+app.url_map.converters['list'] = ListConverter
+
+
+
+ +
+
+import_name
+

The name of the package or module that this object belongs +to. Do not change this once it is set by the constructor.

+
+ +
+
+template_folder
+

The path to the templates folder, relative to +root_path, to add to the template loader. None if +templates should not be added.

+
+ +
+
+root_path
+

Absolute path to the package on the filesystem. Used to look +up resources contained in the package.

+
+ +
+
+view_functions: dict[str, ft.RouteCallable]
+

A dictionary mapping endpoint names to view functions.

+

To register a view function, use the route() decorator.

+

This data structure is internal. It should not be modified +directly and its format may change at any time.

+
+ +
+
+error_handler_spec: dict[ft.AppOrBlueprintKey, dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]]]
+

A data structure of registered error handlers, in the format +{scope: {code: {class: handler}}}. The scope key is +the name of a blueprint the handlers are active for, or +None for all requests. The code key is the HTTP +status code for HTTPException, or None for +other exceptions. The innermost dictionary maps exception +classes to handler functions.

+

To register an error handler, use the errorhandler() +decorator.

+

This data structure is internal. It should not be modified +directly and its format may change at any time.

+
+ +
+
+before_request_funcs: dict[ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]]
+

A data structure of functions to call at the beginning of +each request, in the format {scope: [functions]}. The +scope key is the name of a blueprint the functions are +active for, or None for all requests.

+

To register a function, use the before_request() +decorator.

+

This data structure is internal. It should not be modified +directly and its format may change at any time.

+
+ +
+
+after_request_funcs: dict[ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]]]
+

A data structure of functions to call at the end of each +request, in the format {scope: [functions]}. The +scope key is the name of a blueprint the functions are +active for, or None for all requests.

+

To register a function, use the after_request() +decorator.

+

This data structure is internal. It should not be modified +directly and its format may change at any time.

+
+ +
+
+teardown_request_funcs: dict[ft.AppOrBlueprintKey, list[ft.TeardownCallable]]
+

A data structure of functions to call at the end of each +request even if an exception is raised, in the format +{scope: [functions]}. The scope key is the name of a +blueprint the functions are active for, or None for all +requests.

+

To register a function, use the teardown_request() +decorator.

+

This data structure is internal. It should not be modified +directly and its format may change at any time.

+
+ +
+
+template_context_processors: dict[ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]]
+

A data structure of functions to call to pass extra context +values when rendering templates, in the format +{scope: [functions]}. The scope key is the name of a +blueprint the functions are active for, or None for all +requests.

+

To register a function, use the context_processor() +decorator.

+

This data structure is internal. It should not be modified +directly and its format may change at any time.

+
+ +
+
+url_value_preprocessors: dict[ft.AppOrBlueprintKey, list[ft.URLValuePreprocessorCallable]]
+

A data structure of functions to call to modify the keyword +arguments passed to the view function, in the format +{scope: [functions]}. The scope key is the name of a +blueprint the functions are active for, or None for all +requests.

+

To register a function, use the +url_value_preprocessor() decorator.

+

This data structure is internal. It should not be modified +directly and its format may change at any time.

+
+ +
+
+url_default_functions: dict[ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]]
+

A data structure of functions to call to modify the keyword +arguments when generating URLs, in the format +{scope: [functions]}. The scope key is the name of a +blueprint the functions are active for, or None for all +requests.

+

To register a function, use the url_defaults() +decorator.

+

This data structure is internal. It should not be modified +directly and its format may change at any time.

+
+ +
+ +
+
+

Blueprint Objects

+
+
+class flask.Blueprint(name, import_name, static_folder=None, static_url_path=None, template_folder=None, url_prefix=None, subdomain=None, url_defaults=None, root_path=None, cli_group=_sentinel)
+
+
Parameters:
+
+
+
+
+
+cli: Group
+

The Click command group for registering CLI commands for this +object. The commands are available from the flask command +once the application has been discovered and blueprints have +been registered.

+
+ +
+
+get_send_file_max_age(filename)
+

Used by send_file() to determine the max_age cache +value for a given file path if it wasn’t passed.

+

By default, this returns SEND_FILE_MAX_AGE_DEFAULT from +the configuration of current_app. This defaults +to None, which tells the browser to use conditional requests +instead of a timed cache, which is usually preferable.

+

Note this is a duplicate of the same method in the Flask +class.

+
+Changelog
+

Changed in version 2.0: The default configuration is None instead of 12 hours.

+
+
+

Added in version 0.9.

+
+
+
Parameters:
+

filename (str | None)

+
+
Return type:
+

int | None

+
+
+
+ +
+
+send_static_file(filename)
+

The view function used to serve files from +static_folder. A route is automatically registered for +this view at static_url_path if static_folder is +set.

+

Note this is a duplicate of the same method in the Flask +class.

+
+Changelog
+

Added in version 0.5.

+
+
+
Parameters:
+

filename (str)

+
+
Return type:
+

Response

+
+
+
+ +
+
+open_resource(resource, mode='rb', encoding='utf-8')
+

Open a resource file relative to root_path for reading. The +blueprint-relative equivalent of the app’s open_resource() +method.

+
+
Parameters:
+
    +
  • resource (str) – Path to the resource relative to root_path.

  • +
  • mode (str) – Open the file in this mode. Only reading is supported, +valid values are "r" (or "rt") and "rb".

  • +
  • encoding (str | None) – Open the file with this encoding when opening in text +mode. This is ignored when opening in binary mode.

  • +
+
+
Return type:
+

IO

+
+
+
+

Changed in version 3.1: Added the encoding parameter.

+
+
+ +
+
+add_app_template_filter(f, name=None)
+

Register a template filter, available in any template rendered by the +application. Works like the app_template_filter() decorator. Equivalent to +Flask.add_template_filter().

+
+
Parameters:
+
    +
  • name (str | None) – the optional name of the filter, otherwise the +function name will be used.

  • +
  • f (Callable[[...], Any])

  • +
+
+
Return type:
+

None

+
+
+
+ +
+
+add_app_template_global(f, name=None)
+

Register a template global, available in any template rendered by the +application. Works like the app_template_global() decorator. Equivalent to +Flask.add_template_global().

+
+Changelog
+

Added in version 0.10.

+
+
+
Parameters:
+
    +
  • name (str | None) – the optional name of the global, otherwise the +function name will be used.

  • +
  • f (Callable[[...], Any])

  • +
+
+
Return type:
+

None

+
+
+
+ +
+
+add_app_template_test(f, name=None)
+

Register a template test, available in any template rendered by the +application. Works like the app_template_test() decorator. Equivalent to +Flask.add_template_test().

+
+Changelog
+

Added in version 0.10.

+
+
+
Parameters:
+
    +
  • name (str | None) – the optional name of the test, otherwise the +function name will be used.

  • +
  • f (Callable[[...], bool])

  • +
+
+
Return type:
+

None

+
+
+
+ +
+
+add_url_rule(rule, endpoint=None, view_func=None, provide_automatic_options=None, **options)
+

Register a URL rule with the blueprint. See Flask.add_url_rule() for +full documentation.

+

The URL rule is prefixed with the blueprint’s URL prefix. The endpoint name, +used with url_for(), is prefixed with the blueprint’s name.

+
+
Parameters:
+
    +
  • rule (str)

  • +
  • endpoint (str | None)

  • +
  • view_func (ft.RouteCallable | None)

  • +
  • provide_automatic_options (bool | None)

  • +
  • options (t.Any)

  • +
+
+
Return type:
+

None

+
+
+
+ +
+
+after_app_request(f)
+

Like after_request(), but after every request, not only those handled +by the blueprint. Equivalent to Flask.after_request().

+
+
Parameters:
+

f (T_after_request)

+
+
Return type:
+

T_after_request

+
+
+
+ +
+
+after_request(f)
+

Register a function to run after each request to this object.

+

The function is called with the response object, and must return +a response object. This allows the functions to modify or +replace the response before it is sent.

+

If a function raises an exception, any remaining +after_request functions will not be called. Therefore, this +should not be used for actions that must execute, such as to +close resources. Use teardown_request() for that.

+

This is available on both app and blueprint objects. When used on an app, this +executes after every request. When used on a blueprint, this executes after +every request that the blueprint handles. To register with a blueprint and +execute after every request, use Blueprint.after_app_request().

+
+
Parameters:
+

f (T_after_request)

+
+
Return type:
+

T_after_request

+
+
+
+ +
+
+app_context_processor(f)
+

Like context_processor(), but for templates rendered by every view, not +only by the blueprint. Equivalent to Flask.context_processor().

+
+
Parameters:
+

f (T_template_context_processor)

+
+
Return type:
+

T_template_context_processor

+
+
+
+ +
+
+app_errorhandler(code)
+

Like errorhandler(), but for every request, not only those handled by +the blueprint. Equivalent to Flask.errorhandler().

+
+
Parameters:
+

code (type[Exception] | int)

+
+
Return type:
+

Callable[[T_error_handler], T_error_handler]

+
+
+
+ +
+
+app_template_filter(name=None)
+

Register a template filter, available in any template rendered by the +application. Equivalent to Flask.template_filter().

+
+
Parameters:
+

name (str | None) – the optional name of the filter, otherwise the +function name will be used.

+
+
Return type:
+

Callable[[T_template_filter], T_template_filter]

+
+
+
+ +
+
+app_template_global(name=None)
+

Register a template global, available in any template rendered by the +application. Equivalent to Flask.template_global().

+
+Changelog
+

Added in version 0.10.

+
+
+
Parameters:
+

name (str | None) – the optional name of the global, otherwise the +function name will be used.

+
+
Return type:
+

Callable[[T_template_global], T_template_global]

+
+
+
+ +
+
+app_template_test(name=None)
+

Register a template test, available in any template rendered by the +application. Equivalent to Flask.template_test().

+
+Changelog
+

Added in version 0.10.

+
+
+
Parameters:
+

name (str | None) – the optional name of the test, otherwise the +function name will be used.

+
+
Return type:
+

Callable[[T_template_test], T_template_test]

+
+
+
+ +
+
+app_url_defaults(f)
+

Like url_defaults(), but for every request, not only those handled by +the blueprint. Equivalent to Flask.url_defaults().

+
+
Parameters:
+

f (T_url_defaults)

+
+
Return type:
+

T_url_defaults

+
+
+
+ +
+
+app_url_value_preprocessor(f)
+

Like url_value_preprocessor(), but for every request, not only those +handled by the blueprint. Equivalent to Flask.url_value_preprocessor().

+
+
Parameters:
+

f (T_url_value_preprocessor)

+
+
Return type:
+

T_url_value_preprocessor

+
+
+
+ +
+
+before_app_request(f)
+

Like before_request(), but before every request, not only those handled +by the blueprint. Equivalent to Flask.before_request().

+
+
Parameters:
+

f (T_before_request)

+
+
Return type:
+

T_before_request

+
+
+
+ +
+
+before_request(f)
+

Register a function to run before each request.

+

For example, this can be used to open a database connection, or +to load the logged in user from the session.

+
@app.before_request
+def load_user():
+    if "user_id" in session:
+        g.user = db.session.get(session["user_id"])
+
+
+

The function will be called without any arguments. If it returns +a non-None value, the value is handled as if it was the +return value from the view, and further request handling is +stopped.

+

This is available on both app and blueprint objects. When used on an app, this +executes before every request. When used on a blueprint, this executes before +every request that the blueprint handles. To register with a blueprint and +execute before every request, use Blueprint.before_app_request().

+
+
Parameters:
+

f (T_before_request)

+
+
Return type:
+

T_before_request

+
+
+
+ +
+
+context_processor(f)
+

Registers a template context processor function. These functions run before +rendering a template. The keys of the returned dict are added as variables +available in the template.

+

This is available on both app and blueprint objects. When used on an app, this +is called for every rendered template. When used on a blueprint, this is called +for templates rendered from the blueprint’s views. To register with a blueprint +and affect every template, use Blueprint.app_context_processor().

+
+
Parameters:
+

f (T_template_context_processor)

+
+
Return type:
+

T_template_context_processor

+
+
+
+ +
+
+delete(rule, **options)
+

Shortcut for route() with methods=["DELETE"].

+
+Changelog
+

Added in version 2.0.

+
+
+
Parameters:
+
+
+
Return type:
+

Callable[[T_route], T_route]

+
+
+
+ +
+
+endpoint(endpoint)
+

Decorate a view function to register it for the given +endpoint. Used if a rule is added without a view_func with +add_url_rule().

+
app.add_url_rule("/ex", endpoint="example")
+
+@app.endpoint("example")
+def example():
+    ...
+
+
+
+
Parameters:
+

endpoint (str) – The endpoint name to associate with the view +function.

+
+
Return type:
+

Callable[[F], F]

+
+
+
+ +
+
+errorhandler(code_or_exception)
+

Register a function to handle errors by code or exception class.

+

A decorator that is used to register a function given an +error code. Example:

+
@app.errorhandler(404)
+def page_not_found(error):
+    return 'This page does not exist', 404
+
+
+

You can also register handlers for arbitrary exceptions:

+
@app.errorhandler(DatabaseError)
+def special_exception_handler(error):
+    return 'Database connection failed', 500
+
+
+

This is available on both app and blueprint objects. When used on an app, this +can handle errors from every request. When used on a blueprint, this can handle +errors from requests that the blueprint handles. To register with a blueprint +and affect every request, use Blueprint.app_errorhandler().

+
+Changelog
+

Added in version 0.7: Use register_error_handler() instead of modifying +error_handler_spec directly, for application wide error +handlers.

+
+
+

Added in version 0.7: One can now additionally also register custom exception types +that do not necessarily have to be a subclass of the +HTTPException class.

+
+
+
Parameters:
+

code_or_exception (type[Exception] | int) – the code as integer for the handler, or +an arbitrary exception

+
+
Return type:
+

Callable[[T_error_handler], T_error_handler]

+
+
+
+ +
+
+get(rule, **options)
+

Shortcut for route() with methods=["GET"].

+
+Changelog
+

Added in version 2.0.

+
+
+
Parameters:
+
+
+
Return type:
+

Callable[[T_route], T_route]

+
+
+
+ +
+
+property has_static_folder: bool
+

True if static_folder is set.

+
+Changelog
+

Added in version 0.5.

+
+
+ +
+
+property jinja_loader: BaseLoader | None
+

The Jinja loader for this object’s templates. By default this +is a class jinja2.loaders.FileSystemLoader to +template_folder if it is set.

+
+Changelog
+

Added in version 0.5.

+
+
+ +
+
+make_setup_state(app, options, first_registration=False)
+

Creates an instance of BlueprintSetupState() +object that is later passed to the register callback functions. +Subclasses can override this to return a subclass of the setup state.

+
+
Parameters:
+
    +
  • app (App)

  • +
  • options (dict[str, t.Any])

  • +
  • first_registration (bool)

  • +
+
+
Return type:
+

BlueprintSetupState

+
+
+
+ +
+
+patch(rule, **options)
+

Shortcut for route() with methods=["PATCH"].

+
+Changelog
+

Added in version 2.0.

+
+
+
Parameters:
+
+
+
Return type:
+

Callable[[T_route], T_route]

+
+
+
+ +
+
+post(rule, **options)
+

Shortcut for route() with methods=["POST"].

+
+Changelog
+

Added in version 2.0.

+
+
+
Parameters:
+
+
+
Return type:
+

Callable[[T_route], T_route]

+
+
+
+ +
+
+put(rule, **options)
+

Shortcut for route() with methods=["PUT"].

+
+Changelog
+

Added in version 2.0.

+
+
+
Parameters:
+
+
+
Return type:
+

Callable[[T_route], T_route]

+
+
+
+ +
+
+record(func)
+

Registers a function that is called when the blueprint is +registered on the application. This function is called with the +state as argument as returned by the make_setup_state() +method.

+
+
Parameters:
+

func (Callable[[BlueprintSetupState], None])

+
+
Return type:
+

None

+
+
+
+ +
+
+record_once(func)
+

Works like record() but wraps the function in another +function that will ensure the function is only called once. If the +blueprint is registered a second time on the application, the +function passed is not called.

+
+
Parameters:
+

func (Callable[[BlueprintSetupState], None])

+
+
Return type:
+

None

+
+
+
+ +
+
+register(app, options)
+

Called by Flask.register_blueprint() to register all +views and callbacks registered on the blueprint with the +application. Creates a BlueprintSetupState and calls +each record() callback with it.

+
+
Parameters:
+
    +
  • app (App) – The application this blueprint is being registered +with.

  • +
  • options (dict[str, t.Any]) – Keyword arguments forwarded from +register_blueprint().

  • +
+
+
Return type:
+

None

+
+
+
+Changelog
+

Changed in version 2.3: Nested blueprints now correctly apply subdomains.

+
+
+

Changed in version 2.1: Registering the same blueprint with the same name multiple +times is an error.

+
+
+

Changed in version 2.0.1: Nested blueprints are registered with their dotted name. +This allows different blueprints with the same name to be +nested at different locations.

+
+
+

Changed in version 2.0.1: The name option can be used to change the (pre-dotted) +name the blueprint is registered with. This allows the same +blueprint to be registered multiple times with unique names +for url_for.

+
+
+ +
+
+register_blueprint(blueprint, **options)
+

Register a Blueprint on this blueprint. Keyword +arguments passed to this method will override the defaults set +on the blueprint.

+
+Changelog
+

Changed in version 2.0.1: The name option can be used to change the (pre-dotted) +name the blueprint is registered with. This allows the same +blueprint to be registered multiple times with unique names +for url_for.

+
+
+

Added in version 2.0.

+
+
+
Parameters:
+
    +
  • blueprint (Blueprint)

  • +
  • options (Any)

  • +
+
+
Return type:
+

None

+
+
+
+ +
+
+register_error_handler(code_or_exception, f)
+

Alternative error attach function to the errorhandler() +decorator that is more straightforward to use for non decorator +usage.

+
+Changelog
+

Added in version 0.7.

+
+
+
Parameters:
+
+
+
Return type:
+

None

+
+
+
+ +
+
+route(rule, **options)
+

Decorate a view function to register it with the given URL +rule and options. Calls add_url_rule(), which has more +details about the implementation.

+
@app.route("/")
+def index():
+    return "Hello, World!"
+
+
+

See URL Route Registrations.

+

The endpoint name for the route defaults to the name of the view +function if the endpoint parameter isn’t passed.

+

The methods parameter defaults to ["GET"]. HEAD and +OPTIONS are added automatically.

+
+
Parameters:
+
    +
  • rule (str) – The URL rule string.

  • +
  • options (Any) – Extra options passed to the +Rule object.

  • +
+
+
Return type:
+

Callable[[T_route], T_route]

+
+
+
+ +
+
+property static_folder: str | None
+

The absolute path to the configured static folder. None +if no static folder is set.

+
+ +
+
+property static_url_path: str | None
+

The URL prefix that the static route will be accessible from.

+

If it was not configured during init, it is derived from +static_folder.

+
+ +
+
+teardown_app_request(f)
+

Like teardown_request(), but after every request, not only those +handled by the blueprint. Equivalent to Flask.teardown_request().

+
+
Parameters:
+

f (T_teardown)

+
+
Return type:
+

T_teardown

+
+
+
+ +
+
+teardown_request(f)
+

Register a function to be called when the request context is +popped. Typically this happens at the end of each request, but +contexts may be pushed manually as well during testing.

+
with app.test_request_context():
+    ...
+
+
+

When the with block exits (or ctx.pop() is called), the +teardown functions are called just before the request context is +made inactive.

+

When a teardown function was called because of an unhandled +exception it will be passed an error object. If an +errorhandler() is registered, it will handle the exception +and the teardown will not receive it.

+

Teardown functions must avoid raising exceptions. If they +execute code that might fail they must surround that code with a +try/except block and log any errors.

+

The return values of teardown functions are ignored.

+

This is available on both app and blueprint objects. When used on an app, this +executes after every request. When used on a blueprint, this executes after +every request that the blueprint handles. To register with a blueprint and +execute after every request, use Blueprint.teardown_app_request().

+
+
Parameters:
+

f (T_teardown)

+
+
Return type:
+

T_teardown

+
+
+
+ +
+
+url_defaults(f)
+

Callback function for URL defaults for all view functions of the +application. It’s called with the endpoint and values and should +update the values passed in place.

+

This is available on both app and blueprint objects. When used on an app, this +is called for every request. When used on a blueprint, this is called for +requests that the blueprint handles. To register with a blueprint and affect +every request, use Blueprint.app_url_defaults().

+
+
Parameters:
+

f (T_url_defaults)

+
+
Return type:
+

T_url_defaults

+
+
+
+ +
+
+url_value_preprocessor(f)
+

Register a URL value preprocessor function for all view +functions in the application. These functions will be called before the +before_request() functions.

+

The function can modify the values captured from the matched url before +they are passed to the view. For example, this can be used to pop a +common language code value and place it in g rather than pass it to +every view.

+

The function is passed the endpoint name and values dict. The return +value is ignored.

+

This is available on both app and blueprint objects. When used on an app, this +is called for every request. When used on a blueprint, this is called for +requests that the blueprint handles. To register with a blueprint and affect +every request, use Blueprint.app_url_value_preprocessor().

+
+
Parameters:
+

f (T_url_value_preprocessor)

+
+
Return type:
+

T_url_value_preprocessor

+
+
+
+ +
+
+import_name
+

The name of the package or module that this object belongs +to. Do not change this once it is set by the constructor.

+
+ +
+
+template_folder
+

The path to the templates folder, relative to +root_path, to add to the template loader. None if +templates should not be added.

+
+ +
+
+root_path
+

Absolute path to the package on the filesystem. Used to look +up resources contained in the package.

+
+ +
+
+view_functions: dict[str, ft.RouteCallable]
+

A dictionary mapping endpoint names to view functions.

+

To register a view function, use the route() decorator.

+

This data structure is internal. It should not be modified +directly and its format may change at any time.

+
+ +
+
+error_handler_spec: dict[ft.AppOrBlueprintKey, dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]]]
+

A data structure of registered error handlers, in the format +{scope: {code: {class: handler}}}. The scope key is +the name of a blueprint the handlers are active for, or +None for all requests. The code key is the HTTP +status code for HTTPException, or None for +other exceptions. The innermost dictionary maps exception +classes to handler functions.

+

To register an error handler, use the errorhandler() +decorator.

+

This data structure is internal. It should not be modified +directly and its format may change at any time.

+
+ +
+
+before_request_funcs: dict[ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]]
+

A data structure of functions to call at the beginning of +each request, in the format {scope: [functions]}. The +scope key is the name of a blueprint the functions are +active for, or None for all requests.

+

To register a function, use the before_request() +decorator.

+

This data structure is internal. It should not be modified +directly and its format may change at any time.

+
+ +
+
+after_request_funcs: dict[ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]]]
+

A data structure of functions to call at the end of each +request, in the format {scope: [functions]}. The +scope key is the name of a blueprint the functions are +active for, or None for all requests.

+

To register a function, use the after_request() +decorator.

+

This data structure is internal. It should not be modified +directly and its format may change at any time.

+
+ +
+
+teardown_request_funcs: dict[ft.AppOrBlueprintKey, list[ft.TeardownCallable]]
+

A data structure of functions to call at the end of each +request even if an exception is raised, in the format +{scope: [functions]}. The scope key is the name of a +blueprint the functions are active for, or None for all +requests.

+

To register a function, use the teardown_request() +decorator.

+

This data structure is internal. It should not be modified +directly and its format may change at any time.

+
+ +
+
+template_context_processors: dict[ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]]
+

A data structure of functions to call to pass extra context +values when rendering templates, in the format +{scope: [functions]}. The scope key is the name of a +blueprint the functions are active for, or None for all +requests.

+

To register a function, use the context_processor() +decorator.

+

This data structure is internal. It should not be modified +directly and its format may change at any time.

+
+ +
+
+url_value_preprocessors: dict[ft.AppOrBlueprintKey, list[ft.URLValuePreprocessorCallable]]
+

A data structure of functions to call to modify the keyword +arguments passed to the view function, in the format +{scope: [functions]}. The scope key is the name of a +blueprint the functions are active for, or None for all +requests.

+

To register a function, use the +url_value_preprocessor() decorator.

+

This data structure is internal. It should not be modified +directly and its format may change at any time.

+
+ +
+
+url_default_functions: dict[ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]]
+

A data structure of functions to call to modify the keyword +arguments when generating URLs, in the format +{scope: [functions]}. The scope key is the name of a +blueprint the functions are active for, or None for all +requests.

+

To register a function, use the url_defaults() +decorator.

+

This data structure is internal. It should not be modified +directly and its format may change at any time.

+
+ +
+ +
+
+

Incoming Request Data

+
+
+class flask.Request(environ, populate_request=True, shallow=False)
+

The request object used by default in Flask. Remembers the +matched endpoint and view arguments.

+

It is what ends up as request. If you want to replace +the request object used you can subclass this and set +request_class to your subclass.

+

The request object is a Request subclass and +provides all of the attributes Werkzeug defines plus a few Flask +specific ones.

+
+
Parameters:
+
    +
  • environ (WSGIEnvironment)

  • +
  • populate_request (bool)

  • +
  • shallow (bool)

  • +
+
+
+
+
+url_rule: Rule | None = None
+

The internal URL rule that matched the request. This can be +useful to inspect which methods are allowed for the URL from +a before/after handler (request.url_rule.methods) etc. +Though if the request’s method was invalid for the URL rule, +the valid list is available in routing_exception.valid_methods +instead (an attribute of the Werkzeug exception +MethodNotAllowed) +because the request was never internally bound.

+
+Changelog
+

Added in version 0.6.

+
+
+ +
+
+view_args: dict[str, t.Any] | None = None
+

A dict of view arguments that matched the request. If an exception +happened when matching, this will be None.

+
+ +
+
+routing_exception: HTTPException | None = None
+

If matching the URL failed, this is the exception that will be +raised / was raised as part of the request handling. This is +usually a NotFound exception or +something similar.

+
+ +
+
+property max_content_length: int | None
+

The maximum number of bytes that will be read during this request. If +this limit is exceeded, a 413 RequestEntityTooLarge +error is raised. If it is set to None, no limit is enforced at the +Flask application level. However, if it is None and the request has +no Content-Length header and the WSGI server does not indicate that +it terminates the stream, then no data is read to avoid an infinite +stream.

+

Each request defaults to the MAX_CONTENT_LENGTH config, which +defaults to None. It can be set on a specific request to apply +the limit to that specific view. This should be set appropriately based +on an application’s or view’s specific needs.

+
+

Changed in version 3.1: This can be set per-request.

+
+
+Changelog
+

Changed in version 0.6: This is configurable through Flask config.

+
+
+ +
+
+property max_form_memory_size: int | None
+

The maximum size in bytes any non-file form field may be in a +multipart/form-data body. If this limit is exceeded, a 413 +RequestEntityTooLarge error is raised. If it +is set to None, no limit is enforced at the Flask application level.

+

Each request defaults to the MAX_FORM_MEMORY_SIZE config, which +defaults to 500_000. It can be set on a specific request to +apply the limit to that specific view. This should be set appropriately +based on an application’s or view’s specific needs.

+
+

Changed in version 3.1: This is configurable through Flask config.

+
+
+ +
+
+property max_form_parts: int | None
+

The maximum number of fields that may be present in a +multipart/form-data body. If this limit is exceeded, a 413 +RequestEntityTooLarge error is raised. If it +is set to None, no limit is enforced at the Flask application level.

+

Each request defaults to the MAX_FORM_PARTS config, which +defaults to 1_000. It can be set on a specific request to apply +the limit to that specific view. This should be set appropriately based +on an application’s or view’s specific needs.

+
+

Changed in version 3.1: This is configurable through Flask config.

+
+
+ +
+
+property endpoint: str | None
+

The endpoint that matched the request URL.

+

This will be None if matching failed or has not been +performed yet.

+

This in combination with view_args can be used to +reconstruct the same URL or a modified URL.

+
+ +
+
+property blueprint: str | None
+

The registered name of the current blueprint.

+

This will be None if the endpoint is not part of a +blueprint, or if URL matching failed or has not been performed +yet.

+

This does not necessarily match the name the blueprint was +created with. It may have been nested, or registered with a +different name.

+
+ +
+
+property blueprints: list[str]
+

The registered names of the current blueprint upwards through +parent blueprints.

+

This will be an empty list if there is no current blueprint, or +if URL matching failed.

+
+Changelog
+

Added in version 2.0.1.

+
+
+ +
+
+on_json_loading_failed(e)
+

Called if get_json() fails and isn’t silenced.

+

If this method returns a value, it is used as the return value +for get_json(). The default implementation raises +BadRequest.

+
+
Parameters:
+

e (ValueError | None) – If parsing failed, this is the exception. It will be +None if the content type wasn’t application/json.

+
+
Return type:
+

Any

+
+
+
+Changelog
+

Changed in version 2.3: Raise a 415 error instead of 400.

+
+
+ +
+
+property accept_charsets: CharsetAccept
+

List of charsets this client supports as +CharsetAccept object.

+
+ +
+
+property accept_encodings: Accept
+

List of encodings this client accepts. Encodings in a HTTP term +are compression encodings such as gzip. For charsets have a look at +accept_charset.

+
+ +
+
+property accept_languages: LanguageAccept
+

List of languages this client accepts as +LanguageAccept object.

+
+ +
+
+property accept_mimetypes: MIMEAccept
+

List of mimetypes this client supports as +MIMEAccept object.

+
+ +
+
+access_control_request_headers
+

Sent with a preflight request to indicate which headers will be sent with the cross origin request. Set access_control_allow_headers on the response to indicate which headers are allowed.

+
+ +
+
+access_control_request_method
+

Sent with a preflight request to indicate which method will be used for the cross origin request. Set access_control_allow_methods on the response to indicate which methods are allowed.

+
+ +
+
+property access_route: list[str]
+

If a forwarded header exists this is a list of all ip addresses +from the client ip to the last proxy server.

+
+ +
+
+classmethod application(f)
+

Decorate a function as responder that accepts the request as +the last argument. This works like the responder() +decorator but the function is passed the request object as the +last argument and the request object will be closed +automatically:

+
@Request.application
+def my_wsgi_app(request):
+    return Response('Hello World!')
+
+
+

As of Werkzeug 0.14 HTTP exceptions are automatically caught and +converted to responses instead of failing.

+
+
Parameters:
+

f (t.Callable[[Request], WSGIApplication]) – the WSGI callable to decorate

+
+
Returns:
+

a new WSGI callable

+
+
Return type:
+

WSGIApplication

+
+
+
+ +
+
+property args: MultiDict[str, str]
+

The parsed URL parameters (the part in the URL after the question +mark).

+

By default an +ImmutableMultiDict +is returned from this function. This can be changed by setting +parameter_storage_class to a different type. This might +be necessary if the order of the form data is important.

+
+Changelog
+

Changed in version 2.3: Invalid bytes remain percent encoded.

+
+
+ +
+
+property authorization: Authorization | None
+

The Authorization header parsed into an Authorization object. +None if the header is not present.

+
+Changelog
+

Changed in version 2.3: Authorization is no longer a dict. The token attribute +was added for auth schemes that use a token instead of parameters.

+
+
+ +
+
+property base_url: str
+

Like url but without the query string.

+
+ +
+
+property cache_control: RequestCacheControl
+

A RequestCacheControl object +for the incoming cache control headers.

+
+ +
+
+close()
+

Closes associated resources of this request object. This +closes all file handles explicitly. You can also use the request +object in a with statement which will automatically close it.

+
+Changelog
+

Added in version 0.9.

+
+
+
Return type:
+

None

+
+
+
+ +
+
+content_encoding
+

The Content-Encoding entity-header field is used as a +modifier to the media-type. When present, its value indicates +what additional content codings have been applied to the +entity-body, and thus what decoding mechanisms must be applied +in order to obtain the media-type referenced by the Content-Type +header field.

+
+Changelog
+

Added in version 0.9.

+
+
+ +
+
+property content_length: int | None
+

The Content-Length entity-header field indicates the size of the +entity-body in bytes or, in the case of the HEAD method, the size of +the entity-body that would have been sent had the request been a +GET.

+
+ +
+
+content_md5
+

The Content-MD5 entity-header field, as defined in +RFC 1864, is an MD5 digest of the entity-body for the purpose of +providing an end-to-end message integrity check (MIC) of the +entity-body. (Note: a MIC is good for detecting accidental +modification of the entity-body in transit, but is not proof +against malicious attacks.)

+
+Changelog
+

Added in version 0.9.

+
+
+ +
+
+content_type
+

The Content-Type entity-header field indicates the media +type of the entity-body sent to the recipient or, in the case of +the HEAD method, the media type that would have been sent had +the request been a GET.

+
+ +
+
+property cookies: ImmutableMultiDict[str, str]
+

A dict with the contents of all cookies transmitted with +the request.

+
+ +
+
+property data: bytes
+

The raw data read from stream. Will be empty if the request +represents form data.

+

To get the raw data even if it represents form data, use get_data().

+
+ +
+
+date
+

The Date general-header field represents the date and +time at which the message was originated, having the same +semantics as orig-date in RFC 822.

+
+Changelog
+

Changed in version 2.0: The datetime object is timezone-aware.

+
+
+ +
+
+dict_storage_class
+

alias of ImmutableMultiDict

+
+ +
+
+property files: ImmutableMultiDict[str, FileStorage]
+

MultiDict object containing +all uploaded files. Each key in files is the name from the +<input type="file" name="">. Each value in files is a +Werkzeug FileStorage object.

+

It basically behaves like a standard file object you know from Python, +with the difference that it also has a +save() function that can +store the file on the filesystem.

+

Note that files will only contain data if the request method was +POST, PUT or PATCH and the <form> that posted to the request had +enctype="multipart/form-data". It will be empty otherwise.

+

See the MultiDict / +FileStorage documentation for +more details about the used data structure.

+
+ +
+
+property form: ImmutableMultiDict[str, str]
+

The form parameters. By default an +ImmutableMultiDict +is returned from this function. This can be changed by setting +parameter_storage_class to a different type. This might +be necessary if the order of the form data is important.

+

Please keep in mind that file uploads will not end up here, but instead +in the files attribute.

+
+Changelog
+

Changed in version 0.9: Previous to Werkzeug 0.9 this would only contain form data for POST +and PUT requests.

+
+
+ +
+
+form_data_parser_class
+

alias of FormDataParser

+
+ +
+
+classmethod from_values(*args, **kwargs)
+

Create a new request object based on the values provided. If +environ is given missing values are filled from there. This method is +useful for small scripts when you need to simulate a request from an URL. +Do not use this method for unittesting, there is a full featured client +object (Client) that allows to create multipart requests, +support for cookies etc.

+

This accepts the same options as the +EnvironBuilder.

+
+Changelog
+

Changed in version 0.5: This method now accepts the same arguments as +EnvironBuilder. Because of this the +environ parameter is now called environ_overrides.

+
+
+
Returns:
+

request object

+
+
Parameters:
+
+
+
Return type:
+

Request

+
+
+
+ +
+
+property full_path: str
+

Requested path, including the query string.

+
+ +
+
+get_data(cache=True, as_text=False, parse_form_data=False)
+

This reads the buffered incoming data from the client into one +bytes object. By default this is cached but that behavior can be +changed by setting cache to False.

+

Usually it’s a bad idea to call this method without checking the +content length first as a client could send dozens of megabytes or more +to cause memory problems on the server.

+

Note that if the form data was already parsed this method will not +return anything as form data parsing does not cache the data like +this method does. To implicitly invoke form data parsing function +set parse_form_data to True. When this is done the return value +of this method will be an empty string if the form parser handles +the data. This generally is not necessary as if the whole data is +cached (which is the default) the form parser will used the cached +data to parse the form data. Please be generally aware of checking +the content length first in any case before calling this method +to avoid exhausting server memory.

+

If as_text is set to True the return value will be a decoded +string.

+
+Changelog
+

Added in version 0.9.

+
+
+
Parameters:
+
+
+
Return type:
+

bytes | str

+
+
+
+ +
+
+get_json(force=False, silent=False, cache=True)
+

Parse data as JSON.

+

If the mimetype does not indicate JSON +(application/json, see is_json), or parsing +fails, on_json_loading_failed() is called and +its return value is used as the return value. By default this +raises a 415 Unsupported Media Type resp.

+
+
Parameters:
+
    +
  • force (bool) – Ignore the mimetype and always try to parse JSON.

  • +
  • silent (bool) – Silence mimetype and parsing errors, and +return None instead.

  • +
  • cache (bool) – Store the parsed JSON to return for subsequent +calls.

  • +
+
+
Return type:
+

Any | None

+
+
+
+Changelog
+

Changed in version 2.3: Raise a 415 error instead of 400.

+
+
+

Changed in version 2.1: Raise a 400 error if the content type is incorrect.

+
+
+ +
+
+property host: str
+

The host name the request was made to, including the port if +it’s non-standard. Validated with trusted_hosts.

+
+ +
+
+property host_url: str
+

The request URL scheme and host only.

+
+ +
+
+property if_match: ETags
+

An object containing all the etags in the If-Match header.

+
+
Return type:
+

ETags

+
+
+
+ +
+
+property if_modified_since: datetime | None
+

The parsed If-Modified-Since header as a datetime object.

+
+Changelog
+

Changed in version 2.0: The datetime object is timezone-aware.

+
+
+ +
+
+property if_none_match: ETags
+

An object containing all the etags in the If-None-Match header.

+
+
Return type:
+

ETags

+
+
+
+ +
+
+property if_range: IfRange
+

The parsed If-Range header.

+
+Changelog
+

Changed in version 2.0: IfRange.date is timezone-aware.

+
+
+

Added in version 0.7.

+
+
+ +
+
+property if_unmodified_since: datetime | None
+

The parsed If-Unmodified-Since header as a datetime object.

+
+Changelog
+

Changed in version 2.0: The datetime object is timezone-aware.

+
+
+ +
+
+input_stream
+

The raw WSGI input stream, without any safety checks.

+

This is dangerous to use. It does not guard against infinite streams or reading +past content_length or max_content_length.

+

Use stream instead.

+
+ +
+
+property is_json: bool
+

Check if the mimetype indicates JSON data, either +application/json or application/*+json.

+
+ +
+
+is_multiprocess
+

boolean that is True if the application is served by a +WSGI server that spawns multiple processes.

+
+ +
+
+is_multithread
+

boolean that is True if the application is served by a +multithreaded WSGI server.

+
+ +
+
+is_run_once
+

boolean that is True if the application will be +executed only once in a process lifetime. This is the case for +CGI for example, but it’s not guaranteed that the execution only +happens one time.

+
+ +
+
+property is_secure: bool
+

True if the request was made with a secure protocol +(HTTPS or WSS).

+
+ +
+
+property json: Any | None
+

The parsed JSON data if mimetype indicates JSON +(application/json, see is_json).

+

Calls get_json() with default arguments.

+

If the request content type is not application/json, this +will raise a 415 Unsupported Media Type error.

+
+Changelog
+

Changed in version 2.3: Raise a 415 error instead of 400.

+
+
+

Changed in version 2.1: Raise a 400 error if the content type is incorrect.

+
+
+ +
+
+list_storage_class
+

alias of ImmutableList

+
+ +
+
+make_form_data_parser()
+

Creates the form data parser. Instantiates the +form_data_parser_class with some parameters.

+
+Changelog
+

Added in version 0.8.

+
+
+
Return type:
+

FormDataParser

+
+
+
+ +
+
+max_forwards
+

The Max-Forwards request-header field provides a +mechanism with the TRACE and OPTIONS methods to limit the number +of proxies or gateways that can forward the request to the next +inbound server.

+
+ +
+
+property mimetype: str
+

Like content_type, but without parameters (eg, without +charset, type etc.) and always lowercase. For example if the content +type is text/HTML; charset=utf-8 the mimetype would be +'text/html'.

+
+ +
+
+property mimetype_params: dict[str, str]
+

The mimetype parameters as dict. For example if the content +type is text/html; charset=utf-8 the params would be +{'charset': 'utf-8'}.

+
+ +
+
+origin
+

The host that the request originated from. Set access_control_allow_origin on the response to indicate which origins are allowed.

+
+ +
+
+parameter_storage_class
+

alias of ImmutableMultiDict

+
+ +
+
+property pragma: HeaderSet
+

The Pragma general-header field is used to include +implementation-specific directives that might apply to any recipient +along the request/response chain. All pragma directives specify +optional behavior from the viewpoint of the protocol; however, some +systems MAY require that behavior be consistent with the directives.

+
+ +
+
+property range: Range | None
+

The parsed Range header.

+
+Changelog
+

Added in version 0.7.

+
+
+
Return type:
+

Range

+
+
+
+ +
+
+referrer
+

The Referer[sic] request-header field allows the client +to specify, for the server’s benefit, the address (URI) of the +resource from which the Request-URI was obtained (the +“referrer”, although the header field is misspelled).

+
+ +
+
+remote_user
+

If the server supports user authentication, and the +script is protected, this attribute contains the username the +user has authenticated as.

+
+ +
+
+property root_url: str
+

The request URL scheme, host, and root path. This is the root +that the application is accessed from.

+
+ +
+
+property script_root: str
+

Alias for self.root_path. environ["SCRIPT_ROOT"] +without a trailing slash.

+
+ +
+
+property stream: IO[bytes]
+

The WSGI input stream, with safety checks. This stream can only be consumed +once.

+

Use get_data() to get the full data as bytes or text. The data +attribute will contain the full bytes only if they do not represent form data. +The form attribute will contain the parsed form data in that case.

+

Unlike input_stream, this stream guards against infinite streams or +reading past content_length or max_content_length.

+

If max_content_length is set, it can be enforced on streams if +wsgi.input_terminated is set. Otherwise, an empty stream is returned.

+

If the limit is reached before the underlying stream is exhausted (such as a +file that is too large, or an infinite stream), the remaining contents of the +stream cannot be read safely. Depending on how the server handles this, clients +may show a “connection reset” failure instead of seeing the 413 response.

+
+Changelog
+

Changed in version 2.3: Check max_content_length preemptively and while reading.

+
+
+

Changed in version 0.9: The stream is always set (but may be consumed) even if form parsing was +accessed first.

+
+
+ +
+
+trusted_hosts: list[str] | None = None
+

Valid host names when handling requests. By default all hosts are +trusted, which means that whatever the client says the host is +will be accepted.

+

Because Host and X-Forwarded-Host headers can be set to +any value by a malicious client, it is recommended to either set +this property or implement similar validation in the proxy (if +the application is being run behind one).

+
+Changelog
+

Added in version 0.9.

+
+
+ +
+
+property url: str
+

The full request URL with the scheme, host, root path, path, +and query string.

+
+ +
+
+property url_root: str
+

Alias for root_url. The URL with scheme, host, and +root path. For example, https://example.com/app/.

+
+ +
+
+property user_agent: UserAgent
+

The user agent. Use user_agent.string to get the header +value. Set user_agent_class to a subclass of +UserAgent to provide parsing for +the other properties or other extended data.

+
+Changelog
+

Changed in version 2.1: The built-in parser was removed. Set user_agent_class to a UserAgent +subclass to parse data from the string.

+
+
+ +
+
+user_agent_class
+

alias of UserAgent

+
+ +
+
+property values: CombinedMultiDict[str, str]
+

A werkzeug.datastructures.CombinedMultiDict that +combines args and form.

+

For GET requests, only args are present, not form.

+
+Changelog
+

Changed in version 2.0: For GET requests, only args are present, not form.

+
+
+ +
+
+property want_form_data_parsed: bool
+

True if the request method carries content. By default +this is true if a Content-Type is sent.

+
+Changelog
+

Added in version 0.8.

+
+
+ +
+
+environ: WSGIEnvironment
+

The WSGI environment containing HTTP headers and information from +the WSGI server.

+
+ +
+
+shallow: bool
+

Set when creating the request object. If True, reading from +the request body will cause a RuntimeException. Useful to +prevent modifying the stream from middleware.

+
+ +
+
+method
+

The method the request was made with, such as GET.

+
+ +
+
+scheme
+

The URL scheme of the protocol the request used, such as +https or wss.

+
+ +
+
+server
+

The address of the server. (host, port), (path, None) +for unix sockets, or None if not known.

+
+ +
+
+root_path
+

The prefix that the application is mounted under, without a +trailing slash. path comes after this.

+
+ +
+
+path
+

The path part of the URL after root_path. This is the +path used for routing within the application.

+
+ +
+
+query_string
+

The part of the URL after the “?”. This is the raw value, use +args for the parsed values.

+
+ +
+
+headers
+

The headers received with the request.

+
+ +
+
+remote_addr
+

The address of the client sending the request.

+
+ +
+ +
+
+flask.request
+

To access incoming request data, you can use the global request +object. Flask parses incoming request data for you and gives you +access to it through that global object. Internally Flask makes +sure that you always get the correct data for the active thread if you +are in a multithreaded environment.

+

This is a proxy. See Notes On Proxies for more information.

+

The request object is an instance of a Request.

+
+ +
+
+

Response Objects

+
+
+class flask.Response(response=None, status=None, headers=None, mimetype=None, content_type=None, direct_passthrough=False)
+

The response object that is used by default in Flask. Works like the +response object from Werkzeug but is set to have an HTML mimetype by +default. Quite often you don’t have to create this object yourself because +make_response() will take care of that for you.

+

If you want to replace the response object used you can subclass this and +set response_class to your subclass.

+
+Changelog
+

Changed in version 1.0: JSON support is added to the response, like the request. This is useful +when testing to get the test client response data as JSON.

+
+
+

Changed in version 1.0: Added max_cookie_size.

+
+
+
Parameters:
+
+
+
+
+
+default_mimetype: str | None = 'text/html'
+

the default mimetype if none is provided.

+
+ +
+
+accept_ranges
+

The Accept-Ranges header. Even though the name would +indicate that multiple values are supported, it must be one +string token only.

+

The values 'bytes' and 'none' are common.

+
+Changelog
+

Added in version 0.7.

+
+
+ +
+
+property access_control_allow_credentials: bool
+

Whether credentials can be shared by the browser to +JavaScript code. As part of the preflight request it indicates +whether credentials can be used on the cross origin request.

+
+ +
+
+access_control_allow_headers
+

Which headers can be sent with the cross origin request.

+
+ +
+
+access_control_allow_methods
+

Which methods can be used for the cross origin request.

+
+ +
+
+access_control_allow_origin
+

The origin or ‘*’ for any origin that may make cross origin requests.

+
+ +
+
+access_control_expose_headers
+

Which headers can be shared by the browser to JavaScript code.

+
+ +
+
+access_control_max_age
+

The maximum age in seconds the access control settings can be cached for.

+
+ +
+
+add_etag(overwrite=False, weak=False)
+

Add an etag for the current response if there is none yet.

+
+Changelog
+

Changed in version 2.0: SHA-1 is used to generate the value. MD5 may not be +available in some environments.

+
+
+
Parameters:
+
+
+
Return type:
+

None

+
+
+
+ +
+
+age
+

The Age response-header field conveys the sender’s +estimate of the amount of time since the response (or its +revalidation) was generated at the origin server.

+

Age values are non-negative decimal integers, representing time +in seconds.

+
+ +
+
+property allow: HeaderSet
+

The Allow entity-header field lists the set of methods +supported by the resource identified by the Request-URI. The +purpose of this field is strictly to inform the recipient of +valid methods associated with the resource. An Allow header +field MUST be present in a 405 (Method Not Allowed) +response.

+
+ +
+
+automatically_set_content_length = True
+

Should this response object automatically set the content-length +header if possible? This is true by default.

+
+Changelog
+

Added in version 0.8.

+
+
+ +
+
+property cache_control: ResponseCacheControl
+

The Cache-Control general-header field is used to specify +directives that MUST be obeyed by all caching mechanisms along the +request/response chain.

+
+ +
+
+calculate_content_length()
+

Returns the content length if available or None otherwise.

+
+
Return type:
+

int | None

+
+
+
+ +
+
+call_on_close(func)
+

Adds a function to the internal list of functions that should +be called as part of closing down the response. Since 0.7 this +function also returns the function that was passed so that this +can be used as a decorator.

+
+Changelog
+

Added in version 0.6.

+
+
+
Parameters:
+

func (Callable[[], Any])

+
+
Return type:
+

Callable[[], Any]

+
+
+
+ +
+
+close()
+

Close the wrapped response if possible. You can also use the object +in a with statement which will automatically close it.

+
+Changelog
+

Added in version 0.9: Can now be used in a with statement.

+
+
+
Return type:
+

None

+
+
+
+ +
+
+content_encoding
+

The Content-Encoding entity-header field is used as a +modifier to the media-type. When present, its value indicates +what additional content codings have been applied to the +entity-body, and thus what decoding mechanisms must be applied +in order to obtain the media-type referenced by the Content-Type +header field.

+
+ +
+
+property content_language: HeaderSet
+

The Content-Language entity-header field describes the +natural language(s) of the intended audience for the enclosed +entity. Note that this might not be equivalent to all the +languages used within the entity-body.

+
+ +
+
+content_length
+

The Content-Length entity-header field indicates the size +of the entity-body, in decimal number of OCTETs, sent to the +recipient or, in the case of the HEAD method, the size of the +entity-body that would have been sent had the request been a +GET.

+
+ +
+
+content_location
+

The Content-Location entity-header field MAY be used to +supply the resource location for the entity enclosed in the +message when that entity is accessible from a location separate +from the requested resource’s URI.

+
+ +
+
+content_md5
+

The Content-MD5 entity-header field, as defined in +RFC 1864, is an MD5 digest of the entity-body for the purpose of +providing an end-to-end message integrity check (MIC) of the +entity-body. (Note: a MIC is good for detecting accidental +modification of the entity-body in transit, but is not proof +against malicious attacks.)

+
+ +
+
+property content_range: ContentRange
+

The Content-Range header as a +ContentRange object. Available +even if the header is not set.

+
+Changelog
+

Added in version 0.7.

+
+
+ +
+
+property content_security_policy: ContentSecurityPolicy
+

The Content-Security-Policy header as a +ContentSecurityPolicy object. Available +even if the header is not set.

+

The Content-Security-Policy header adds an additional layer of +security to help detect and mitigate certain types of attacks.

+
+ +
+
+property content_security_policy_report_only: ContentSecurityPolicy
+

The Content-Security-policy-report-only header as a +ContentSecurityPolicy object. Available +even if the header is not set.

+

The Content-Security-Policy-Report-Only header adds a csp policy +that is not enforced but is reported thereby helping detect +certain types of attacks.

+
+ +
+
+content_type
+

The Content-Type entity-header field indicates the media +type of the entity-body sent to the recipient or, in the case of +the HEAD method, the media type that would have been sent had +the request been a GET.

+
+ +
+
+cross_origin_embedder_policy
+

Prevents a document from loading any cross-origin resources that do not +explicitly grant the document permission. Values must be a member of the +werkzeug.http.COEP enum.

+
+ +
+
+cross_origin_opener_policy
+

Allows control over sharing of browsing context group with cross-origin +documents. Values must be a member of the werkzeug.http.COOP enum.

+
+ +
+
+property data: bytes | str
+

A descriptor that calls get_data() and set_data().

+
+ +
+
+date
+

The Date general-header field represents the date and +time at which the message was originated, having the same +semantics as orig-date in RFC 822.

+
+Changelog
+

Changed in version 2.0: The datetime object is timezone-aware.

+
+
+ +
+
+default_status = 200
+

the default status if none is provided.

+
+ +
+ +

Delete a cookie. Fails silently if key doesn’t exist.

+
+
Parameters:
+
    +
  • key (str) – the key (name) of the cookie to be deleted.

  • +
  • path (str | None) – if the cookie that should be deleted was limited to a +path, the path has to be defined here.

  • +
  • domain (str | None) – if the cookie that should be deleted was limited to a +domain, that domain has to be defined here.

  • +
  • secure (bool) – If True, the cookie will only be available +via HTTPS.

  • +
  • httponly (bool) – Disallow JavaScript access to the cookie.

  • +
  • samesite (str | None) – Limit the scope of the cookie to only be +attached to requests that are “same-site”.

  • +
  • partitioned (bool) – If True, the cookie will be partitioned.

  • +
+
+
Return type:
+

None

+
+
+
+ +
+
+expires
+

The Expires entity-header field gives the date/time after +which the response is considered stale. A stale cache entry may +not normally be returned by a cache.

+
+Changelog
+

Changed in version 2.0: The datetime object is timezone-aware.

+
+
+ +
+
+classmethod force_type(response, environ=None)
+

Enforce that the WSGI response is a response object of the current +type. Werkzeug will use the Response internally in many +situations like the exceptions. If you call get_response() on an +exception you will get back a regular Response object, even +if you are using a custom subclass.

+

This method can enforce a given response type, and it will also +convert arbitrary WSGI callables into response objects if an environ +is provided:

+
# convert a Werkzeug response object into an instance of the
+# MyResponseClass subclass.
+response = MyResponseClass.force_type(response)
+
+# convert any WSGI application into a response object
+response = MyResponseClass.force_type(response, environ)
+
+
+

This is especially useful if you want to post-process responses in +the main dispatcher and use functionality provided by your subclass.

+

Keep in mind that this will modify response objects in place if +possible!

+
+
Parameters:
+
    +
  • response (Response) – a response object or wsgi application.

  • +
  • environ (WSGIEnvironment | None) – a WSGI environment object.

  • +
+
+
Returns:
+

a response object.

+
+
Return type:
+

Response

+
+
+
+ +
+
+freeze()
+

Make the response object ready to be pickled. Does the +following:

+
    +
  • Buffer the response into a list, ignoring +implicity_sequence_conversion and +direct_passthrough.

  • +
  • Set the Content-Length header.

  • +
  • Generate an ETag header if one is not already set.

  • +
+
+Changelog
+

Changed in version 2.1: Removed the no_etag parameter.

+
+
+

Changed in version 2.0: An ETag header is always added.

+
+
+

Changed in version 0.6: The Content-Length header is set.

+
+
+
Return type:
+

None

+
+
+
+ +
+
+classmethod from_app(app, environ, buffered=False)
+

Create a new response object from an application output. This +works best if you pass it an application that returns a generator all +the time. Sometimes applications may use the write() callable +returned by the start_response function. This tries to resolve such +edge cases automatically. But if you don’t get the expected output +you should set buffered to True which enforces buffering.

+
+
Parameters:
+
    +
  • app (WSGIApplication) – the WSGI application to execute.

  • +
  • environ (WSGIEnvironment) – the WSGI environment to execute against.

  • +
  • buffered (bool) – set to True to enforce buffering.

  • +
+
+
Returns:
+

a response object.

+
+
Return type:
+

Response

+
+
+
+ +
+
+get_app_iter(environ)
+

Returns the application iterator for the given environ. Depending +on the request method and the current status code the return value +might be an empty response rather than the one from the response.

+

If the request method is HEAD or the status code is in a range +where the HTTP specification requires an empty response, an empty +iterable is returned.

+
+Changelog
+

Added in version 0.6.

+
+
+
Parameters:
+

environ (WSGIEnvironment) – the WSGI environment of the request.

+
+
Returns:
+

a response iterable.

+
+
Return type:
+

t.Iterable[bytes]

+
+
+
+ +
+
+get_data(as_text=False)
+

The string representation of the response body. Whenever you call +this property the response iterable is encoded and flattened. This +can lead to unwanted behavior if you stream big data.

+

This behavior can be disabled by setting +implicit_sequence_conversion to False.

+

If as_text is set to True the return value will be a decoded +string.

+
+Changelog
+

Added in version 0.9.

+
+
+
Parameters:
+

as_text (bool)

+
+
Return type:
+

bytes | str

+
+
+
+ +
+
+get_etag()
+

Return a tuple in the form (etag, is_weak). If there is no +ETag the return value is (None, None).

+
+
Return type:
+

tuple[str, bool] | tuple[None, None]

+
+
+
+ +
+
+get_json(force=False, silent=False)
+

Parse data as JSON. Useful during testing.

+

If the mimetype does not indicate JSON +(application/json, see is_json), this +returns None.

+

Unlike Request.get_json(), the result is not cached.

+
+
Parameters:
+
    +
  • force (bool) – Ignore the mimetype and always try to parse JSON.

  • +
  • silent (bool) – Silence parsing errors and return None +instead.

  • +
+
+
Return type:
+

Any | None

+
+
+
+ +
+
+get_wsgi_headers(environ)
+

This is automatically called right before the response is started +and returns headers modified for the given environment. It returns a +copy of the headers from the response with some modifications applied +if necessary.

+

For example the location header (if present) is joined with the root +URL of the environment. Also the content length is automatically set +to zero here for certain status codes.

+
+Changelog
+

Changed in version 0.6: Previously that function was called fix_headers and modified +the response object in place. Also since 0.6, IRIs in location +and content-location headers are handled properly.

+

Also starting with 0.6, Werkzeug will attempt to set the content +length if it is able to figure it out on its own. This is the +case if all the strings in the response iterable are already +encoded and the iterable is buffered.

+
+
+
Parameters:
+

environ (WSGIEnvironment) – the WSGI environment of the request.

+
+
Returns:
+

returns a new Headers +object.

+
+
Return type:
+

Headers

+
+
+
+ +
+
+get_wsgi_response(environ)
+

Returns the final WSGI response as tuple. The first item in +the tuple is the application iterator, the second the status and +the third the list of headers. The response returned is created +specially for the given environment. For example if the request +method in the WSGI environment is 'HEAD' the response will +be empty and only the headers and status code will be present.

+
+Changelog
+

Added in version 0.6.

+
+
+
Parameters:
+

environ (WSGIEnvironment) – the WSGI environment of the request.

+
+
Returns:
+

an (app_iter, status, headers) tuple.

+
+
Return type:
+

tuple[t.Iterable[bytes], str, list[tuple[str, str]]]

+
+
+
+ +
+
+implicit_sequence_conversion = True
+

if set to False accessing properties on the response object will +not try to consume the response iterator and convert it into a list.

+
+Changelog
+

Added in version 0.6.2: That attribute was previously called implicit_seqence_conversion. +(Notice the typo). If you did use this feature, you have to adapt +your code to the name change.

+
+
+ +
+
+property is_json: bool
+

Check if the mimetype indicates JSON data, either +application/json or application/*+json.

+
+ +
+
+property is_sequence: bool
+

If the iterator is buffered, this property will be True. A +response object will consider an iterator to be buffered if the +response attribute is a list or tuple.

+
+Changelog
+

Added in version 0.6.

+
+
+ +
+
+property is_streamed: bool
+

If the response is streamed (the response is not an iterable with +a length information) this property is True. In this case streamed +means that there is no information about the number of iterations. +This is usually True if a generator is passed to the response object.

+

This is useful for checking before applying some sort of post +filtering that should not take place for streamed responses.

+
+ +
+
+iter_encoded()
+

Iter the response encoded with the encoding of the response. +If the response object is invoked as WSGI application the return +value of this method is used as application iterator unless +direct_passthrough was activated.

+
+
Return type:
+

Iterator[bytes]

+
+
+
+ +
+
+property json: Any | None
+

The parsed JSON data if mimetype indicates JSON +(application/json, see is_json).

+

Calls get_json() with default arguments.

+
+ +
+
+last_modified
+

The Last-Modified entity-header field indicates the date +and time at which the origin server believes the variant was +last modified.

+
+Changelog
+

Changed in version 2.0: The datetime object is timezone-aware.

+
+
+ +
+
+location
+

The Location response-header field is used to redirect +the recipient to a location other than the Request-URI for +completion of the request or identification of a new +resource.

+
+ +
+
+make_conditional(request_or_environ, accept_ranges=False, complete_length=None)
+

Make the response conditional to the request. This method works +best if an etag was defined for the response already. The add_etag +method can be used to do that. If called without etag just the date +header is set.

+

This does nothing if the request method in the request or environ is +anything but GET or HEAD.

+

For optimal performance when handling range requests, it’s recommended +that your response data object implements seekable, seek and tell +methods as described by io.IOBase. Objects returned by +wrap_file() automatically implement those methods.

+

It does not remove the body of the response because that’s something +the __call__() function does for us automatically.

+

Returns self so that you can do return resp.make_conditional(req) +but modifies the object in-place.

+
+
Parameters:
+
    +
  • request_or_environ (WSGIEnvironment | Request) – a request object or WSGI environment to be +used to make the response conditional +against.

  • +
  • accept_ranges (bool | str) – This parameter dictates the value of +Accept-Ranges header. If False (default), +the header is not set. If True, it will be set +to "bytes". If it’s a string, it will use this +value.

  • +
  • complete_length (int | None) – Will be used only in valid Range Requests. +It will set Content-Range complete length +value and compute Content-Length real value. +This parameter is mandatory for successful +Range Requests completion.

  • +
+
+
Raises:
+

RequestedRangeNotSatisfiable +if Range header could not be parsed or satisfied.

+
+
Return type:
+

Response

+
+
+
+Changelog
+

Changed in version 2.0: Range processing is skipped if length is 0 instead of +raising a 416 Range Not Satisfiable error.

+
+
+ +
+
+make_sequence()
+

Converts the response iterator in a list. By default this happens +automatically if required. If implicit_sequence_conversion is +disabled, this method is not automatically called and some properties +might raise exceptions. This also encodes all the items.

+
+Changelog
+

Added in version 0.6.

+
+
+
Return type:
+

None

+
+
+
+ +
+
+property mimetype: str | None
+

The mimetype (content type without charset etc.)

+
+ +
+
+property mimetype_params: dict[str, str]
+

The mimetype parameters as dict. For example if the +content type is text/html; charset=utf-8 the params would be +{'charset': 'utf-8'}.

+
+Changelog
+

Added in version 0.5.

+
+
+ +
+
+property retry_after: datetime | None
+

The Retry-After response-header field can be used with a +503 (Service Unavailable) response to indicate how long the +service is expected to be unavailable to the requesting client.

+

Time in seconds until expiration or date.

+
+Changelog
+

Changed in version 2.0: The datetime object is timezone-aware.

+
+
+ +
+ +

Sets a cookie.

+

A warning is raised if the size of the cookie header exceeds +max_cookie_size, but the header will still be set.

+
+
Parameters:
+
    +
  • key (str) – the key (name) of the cookie to be set.

  • +
  • value (str) – the value of the cookie.

  • +
  • max_age (timedelta | int | None) – should be a number of seconds, or None (default) if +the cookie should last only as long as the client’s +browser session.

  • +
  • expires (str | datetime | int | float | None) – should be a datetime object or UNIX timestamp.

  • +
  • path (str | None) – limits the cookie to a given path, per default it will +span the whole domain.

  • +
  • domain (str | None) – if you want to set a cross-domain cookie. For example, +domain="example.com" will set a cookie that is +readable by the domain www.example.com, +foo.example.com etc. Otherwise, a cookie will only +be readable by the domain that set it.

  • +
  • secure (bool) – If True, the cookie will only be available +via HTTPS.

  • +
  • httponly (bool) – Disallow JavaScript access to the cookie.

  • +
  • samesite (str | None) – Limit the scope of the cookie to only be +attached to requests that are “same-site”.

  • +
  • partitioned (bool) – If True, the cookie will be partitioned.

  • +
+
+
Return type:
+

None

+
+
+
+

Changed in version 3.1: The partitioned parameter was added.

+
+
+ +
+
+set_data(value)
+

Sets a new string as response. The value must be a string or +bytes. If a string is set it’s encoded to the charset of the +response (utf-8 by default).

+
+Changelog
+

Added in version 0.9.

+
+
+
Parameters:
+

value (bytes | str)

+
+
Return type:
+

None

+
+
+
+ +
+
+set_etag(etag, weak=False)
+

Set the etag, and override the old one if there was one.

+
+
Parameters:
+
+
+
Return type:
+

None

+
+
+
+ +
+
+property status: str
+

The HTTP status code as a string.

+
+ +
+
+property status_code: int
+

The HTTP status code as a number.

+
+ +
+
+property stream: ResponseStream
+

The response iterable as write-only stream.

+
+ +
+
+property vary: HeaderSet
+

The Vary field value indicates the set of request-header +fields that fully determines, while the response is fresh, +whether a cache is permitted to use the response to reply to a +subsequent request without revalidation.

+
+ +
+
+property www_authenticate: WWWAuthenticate
+

The WWW-Authenticate header parsed into a WWWAuthenticate +object. Modifying the object will modify the header value.

+

This header is not set by default. To set this header, assign an instance of +WWWAuthenticate to this attribute.

+
response.www_authenticate = WWWAuthenticate(
+    "basic", {"realm": "Authentication Required"}
+)
+
+
+

Multiple values for this header can be sent to give the client multiple options. +Assign a list to set multiple headers. However, modifying the items in the list +will not automatically update the header values, and accessing this attribute +will only ever return the first value.

+

To unset this header, assign None or use del.

+
+Changelog
+

Changed in version 2.3: This attribute can be assigned to to set the header. A list can be assigned +to set multiple header values. Use del to unset the header.

+
+
+

Changed in version 2.3: WWWAuthenticate is no longer a dict. The token attribute +was added for auth challenges that use a token instead of parameters.

+
+
+ +
+
+response: t.Iterable[str] | t.Iterable[bytes]
+

The response body to send as the WSGI iterable. A list of strings +or bytes represents a fixed-length response, any other iterable +is a streaming response. Strings are encoded to bytes as UTF-8.

+

Do not set to a plain string or bytes, that will cause sending +the response to be very inefficient as it will iterate one byte +at a time.

+
+ +
+
+direct_passthrough
+

Pass the response body directly through as the WSGI iterable. +This can be used when the body is a binary file or other +iterator of bytes, to skip some unnecessary checks. Use +send_file() instead of setting this +manually.

+
+ +
+
+autocorrect_location_header = False
+

If a redirect Location header is a relative URL, make it an +absolute URL, including scheme and domain.

+
+Changelog
+

Changed in version 2.1: This is disabled by default, so responses will send relative +redirects.

+
+
+

Added in version 0.8.

+
+
+ +
+ +

Read-only view of the MAX_COOKIE_SIZE config key.

+

See max_cookie_size in +Werkzeug’s docs.

+
+ +
+ +
+
+

Sessions

+

If you have set Flask.secret_key (or configured it from +SECRET_KEY) you can use sessions in Flask applications. A session makes +it possible to remember information from one request to another. The way Flask +does this is by using a signed cookie. The user can look at the session +contents, but can’t modify it unless they know the secret key, so make sure to +set that to something complex and unguessable.

+

To access the current session you can use the session object:

+
+
+class flask.session
+

The session object works pretty much like an ordinary dict, with the +difference that it keeps track of modifications.

+

This is a proxy. See Notes On Proxies for more information.

+

The following attributes are interesting:

+
+
+new
+

True if the session is new, False otherwise.

+
+ +
+
+modified
+

True if the session object detected a modification. Be advised +that modifications on mutable structures are not picked up +automatically, in that situation you have to explicitly set the +attribute to True yourself. Here an example:

+
# this change is not picked up because a mutable object (here
+# a list) is changed.
+session['objects'].append(42)
+# so mark it as modified yourself
+session.modified = True
+
+
+
+ +
+
+permanent
+

If set to True the session lives for +permanent_session_lifetime seconds. The +default is 31 days. If set to False (which is the default) the +session will be deleted when the user closes the browser.

+
+ +
+ +
+
+

Session Interface

+
+Changelog
+

Added in version 0.8.

+
+

The session interface provides a simple way to replace the session +implementation that Flask is using.

+
+
+class flask.sessions.SessionInterface
+

The basic interface you have to implement in order to replace the +default session interface which uses werkzeug’s securecookie +implementation. The only methods you have to implement are +open_session() and save_session(), the others have +useful defaults which you don’t need to change.

+

The session object returned by the open_session() method has to +provide a dictionary like interface plus the properties and methods +from the SessionMixin. We recommend just subclassing a dict +and adding that mixin:

+
class Session(dict, SessionMixin):
+    pass
+
+
+

If open_session() returns None Flask will call into +make_null_session() to create a session that acts as replacement +if the session support cannot work because some requirement is not +fulfilled. The default NullSession class that is created +will complain that the secret key was not set.

+

To replace the session interface on an application all you have to do +is to assign flask.Flask.session_interface:

+
app = Flask(__name__)
+app.session_interface = MySessionInterface()
+
+
+

Multiple requests with the same session may be sent and handled +concurrently. When implementing a new session interface, consider +whether reads or writes to the backing store must be synchronized. +There is no guarantee on the order in which the session for each +request is opened or saved, it will occur in the order that requests +begin and end processing.

+
+Changelog
+

Added in version 0.8.

+
+
+
+null_session_class
+

make_null_session() will look here for the class that should +be created when a null session is requested. Likewise the +is_null_session() method will perform a typecheck against +this type.

+

alias of NullSession

+
+ +
+
+pickle_based = False
+

A flag that indicates if the session interface is pickle based. +This can be used by Flask extensions to make a decision in regards +to how to deal with the session object.

+
+Changelog
+

Added in version 0.10.

+
+
+ +
+
+make_null_session(app)
+

Creates a null session which acts as a replacement object if the +real session support could not be loaded due to a configuration +error. This mainly aids the user experience because the job of the +null session is to still support lookup without complaining but +modifications are answered with a helpful error message of what +failed.

+

This creates an instance of null_session_class by default.

+
+
Parameters:
+

app (Flask)

+
+
Return type:
+

NullSession

+
+
+
+ +
+
+is_null_session(obj)
+

Checks if a given object is a null session. Null sessions are +not asked to be saved.

+

This checks if the object is an instance of null_session_class +by default.

+
+
Parameters:
+

obj (object)

+
+
Return type:
+

bool

+
+
+
+ +
+ +

The name of the session cookie. Uses``app.config[“SESSION_COOKIE_NAME”]``.

+
+
Parameters:
+

app (Flask)

+
+
Return type:
+

str

+
+
+
+ +
+ +

The value of the Domain parameter on the session cookie. If not set, +browsers will only send the cookie to the exact domain it was set from. +Otherwise, they will send it to any subdomain of the given value as well.

+

Uses the SESSION_COOKIE_DOMAIN config.

+
+Changelog
+

Changed in version 2.3: Not set by default, does not fall back to SERVER_NAME.

+
+
+
Parameters:
+

app (Flask)

+
+
Return type:
+

str | None

+
+
+
+ +
+ +

Returns the path for which the cookie should be valid. The +default implementation uses the value from the SESSION_COOKIE_PATH +config var if it’s set, and falls back to APPLICATION_ROOT or +uses / if it’s None.

+
+
Parameters:
+

app (Flask)

+
+
Return type:
+

str

+
+
+
+ +
+ +

Returns True if the session cookie should be httponly. This +currently just returns the value of the SESSION_COOKIE_HTTPONLY +config var.

+
+
Parameters:
+

app (Flask)

+
+
Return type:
+

bool

+
+
+
+ +
+ +

Returns True if the cookie should be secure. This currently +just returns the value of the SESSION_COOKIE_SECURE setting.

+
+
Parameters:
+

app (Flask)

+
+
Return type:
+

bool

+
+
+
+ +
+ +

Return 'Strict' or 'Lax' if the cookie should use the +SameSite attribute. This currently just returns the value of +the SESSION_COOKIE_SAMESITE setting.

+
+
Parameters:
+

app (Flask)

+
+
Return type:
+

str | None

+
+
+
+ +
+ +

Returns True if the cookie should be partitioned. By default, uses +the value of SESSION_COOKIE_PARTITIONED.

+
+

Added in version 3.1.

+
+
+
Parameters:
+

app (Flask)

+
+
Return type:
+

bool

+
+
+
+ +
+
+get_expiration_time(app, session)
+

A helper method that returns an expiration date for the session +or None if the session is linked to the browser session. The +default implementation returns now + the permanent session +lifetime configured on the application.

+
+
Parameters:
+
+
+
Return type:
+

datetime | None

+
+
+
+ +
+ +

Used by session backends to determine if a Set-Cookie header +should be set for this session cookie for this response. If the session +has been modified, the cookie is set. If the session is permanent and +the SESSION_REFRESH_EACH_REQUEST config is true, the cookie is +always set.

+

This check is usually skipped if the session was deleted.

+
+Changelog
+

Added in version 0.11.

+
+
+
Parameters:
+
+
+
Return type:
+

bool

+
+
+
+ +
+
+open_session(app, request)
+

This is called at the beginning of each request, after +pushing the request context, before matching the URL.

+

This must return an object which implements a dictionary-like +interface as well as the SessionMixin interface.

+

This will return None to indicate that loading failed in +some way that is not immediately an error. The request +context will fall back to using make_null_session() +in this case.

+
+
Parameters:
+
+
+
Return type:
+

SessionMixin | None

+
+
+
+ +
+
+save_session(app, session, response)
+

This is called at the end of each request, after generating +a response, before removing the request context. It is skipped +if is_null_session() returns True.

+
+
Parameters:
+
+
+
Return type:
+

None

+
+
+
+ +
+ +
+
+class flask.sessions.SecureCookieSessionInterface
+

The default session interface that stores sessions in signed cookies +through the itsdangerous module.

+
+
+salt = 'cookie-session'
+

the salt that should be applied on top of the secret key for the +signing of cookie based sessions.

+
+ +
+
+static digest_method(string=b'')
+

the hash function to use for the signature. The default is sha1

+
+
Parameters:
+

string (bytes)

+
+
Return type:
+

Any

+
+
+
+ +
+
+key_derivation = 'hmac'
+

the name of the itsdangerous supported key derivation. The default +is hmac.

+
+ +
+
+serializer = <flask.json.tag.TaggedJSONSerializer object>
+

A python serializer for the payload. The default is a compact +JSON derived serializer with support for some extra Python types +such as datetime objects or tuples.

+
+ +
+
+session_class
+

alias of SecureCookieSession

+
+ +
+
+open_session(app, request)
+

This is called at the beginning of each request, after +pushing the request context, before matching the URL.

+

This must return an object which implements a dictionary-like +interface as well as the SessionMixin interface.

+

This will return None to indicate that loading failed in +some way that is not immediately an error. The request +context will fall back to using make_null_session() +in this case.

+
+
Parameters:
+
+
+
Return type:
+

SecureCookieSession | None

+
+
+
+ +
+
+save_session(app, session, response)
+

This is called at the end of each request, after generating +a response, before removing the request context. It is skipped +if is_null_session() returns True.

+
+
Parameters:
+
+
+
Return type:
+

None

+
+
+
+ +
+ +
+
+class flask.sessions.SecureCookieSession(initial=None)
+

Base class for sessions based on signed cookies.

+

This session backend will set the modified and +accessed attributes. It cannot reliably track whether a +session is new (vs. empty), so new remains hard coded to +False.

+
+
Parameters:
+

initial (c.Mapping[str, t.Any] | c.Iterable[tuple[str, t.Any]] | None)

+
+
+
+
+modified = False
+

When data is changed, this is set to True. Only the session +dictionary itself is tracked; if the session contains mutable +data (for example a nested dict) then this must be set to +True manually when modifying that data. The session cookie +will only be written to the response if this is True.

+
+ +
+
+accessed = False
+

header, which allows caching proxies to cache different pages for +different users.

+
+ +
+
+get(key, default=None)
+

Return the value for key if key is in the dictionary, else default.

+
+
Parameters:
+
+
+
Return type:
+

Any

+
+
+
+ +
+
+setdefault(key, default=None)
+

Insert key with a value of default if key is not in the dictionary.

+

Return the value for key if key is in the dictionary, else default.

+
+
Parameters:
+
+
+
Return type:
+

Any

+
+
+
+ +
+ +
+
+class flask.sessions.NullSession(initial=None)
+

Class used to generate nicer error messages if sessions are not +available. Will still allow read-only access to the empty session +but fail on setting.

+
+
Parameters:
+

initial (c.Mapping[str, t.Any] | c.Iterable[tuple[str, t.Any]] | None)

+
+
+
+
+clear() None.  Remove all items from D.
+
+
Parameters:
+
+
+
Return type:
+

NoReturn

+
+
+
+ +
+
+pop(k[, d]) v, remove specified key and return the corresponding value.
+

If the key is not found, return the default if given; otherwise, +raise a KeyError.

+
+
Parameters:
+
+
+
Return type:
+

NoReturn

+
+
+
+ +
+
+popitem(*args, **kwargs)
+

Remove and return a (key, value) pair as a 2-tuple.

+

Pairs are returned in LIFO (last-in, first-out) order. +Raises KeyError if the dict is empty.

+
+
Parameters:
+
+
+
Return type:
+

NoReturn

+
+
+
+ +
+
+update([E, ]**F) None.  Update D from dict/iterable E and F.
+

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] +If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v +In either case, this is followed by: for k in F: D[k] = F[k]

+
+
Parameters:
+
+
+
Return type:
+

NoReturn

+
+
+
+ +
+
+setdefault(*args, **kwargs)
+

Insert key with a value of default if key is not in the dictionary.

+

Return the value for key if key is in the dictionary, else default.

+
+
Parameters:
+
+
+
Return type:
+

NoReturn

+
+
+
+ +
+ +
+
+class flask.sessions.SessionMixin
+

Expands a basic dictionary with session attributes.

+
+
+property permanent: bool
+

This reflects the '_permanent' key in the dict.

+
+ +
+
+modified = True
+

Some implementations can detect changes to the session and set +this when that happens. The mixin default is hard coded to +True.

+
+ +
+
+accessed = True
+

Some implementations can detect when session data is read or +written and set this when that happens. The mixin default is hard +coded to True.

+
+ +
+ +
+

Notice

+

The PERMANENT_SESSION_LIFETIME config can be an integer or timedelta. +The permanent_session_lifetime attribute is always a +timedelta.

+
+
+
+

Test Client

+
+
+class flask.testing.FlaskClient(*args, **kwargs)
+

Works like a regular Werkzeug test client but has knowledge about +Flask’s contexts to defer the cleanup of the request context until +the end of a with block. For general information about how to +use this class refer to werkzeug.test.Client.

+
+Changelog
+

Changed in version 0.12: app.test_client() includes preset default environment, which can be +set after instantiation of the app.test_client() object in +client.environ_base.

+
+

Basic usage is outlined in the Testing Flask Applications chapter.

+
+
Parameters:
+
    +
  • args (t.Any)

  • +
  • kwargs (t.Any)

  • +
+
+
+
+
+session_transaction(*args, **kwargs)
+

When used in combination with a with statement this opens a +session transaction. This can be used to modify the session that +the test client uses. Once the with block is left the session is +stored back.

+
with client.session_transaction() as session:
+    session['value'] = 42
+
+
+

Internally this is implemented by going through a temporary test +request context and since session handling could depend on +request variables this function accepts the same arguments as +test_request_context() which are directly +passed through.

+
+
Parameters:
+
+
+
Return type:
+

Iterator[SessionMixin]

+
+
+
+ +
+
+open(*args, buffered=False, follow_redirects=False, **kwargs)
+

Generate an environ dict from the given arguments, make a +request to the application using it, and return the response.

+
+
Parameters:
+
    +
  • args (t.Any) – Passed to EnvironBuilder to create the +environ for the request. If a single arg is passed, it can +be an existing EnvironBuilder or an environ dict.

  • +
  • buffered (bool) – Convert the iterator returned by the app into +a list. If the iterator has a close() method, it is +called automatically.

  • +
  • follow_redirects (bool) – Make additional requests to follow HTTP +redirects until a non-redirect status is returned. +TestResponse.history lists the intermediate +responses.

  • +
  • kwargs (t.Any)

  • +
+
+
Return type:
+

TestResponse

+
+
+
+Changelog
+

Changed in version 2.1: Removed the as_tuple parameter.

+
+
+

Changed in version 2.0: The request input stream is closed when calling +response.close(). Input streams for redirects are +automatically closed.

+
+
+

Changed in version 0.5: If a dict is provided as file in the dict for the data +parameter the content type has to be called content_type +instead of mimetype. This change was made for +consistency with werkzeug.FileWrapper.

+
+
+

Changed in version 0.5: Added the follow_redirects parameter.

+
+
+ +
+ +
+
+

Test CLI Runner

+
+
+class flask.testing.FlaskCliRunner(app, **kwargs)
+

A CliRunner for testing a Flask app’s +CLI commands. Typically created using +test_cli_runner(). See Running Commands with the CLI Runner.

+
+
Parameters:
+
    +
  • app (Flask)

  • +
  • kwargs (t.Any)

  • +
+
+
+
+
+invoke(cli=None, args=None, **kwargs)
+

Invokes a CLI command in an isolated environment. See +CliRunner.invoke for +full method documentation. See Running Commands with the CLI Runner for examples.

+

If the obj argument is not given, passes an instance of +ScriptInfo that knows how to load the Flask +app being tested.

+
+
Parameters:
+
    +
  • cli (Any) – Command object to invoke. Default is the app’s +cli group.

  • +
  • args (Any) – List of strings to invoke the command with.

  • +
  • kwargs (Any)

  • +
+
+
Returns:
+

a Result object.

+
+
Return type:
+

Result

+
+
+
+ +
+ +
+
+

Application Globals

+

To share data that is valid for one request only from one function to +another, a global variable is not good enough because it would break in +threaded environments. Flask provides you with a special object that +ensures it is only valid for the active request and that will return +different values for each request. In a nutshell: it does the right +thing, like it does for request and session.

+
+
+flask.g
+

A namespace object that can store data during an +application context. This is an instance of +Flask.app_ctx_globals_class, which defaults to +ctx._AppCtxGlobals.

+

This is a good place to store resources during a request. For +example, a before_request function could load a user object from +a session id, then set g.user to be used in the view function.

+

This is a proxy. See Notes On Proxies for more information.

+
+Changelog
+

Changed in version 0.10: Bound to the application context instead of the request context.

+
+
+ +
+
+class flask.ctx._AppCtxGlobals
+

A plain object. Used as a namespace for storing data during an +application context.

+

Creating an app context automatically creates this object, which is +made available as the g proxy.

+
+
+'key' in g
+

Check whether an attribute is present.

+
+Changelog
+

Added in version 0.10.

+
+
+ +
+
+iter(g)
+

Return an iterator over the attribute names.

+
+Changelog
+

Added in version 0.10.

+
+
+ +
+
+get(name, default=None)
+

Get an attribute by name, or a default value. Like +dict.get().

+
+
Parameters:
+
    +
  • name (str) – Name of attribute to get.

  • +
  • default (Any | None) – Value to return if the attribute is not present.

  • +
+
+
Return type:
+

Any

+
+
+
+Changelog
+

Added in version 0.10.

+
+
+ +
+
+pop(name, default=_sentinel)
+

Get and remove an attribute by name. Like dict.pop().

+
+
Parameters:
+
    +
  • name (str) – Name of attribute to pop.

  • +
  • default (Any) – Value to return if the attribute is not present, +instead of raising a KeyError.

  • +
+
+
Return type:
+

Any

+
+
+
+Changelog
+

Added in version 0.11.

+
+
+ +
+
+setdefault(name, default=None)
+

Get the value of an attribute if it is present, otherwise +set and return a default value. Like dict.setdefault().

+
+
Parameters:
+
    +
  • name (str) – Name of attribute to get.

  • +
  • default (Any) – Value to set and return if the attribute is not +present.

  • +
+
+
Return type:
+

Any

+
+
+
+Changelog
+

Added in version 0.11.

+
+
+ +
+ +
+
+

Useful Functions and Classes

+
+
+flask.current_app
+

A proxy to the application handling the current request. This is +useful to access the application without needing to import it, or if +it can’t be imported, such as when using the application factory +pattern or in blueprints and extensions.

+

This is only available when an +application context is pushed. This happens +automatically during requests and CLI commands. It can be controlled +manually with app_context().

+

This is a proxy. See Notes On Proxies for more information.

+
+ +
+
+flask.has_request_context()
+

If you have code that wants to test if a request context is there or +not this function can be used. For instance, you may want to take advantage +of request information if the request object is available, but fail +silently if it is unavailable.

+
class User(db.Model):
+
+    def __init__(self, username, remote_addr=None):
+        self.username = username
+        if remote_addr is None and has_request_context():
+            remote_addr = request.remote_addr
+        self.remote_addr = remote_addr
+
+
+

Alternatively you can also just test any of the context bound objects +(such as request or g) for truthness:

+
class User(db.Model):
+
+    def __init__(self, username, remote_addr=None):
+        self.username = username
+        if remote_addr is None and request:
+            remote_addr = request.remote_addr
+        self.remote_addr = remote_addr
+
+
+
+Changelog
+

Added in version 0.7.

+
+
+
Return type:
+

bool

+
+
+
+ +
+
+flask.copy_current_request_context(f)
+

A helper function that decorates a function to retain the current +request context. This is useful when working with greenlets. The moment +the function is decorated a copy of the request context is created and +then pushed when the function is called. The current session is also +included in the copied request context.

+

Example:

+
import gevent
+from flask import copy_current_request_context
+
+@app.route('/')
+def index():
+    @copy_current_request_context
+    def do_some_work():
+        # do some work here, it can access flask.request or
+        # flask.session like you would otherwise in the view function.
+        ...
+    gevent.spawn(do_some_work)
+    return 'Regular response'
+
+
+
+Changelog
+

Added in version 0.10.

+
+
+
Parameters:
+

f (F)

+
+
Return type:
+

F

+
+
+
+ +
+
+flask.has_app_context()
+

Works like has_request_context() but for the application +context. You can also just do a boolean check on the +current_app object instead.

+
+Changelog
+

Added in version 0.9.

+
+
+
Return type:
+

bool

+
+
+
+ +
+
+flask.url_for(endpoint, *, _anchor=None, _method=None, _scheme=None, _external=None, **values)
+

Generate a URL to the given endpoint with the given values.

+

This requires an active request or application context, and calls +current_app.url_for(). See that method +for full documentation.

+
+
Parameters:
+
    +
  • endpoint (str) – The endpoint name associated with the URL to +generate. If this starts with a ., the current blueprint +name (if any) will be used.

  • +
  • _anchor (str | None) – If given, append this as #anchor to the URL.

  • +
  • _method (str | None) – If given, generate the URL associated with this +method for the endpoint.

  • +
  • _scheme (str | None) – If given, the URL will have this scheme if it is +external.

  • +
  • _external (bool | None) – If given, prefer the URL to be internal (False) or +require it to be external (True). External URLs include the +scheme and domain. When not in an active request, URLs are +external by default.

  • +
  • values (Any) – Values to use for the variable parts of the URL rule. +Unknown keys are appended as query string arguments, like +?a=b&c=d.

  • +
+
+
Return type:
+

str

+
+
+
+Changelog
+

Changed in version 2.2: Calls current_app.url_for, allowing an app to override the +behavior.

+
+
+

Changed in version 0.10: The _scheme parameter was added.

+
+
+

Changed in version 0.9: The _anchor and _method parameters were added.

+
+
+

Changed in version 0.9: Calls app.handle_url_build_error on build errors.

+
+
+ +
+
+flask.abort(code, *args, **kwargs)
+

Raise an HTTPException for the given +status code.

+

If current_app is available, it will call its +aborter object, otherwise it will use +werkzeug.exceptions.abort().

+
+
Parameters:
+
    +
  • code (int | Response) – The status code for the exception, which must be +registered in app.aborter.

  • +
  • args (Any) – Passed to the exception.

  • +
  • kwargs (Any) – Passed to the exception.

  • +
+
+
Return type:
+

NoReturn

+
+
+
+Changelog
+

Added in version 2.2: Calls current_app.aborter if available instead of always +using Werkzeug’s default abort.

+
+
+ +
+
+flask.redirect(location, code=302, Response=None)
+

Create a redirect response object.

+

If current_app is available, it will use its +redirect() method, otherwise it will use +werkzeug.utils.redirect().

+
+
Parameters:
+
    +
  • location (str) – The URL to redirect to.

  • +
  • code (int) – The status code for the redirect.

  • +
  • Response (type[Response] | None) – The response class to use. Not used when +current_app is active, which uses app.response_class.

  • +
+
+
Return type:
+

Response

+
+
+
+Changelog
+

Added in version 2.2: Calls current_app.redirect if available instead of always +using Werkzeug’s default redirect.

+
+
+ +
+
+flask.make_response(*args)
+

Sometimes it is necessary to set additional headers in a view. Because +views do not have to return response objects but can return a value that +is converted into a response object by Flask itself, it becomes tricky to +add headers to it. This function can be called instead of using a return +and you will get a response object which you can use to attach headers.

+

If view looked like this and you want to add a new header:

+
def index():
+    return render_template('index.html', foo=42)
+
+
+

You can now do something like this:

+
def index():
+    response = make_response(render_template('index.html', foo=42))
+    response.headers['X-Parachutes'] = 'parachutes are cool'
+    return response
+
+
+

This function accepts the very same arguments you can return from a +view function. This for example creates a response with a 404 error +code:

+
response = make_response(render_template('not_found.html'), 404)
+
+
+

The other use case of this function is to force the return value of a +view function into a response which is helpful with view +decorators:

+
response = make_response(view_function())
+response.headers['X-Parachutes'] = 'parachutes are cool'
+
+
+

Internally this function does the following things:

+ +
+Changelog
+

Added in version 0.6.

+
+
+
Parameters:
+

args (t.Any)

+
+
Return type:
+

Response

+
+
+
+ +
+
+flask.after_this_request(f)
+

Executes a function after this request. This is useful to modify +response objects. The function is passed the response object and has +to return the same or a new one.

+

Example:

+
@app.route('/')
+def index():
+    @after_this_request
+    def add_header(response):
+        response.headers['X-Foo'] = 'Parachute'
+        return response
+    return 'Hello World!'
+
+
+

This is more useful if a function other than the view function wants to +modify a response. For instance think of a decorator that wants to add +some headers without converting the return value into a response object.

+
+Changelog
+

Added in version 0.9.

+
+
+
Parameters:
+

f (Callable[[Any], Any] | Callable[[Any], Awaitable[Any]])

+
+
Return type:
+

Callable[[Any], Any] | Callable[[Any], Awaitable[Any]]

+
+
+
+ +
+
+flask.send_file(path_or_file, mimetype=None, as_attachment=False, download_name=None, conditional=True, etag=True, last_modified=None, max_age=None)
+

Send the contents of a file to the client.

+

The first argument can be a file path or a file-like object. Paths +are preferred in most cases because Werkzeug can manage the file and +get extra information from the path. Passing a file-like object +requires that the file is opened in binary mode, and is mostly +useful when building a file in memory with io.BytesIO.

+

Never pass file paths provided by a user. The path is assumed to be +trusted, so a user could craft a path to access a file you didn’t +intend. Use send_from_directory() to safely serve +user-requested paths from within a directory.

+

If the WSGI server sets a file_wrapper in environ, it is +used, otherwise Werkzeug’s built-in wrapper is used. Alternatively, +if the HTTP server supports X-Sendfile, configuring Flask with +USE_X_SENDFILE = True will tell the server to send the given +path, which is much more efficient than reading it in Python.

+
+
Parameters:
+
    +
  • path_or_file (os.PathLike[t.AnyStr] | str | t.BinaryIO) – The path to the file to send, relative to the +current working directory if a relative path is given. +Alternatively, a file-like object opened in binary mode. Make +sure the file pointer is seeked to the start of the data.

  • +
  • mimetype (str | None) – The MIME type to send for the file. If not +provided, it will try to detect it from the file name.

  • +
  • as_attachment (bool) – Indicate to a browser that it should offer to +save the file instead of displaying it.

  • +
  • download_name (str | None) – The default name browsers will use when saving +the file. Defaults to the passed file name.

  • +
  • conditional (bool) – Enable conditional and range responses based on +request headers. Requires passing a file path and environ.

  • +
  • etag (bool | str) – Calculate an ETag for the file, which requires passing +a file path. Can also be a string to use instead.

  • +
  • last_modified (datetime | int | float | None) – The last modified time to send for the file, +in seconds. If not provided, it will try to detect it from the +file path.

  • +
  • max_age (None | (int | t.Callable[[str | None], int | None])) – How long the client should cache the file, in +seconds. If set, Cache-Control will be public, otherwise +it will be no-cache to prefer conditional caching.

  • +
+
+
Return type:
+

Response

+
+
+
+Changelog
+

Changed in version 2.0: download_name replaces the attachment_filename +parameter. If as_attachment=False, it is passed with +Content-Disposition: inline instead.

+
+
+

Changed in version 2.0: max_age replaces the cache_timeout parameter. +conditional is enabled and max_age is not set by +default.

+
+
+

Changed in version 2.0: etag replaces the add_etags parameter. It can be a +string to use instead of generating one.

+
+
+

Changed in version 2.0: Passing a file-like object that inherits from +TextIOBase will raise a ValueError rather +than sending an empty file.

+
+
+

Added in version 2.0: Moved the implementation to Werkzeug. This is now a wrapper to +pass some Flask-specific arguments.

+
+
+

Changed in version 1.1: filename may be a PathLike object.

+
+
+

Changed in version 1.1: Passing a BytesIO object supports range requests.

+
+
+

Changed in version 1.0.3: Filenames are encoded with ASCII instead of Latin-1 for broader +compatibility with WSGI servers.

+
+
+

Changed in version 1.0: UTF-8 filenames as specified in RFC 2231 are supported.

+
+
+

Changed in version 0.12: The filename is no longer automatically inferred from file +objects. If you want to use automatic MIME and etag support, +pass a filename via filename_or_fp or +attachment_filename.

+
+
+

Changed in version 0.12: attachment_filename is preferred over filename for MIME +detection.

+
+
+

Changed in version 0.9: cache_timeout defaults to +Flask.get_send_file_max_age().

+
+
+

Changed in version 0.7: MIME guessing and etag support for file-like objects was +removed because it was unreliable. Pass a filename if you are +able to, otherwise attach an etag yourself.

+
+
+

Changed in version 0.5: The add_etags, cache_timeout and conditional +parameters were added. The default behavior is to add etags.

+
+
+

Added in version 0.2.

+
+
+ +
+
+flask.send_from_directory(directory, path, **kwargs)
+

Send a file from within a directory using send_file().

+
@app.route("/uploads/<path:name>")
+def download_file(name):
+    return send_from_directory(
+        app.config['UPLOAD_FOLDER'], name, as_attachment=True
+    )
+
+
+

This is a secure way to serve files from a folder, such as static +files or uploads. Uses safe_join() to +ensure the path coming from the client is not maliciously crafted to +point outside the specified directory.

+

If the final path does not point to an existing regular file, +raises a 404 NotFound error.

+
+
Parameters:
+
    +
  • directory (os.PathLike[str] | str) – The directory that path must be located under, +relative to the current application’s root path. This must not +be a value provided by the client, otherwise it becomes insecure.

  • +
  • path (os.PathLike[str] | str) – The path to the file to send, relative to +directory.

  • +
  • kwargs (t.Any) – Arguments to pass to send_file().

  • +
+
+
Return type:
+

Response

+
+
+
+Changelog
+

Changed in version 2.0: path replaces the filename parameter.

+
+
+

Added in version 2.0: Moved the implementation to Werkzeug. This is now a wrapper to +pass some Flask-specific arguments.

+
+
+

Added in version 0.5.

+
+
+ +
+
+

Message Flashing

+
+
+flask.flash(message, category='message')
+

Flashes a message to the next request. In order to remove the +flashed message from the session and to display it to the user, +the template has to call get_flashed_messages().

+
+Changelog
+

Changed in version 0.3: category parameter added.

+
+
+
Parameters:
+
    +
  • message (str) – the message to be flashed.

  • +
  • category (str) – the category for the message. The following values +are recommended: 'message' for any kind of message, +'error' for errors, 'info' for information +messages and 'warning' for warnings. However any +kind of string can be used as category.

  • +
+
+
Return type:
+

None

+
+
+
+ +
+
+flask.get_flashed_messages(with_categories=False, category_filter=())
+

Pulls all flashed messages from the session and returns them. +Further calls in the same request to the function will return +the same messages. By default just the messages are returned, +but when with_categories is set to True, the return value will +be a list of tuples in the form (category, message) instead.

+

Filter the flashed messages to one or more categories by providing those +categories in category_filter. This allows rendering categories in +separate html blocks. The with_categories and category_filter +arguments are distinct:

+
    +
  • with_categories controls whether categories are returned with message +text (True gives a tuple, where False gives just the message text).

  • +
  • category_filter filters the messages down to only those matching the +provided categories.

  • +
+

See Message Flashing for examples.

+
+Changelog
+

Changed in version 0.9: category_filter parameter added.

+
+
+

Changed in version 0.3: with_categories parameter added.

+
+
+
Parameters:
+
    +
  • with_categories (bool) – set to True to also receive categories.

  • +
  • category_filter (Iterable[str]) – filter of categories to limit return values. Only +categories in the list will be returned.

  • +
+
+
Return type:
+

list[str] | list[tuple[str, str]]

+
+
+
+ +
+
+

JSON Support

+

Flask uses Python’s built-in json module for handling JSON by +default. The JSON implementation can be changed by assigning a different +provider to flask.Flask.json_provider_class or +flask.Flask.json. The functions provided by flask.json will +use methods on app.json if an app context is active.

+

Jinja’s |tojson filter is configured to use the app’s JSON provider. +The filter marks the output with |safe. Use it to render data inside +HTML <script> tags.

+
<script>
+    const names = {{ names|tojson }};
+    renderChart(names, {{ axis_data|tojson }});
+</script>
+
+
+
+
+flask.json.jsonify(*args, **kwargs)
+

Serialize the given arguments as JSON, and return a +Response object with the application/json +mimetype. A dict or list returned from a view will be converted to a +JSON response automatically without needing to call this.

+

This requires an active request or application context, and calls +app.json.response().

+

In debug mode, the output is formatted with indentation to make it +easier to read. This may also be controlled by the provider.

+

Either positional or keyword arguments can be given, not both. +If no arguments are given, None is serialized.

+
+
Parameters:
+
    +
  • args (t.Any) – A single value to serialize, or multiple values to +treat as a list to serialize.

  • +
  • kwargs (t.Any) – Treat as a dict to serialize.

  • +
+
+
Return type:
+

Response

+
+
+
+Changelog
+

Changed in version 2.2: Calls current_app.json.response, allowing an app to override +the behavior.

+
+
+

Changed in version 2.0.2: decimal.Decimal is supported by converting to a string.

+
+
+

Changed in version 0.11: Added support for serializing top-level arrays. This was a +security risk in ancient browsers. See JSON Security.

+
+
+

Added in version 0.2.

+
+
+ +
+
+flask.json.dumps(obj, **kwargs)
+

Serialize data as JSON.

+

If current_app is available, it will use its +app.json.dumps() +method, otherwise it will use json.dumps().

+
+
Parameters:
+
    +
  • obj (Any) – The data to serialize.

  • +
  • kwargs (Any) – Arguments passed to the dumps implementation.

  • +
+
+
Return type:
+

str

+
+
+
+Changelog
+

Changed in version 2.3: The app parameter was removed.

+
+
+

Changed in version 2.2: Calls current_app.json.dumps, allowing an app to override +the behavior.

+
+
+

Changed in version 2.0.2: decimal.Decimal is supported by converting to a string.

+
+
+

Changed in version 2.0: encoding will be removed in Flask 2.1.

+
+
+

Changed in version 1.0.3: app can be passed directly, rather than requiring an app +context for configuration.

+
+
+ +
+
+flask.json.dump(obj, fp, **kwargs)
+

Serialize data as JSON and write to a file.

+

If current_app is available, it will use its +app.json.dump() +method, otherwise it will use json.dump().

+
+
Parameters:
+
    +
  • obj (Any) – The data to serialize.

  • +
  • fp (IO[str]) – A file opened for writing text. Should use the UTF-8 +encoding to be valid JSON.

  • +
  • kwargs (Any) – Arguments passed to the dump implementation.

  • +
+
+
Return type:
+

None

+
+
+
+Changelog
+

Changed in version 2.3: The app parameter was removed.

+
+
+

Changed in version 2.2: Calls current_app.json.dump, allowing an app to override +the behavior.

+
+
+

Changed in version 2.0: Writing to a binary file, and the encoding argument, will be +removed in Flask 2.1.

+
+
+ +
+
+flask.json.loads(s, **kwargs)
+

Deserialize data as JSON.

+

If current_app is available, it will use its +app.json.loads() +method, otherwise it will use json.loads().

+
+
Parameters:
+
    +
  • s (str | bytes) – Text or UTF-8 bytes.

  • +
  • kwargs (Any) – Arguments passed to the loads implementation.

  • +
+
+
Return type:
+

Any

+
+
+
+Changelog
+

Changed in version 2.3: The app parameter was removed.

+
+
+

Changed in version 2.2: Calls current_app.json.loads, allowing an app to override +the behavior.

+
+
+

Changed in version 2.0: encoding will be removed in Flask 2.1. The data must be a +string or UTF-8 bytes.

+
+
+

Changed in version 1.0.3: app can be passed directly, rather than requiring an app +context for configuration.

+
+
+ +
+
+flask.json.load(fp, **kwargs)
+

Deserialize data as JSON read from a file.

+

If current_app is available, it will use its +app.json.load() +method, otherwise it will use json.load().

+
+
Parameters:
+
    +
  • fp (IO) – A file opened for reading text or UTF-8 bytes.

  • +
  • kwargs (Any) – Arguments passed to the load implementation.

  • +
+
+
Return type:
+

Any

+
+
+
+Changelog
+

Changed in version 2.3: The app parameter was removed.

+
+
+

Changed in version 2.2: Calls current_app.json.load, allowing an app to override +the behavior.

+
+
+

Changed in version 2.2: The app parameter will be removed in Flask 2.3.

+
+
+

Changed in version 2.0: encoding will be removed in Flask 2.1. The file must be text +mode, or binary mode with UTF-8 bytes.

+
+
+ +
+
+class flask.json.provider.JSONProvider(app)
+

A standard set of JSON operations for an application. Subclasses +of this can be used to customize JSON behavior or use different +JSON libraries.

+

To implement a provider for a specific library, subclass this base +class and implement at least dumps() and loads(). All +other methods have default implementations.

+

To use a different provider, either subclass Flask and set +json_provider_class to a provider class, or set +app.json to an instance of the class.

+
+
Parameters:
+

app (App) – An application instance. This will be stored as a +weakref.proxy on the _app attribute.

+
+
+
+Changelog
+

Added in version 2.2.

+
+
+
+dumps(obj, **kwargs)
+

Serialize data as JSON.

+
+
Parameters:
+
    +
  • obj (Any) – The data to serialize.

  • +
  • kwargs (Any) – May be passed to the underlying JSON library.

  • +
+
+
Return type:
+

str

+
+
+
+ +
+
+dump(obj, fp, **kwargs)
+

Serialize data as JSON and write to a file.

+
+
Parameters:
+
    +
  • obj (Any) – The data to serialize.

  • +
  • fp (IO[str]) – A file opened for writing text. Should use the UTF-8 +encoding to be valid JSON.

  • +
  • kwargs (Any) – May be passed to the underlying JSON library.

  • +
+
+
Return type:
+

None

+
+
+
+ +
+
+loads(s, **kwargs)
+

Deserialize data as JSON.

+
+
Parameters:
+
    +
  • s (str | bytes) – Text or UTF-8 bytes.

  • +
  • kwargs (Any) – May be passed to the underlying JSON library.

  • +
+
+
Return type:
+

Any

+
+
+
+ +
+
+load(fp, **kwargs)
+

Deserialize data as JSON read from a file.

+
+
Parameters:
+
    +
  • fp (IO) – A file opened for reading text or UTF-8 bytes.

  • +
  • kwargs (Any) – May be passed to the underlying JSON library.

  • +
+
+
Return type:
+

Any

+
+
+
+ +
+
+response(*args, **kwargs)
+

Serialize the given arguments as JSON, and return a +Response object with the application/json +mimetype.

+

The jsonify() function calls this method for +the current application.

+

Either positional or keyword arguments can be given, not both. +If no arguments are given, None is serialized.

+
+
Parameters:
+
    +
  • args (t.Any) – A single value to serialize, or multiple values to +treat as a list to serialize.

  • +
  • kwargs (t.Any) – Treat as a dict to serialize.

  • +
+
+
Return type:
+

Response

+
+
+
+ +
+ +
+
+class flask.json.provider.DefaultJSONProvider(app)
+

Provide JSON operations using Python’s built-in json +library. Serializes the following additional data types:

+ +
+
Parameters:
+

app (App)

+
+
+
+
+static default(o)
+

Apply this function to any object that json.dumps() does +not know how to serialize. It should return a valid JSON type or +raise a TypeError.

+
+
Parameters:
+

o (Any)

+
+
Return type:
+

Any

+
+
+
+ +
+
+ensure_ascii = True
+

Replace non-ASCII characters with escape sequences. This may be +more compatible with some clients, but can be disabled for better +performance and size.

+
+ +
+
+sort_keys = True
+

Sort the keys in any serialized dicts. This may be useful for +some caching situations, but can be disabled for better performance. +When enabled, keys must all be strings, they are not converted +before sorting.

+
+ +
+
+compact: bool | None = None
+

If True, or None out of debug mode, the response() +output will not add indentation, newlines, or spaces. If False, +or None in debug mode, it will use a non-compact representation.

+
+ +
+
+mimetype = 'application/json'
+

The mimetype set in response().

+
+ +
+
+dumps(obj, **kwargs)
+

Serialize data as JSON to a string.

+

Keyword arguments are passed to json.dumps(). Sets some +parameter defaults from the default, +ensure_ascii, and sort_keys attributes.

+
+
Parameters:
+
+
+
Return type:
+

str

+
+
+
+ +
+
+loads(s, **kwargs)
+

Deserialize data as JSON from a string or bytes.

+
+
Parameters:
+
+
+
Return type:
+

Any

+
+
+
+ +
+
+response(*args, **kwargs)
+

Serialize the given arguments as JSON, and return a +Response object with it. The response mimetype +will be “application/json” and can be changed with +mimetype.

+

If compact is False or debug mode is enabled, the +output will be formatted to be easier to read.

+

Either positional or keyword arguments can be given, not both. +If no arguments are given, None is serialized.

+
+
Parameters:
+
    +
  • args (t.Any) – A single value to serialize, or multiple values to +treat as a list to serialize.

  • +
  • kwargs (t.Any) – Treat as a dict to serialize.

  • +
+
+
Return type:
+

Response

+
+
+
+ +
+ +
+

Tagged JSON

+

A compact representation for lossless serialization of non-standard JSON +types. SecureCookieSessionInterface uses this +to serialize the session data, but it may be useful in other places. It +can be extended to support other types.

+
+
+class flask.json.tag.TaggedJSONSerializer
+

Serializer that uses a tag system to compactly represent objects that +are not JSON types. Passed as the intermediate serializer to +itsdangerous.Serializer.

+

The following extra types are supported:

+ +
+
+
+
+default_tags = [<class 'flask.json.tag.TagDict'>, <class 'flask.json.tag.PassDict'>, <class 'flask.json.tag.TagTuple'>, <class 'flask.json.tag.PassList'>, <class 'flask.json.tag.TagBytes'>, <class 'flask.json.tag.TagMarkup'>, <class 'flask.json.tag.TagUUID'>, <class 'flask.json.tag.TagDateTime'>]
+

Tag classes to bind when creating the serializer. Other tags can be +added later using register().

+
+ +
+
+register(tag_class, force=False, index=None)
+

Register a new tag with this serializer.

+
+
Parameters:
+
    +
  • tag_class (type[JSONTag]) – tag class to register. Will be instantiated with this +serializer instance.

  • +
  • force (bool) – overwrite an existing tag. If false (default), a +KeyError is raised.

  • +
  • index (int | None) – index to insert the new tag in the tag order. Useful when +the new tag is a special case of an existing tag. If None +(default), the tag is appended to the end of the order.

  • +
+
+
Raises:
+

KeyError – if the tag key is already registered and force is +not true.

+
+
Return type:
+

None

+
+
+
+ +
+
+tag(value)
+

Convert a value to a tagged representation if necessary.

+
+
Parameters:
+

value (Any)

+
+
Return type:
+

Any

+
+
+
+ +
+
+untag(value)
+

Convert a tagged representation back to the original type.

+
+
Parameters:
+

value (dict[str, Any])

+
+
Return type:
+

Any

+
+
+
+ +
+
+dumps(value)
+

Tag the value and dump it to a compact JSON string.

+
+
Parameters:
+

value (Any)

+
+
Return type:
+

str

+
+
+
+ +
+
+loads(value)
+

Load data from a JSON string and deserialized any tagged objects.

+
+
Parameters:
+

value (str)

+
+
Return type:
+

Any

+
+
+
+ +
+ +
+
+class flask.json.tag.JSONTag(serializer)
+

Base class for defining type tags for TaggedJSONSerializer.

+
+
Parameters:
+

serializer (TaggedJSONSerializer)

+
+
+
+
+key: str = ''
+

The tag to mark the serialized object with. If empty, this tag is +only used as an intermediate step during tagging.

+
+ +
+
+check(value)
+

Check if the given value should be tagged by this tag.

+
+
Parameters:
+

value (Any)

+
+
Return type:
+

bool

+
+
+
+ +
+
+to_json(value)
+

Convert the Python object to an object that is a valid JSON type. +The tag will be added later.

+
+
Parameters:
+

value (Any)

+
+
Return type:
+

Any

+
+
+
+ +
+
+to_python(value)
+

Convert the JSON representation back to the correct type. The tag +will already be removed.

+
+
Parameters:
+

value (Any)

+
+
Return type:
+

Any

+
+
+
+ +
+
+tag(value)
+

Convert the value to a valid JSON type and add the tag structure +around it.

+
+
Parameters:
+

value (Any)

+
+
Return type:
+

dict[str, Any]

+
+
+
+ +
+ +

Let’s see an example that adds support for +OrderedDict. Dicts don’t have an order in JSON, so +to handle this we will dump the items as a list of [key, value] +pairs. Subclass JSONTag and give it the new key ' od' to +identify the type. The session serializer processes dicts first, so +insert the new tag at the front of the order since OrderedDict must +be processed before dict.

+
from flask.json.tag import JSONTag
+
+class TagOrderedDict(JSONTag):
+    __slots__ = ('serializer',)
+    key = ' od'
+
+    def check(self, value):
+        return isinstance(value, OrderedDict)
+
+    def to_json(self, value):
+        return [[k, self.serializer.tag(v)] for k, v in iteritems(value)]
+
+    def to_python(self, value):
+        return OrderedDict(value)
+
+app.session_interface.serializer.register(TagOrderedDict, index=0)
+
+
+
+
+
+

Template Rendering

+
+
+flask.render_template(template_name_or_list, **context)
+

Render a template by name with the given context.

+
+
Parameters:
+
    +
  • template_name_or_list (str | Template | list[str | Template]) – The name of the template to render. If +a list is given, the first name to exist will be rendered.

  • +
  • context (Any) – The variables to make available in the template.

  • +
+
+
Return type:
+

str

+
+
+
+ +
+
+flask.render_template_string(source, **context)
+

Render a template from the given source string with the given +context.

+
+
Parameters:
+
    +
  • source (str) – The source code of the template to render.

  • +
  • context (Any) – The variables to make available in the template.

  • +
+
+
Return type:
+

str

+
+
+
+ +
+
+flask.stream_template(template_name_or_list, **context)
+

Render a template by name with the given context as a stream. +This returns an iterator of strings, which can be used as a +streaming response from a view.

+
+
Parameters:
+
    +
  • template_name_or_list (str | Template | list[str | Template]) – The name of the template to render. If +a list is given, the first name to exist will be rendered.

  • +
  • context (Any) – The variables to make available in the template.

  • +
+
+
Return type:
+

Iterator[str]

+
+
+
+Changelog
+

Added in version 2.2.

+
+
+ +
+
+flask.stream_template_string(source, **context)
+

Render a template from the given source string with the given +context as a stream. This returns an iterator of strings, which can +be used as a streaming response from a view.

+
+
Parameters:
+
    +
  • source (str) – The source code of the template to render.

  • +
  • context (Any) – The variables to make available in the template.

  • +
+
+
Return type:
+

Iterator[str]

+
+
+
+Changelog
+

Added in version 2.2.

+
+
+ +
+
+flask.get_template_attribute(template_name, attribute)
+

Loads a macro (or variable) a template exports. This can be used to +invoke a macro from within Python code. If you for example have a +template named _cider.html with the following contents:

+
{% macro hello(name) %}Hello {{ name }}!{% endmacro %}
+
+
+

You can access this from Python code like this:

+
hello = get_template_attribute('_cider.html', 'hello')
+return hello('World')
+
+
+
+Changelog
+

Added in version 0.2.

+
+
+
Parameters:
+
    +
  • template_name (str) – the name of the template

  • +
  • attribute (str) – the name of the variable of macro to access

  • +
+
+
Return type:
+

Any

+
+
+
+ +
+
+

Configuration

+
+
+class flask.Config(root_path, defaults=None)
+

Works exactly like a dict but provides ways to fill it from files +or special dictionaries. There are two common patterns to populate the +config.

+

Either you can fill the config from a config file:

+
app.config.from_pyfile('yourconfig.cfg')
+
+
+

Or alternatively you can define the configuration options in the +module that calls from_object() or provide an import path to +a module that should be loaded. It is also possible to tell it to +use the same module and with that provide the configuration values +just before the call:

+
DEBUG = True
+SECRET_KEY = 'development key'
+app.config.from_object(__name__)
+
+
+

In both cases (loading from any Python file or loading from modules), +only uppercase keys are added to the config. This makes it possible to use +lowercase values in the config file for temporary values that are not added +to the config or to define the config keys in the same file that implements +the application.

+

Probably the most interesting way to load configurations is from an +environment variable pointing to a file:

+
app.config.from_envvar('YOURAPPLICATION_SETTINGS')
+
+
+

In this case before launching the application you have to set this +environment variable to the file you want to use. On Linux and OS X +use the export statement:

+
export YOURAPPLICATION_SETTINGS='/path/to/config/file'
+
+
+

On windows use set instead.

+
+
Parameters:
+
    +
  • root_path (str | os.PathLike[str]) – path to which files are read relative from. When the +config object is created by the application, this is +the application’s root_path.

  • +
  • defaults (dict[str, t.Any] | None) – an optional dictionary of default values

  • +
+
+
+
+
+from_envvar(variable_name, silent=False)
+

Loads a configuration from an environment variable pointing to +a configuration file. This is basically just a shortcut with nicer +error messages for this line of code:

+
app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])
+
+
+
+
Parameters:
+
    +
  • variable_name (str) – name of the environment variable

  • +
  • silent (bool) – set to True if you want silent failure for missing +files.

  • +
+
+
Returns:
+

True if the file was loaded successfully.

+
+
Return type:
+

bool

+
+
+
+ +
+
+from_prefixed_env(prefix='FLASK', *, loads=json.loads)
+

Load any environment variables that start with FLASK_, +dropping the prefix from the env key for the config key. Values +are passed through a loading function to attempt to convert them +to more specific types than strings.

+

Keys are loaded in sorted() order.

+

The default loading function attempts to parse values as any +valid JSON type, including dicts and lists.

+

Specific items in nested dicts can be set by separating the +keys with double underscores (__). If an intermediate key +doesn’t exist, it will be initialized to an empty dict.

+
+
Parameters:
+
    +
  • prefix (str) – Load env vars that start with this prefix, +separated with an underscore (_).

  • +
  • loads (Callable[[str], Any]) – Pass each string value to this function and use +the returned value as the config value. If any error is +raised it is ignored and the value remains a string. The +default is json.loads().

  • +
+
+
Return type:
+

bool

+
+
+
+Changelog
+

Added in version 2.1.

+
+
+ +
+
+from_pyfile(filename, silent=False)
+

Updates the values in the config from a Python file. This function +behaves as if the file was imported as module with the +from_object() function.

+
+
Parameters:
+
    +
  • filename (str | PathLike[str]) – the filename of the config. This can either be an +absolute filename or a filename relative to the +root path.

  • +
  • silent (bool) – set to True if you want silent failure for missing +files.

  • +
+
+
Returns:
+

True if the file was loaded successfully.

+
+
Return type:
+

bool

+
+
+
+Changelog
+

Added in version 0.7: silent parameter.

+
+
+ +
+
+from_object(obj)
+

Updates the values from the given object. An object can be of one +of the following two types:

+
    +
  • a string: in this case the object with that name will be imported

  • +
  • an actual object reference: that object is used directly

  • +
+

Objects are usually either modules or classes. from_object() +loads only the uppercase attributes of the module/class. A dict +object will not work with from_object() because the keys of a +dict are not attributes of the dict class.

+

Example of module-based configuration:

+
app.config.from_object('yourapplication.default_config')
+from yourapplication import default_config
+app.config.from_object(default_config)
+
+
+

Nothing is done to the object before loading. If the object is a +class and has @property attributes, it needs to be +instantiated before being passed to this method.

+

You should not use this function to load the actual configuration but +rather configuration defaults. The actual config should be loaded +with from_pyfile() and ideally from a location not within the +package because the package might be installed system wide.

+

See Development / Production for an example of class-based configuration +using from_object().

+
+
Parameters:
+

obj (object | str) – an import name or object

+
+
Return type:
+

None

+
+
+
+ +
+
+from_file(filename, load, silent=False, text=True)
+

Update the values in the config from a file that is loaded +using the load parameter. The loaded data is passed to the +from_mapping() method.

+
import json
+app.config.from_file("config.json", load=json.load)
+
+import tomllib
+app.config.from_file("config.toml", load=tomllib.load, text=False)
+
+
+
+
Parameters:
+
    +
  • filename (str | PathLike[str]) – The path to the data file. This can be an +absolute path or relative to the config root path.

  • +
  • load (Callable[[Reader], Mapping] where Reader +implements a read method.) – A callable that takes a file handle and returns a +mapping of loaded data from the file.

  • +
  • silent (bool) – Ignore the file if it doesn’t exist.

  • +
  • text (bool) – Open the file in text or binary mode.

  • +
+
+
Returns:
+

True if the file was loaded successfully.

+
+
Return type:
+

bool

+
+
+
+Changelog
+

Changed in version 2.3: The text parameter was added.

+
+
+

Added in version 2.0.

+
+
+ +
+
+from_mapping(mapping=None, **kwargs)
+

Updates the config like update() ignoring items with +non-upper keys.

+
+
Returns:
+

Always returns True.

+
+
Parameters:
+
+
+
Return type:
+

bool

+
+
+
+Changelog
+

Added in version 0.11.

+
+
+ +
+
+get_namespace(namespace, lowercase=True, trim_namespace=True)
+

Returns a dictionary containing a subset of configuration options +that match the specified namespace/prefix. Example usage:

+
app.config['IMAGE_STORE_TYPE'] = 'fs'
+app.config['IMAGE_STORE_PATH'] = '/var/app/images'
+app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'
+image_store_config = app.config.get_namespace('IMAGE_STORE_')
+
+
+

The resulting dictionary image_store_config would look like:

+
{
+    'type': 'fs',
+    'path': '/var/app/images',
+    'base_url': 'http://img.website.com'
+}
+
+
+

This is often useful when configuration options map directly to +keyword arguments in functions or class constructors.

+
+
Parameters:
+
    +
  • namespace (str) – a configuration namespace

  • +
  • lowercase (bool) – a flag indicating if the keys of the resulting +dictionary should be lowercase

  • +
  • trim_namespace (bool) – a flag indicating if the keys of the resulting +dictionary should not include the namespace

  • +
+
+
Return type:
+

dict[str, Any]

+
+
+
+Changelog
+

Added in version 0.11.

+
+
+ +
+ +
+
+

Stream Helpers

+
+
+flask.stream_with_context(generator_or_function: Iterator) Iterator
+
+flask.stream_with_context(generator_or_function: Callable[[...], Iterator]) Callable[[Iterator], Iterator]
+

Request contexts disappear when the response is started on the server. +This is done for efficiency reasons and to make it less likely to encounter +memory leaks with badly written WSGI middlewares. The downside is that if +you are using streamed responses, the generator cannot access request bound +information any more.

+

This function however can help you keep the context around for longer:

+
from flask import stream_with_context, request, Response
+
+@app.route('/stream')
+def streamed_response():
+    @stream_with_context
+    def generate():
+        yield 'Hello '
+        yield request.args['name']
+        yield '!'
+    return Response(generate())
+
+
+

Alternatively it can also be used around a specific generator:

+
from flask import stream_with_context, request, Response
+
+@app.route('/stream')
+def streamed_response():
+    def generate():
+        yield 'Hello '
+        yield request.args['name']
+        yield '!'
+    return Response(stream_with_context(generate()))
+
+
+
+Changelog
+

Added in version 0.9.

+
+
+ +
+
+

Useful Internals

+
+
+class flask.ctx.RequestContext(app, environ, request=None, session=None)
+

The request context contains per-request information. The Flask +app creates and pushes it at the beginning of the request, then pops +it at the end of the request. It will create the URL adapter and +request object for the WSGI environment provided.

+

Do not attempt to use this class directly, instead use +test_request_context() and +request_context() to create this object.

+

When the request context is popped, it will evaluate all the +functions registered on the application for teardown execution +(teardown_request()).

+

The request context is automatically popped at the end of the +request. When using the interactive debugger, the context will be +restored so request is still accessible. Similarly, the test +client can preserve the context after the request ends. However, +teardown functions may already have closed some resources such as +database connections.

+
+
Parameters:
+
+
+
+
+
+copy()
+

Creates a copy of this request context with the same request object. +This can be used to move a request context to a different greenlet. +Because the actual request object is the same this cannot be used to +move a request context to a different thread unless access to the +request object is locked.

+
+Changelog
+

Changed in version 1.1: The current session object is used instead of reloading the original +data. This prevents flask.session pointing to an out-of-date object.

+
+
+

Added in version 0.10.

+
+
+
Return type:
+

RequestContext

+
+
+
+ +
+
+match_request()
+

Can be overridden by a subclass to hook into the matching +of the request.

+
+
Return type:
+

None

+
+
+
+ +
+
+pop(exc=_sentinel)
+

Pops the request context and unbinds it by doing that. This will +also trigger the execution of functions registered by the +teardown_request() decorator.

+
+Changelog
+

Changed in version 0.9: Added the exc argument.

+
+
+
Parameters:
+

exc (BaseException | None)

+
+
Return type:
+

None

+
+
+
+ +
+ +
+
+flask.globals.request_ctx
+

The current RequestContext. If a request context +is not active, accessing attributes on this proxy will raise a +RuntimeError.

+

This is an internal object that is essential to how Flask handles +requests. Accessing this should not be needed in most cases. Most +likely you want request and session instead.

+
+ +
+
+class flask.ctx.AppContext(app)
+

The app context contains application-specific information. An app +context is created and pushed at the beginning of each request if +one is not already active. An app context is also pushed when +running CLI commands.

+
+
Parameters:
+

app (Flask)

+
+
+
+
+push()
+

Binds the app context to the current context.

+
+
Return type:
+

None

+
+
+
+ +
+
+pop(exc=_sentinel)
+

Pops the app context.

+
+
Parameters:
+

exc (BaseException | None)

+
+
Return type:
+

None

+
+
+
+ +
+ +
+
+flask.globals.app_ctx
+

The current AppContext. If an app context is not +active, accessing attributes on this proxy will raise a +RuntimeError.

+

This is an internal object that is essential to how Flask handles +requests. Accessing this should not be needed in most cases. Most +likely you want current_app and g instead.

+
+ +
+
+class flask.blueprints.BlueprintSetupState(blueprint, app, options, first_registration)
+

Temporary holder object for registering a blueprint with the +application. An instance of this class is created by the +make_setup_state() method and later passed +to all register callback functions.

+
+
Parameters:
+
    +
  • blueprint (Blueprint)

  • +
  • app (App)

  • +
  • options (t.Any)

  • +
  • first_registration (bool)

  • +
+
+
+
+
+app
+

a reference to the current application

+
+ +
+
+blueprint
+

a reference to the blueprint that created this setup state.

+
+ +
+
+options
+

a dictionary with all options that were passed to the +register_blueprint() method.

+
+ +
+
+first_registration
+

as blueprints can be registered multiple times with the +application and not everything wants to be registered +multiple times on it, this attribute can be used to figure +out if the blueprint was registered in the past already.

+
+ +
+
+subdomain
+

The subdomain that the blueprint should be active for, None +otherwise.

+
+ +
+
+url_prefix
+

The prefix that should be used for all URLs defined on the +blueprint.

+
+ +
+
+url_defaults
+

A dictionary with URL defaults that is added to each and every +URL that was defined with the blueprint.

+
+ +
+
+add_url_rule(rule, endpoint=None, view_func=None, **options)
+

A helper method to register a rule (and optionally a view function) +to the application. The endpoint is automatically prefixed with the +blueprint’s name.

+
+
Parameters:
+
    +
  • rule (str)

  • +
  • endpoint (str | None)

  • +
  • view_func (ft.RouteCallable | None)

  • +
  • options (t.Any)

  • +
+
+
Return type:
+

None

+
+
+
+ +
+ +
+
+

Signals

+

Signals are provided by the Blinker library. See Signals for an introduction.

+
+
+flask.template_rendered
+

This signal is sent when a template was successfully rendered. The +signal is invoked with the instance of the template as template +and the context as dictionary (named context).

+

Example subscriber:

+
def log_template_renders(sender, template, context, **extra):
+    sender.logger.debug('Rendering template "%s" with context %s',
+                        template.name or 'string template',
+                        context)
+
+from flask import template_rendered
+template_rendered.connect(log_template_renders, app)
+
+
+
+ +
+
+flask.before_render_template
+

This signal is sent before template rendering process. The +signal is invoked with the instance of the template as template +and the context as dictionary (named context).

+

Example subscriber:

+
def log_template_renders(sender, template, context, **extra):
+    sender.logger.debug('Rendering template "%s" with context %s',
+                        template.name or 'string template',
+                        context)
+
+from flask import before_render_template
+before_render_template.connect(log_template_renders, app)
+
+
+
+ +
+
+flask.request_started
+

This signal is sent when the request context is set up, before +any request processing happens. Because the request context is already +bound, the subscriber can access the request with the standard global +proxies such as request.

+

Example subscriber:

+
def log_request(sender, **extra):
+    sender.logger.debug('Request context is set up')
+
+from flask import request_started
+request_started.connect(log_request, app)
+
+
+
+ +
+
+flask.request_finished
+

This signal is sent right before the response is sent to the client. +It is passed the response to be sent named response.

+

Example subscriber:

+
def log_response(sender, response, **extra):
+    sender.logger.debug('Request context is about to close down. '
+                        'Response: %s', response)
+
+from flask import request_finished
+request_finished.connect(log_response, app)
+
+
+
+ +
+
+flask.got_request_exception
+

This signal is sent when an unhandled exception happens during +request processing, including when debugging. The exception is +passed to the subscriber as exception.

+

This signal is not sent for +HTTPException, or other exceptions that +have error handlers registered, unless the exception was raised from +an error handler.

+

This example shows how to do some extra logging if a theoretical +SecurityException was raised:

+
from flask import got_request_exception
+
+def log_security_exception(sender, exception, **extra):
+    if not isinstance(exception, SecurityException):
+        return
+
+    security_logger.exception(
+        f"SecurityException at {request.url!r}",
+        exc_info=exception,
+    )
+
+got_request_exception.connect(log_security_exception, app)
+
+
+
+ +
+
+flask.request_tearing_down
+

This signal is sent when the request is tearing down. This is always +called, even if an exception is caused. Currently functions listening +to this signal are called after the regular teardown handlers, but this +is not something you can rely on.

+

Example subscriber:

+
def close_db_connection(sender, **extra):
+    session.close()
+
+from flask import request_tearing_down
+request_tearing_down.connect(close_db_connection, app)
+
+
+

As of Flask 0.9, this will also be passed an exc keyword argument +that has a reference to the exception that caused the teardown if +there was one.

+
+ +
+
+flask.appcontext_tearing_down
+

This signal is sent when the app context is tearing down. This is always +called, even if an exception is caused. Currently functions listening +to this signal are called after the regular teardown handlers, but this +is not something you can rely on.

+

Example subscriber:

+
def close_db_connection(sender, **extra):
+    session.close()
+
+from flask import appcontext_tearing_down
+appcontext_tearing_down.connect(close_db_connection, app)
+
+
+

This will also be passed an exc keyword argument that has a reference +to the exception that caused the teardown if there was one.

+
+ +
+
+flask.appcontext_pushed
+

This signal is sent when an application context is pushed. The sender +is the application. This is usually useful for unittests in order to +temporarily hook in information. For instance it can be used to +set a resource early onto the g object.

+

Example usage:

+
from contextlib import contextmanager
+from flask import appcontext_pushed
+
+@contextmanager
+def user_set(app, user):
+    def handler(sender, **kwargs):
+        g.user = user
+    with appcontext_pushed.connected_to(handler, app):
+        yield
+
+
+

And in the testcode:

+
def test_user_me(self):
+    with user_set(app, 'john'):
+        c = app.test_client()
+        resp = c.get('/users/me')
+        assert resp.data == 'username=john'
+
+
+
+Changelog
+

Added in version 0.10.

+
+
+ +
+
+flask.appcontext_popped
+

This signal is sent when an application context is popped. The sender +is the application. This usually falls in line with the +appcontext_tearing_down signal.

+
+Changelog
+

Added in version 0.10.

+
+
+ +
+
+flask.message_flashed
+

This signal is sent when the application is flashing a message. The +messages is sent as message keyword argument and the category as +category.

+

Example subscriber:

+
recorded = []
+def record(sender, message, category, **extra):
+    recorded.append((message, category))
+
+from flask import message_flashed
+message_flashed.connect(record, app)
+
+
+
+Changelog
+

Added in version 0.10.

+
+
+ +
+
+

Class-Based Views

+
+Changelog
+

Added in version 0.7.

+
+
+
+class flask.views.View
+

Subclass this class and override dispatch_request() to +create a generic class-based view. Call as_view() to create a +view function that creates an instance of the class with the given +arguments and calls its dispatch_request method with any URL +variables.

+

See Class-based Views for a detailed guide.

+
class Hello(View):
+    init_every_request = False
+
+    def dispatch_request(self, name):
+        return f"Hello, {name}!"
+
+app.add_url_rule(
+    "/hello/<name>", view_func=Hello.as_view("hello")
+)
+
+
+

Set methods on the class to change what methods the view +accepts.

+

Set decorators on the class to apply a list of decorators to +the generated view function. Decorators applied to the class itself +will not be applied to the generated view function!

+

Set init_every_request to False for efficiency, unless +you need to store request-global data on self.

+
+
+methods: ClassVar[Collection[str] | None] = None
+

The methods this view is registered for. Uses the same default +(["GET", "HEAD", "OPTIONS"]) as route and +add_url_rule by default.

+
+ +
+
+provide_automatic_options: ClassVar[bool | None] = None
+

Control whether the OPTIONS method is handled automatically. +Uses the same default (True) as route and +add_url_rule by default.

+
+ +
+
+decorators: ClassVar[list[Callable[[...], Any]]] = []
+

A list of decorators to apply, in order, to the generated view +function. Remember that @decorator syntax is applied bottom +to top, so the first decorator in the list would be the bottom +decorator.

+
+Changelog
+

Added in version 0.8.

+
+
+ +
+
+init_every_request: ClassVar[bool] = True
+

Create a new instance of this view class for every request by +default. If a view subclass sets this to False, the same +instance is used for every request.

+

A single instance is more efficient, especially if complex setup +is done during init. However, storing data on self is no +longer safe across requests, and g should be used +instead.

+
+Changelog
+

Added in version 2.2.

+
+
+ +
+
+dispatch_request()
+

The actual view function behavior. Subclasses must override +this and return a valid response. Any variables from the URL +rule are passed as keyword arguments.

+
+
Return type:
+

ft.ResponseReturnValue

+
+
+
+ +
+
+classmethod as_view(name, *class_args, **class_kwargs)
+

Convert the class into a view function that can be registered +for a route.

+

By default, the generated view will create a new instance of the +view class for every request and call its +dispatch_request() method. If the view class sets +init_every_request to False, the same instance will +be used for every request.

+

Except for name, all other arguments passed to this method +are forwarded to the view class __init__ method.

+
+Changelog
+

Changed in version 2.2: Added the init_every_request class attribute.

+
+
+
Parameters:
+
    +
  • name (str)

  • +
  • class_args (t.Any)

  • +
  • class_kwargs (t.Any)

  • +
+
+
Return type:
+

ft.RouteCallable

+
+
+
+ +
+ +
+
+class flask.views.MethodView
+

Dispatches request methods to the corresponding instance methods. +For example, if you implement a get method, it will be used to +handle GET requests.

+

This can be useful for defining a REST API.

+

methods is automatically set based on the methods defined on +the class.

+

See Class-based Views for a detailed guide.

+
class CounterAPI(MethodView):
+    def get(self):
+        return str(session.get("counter", 0))
+
+    def post(self):
+        session["counter"] = session.get("counter", 0) + 1
+        return redirect(url_for("counter"))
+
+app.add_url_rule(
+    "/counter", view_func=CounterAPI.as_view("counter")
+)
+
+
+
+
+dispatch_request(**kwargs)
+

The actual view function behavior. Subclasses must override +this and return a valid response. Any variables from the URL +rule are passed as keyword arguments.

+
+
Parameters:
+

kwargs (t.Any)

+
+
Return type:
+

ft.ResponseReturnValue

+
+
+
+ +
+ +
+
+

URL Route Registrations

+

Generally there are three ways to define rules for the routing system:

+
    +
  1. You can use the flask.Flask.route() decorator.

  2. +
  3. You can use the flask.Flask.add_url_rule() function.

  4. +
  5. You can directly access the underlying Werkzeug routing system +which is exposed as flask.Flask.url_map.

  6. +
+

Variable parts in the route can be specified with angular brackets +(/user/<username>). By default a variable part in the URL accepts any +string without a slash however a different converter can be specified as +well by using <converter:name>.

+

Variable parts are passed to the view function as keyword arguments.

+

The following converters are available:

+ + + + + + + + + + + + + + + + + + + + + +

string

accepts any text without a slash (the default)

int

accepts integers

float

like int but for floating point values

path

like the default but also accepts slashes

any

matches one of the items provided

uuid

accepts UUID strings

+

Custom converters can be defined using flask.Flask.url_map.

+

Here are some examples:

+
@app.route('/')
+def index():
+    pass
+
+@app.route('/<username>')
+def show_user(username):
+    pass
+
+@app.route('/post/<int:post_id>')
+def show_post(post_id):
+    pass
+
+
+

An important detail to keep in mind is how Flask deals with trailing +slashes. The idea is to keep each URL unique so the following rules +apply:

+
    +
  1. If a rule ends with a slash and is requested without a slash by the +user, the user is automatically redirected to the same page with a +trailing slash attached.

  2. +
  3. If a rule does not end with a trailing slash and the user requests the +page with a trailing slash, a 404 not found is raised.

  4. +
+

This is consistent with how web servers deal with static files. This +also makes it possible to use relative link targets safely.

+

You can also define multiple rules for the same function. They have to be +unique however. Defaults can also be specified. Here for example is a +definition for a URL that accepts an optional page:

+
@app.route('/users/', defaults={'page': 1})
+@app.route('/users/page/<int:page>')
+def show_users(page):
+    pass
+
+
+

This specifies that /users/ will be the URL for page one and +/users/page/N will be the URL for page N.

+

If a URL contains a default value, it will be redirected to its simpler +form with a 301 redirect. In the above example, /users/page/1 will +be redirected to /users/. If your route handles GET and POST +requests, make sure the default route only handles GET, as redirects +can’t preserve form data.

+
@app.route('/region/', defaults={'id': 1})
+@app.route('/region/<int:id>', methods=['GET', 'POST'])
+def region(id):
+   pass
+
+
+

Here are the parameters that route() and +add_url_rule() accept. The only difference is that +with the route parameter the view function is defined with the decorator +instead of the view_func parameter.

+ + + + + + + + + + + + + + + + + + + + + +

rule

the URL rule as string

endpoint

the endpoint for the registered URL rule. Flask itself +assumes that the name of the view function is the name +of the endpoint if not explicitly stated.

view_func

the function to call when serving a request to the +provided endpoint. If this is not provided one can +specify the function later by storing it in the +view_functions dictionary with the +endpoint as key.

defaults

A dictionary with defaults for this rule. See the +example above for how defaults work.

subdomain

specifies the rule for the subdomain in case subdomain +matching is in use. If not specified the default +subdomain is assumed.

**options

the options to be forwarded to the underlying +Rule object. A change to +Werkzeug is handling of method options. methods is a list +of methods this rule should be limited to (GET, POST +etc.). By default a rule just listens for GET (and +implicitly HEAD). Starting with Flask 0.6, OPTIONS is +implicitly added and handled by the standard request +handling. They have to be specified as keyword arguments.

+
+
+

View Function Options

+

For internal usage the view functions can have some attributes attached to +customize behavior the view function would normally not have control over. +The following attributes can be provided optionally to either override +some defaults to add_url_rule() or general behavior:

+
    +
  • __name__: The name of a function is by default used as endpoint. If +endpoint is provided explicitly this value is used. Additionally this +will be prefixed with the name of the blueprint by default which +cannot be customized from the function itself.

  • +
  • methods: If methods are not provided when the URL rule is added, +Flask will look on the view function object itself if a methods +attribute exists. If it does, it will pull the information for the +methods from there.

  • +
  • provide_automatic_options: if this attribute is set Flask will +either force enable or disable the automatic implementation of the +HTTP OPTIONS response. This can be useful when working with +decorators that want to customize the OPTIONS response on a per-view +basis.

  • +
  • required_methods: if this attribute is set, Flask will always add +these methods when registering a URL rule even if the methods were +explicitly overridden in the route() call.

  • +
+

Full example:

+
def index():
+    if request.method == 'OPTIONS':
+        # custom options handling here
+        ...
+    return 'Hello World!'
+index.provide_automatic_options = False
+index.methods = ['GET', 'OPTIONS']
+
+app.add_url_rule('/', index)
+
+
+
+Changelog
+

Added in version 0.8: The provide_automatic_options functionality was added.

+
+
+
+

Command Line Interface

+
+
+class flask.cli.FlaskGroup(add_default_commands=True, create_app=None, add_version_option=True, load_dotenv=True, set_debug_flag=True, **extra)
+

Special subclass of the AppGroup group that supports +loading more commands from the configured Flask app. Normally a +developer does not have to interface with this class but there are +some very advanced use cases for which it makes sense to create an +instance of this. see Custom Scripts.

+
+
Parameters:
+
    +
  • add_default_commands (bool) – if this is True then the default run and +shell commands will be added.

  • +
  • add_version_option (bool) – adds the --version option.

  • +
  • create_app (t.Callable[..., Flask] | None) – an optional callback that is passed the script info and +returns the loaded app.

  • +
  • load_dotenv (bool) – Load the nearest .env and .flaskenv +files to set environment variables. Will also change the working +directory to the directory containing the first file found.

  • +
  • set_debug_flag (bool) – Set the app’s debug flag.

  • +
  • extra (t.Any)

  • +
+
+
+
+

Changed in version 3.1: -e path takes precedence over default .env and .flaskenv files.

+
+
+Changelog
+

Changed in version 2.2: Added the -A/--app, --debug/--no-debug, -e/--env-file options.

+
+
+

Changed in version 2.2: An app context is pushed when running app.cli commands, so +@with_appcontext is no longer required for those commands.

+
+
+

Changed in version 1.0: If installed, python-dotenv will be used to load environment variables +from .env and .flaskenv files.

+
+
+
+get_command(ctx, name)
+

Given a context and a command name, this returns a +Command object if it exists or returns None.

+
+
Parameters:
+
+
+
Return type:
+

Command | None

+
+
+
+ +
+
+list_commands(ctx)
+

Returns a list of subcommand names in the order they should +appear.

+
+
Parameters:
+

ctx (Context)

+
+
Return type:
+

list[str]

+
+
+
+ +
+
+make_context(info_name, args, parent=None, **extra)
+

This function when given an info name and arguments will kick +off the parsing and create a new Context. It does not +invoke the actual command callback though.

+

To quickly customize the context class used without overriding +this method, set the context_class attribute.

+
+
Parameters:
+
    +
  • info_name (str | None) – the info name for this invocation. Generally this +is the most descriptive name for the script or +command. For the toplevel script it’s usually +the name of the script, for commands below it’s +the name of the command.

  • +
  • args (list[str]) – the arguments to parse as list of strings.

  • +
  • parent (Context | None) – the parent context if available.

  • +
  • extra (Any) – extra keyword arguments forwarded to the context +constructor.

  • +
+
+
Return type:
+

Context

+
+
+
+

Changed in version 8.0: Added the context_class attribute.

+
+
+ +
+
+parse_args(ctx, args)
+

Given a context and a list of arguments this creates the parser +and parses the arguments, then modifies the context as necessary. +This is automatically invoked by make_context().

+
+
Parameters:
+
+
+
Return type:
+

list[str]

+
+
+
+ +
+ +
+
+class flask.cli.AppGroup(name=None, commands=None, **attrs)
+

This works similar to a regular click Group but it +changes the behavior of the command() decorator so that it +automatically wraps the functions in with_appcontext().

+

Not to be confused with FlaskGroup.

+
+
Parameters:
+
+
+
+
+
+command(*args, **kwargs)
+

This works exactly like the method of the same name on a regular +click.Group but it wraps callbacks in with_appcontext() +unless it’s disabled by passing with_appcontext=False.

+
+
Parameters:
+
+
+
Return type:
+

Callable[[Callable[[…], Any]], Command]

+
+
+
+ +
+
+group(*args, **kwargs)
+

This works exactly like the method of the same name on a regular +click.Group but it defaults the group class to +AppGroup.

+
+
Parameters:
+
+
+
Return type:
+

Callable[[Callable[[…], Any]], Group]

+
+
+
+ +
+ +
+
+class flask.cli.ScriptInfo(app_import_path=None, create_app=None, set_debug_flag=True, load_dotenv_defaults=True)
+

Helper object to deal with Flask applications. This is usually not +necessary to interface with as it’s used internally in the dispatching +to click. In future versions of Flask this object will most likely play +a bigger role. Typically it’s created automatically by the +FlaskGroup but you can also manually create it and pass it +onwards as click object.

+
+

Changed in version 3.1: Added the load_dotenv_defaults parameter and attribute.

+
+
+
Parameters:
+
    +
  • app_import_path (str | None)

  • +
  • create_app (t.Callable[..., Flask] | None)

  • +
  • set_debug_flag (bool)

  • +
  • load_dotenv_defaults (bool)

  • +
+
+
+
+
+app_import_path
+

Optionally the import path for the Flask application.

+
+ +
+
+create_app
+

Optionally a function that is passed the script info to create +the instance of the application.

+
+ +
+
+data: dict[t.Any, t.Any]
+

A dictionary with arbitrary data that can be associated with +this script info.

+
+ +
+
+load_dotenv_defaults
+

Whether default .flaskenv and .env files should be loaded.

+

ScriptInfo doesn’t load anything, this is for reference when doing +the load elsewhere during processing.

+
+

Added in version 3.1.

+
+
+ +
+
+load_app()
+

Loads the Flask app (if not yet loaded) and returns it. Calling +this multiple times will just result in the already loaded app to +be returned.

+
+
Return type:
+

Flask

+
+
+
+ +
+ +
+
+flask.cli.load_dotenv(path=None, load_defaults=True)
+

Load “dotenv” files to set environment variables. A given path takes +precedence over .env, which takes precedence over .flaskenv. After +loading and combining these files, values are only set if the key is not +already set in os.environ.

+

This is a no-op if python-dotenv is not installed.

+
+
Parameters:
+
    +
  • path (str | PathLike[str] | None) – Load the file at this location.

  • +
  • load_defaults (bool) – Search for and load the default .flaskenv and +.env files.

  • +
+
+
Returns:
+

True if at least one env var was loaded.

+
+
Return type:
+

bool

+
+
+
+

Changed in version 3.1: Added the load_defaults parameter. A given path takes precedence +over default files.

+
+
+Changelog
+

Changed in version 2.0: The current directory is not changed to the location of the +loaded file.

+
+
+

Changed in version 2.0: When loading the env files, set the default encoding to UTF-8.

+
+
+

Changed in version 1.1.0: Returns False when python-dotenv is not installed, or when +the given path isn’t a file.

+
+
+

Added in version 1.0.

+
+
+ +
+
+flask.cli.with_appcontext(f)
+

Wraps a callback so that it’s guaranteed to be executed with the +script’s application context.

+

Custom commands (and their options) registered under app.cli or +blueprint.cli will always have an app context available, this +decorator is not required in that case.

+
+Changelog
+

Changed in version 2.2: The app context is active for subcommands as well as the +decorated callback. The app context is always available to +app.cli command and parameter callbacks.

+
+
+
Parameters:
+

f (F)

+
+
Return type:
+

F

+
+
+
+ +
+
+flask.cli.pass_script_info(f)
+

Marks a function so that an instance of ScriptInfo is passed +as first argument to the click callback.

+
+
Parameters:
+

f (t.Callable[te.Concatenate[T, P], R])

+
+
Return type:
+

t.Callable[P, R]

+
+
+
+ +
+
+flask.cli.run_command = <Command run>
+

Run a local development server.

+

This server is for development purposes only. It does not provide +the stability, security, or performance of production WSGI servers.

+

The reloader and debugger are enabled by default with the ‘–debug’ +option.

+
+
Parameters:
+
+
+
Return type:
+

Any

+
+
+
+ +
+
+flask.cli.shell_command = <Command shell>
+

Run an interactive Python shell in the context of a given +Flask application. The application will populate the default +namespace of this shell according to its configuration.

+

This is useful for executing small snippets of management code +without having to manually configure the application.

+
+
Parameters:
+
+
+
Return type:
+

Any

+
+
+
+ +
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/appcontext/index.html b/_build/appcontext/index.html new file mode 100644 index 00000000..525d6e4c --- /dev/null +++ b/_build/appcontext/index.html @@ -0,0 +1,228 @@ + + + + + + + + The Application Context — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

The Application Context

+

The application context keeps track of the application-level data during +a request, CLI command, or other activity. Rather than passing the +application around to each function, the current_app and +g proxies are accessed instead.

+

This is similar to The Request Context, which keeps track of +request-level data during a request. A corresponding application context +is pushed when a request context is pushed.

+
+

Purpose of the Context

+

The Flask application object has attributes, such as +config, that are useful to access within views and +CLI commands. However, importing the app instance +within the modules in your project is prone to circular import issues. +When using the app factory pattern or +writing reusable blueprints or +extensions there won’t be an app instance to +import at all.

+

Flask solves this issue with the application context. Rather than +referring to an app directly, you use the current_app +proxy, which points to the application handling the current activity.

+

Flask automatically pushes an application context when handling a +request. View functions, error handlers, and other functions that run +during a request will have access to current_app.

+

Flask will also automatically push an app context when running CLI +commands registered with Flask.cli using @app.cli.command().

+
+
+

Lifetime of the Context

+

The application context is created and destroyed as necessary. When a +Flask application begins handling a request, it pushes an application +context and a request context. When the request +ends it pops the request context then the application context. +Typically, an application context will have the same lifetime as a +request.

+

See The Request Context for more information about how the contexts work +and the full life cycle of a request.

+
+
+

Manually Push a Context

+

If you try to access current_app, or anything that uses it, +outside an application context, you’ll get this error message:

+
RuntimeError: Working outside of application context.
+
+This typically means that you attempted to use functionality that
+needed to interface with the current application object in some way.
+To solve this, set up an application context with app.app_context().
+
+
+

If you see that error while configuring your application, such as when +initializing an extension, you can push a context manually since you +have direct access to the app. Use app_context() in a +with block, and everything that runs in the block will have access +to current_app.

+
def create_app():
+    app = Flask(__name__)
+
+    with app.app_context():
+        init_db()
+
+    return app
+
+
+

If you see that error somewhere else in your code not related to +configuring the application, it most likely indicates that you should +move that code into a view function or CLI command.

+
+
+

Storing Data

+

The application context is a good place to store common data during a +request or CLI command. Flask provides the g object for this +purpose. It is a simple namespace object that has the same lifetime as +an application context.

+
+

Note

+

The g name stands for “global”, but that is referring to the +data being global within a context. The data on g is lost +after the context ends, and it is not an appropriate place to store +data between requests. Use the session or a database to +store data across requests.

+
+

A common use for g is to manage resources during a request.

+
    +
  1. get_X() creates resource X if it does not exist, caching it +as g.X.

  2. +
  3. teardown_X() closes or otherwise deallocates the resource if it +exists. It is registered as a teardown_appcontext() +handler.

  4. +
+

For example, you can manage a database connection using this pattern:

+
from flask import g
+
+def get_db():
+    if 'db' not in g:
+        g.db = connect_to_database()
+
+    return g.db
+
+@app.teardown_appcontext
+def teardown_db(exception):
+    db = g.pop('db', None)
+
+    if db is not None:
+        db.close()
+
+
+

During a request, every call to get_db() will return the same +connection, and it will be closed automatically at the end of the +request.

+

You can use LocalProxy to make a new context +local from get_db():

+
from werkzeug.local import LocalProxy
+db = LocalProxy(get_db)
+
+
+

Accessing db will call get_db internally, in the same way that +current_app works.

+
+
+

Events and Signals

+

The application will call functions registered with teardown_appcontext() +when the application context is popped.

+

The following signals are sent: appcontext_pushed, +appcontext_tearing_down, and appcontext_popped.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/async-await/index.html b/_build/async-await/index.html new file mode 100644 index 00000000..04184507 --- /dev/null +++ b/_build/async-await/index.html @@ -0,0 +1,204 @@ + + + + + + + + Using async and await — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Using async and await

+
+Changelog
+

Added in version 2.0.

+
+

Routes, error handlers, before request, after request, and teardown +functions can all be coroutine functions if Flask is installed with the +async extra (pip install flask[async]). This allows views to be +defined with async def and use await.

+
@app.route("/get-data")
+async def get_data():
+    data = await async_db_query(...)
+    return jsonify(data)
+
+
+

Pluggable class-based views also support handlers that are implemented as +coroutines. This applies to the dispatch_request() +method in views that inherit from the flask.views.View class, as +well as all the HTTP method handlers in views that inherit from the +flask.views.MethodView class.

+
+

Using async with greenlet

+

When using gevent or eventlet to serve an application or patch the +runtime, greenlet>=1.0 is required. When using PyPy, PyPy>=7.3.7 is +required.

+
+
+

Performance

+

Async functions require an event loop to run. Flask, as a WSGI +application, uses one worker to handle one request/response cycle. +When a request comes in to an async view, Flask will start an event loop +in a thread, run the view function there, then return the result.

+

Each request still ties up one worker, even for async views. The upside +is that you can run async code within a view, for example to make +multiple concurrent database queries, HTTP requests to an external API, +etc. However, the number of requests your application can handle at one +time will remain the same.

+

Async is not inherently faster than sync code. Async is beneficial +when performing concurrent IO-bound tasks, but will probably not improve +CPU-bound tasks. Traditional Flask views will still be appropriate for +most use cases, but Flask’s async support enables writing and using +code that wasn’t possible natively before.

+
+
+

Background tasks

+

Async functions will run in an event loop until they complete, at +which stage the event loop will stop. This means any additional +spawned tasks that haven’t completed when the async function completes +will be cancelled. Therefore you cannot spawn background tasks, for +example via asyncio.create_task.

+

If you wish to use background tasks it is best to use a task queue to +trigger background work, rather than spawn tasks in a view +function. With that in mind you can spawn asyncio tasks by serving +Flask with an ASGI server and utilising the asgiref WsgiToAsgi adapter +as described in ASGI. This works as the adapter creates +an event loop that runs continually.

+
+
+

When to use Quart instead

+

Flask’s async support is less performant than async-first frameworks due +to the way it is implemented. If you have a mainly async codebase it +would make sense to consider Quart. Quart is a reimplementation of +Flask based on the ASGI standard instead of WSGI. This allows it to +handle many concurrent requests, long running requests, and websockets +without requiring multiple worker processes or threads.

+

It has also already been possible to run Flask with Gevent or Eventlet +to get many of the benefits of async request handling. These libraries +patch low-level Python functions to accomplish this, whereas async/ +await and ASGI use standard, modern Python capabilities. Deciding +whether you should use Flask, Quart, or something else is ultimately up +to understanding the specific needs of your project.

+
+
+

Extensions

+

Flask extensions predating Flask’s async support do not expect async views. +If they provide decorators to add functionality to views, those will probably +not work with async views because they will not await the function or be +awaitable. Other functions they provide will not be awaitable either and +will probably be blocking if called within an async view.

+

Extension authors can support async functions by utilising the +flask.Flask.ensure_sync() method. For example, if the extension +provides a view function decorator add ensure_sync before calling +the decorated function,

+
def extension(func):
+    @wraps(func)
+    def wrapper(*args, **kwargs):
+        ...  # Extension logic
+        return current_app.ensure_sync(func)(*args, **kwargs)
+
+    return wrapper
+
+
+

Check the changelog of the extension you want to use to see if they’ve +implemented async support, or make a feature request or PR to them.

+
+
+

Other event loops

+

At the moment Flask only supports asyncio. It’s possible to +override flask.Flask.ensure_sync() to change how async functions +are wrapped to use a different library.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/blueprints/index.html b/_build/blueprints/index.html new file mode 100644 index 00000000..0439f5a1 --- /dev/null +++ b/_build/blueprints/index.html @@ -0,0 +1,397 @@ + + + + + + + + Modular Applications with Blueprints — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Modular Applications with Blueprints

+
+Changelog
+

Added in version 0.7.

+
+

Flask uses a concept of blueprints for making application components and +supporting common patterns within an application or across applications. +Blueprints can greatly simplify how large applications work and provide a +central means for Flask extensions to register operations on applications. +A Blueprint object works similarly to a Flask +application object, but it is not actually an application. Rather it is a +blueprint of how to construct or extend an application.

+
+

Why Blueprints?

+

Blueprints in Flask are intended for these cases:

+
    +
  • Factor an application into a set of blueprints. This is ideal for +larger applications; a project could instantiate an application object, +initialize several extensions, and register a collection of blueprints.

  • +
  • Register a blueprint on an application at a URL prefix and/or subdomain. +Parameters in the URL prefix/subdomain become common view arguments +(with defaults) across all view functions in the blueprint.

  • +
  • Register a blueprint multiple times on an application with different URL +rules.

  • +
  • Provide template filters, static files, templates, and other utilities +through blueprints. A blueprint does not have to implement applications +or view functions.

  • +
  • Register a blueprint on an application for any of these cases when +initializing a Flask extension.

  • +
+

A blueprint in Flask is not a pluggable app because it is not actually an +application – it’s a set of operations which can be registered on an +application, even multiple times. Why not have multiple application +objects? You can do that (see Application Dispatching), but your +applications will have separate configs and will be managed at the WSGI +layer.

+

Blueprints instead provide separation at the Flask level, share +application config, and can change an application object as necessary with +being registered. The downside is that you cannot unregister a blueprint +once an application was created without having to destroy the whole +application object.

+
+
+

The Concept of Blueprints

+

The basic concept of blueprints is that they record operations to execute +when registered on an application. Flask associates view functions with +blueprints when dispatching requests and generating URLs from one endpoint +to another.

+
+
+

My First Blueprint

+

This is what a very basic blueprint looks like. In this case we want to +implement a blueprint that does simple rendering of static templates:

+
from flask import Blueprint, render_template, abort
+from jinja2 import TemplateNotFound
+
+simple_page = Blueprint('simple_page', __name__,
+                        template_folder='templates')
+
+@simple_page.route('/', defaults={'page': 'index'})
+@simple_page.route('/<page>')
+def show(page):
+    try:
+        return render_template(f'pages/{page}.html')
+    except TemplateNotFound:
+        abort(404)
+
+
+

When you bind a function with the help of the @simple_page.route +decorator, the blueprint will record the intention of registering the +function show on the application when it’s later registered. +Additionally it will prefix the endpoint of the function with the +name of the blueprint which was given to the Blueprint +constructor (in this case also simple_page). The blueprint’s name +does not modify the URL, only the endpoint.

+
+
+

Registering Blueprints

+

So how do you register that blueprint? Like this:

+
from flask import Flask
+from yourapplication.simple_page import simple_page
+
+app = Flask(__name__)
+app.register_blueprint(simple_page)
+
+
+

If you check the rules registered on the application, you will find +these:

+
>>> app.url_map
+Map([<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>,
+ <Rule '/<page>' (HEAD, OPTIONS, GET) -> simple_page.show>,
+ <Rule '/' (HEAD, OPTIONS, GET) -> simple_page.show>])
+
+
+

The first one is obviously from the application itself for the static +files. The other two are for the show function of the simple_page +blueprint. As you can see, they are also prefixed with the name of the +blueprint and separated by a dot (.).

+

Blueprints however can also be mounted at different locations:

+
app.register_blueprint(simple_page, url_prefix='/pages')
+
+
+

And sure enough, these are the generated rules:

+
>>> app.url_map
+Map([<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>,
+ <Rule '/pages/<page>' (HEAD, OPTIONS, GET) -> simple_page.show>,
+ <Rule '/pages/' (HEAD, OPTIONS, GET) -> simple_page.show>])
+
+
+

On top of that you can register blueprints multiple times though not every +blueprint might respond properly to that. In fact it depends on how the +blueprint is implemented if it can be mounted more than once.

+
+
+

Nesting Blueprints

+

It is possible to register a blueprint on another blueprint.

+
parent = Blueprint('parent', __name__, url_prefix='/parent')
+child = Blueprint('child', __name__, url_prefix='/child')
+parent.register_blueprint(child)
+app.register_blueprint(parent)
+
+
+

The child blueprint will gain the parent’s name as a prefix to its +name, and child URLs will be prefixed with the parent’s URL prefix.

+
url_for('parent.child.create')
+/parent/child/create
+
+
+

In addition a child blueprint’s will gain their parent’s subdomain, +with their subdomain as prefix if present i.e.

+
parent = Blueprint('parent', __name__, subdomain='parent')
+child = Blueprint('child', __name__, subdomain='child')
+parent.register_blueprint(child)
+app.register_blueprint(parent)
+
+url_for('parent.child.create', _external=True)
+"child.parent.domain.tld"
+
+
+

Blueprint-specific before request functions, etc. registered with the +parent will trigger for the child. If a child does not have an error +handler that can handle a given exception, the parent’s will be tried.

+
+
+

Blueprint Resources

+

Blueprints can provide resources as well. Sometimes you might want to +introduce a blueprint only for the resources it provides.

+
+

Blueprint Resource Folder

+

Like for regular applications, blueprints are considered to be contained +in a folder. While multiple blueprints can originate from the same folder, +it does not have to be the case and it’s usually not recommended.

+

The folder is inferred from the second argument to Blueprint which +is usually __name__. This argument specifies what logical Python +module or package corresponds to the blueprint. If it points to an actual +Python package that package (which is a folder on the filesystem) is the +resource folder. If it’s a module, the package the module is contained in +will be the resource folder. You can access the +Blueprint.root_path property to see what the resource folder is:

+
>>> simple_page.root_path
+'/Users/username/TestProject/yourapplication'
+
+
+

To quickly open sources from this folder you can use the +open_resource() function:

+
with simple_page.open_resource('static/style.css') as f:
+    code = f.read()
+
+
+
+
+

Static Files

+

A blueprint can expose a folder with static files by providing the path +to the folder on the filesystem with the static_folder argument. +It is either an absolute path or relative to the blueprint’s location:

+
admin = Blueprint('admin', __name__, static_folder='static')
+
+
+

By default the rightmost part of the path is where it is exposed on the +web. This can be changed with the static_url_path argument. Because the +folder is called static here it will be available at the +url_prefix of the blueprint + /static. If the blueprint +has the prefix /admin, the static URL will be /admin/static.

+

The endpoint is named blueprint_name.static. You can generate URLs +to it with url_for() like you would with the static folder of the +application:

+
url_for('admin.static', filename='style.css')
+
+
+

However, if the blueprint does not have a url_prefix, it is not +possible to access the blueprint’s static folder. This is because the +URL would be /static in this case, and the application’s /static +route takes precedence. Unlike template folders, blueprint static +folders are not searched if the file does not exist in the application +static folder.

+
+
+

Templates

+

If you want the blueprint to expose templates you can do that by providing +the template_folder parameter to the Blueprint constructor:

+
admin = Blueprint('admin', __name__, template_folder='templates')
+
+
+

For static files, the path can be absolute or relative to the blueprint +resource folder.

+

The template folder is added to the search path of templates but with a lower +priority than the actual application’s template folder. That way you can +easily override templates that a blueprint provides in the actual application. +This also means that if you don’t want a blueprint template to be accidentally +overridden, make sure that no other blueprint or actual application template +has the same relative path. When multiple blueprints provide the same relative +template path the first blueprint registered takes precedence over the others.

+

So if you have a blueprint in the folder yourapplication/admin and you +want to render the template 'admin/index.html' and you have provided +templates as a template_folder you will have to create a file like +this: yourapplication/admin/templates/admin/index.html. The reason +for the extra admin folder is to avoid getting our template overridden +by a template named index.html in the actual application template +folder.

+

To further reiterate this: if you have a blueprint named admin and you +want to render a template called index.html which is specific to this +blueprint, the best idea is to lay out your templates like this:

+
yourpackage/
+    blueprints/
+        admin/
+            templates/
+                admin/
+                    index.html
+            __init__.py
+
+
+

And then when you want to render the template, use admin/index.html as +the name to look up the template by. If you encounter problems loading +the correct templates enable the EXPLAIN_TEMPLATE_LOADING config +variable which will instruct Flask to print out the steps it goes through +to locate templates on every render_template call.

+
+
+
+

Building URLs

+

If you want to link from one page to another you can use the +url_for() function just like you normally would do just that you +prefix the URL endpoint with the name of the blueprint and a dot (.):

+
url_for('admin.index')
+
+
+

Additionally if you are in a view function of a blueprint or a rendered +template and you want to link to another endpoint of the same blueprint, +you can use relative redirects by prefixing the endpoint with a dot only:

+
url_for('.index')
+
+
+

This will link to admin.index for instance in case the current request +was dispatched to any other admin blueprint endpoint.

+
+
+

Blueprint Error Handlers

+

Blueprints support the errorhandler decorator just like the Flask +application object, so it is easy to make Blueprint-specific custom error +pages.

+

Here is an example for a “404 Page Not Found” exception:

+
@simple_page.errorhandler(404)
+def page_not_found(e):
+    return render_template('pages/404.html')
+
+
+

Most errorhandlers will simply work as expected; however, there is a caveat +concerning handlers for 404 and 405 exceptions. These errorhandlers are only +invoked from an appropriate raise statement or a call to abort in another +of the blueprint’s view functions; they are not invoked by, e.g., an invalid URL +access. This is because the blueprint does not “own” a certain URL space, so +the application instance has no way of knowing which blueprint error handler it +should run if given an invalid URL. If you would like to execute different +handling strategies for these errors based on URL prefixes, they may be defined +at the application level using the request proxy object:

+
@app.errorhandler(404)
+@app.errorhandler(405)
+def _handle_api_error(ex):
+    if request.path.startswith('/api/'):
+        return jsonify(error=str(ex)), ex.code
+    else:
+        return ex
+
+
+

See Handling Application Errors.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/changes/index.html b/_build/changes/index.html new file mode 100644 index 00000000..617bcce5 --- /dev/null +++ b/_build/changes/index.html @@ -0,0 +1,1711 @@ + + + + + + + + Changes — Flask Documentation (3.1.x) + + + + + + + + + + + + + +
+
+
+
+ +
+

Changes

+
+

Version 3.1.1

+

Unreleased

+
    +
  • Fix type hint for cli_runner.invoke. #5645

  • +
+
+
+

Version 3.1.0

+

Released 2024-11-13

+
    +
  • Drop support for Python 3.8. #5623

  • +
  • Update minimum dependency versions to latest feature releases. +Werkzeug >= 3.1, ItsDangerous >= 2.2, Blinker >= 1.9. #5624,5633

  • +
  • Provide a configuration option to control automatic option +responses. #5496

  • +
  • Flask.open_resource/open_instance_resource and +Blueprint.open_resource take an encoding parameter to use when +opening in text mode. It defaults to utf-8. #5504

  • +
  • Request.max_content_length can be customized per-request instead of only +through the MAX_CONTENT_LENGTH config. Added +MAX_FORM_MEMORY_SIZE and MAX_FORM_PARTS config. Added documentation +about resource limits to the security page. #5625

  • +
  • Add support for the Partitioned cookie attribute (CHIPS), with the +SESSION_COOKIE_PARTITIONED config. #5472

  • +
  • -e path takes precedence over default .env and .flaskenv files. +load_dotenv loads default files in addition to a path unless +load_defaults=False is passed. #5628

  • +
  • Support key rotation with the SECRET_KEY_FALLBACKS config, a list of old +secret keys that can still be used for unsigning. Extensions will need to +add support. #5621

  • +
  • Fix how setting host_matching=True or subdomain_matching=False +interacts with SERVER_NAME. Setting SERVER_NAME no longer restricts +requests to only that domain. #5553

  • +
  • Request.trusted_hosts is checked during routing, and can be set through +the TRUSTED_HOSTS config. #5636

  • +
+
+
+

Version 3.0.3

+

Released 2024-04-07

+
    +
  • The default hashlib.sha1 may not be available in FIPS builds. Don’t +access it at import time so the developer has time to change the default. +#5448

  • +
  • Don’t initialize the cli attribute in the sansio scaffold, but rather in +the Flask concrete class. #5270

  • +
+
+
+

Version 3.0.2

+

Released 2024-02-03

+
    +
  • Correct type for jinja_loader property. #5388

  • +
  • Fix error with --extra-files and --exclude-patterns CLI options. +#5391

  • +
+
+
+

Version 3.0.1

+

Released 2024-01-18

+
    +
  • Correct type for path argument to send_file. #5336

  • +
  • Fix a typo in an error message for the flask run --key option. #5344

  • +
  • Session data is untagged without relying on the built-in json.loads +object_hook. This allows other JSON providers that don’t implement that. +#5381

  • +
  • Address more type findings when using mypy strict mode. #5383

  • +
+
+
+

Version 3.0.0

+

Released 2023-09-30

+
    +
  • Remove previously deprecated code. #5223

  • +
  • Deprecate the __version__ attribute. Use feature detection, or +importlib.metadata.version("flask"), instead. #5230

  • +
  • Restructure the code such that the Flask (app) and Blueprint +classes have Sans-IO bases. #5127

  • +
  • Allow self as an argument to url_for. #5264

  • +
  • Require Werkzeug >= 3.0.0.

  • +
+
+
+

Version 2.3.3

+

Released 2023-08-21

+
    +
  • Python 3.12 compatibility.

  • +
  • Require Werkzeug >= 2.3.7.

  • +
  • Use flit_core instead of setuptools as build backend.

  • +
  • Refactor how an app’s root and instance paths are determined. #5160

  • +
+
+
+

Version 2.3.2

+

Released 2023-05-01

+
    +
  • Set Vary: Cookie header when the session is accessed, modified, or refreshed.

  • +
  • Update Werkzeug requirement to >=2.3.3 to apply recent bug fixes.

  • +
+
+
+

Version 2.3.1

+

Released 2023-04-25

+
    +
  • Restore deprecated from flask import Markup. #5084

  • +
+
+
+

Version 2.3.0

+

Released 2023-04-25

+
    +
  • Drop support for Python 3.7. #5072

  • +
  • Update minimum requirements to the latest versions: Werkzeug>=2.3.0, Jinja2>3.1.2, +itsdangerous>=2.1.2, click>=8.1.3.

  • +
  • Remove previously deprecated code. #4995

    +
      +
    • The push and pop methods of the deprecated _app_ctx_stack and +_request_ctx_stack objects are removed. top still exists to give +extensions more time to update, but it will be removed.

    • +
    • The FLASK_ENV environment variable, ENV config key, and app.env +property are removed.

    • +
    • The session_cookie_name, send_file_max_age_default, use_x_sendfile, +propagate_exceptions, and templates_auto_reload properties on app +are removed.

    • +
    • The JSON_AS_ASCII, JSON_SORT_KEYS, JSONIFY_MIMETYPE, and +JSONIFY_PRETTYPRINT_REGULAR config keys are removed.

    • +
    • The app.before_first_request and bp.before_app_first_request decorators +are removed.

    • +
    • json_encoder and json_decoder attributes on app and blueprint, and the +corresponding json.JSONEncoder and JSONDecoder classes, are removed.

    • +
    • The json.htmlsafe_dumps and htmlsafe_dump functions are removed.

    • +
    • Calling setup methods on blueprints after registration is an error instead of a +warning. #4997

    • +
    +
  • +
  • Importing escape and Markup from flask is deprecated. Import them +directly from markupsafe instead. #4996

  • +
  • The app.got_first_request property is deprecated. #4997

  • +
  • The locked_cached_property decorator is deprecated. Use a lock inside the +decorated function if locking is needed. #4993

  • +
  • Signals are always available. blinker>=1.6.2 is a required dependency. The +signals_available attribute is deprecated. #5056

  • +
  • Signals support async subscriber functions. #5049

  • +
  • Remove uses of locks that could cause requests to block each other very briefly. +#4993

  • +
  • Use modern packaging metadata with pyproject.toml instead of setup.cfg. +#4947

  • +
  • Ensure subdomains are applied with nested blueprints. #4834

  • +
  • config.from_file can use text=False to indicate that the parser wants a +binary file instead. #4989

  • +
  • If a blueprint is created with an empty name it raises a ValueError. +#5010

  • +
  • SESSION_COOKIE_DOMAIN does not fall back to SERVER_NAME. The default is not +to set the domain, which modern browsers interpret as an exact match rather than +a subdomain match. Warnings about localhost and IP addresses are also removed. +#5051

  • +
  • The routes command shows each rule’s subdomain or host when domain +matching is in use. #5004

  • +
  • Use postponed evaluation of annotations. #5071

  • +
+
+
+

Version 2.2.5

+

Released 2023-05-02

+
    +
  • Update for compatibility with Werkzeug 2.3.3.

  • +
  • Set Vary: Cookie header when the session is accessed, modified, or refreshed.

  • +
+
+
+

Version 2.2.4

+

Released 2023-04-25

+
    +
  • Update for compatibility with Werkzeug 2.3.

  • +
+
+
+

Version 2.2.3

+

Released 2023-02-15

+
    +
  • Autoescape is enabled by default for .svg template files. #4831

  • +
  • Fix the type of template_folder to accept pathlib.Path. #4892

  • +
  • Add --debug option to the flask run command. #4777

  • +
+
+
+

Version 2.2.2

+

Released 2022-08-08

+
    +
  • Update Werkzeug dependency to >= 2.2.2. This includes fixes related +to the new faster router, header parsing, and the development +server. #4754

  • +
  • Fix the default value for app.env to be "production". This +attribute remains deprecated. #4740

  • +
+
+
+

Version 2.2.1

+

Released 2022-08-03

+
    +
  • Setting or accessing json_encoder or json_decoder raises a +deprecation warning. #4732

  • +
+
+
+

Version 2.2.0

+

Released 2022-08-01

+
    +
  • Remove previously deprecated code. #4667

    +
      +
    • Old names for some send_file parameters have been removed. +download_name replaces attachment_filename, max_age +replaces cache_timeout, and etag replaces add_etags. +Additionally, path replaces filename in +send_from_directory.

    • +
    • The RequestContext.g property returning AppContext.g is +removed.

    • +
    +
  • +
  • Update Werkzeug dependency to >= 2.2.

  • +
  • The app and request contexts are managed using Python context vars +directly rather than Werkzeug’s LocalStack. This should result +in better performance and memory use. #4682

    +
      +
    • Extension maintainers, be aware that _app_ctx_stack.top +and _request_ctx_stack.top are deprecated. Store data on +g instead using a unique prefix, like +g._extension_name_attr.

    • +
    +
  • +
  • The FLASK_ENV environment variable and app.env attribute are +deprecated, removing the distinction between development and debug +mode. Debug mode should be controlled directly using the --debug +option or app.run(debug=True). #4714

  • +
  • Some attributes that proxied config keys on app are deprecated: +session_cookie_name, send_file_max_age_default, +use_x_sendfile, propagate_exceptions, and +templates_auto_reload. Use the relevant config keys instead. +#4716

  • +
  • Add new customization points to the Flask app object for many +previously global behaviors.

    +
      +
    • flask.url_for will call app.url_for. #4568

    • +
    • flask.abort will call app.aborter. +Flask.aborter_class and Flask.make_aborter can be used +to customize this aborter. #4567

    • +
    • flask.redirect will call app.redirect. #4569

    • +
    • flask.json is an instance of JSONProvider. A different +provider can be set to use a different JSON library. +flask.jsonify will call app.json.response, other +functions in flask.json will call corresponding functions in +app.json. #4692

    • +
    +
  • +
  • JSON configuration is moved to attributes on the default +app.json provider. JSON_AS_ASCII, JSON_SORT_KEYS, +JSONIFY_MIMETYPE, and JSONIFY_PRETTYPRINT_REGULAR are +deprecated. #4692

  • +
  • Setting custom json_encoder and json_decoder classes on the +app or a blueprint, and the corresponding json.JSONEncoder and +JSONDecoder classes, are deprecated. JSON behavior can now be +overridden using the app.json provider interface. #4692

  • +
  • json.htmlsafe_dumps and json.htmlsafe_dump are deprecated, +the function is built-in to Jinja now. #4692

  • +
  • Refactor register_error_handler to consolidate error checking. +Rewrite some error messages to be more consistent. #4559

  • +
  • Use Blueprint decorators and functions intended for setup after +registering the blueprint will show a warning. In the next version, +this will become an error just like the application setup methods. +#4571

  • +
  • before_first_request is deprecated. Run setup code when creating +the application instead. #4605

  • +
  • Added the View.init_every_request class attribute. If a view +subclass sets this to False, the view will not create a new +instance on every request. #2520.

  • +
  • A flask.cli.FlaskGroup Click group can be nested as a +sub-command in a custom CLI. #3263

  • +
  • Add --app and --debug options to the flask CLI, instead +of requiring that they are set through environment variables. +#2836

  • +
  • Add --env-file option to the flask CLI. This allows +specifying a dotenv file to load in addition to .env and +.flaskenv. #3108

  • +
  • It is no longer required to decorate custom CLI commands on +app.cli or blueprint.cli with @with_appcontext, an app +context will already be active at that point. #2410

  • +
  • SessionInterface.get_expiration_time uses a timezone-aware +value. #4645

  • +
  • View functions can return generators directly instead of wrapping +them in a Response. #4629

  • +
  • Add stream_template and stream_template_string functions to +render a template as a stream of pieces. #4629

  • +
  • A new implementation of context preservation during debugging and +testing. #4666

    +
      +
    • request, g, and other context-locals point to the +correct data when running code in the interactive debugger +console. #2836

    • +
    • Teardown functions are always run at the end of the request, +even if the context is preserved. They are also run after the +preserved context is popped.

    • +
    • stream_with_context preserves context separately from a +with client block. It will be cleaned up when +response.get_data() or response.close() is called.

    • +
    +
  • +
  • Allow returning a list from a view function, to convert it to a +JSON response like a dict is. #4672

  • +
  • When type checking, allow TypedDict to be returned from view +functions. #4695

  • +
  • Remove the --eager-loading/--lazy-loading options from the +flask run command. The app is always eager loaded the first +time, then lazily loaded in the reloader. The reloader always prints +errors immediately but continues serving. Remove the internal +DispatchingApp middleware used by the previous implementation. +#4715

  • +
+
+
+

Version 2.1.3

+

Released 2022-07-13

+
    +
  • Inline some optional imports that are only used for certain CLI +commands. #4606

  • +
  • Relax type annotation for after_request functions. #4600

  • +
  • instance_path for namespace packages uses the path closest to +the imported submodule. #4610

  • +
  • Clearer error message when render_template and +render_template_string are used outside an application context. +#4693

  • +
+
+
+

Version 2.1.2

+

Released 2022-04-28

+
    +
  • Fix type annotation for json.loads, it accepts str or bytes. +#4519

  • +
  • The --cert and --key options on flask run can be given +in either order. #4459

  • +
+
+
+

Version 2.1.1

+

Released on 2022-03-30

+
    +
  • Set the minimum required version of importlib_metadata to 3.6.0, +which is required on Python < 3.10. #4502

  • +
+
+
+

Version 2.1.0

+

Released 2022-03-28

+
    +
  • Drop support for Python 3.6. #4335

  • +
  • Update Click dependency to >= 8.0. #4008

  • +
  • Remove previously deprecated code. #4337

    +
      +
    • The CLI does not pass script_info to app factory functions.

    • +
    • config.from_json is replaced by +config.from_file(name, load=json.load).

    • +
    • json functions no longer take an encoding parameter.

    • +
    • safe_join is removed, use werkzeug.utils.safe_join +instead.

    • +
    • total_seconds is removed, use timedelta.total_seconds +instead.

    • +
    • The same blueprint cannot be registered with the same name. Use +name= when registering to specify a unique name.

    • +
    • The test client’s as_tuple parameter is removed. Use +response.request.environ instead. #4417

    • +
    +
  • +
  • Some parameters in send_file and send_from_directory were +renamed in 2.0. The deprecation period for the old names is extended +to 2.2. Be sure to test with deprecation warnings visible.

    +
      +
    • attachment_filename is renamed to download_name.

    • +
    • cache_timeout is renamed to max_age.

    • +
    • add_etags is renamed to etag.

    • +
    • filename is renamed to path.

    • +
    +
  • +
  • The RequestContext.g property is deprecated. Use g directly +or AppContext.g instead. #3898

  • +
  • copy_current_request_context can decorate async functions. +#4303

  • +
  • The CLI uses importlib.metadata instead of pkg_resources to +load command entry points. #4419

  • +
  • Overriding FlaskClient.open will not cause an error on redirect. +#3396

  • +
  • Add an --exclude-patterns option to the flask run CLI +command to specify patterns that will be ignored by the reloader. +#4188

  • +
  • When using lazy loading (the default with the debugger), the Click +context from the flask run command remains available in the +loader thread. #4460

  • +
  • Deleting the session cookie uses the httponly flag. +#4485

  • +
  • Relax typing for errorhandler to allow the user to use more +precise types and decorate the same function multiple times. +#4095, 4295, 4297

  • +
  • Fix typing for __exit__ methods for better compatibility with +ExitStack. #4474

  • +
  • From Werkzeug, for redirect responses the Location header URL +will remain relative, and exclude the scheme and domain, by default. +#4496

  • +
  • Add Config.from_prefixed_env() to load config values from +environment variables that start with FLASK_ or another prefix. +This parses values as JSON by default, and allows setting keys in +nested dicts. #4479

  • +
+
+
+

Version 2.0.3

+

Released 2022-02-14

+
    +
  • The test client’s as_tuple parameter is deprecated and will be +removed in Werkzeug 2.1. It is now also deprecated in Flask, to be +removed in Flask 2.1, while remaining compatible with both in +2.0.x. Use response.request.environ instead. #4341

  • +
  • Fix type annotation for errorhandler decorator. #4295

  • +
  • Revert a change to the CLI that caused it to hide ImportError +tracebacks when importing the application. #4307

  • +
  • app.json_encoder and json_decoder are only passed to +dumps and loads if they have custom behavior. This improves +performance, mainly on PyPy. #4349

  • +
  • Clearer error message when after_this_request is used outside a +request context. #4333

  • +
+
+
+

Version 2.0.2

+

Released 2021-10-04

+
    +
  • Fix type annotation for teardown_* methods. #4093

  • +
  • Fix type annotation for before_request and before_app_request +decorators. #4104

  • +
  • Fixed the issue where typing requires template global +decorators to accept functions with no arguments. #4098

  • +
  • Support View and MethodView instances with async handlers. #4112

  • +
  • Enhance typing of app.errorhandler decorator. #4095

  • +
  • Fix registering a blueprint twice with differing names. #4124

  • +
  • Fix the type of static_folder to accept pathlib.Path. +#4150

  • +
  • jsonify handles decimal.Decimal by encoding to str. +#4157

  • +
  • Correctly handle raising deferred errors in CLI lazy loading. +#4096

  • +
  • The CLI loader handles **kwargs in a create_app function. +#4170

  • +
  • Fix the order of before_request and other callbacks that trigger +before the view returns. They are called from the app down to the +closest nested blueprint. #4229

  • +
+
+
+

Version 2.0.1

+

Released 2021-05-21

+
    +
  • Re-add the filename parameter in send_from_directory. The +filename parameter has been renamed to path, the old name +is deprecated. #4019

  • +
  • Mark top-level names as exported so type checking understands +imports in user projects. #4024

  • +
  • Fix type annotation for g and inform mypy that it is a namespace +object that has arbitrary attributes. #4020

  • +
  • Fix some types that weren’t available in Python 3.6.0. #4040

  • +
  • Improve typing for send_file, send_from_directory, and +get_send_file_max_age. #4044, #4026

  • +
  • Show an error when a blueprint name contains a dot. The . has +special meaning, it is used to separate (nested) blueprint names and +the endpoint name. #4041

  • +
  • Combine URL prefixes when nesting blueprints that were created with +a url_prefix value. #4037

  • +
  • Revert a change to the order that URL matching was done. The +URL is again matched after the session is loaded, so the session is +available in custom URL converters. #4053

  • +
  • Re-add deprecated Config.from_json, which was accidentally +removed early. #4078

  • +
  • Improve typing for some functions using Callable in their type +signatures, focusing on decorator factories. #4060

  • +
  • Nested blueprints are registered with their dotted name. This allows +different blueprints with the same name to be nested at different +locations. #4069

  • +
  • register_blueprint takes a name option to change the +(pre-dotted) name the blueprint is registered with. This allows the +same blueprint to be registered multiple times with unique names for +url_for. Registering the same blueprint with the same name +multiple times is deprecated. #1091

  • +
  • Improve typing for stream_with_context. #4052

  • +
+
+
+

Version 2.0.0

+

Released 2021-05-11

+
    +
  • Drop support for Python 2 and 3.5.

  • +
  • Bump minimum versions of other Pallets projects: Werkzeug >= 2, +Jinja2 >= 3, MarkupSafe >= 2, ItsDangerous >= 2, Click >= 8. Be sure +to check the change logs for each project. For better compatibility +with other applications (e.g. Celery) that still require Click 7, +there is no hard dependency on Click 8 yet, but using Click 7 will +trigger a DeprecationWarning and Flask 2.1 will depend on Click 8.

  • +
  • JSON support no longer uses simplejson. To use another JSON module, +override app.json_encoder and json_decoder. #3555

  • +
  • The encoding option to JSON functions is deprecated. #3562

  • +
  • Passing script_info to app factory functions is deprecated. This +was not portable outside the flask command. Use +click.get_current_context().obj if it’s needed. #3552

  • +
  • The CLI shows better error messages when the app failed to load +when looking up commands. #2741

  • +
  • Add SessionInterface.get_cookie_name to allow setting the +session cookie name dynamically. #3369

  • +
  • Add Config.from_file to load config using arbitrary file +loaders, such as toml.load or json.load. +Config.from_json is deprecated in favor of this. #3398

  • +
  • The flask run command will only defer errors on reload. Errors +present during the initial call will cause the server to exit with +the traceback immediately. #3431

  • +
  • send_file raises a ValueError when passed an io object +in text mode. Previously, it would respond with 200 OK and an empty +file. #3358

  • +
  • When using ad-hoc certificates, check for the cryptography library +instead of PyOpenSSL. #3492

  • +
  • When specifying a factory function with FLASK_APP, keyword +argument can be passed. #3553

  • +
  • When loading a .env or .flaskenv file, the current working +directory is no longer changed to the location of the file. +#3560

  • +
  • When returning a (response, headers) tuple from a view, the +headers replace rather than extend existing headers on the response. +For example, this allows setting the Content-Type for +jsonify(). Use response.headers.extend() if extending is +desired. #3628

  • +
  • The Scaffold class provides a common API for the Flask and +Blueprint classes. Blueprint information is stored in +attributes just like Flask, rather than opaque lambda functions. +This is intended to improve consistency and maintainability. +#3215

  • +
  • Include samesite and secure options when removing the +session cookie. #3726

  • +
  • Support passing a pathlib.Path to static_folder. #3579

  • +
  • send_file and send_from_directory are wrappers around the +implementations in werkzeug.utils. #3828

  • +
  • Some send_file parameters have been renamed, the old names are +deprecated. attachment_filename is renamed to download_name. +cache_timeout is renamed to max_age. add_etags is +renamed to etag. #3828, 3883

  • +
  • send_file passes download_name even if +as_attachment=False by using Content-Disposition: inline. +#3828

  • +
  • send_file sets conditional=True and max_age=None by +default. Cache-Control is set to no-cache if max_age is +not set, otherwise public. This tells browsers to validate +conditional requests instead of using a timed cache. #3828

  • +
  • helpers.safe_join is deprecated. Use +werkzeug.utils.safe_join instead. #3828

  • +
  • The request context does route matching before opening the session. +This could allow a session interface to change behavior based on +request.endpoint. #3776

  • +
  • Use Jinja’s implementation of the |tojson filter. #3881

  • +
  • Add route decorators for common HTTP methods. For example, +@app.post("/login") is a shortcut for +@app.route("/login", methods=["POST"]). #3907

  • +
  • Support async views, error handlers, before and after request, and +teardown functions. #3412

  • +
  • Support nesting blueprints. #593, 1548, #3923

  • +
  • Set the default encoding to “UTF-8” when loading .env and +.flaskenv files to allow to use non-ASCII characters. #3931

  • +
  • flask shell sets up tab and history completion like the default +python shell if readline is installed. #3941

  • +
  • helpers.total_seconds() is deprecated. Use +timedelta.total_seconds() instead. #3962

  • +
  • Add type hinting. #3973.

  • +
+
+
+

Version 1.1.4

+

Released 2021-05-13

+
    +
  • Update static_folder to use _compat.fspath instead of +os.fspath to continue supporting Python < 3.6 #4050

  • +
+
+
+

Version 1.1.3

+

Released 2021-05-13

+
    +
  • Set maximum versions of Werkzeug, Jinja, Click, and ItsDangerous. +#4043

  • +
  • Re-add support for passing a pathlib.Path for static_folder. +#3579

  • +
+
+
+

Version 1.1.2

+

Released 2020-04-03

+
    +
  • Work around an issue when running the flask command with an +external debugger on Windows. #3297

  • +
  • The static route will not catch all URLs if the Flask +static_folder argument ends with a slash. #3452

  • +
+
+
+

Version 1.1.1

+

Released 2019-07-08

+
    +
  • The flask.json_available flag was added back for compatibility +with some extensions. It will raise a deprecation warning when used, +and will be removed in version 2.0.0. #3288

  • +
+
+
+

Version 1.1.0

+

Released 2019-07-04

+
    +
  • Bump minimum Werkzeug version to >= 0.15.

  • +
  • Drop support for Python 3.4.

  • +
  • Error handlers for InternalServerError or 500 will always be +passed an instance of InternalServerError. If they are invoked +due to an unhandled exception, that original exception is now +available as e.original_exception rather than being passed +directly to the handler. The same is true if the handler is for the +base HTTPException. This makes error handler behavior more +consistent. #3266

    +
      +
    • Flask.finalize_request is called for all unhandled +exceptions even if there is no 500 error handler.

    • +
    +
  • +
  • Flask.logger takes the same name as Flask.name (the value +passed as Flask(import_name). This reverts 1.0’s behavior of +always logging to "flask.app", in order to support multiple apps +in the same process. A warning will be shown if old configuration is +detected that needs to be moved. #2866

  • +
  • RequestContext.copy includes the current session object in the +request context copy. This prevents session pointing to an +out-of-date object. #2935

  • +
  • Using built-in RequestContext, unprintable Unicode characters in +Host header will result in a HTTP 400 response and not HTTP 500 as +previously. #2994

  • +
  • send_file supports PathLike objects as described in +PEP 519, to support pathlib in Python 3. #3059

  • +
  • send_file supports BytesIO partial content. +#2957

  • +
  • open_resource accepts the “rt” file mode. This still does the +same thing as “r”. #3163

  • +
  • The MethodView.methods attribute set in a base class is used by +subclasses. #3138

  • +
  • Flask.jinja_options is a dict instead of an +ImmutableDict to allow easier configuration. Changes must still +be made before creating the environment. #3190

  • +
  • Flask’s JSONMixin for the request and response wrappers was +moved into Werkzeug. Use Werkzeug’s version with Flask-specific +support. This bumps the Werkzeug dependency to >= 0.15. +#3125

  • +
  • The flask command entry point is simplified to take advantage +of Werkzeug 0.15’s better reloader support. This bumps the Werkzeug +dependency to >= 0.15. #3022

  • +
  • Support static_url_path that ends with a forward slash. +#3134

  • +
  • Support empty static_folder without requiring setting an empty +static_url_path as well. #3124

  • +
  • jsonify supports dataclass objects. #3195

  • +
  • Allow customizing the Flask.url_map_class used for routing. +#3069

  • +
  • The development server port can be set to 0, which tells the OS to +pick an available port. #2926

  • +
  • The return value from cli.load_dotenv is more consistent with +the documentation. It will return False if python-dotenv is not +installed, or if the given path isn’t a file. #2937

  • +
  • Signaling support has a stub for the connect_via method when +the Blinker library is not installed. #3208

  • +
  • Add an --extra-files option to the flask run CLI command to +specify extra files that will trigger the reloader on change. +#2897

  • +
  • Allow returning a dictionary from a view function. Similar to how +returning a string will produce a text/html response, returning +a dict will call jsonify to produce a application/json +response. #3111

  • +
  • Blueprints have a cli Click group like app.cli. CLI commands +registered with a blueprint will be available as a group under the +flask command. #1357.

  • +
  • When using the test client as a context manager (with client:), +all preserved request contexts are popped when the block exits, +ensuring nested contexts are cleaned up correctly. #3157

  • +
  • Show a better error message when the view return type is not +supported. #3214

  • +
  • flask.testing.make_test_environ_builder() has been deprecated in +favour of a new class flask.testing.EnvironBuilder. #3232

  • +
  • The flask run command no longer fails if Python is not built +with SSL support. Using the --cert option will show an +appropriate error message. #3211

  • +
  • URL matching now occurs after the request context is pushed, rather +than when it’s created. This allows custom URL converters to access +the app and request contexts, such as to query a database for an id. +#3088

  • +
+
+
+

Version 1.0.4

+

Released 2019-07-04

+
    +
  • The key information for BadRequestKeyError is no longer cleared +outside debug mode, so error handlers can still access it. This +requires upgrading to Werkzeug 0.15.5. #3249

  • +
  • send_file url quotes the “:” and “/” characters for more +compatible UTF-8 filename support in some browsers. #3074

  • +
  • Fixes for PEP 451 import loaders and pytest 5.x. #3275

  • +
  • Show message about dotenv on stderr instead of stdout. #3285

  • +
+
+
+

Version 1.0.3

+

Released 2019-05-17

+
    +
  • send_file encodes filenames as ASCII instead of Latin-1 +(ISO-8859-1). This fixes compatibility with Gunicorn, which is +stricter about header encodings than PEP 3333. #2766

  • +
  • Allow custom CLIs using FlaskGroup to set the debug flag without +it always being overwritten based on environment variables. +#2765

  • +
  • flask --version outputs Werkzeug’s version and simplifies the +Python version. #2825

  • +
  • send_file handles an attachment_filename that is a native +Python 2 string (bytes) with UTF-8 coded bytes. #2933

  • +
  • A catch-all error handler registered for HTTPException will not +handle RoutingException, which is used internally during +routing. This fixes the unexpected behavior that had been introduced +in 1.0. #2986

  • +
  • Passing the json argument to app.test_client does not +push/pop an extra app context. #2900

  • +
+
+
+

Version 1.0.2

+

Released 2018-05-02

+
    +
  • Fix more backwards compatibility issues with merging slashes between +a blueprint prefix and route. #2748

  • +
  • Fix error with flask routes command when there are no routes. +#2751

  • +
+
+
+

Version 1.0.1

+

Released 2018-04-29

+
    +
  • Fix registering partials (with no __name__) as view functions. +#2730

  • +
  • Don’t treat lists returned from view functions the same as tuples. +Only tuples are interpreted as response data. #2736

  • +
  • Extra slashes between a blueprint’s url_prefix and a route URL +are merged. This fixes some backwards compatibility issues with the +change in 1.0. #2731, #2742

  • +
  • Only trap BadRequestKeyError errors in debug mode, not all +BadRequest errors. This allows abort(400) to continue +working as expected. #2735

  • +
  • The FLASK_SKIP_DOTENV environment variable can be set to 1 +to skip automatically loading dotenv files. #2722

  • +
+
+
+

Version 1.0

+

Released 2018-04-26

+
    +
  • Python 2.6 and 3.3 are no longer supported.

  • +
  • Bump minimum dependency versions to the latest stable versions: +Werkzeug >= 0.14, Jinja >= 2.10, itsdangerous >= 0.24, Click >= 5.1. +#2586

  • +
  • Skip app.run when a Flask application is run from the command +line. This avoids some behavior that was confusing to debug.

  • +
  • Change the default for JSONIFY_PRETTYPRINT_REGULAR to +False. ~json.jsonify returns a compact format by default, +and an indented format in debug mode. #2193

  • +
  • Flask.__init__ accepts the host_matching argument and sets +it on Flask.url_map. #1559

  • +
  • Flask.__init__ accepts the static_host argument and passes +it as the host argument when defining the static route. +#1559

  • +
  • send_file supports Unicode in attachment_filename. +#2223

  • +
  • Pass _scheme argument from url_for to +Flask.handle_url_build_error. #2017

  • +
  • Flask.add_url_rule accepts the provide_automatic_options +argument to disable adding the OPTIONS method. #1489

  • +
  • MethodView subclasses inherit method handlers from base classes. +#1936

  • +
  • Errors caused while opening the session at the beginning of the +request are handled by the app’s error handlers. #2254

  • +
  • Blueprints gained Blueprint.json_encoder and +Blueprint.json_decoder attributes to override the app’s +encoder and decoder. #1898

  • +
  • Flask.make_response raises TypeError instead of +ValueError for bad response types. The error messages have been +improved to describe why the type is invalid. #2256

  • +
  • Add routes CLI command to output routes registered on the +application. #2259

  • +
  • Show warning when session cookie domain is a bare hostname or an IP +address, as these may not behave properly in some browsers, such as +Chrome. #2282

  • +
  • Allow IP address as exact session cookie domain. #2282

  • +
  • SESSION_COOKIE_DOMAIN is set if it is detected through +SERVER_NAME. #2282

  • +
  • Auto-detect zero-argument app factory called create_app or +make_app from FLASK_APP. #2297

  • +
  • Factory functions are not required to take a script_info +parameter to work with the flask command. If they take a single +parameter or a parameter named script_info, the ScriptInfo +object will be passed. #2319

  • +
  • FLASK_APP can be set to an app factory, with arguments if +needed, for example FLASK_APP=myproject.app:create_app('dev'). +#2326

  • +
  • FLASK_APP can point to local packages that are not installed in +editable mode, although pip install -e is still preferred. +#2414

  • +
  • The View class attribute +View.provide_automatic_options is set in View.as_view, to be +detected by Flask.add_url_rule. #2316

  • +
  • Error handling will try handlers registered for blueprint, code, +app, code, blueprint, exception, app, exception. +#2314

  • +
  • Cookie is added to the response’s Vary header if the session +is accessed at all during the request (and not deleted). #2288

  • +
  • Flask.test_request_context accepts subdomain and +url_scheme arguments for use when building the base URL. +#1621

  • +
  • Set APPLICATION_ROOT to '/' by default. This was already the +implicit default when it was set to None.

  • +
  • TRAP_BAD_REQUEST_ERRORS is enabled by default in debug mode. +BadRequestKeyError has a message with the bad key in debug mode +instead of the generic bad request message. #2348

  • +
  • Allow registering new tags with TaggedJSONSerializer to support +storing other types in the session cookie. #2352

  • +
  • Only open the session if the request has not been pushed onto the +context stack yet. This allows stream_with_context generators to +access the same session that the containing view uses. #2354

  • +
  • Add json keyword argument for the test client request methods. +This will dump the given object as JSON and set the appropriate +content type. #2358

  • +
  • Extract JSON handling to a mixin applied to both the Request and +Response classes. This adds the Response.is_json and +Response.get_json methods to the response to make testing JSON +response much easier. #2358

  • +
  • Removed error handler caching because it caused unexpected results +for some exception inheritance hierarchies. Register handlers +explicitly for each exception if you want to avoid traversing the +MRO. #2362

  • +
  • Fix incorrect JSON encoding of aware, non-UTC datetimes. #2374

  • +
  • Template auto reloading will honor debug mode even if +Flask.jinja_env was already accessed. #2373

  • +
  • The following old deprecated code was removed. #2385

    +
      +
    • flask.ext - import extensions directly by their name instead +of through the flask.ext namespace. For example, +import flask.ext.sqlalchemy becomes +import flask_sqlalchemy.

    • +
    • Flask.init_jinja_globals - extend +Flask.create_jinja_environment instead.

    • +
    • Flask.error_handlers - tracked by +Flask.error_handler_spec, use Flask.errorhandler +to register handlers.

    • +
    • Flask.request_globals_class - use +Flask.app_ctx_globals_class instead.

    • +
    • Flask.static_path - use Flask.static_url_path instead.

    • +
    • Request.module - use Request.blueprint instead.

    • +
    +
  • +
  • The Request.json property is no longer deprecated. #1421

  • +
  • Support passing a EnvironBuilder or dict to +test_client.open. #2412

  • +
  • The flask command and Flask.run will load environment +variables from .env and .flaskenv files if python-dotenv is +installed. #2416

  • +
  • When passing a full URL to the test client, the scheme in the URL is +used instead of PREFERRED_URL_SCHEME. #2430

  • +
  • Flask.logger has been simplified. LOGGER_NAME and +LOGGER_HANDLER_POLICY config was removed. The logger is always +named flask.app. The level is only set on first access, it +doesn’t check Flask.debug each time. Only one format is used, +not different ones depending on Flask.debug. No handlers are +removed, and a handler is only added if no handlers are already +configured. #2436

  • +
  • Blueprint view function names may not contain dots. #2450

  • +
  • Fix a ValueError caused by invalid Range requests in some +cases. #2526

  • +
  • The development server uses threads by default. #2529

  • +
  • Loading config files with silent=True will ignore ENOTDIR +errors. #2581

  • +
  • Pass --cert and --key options to flask run to run the +development server over HTTPS. #2606

  • +
  • Added SESSION_COOKIE_SAMESITE to control the SameSite +attribute on the session cookie. #2607

  • +
  • Added Flask.test_cli_runner to create a Click runner that can +invoke Flask CLI commands for testing. #2636

  • +
  • Subdomain matching is disabled by default and setting +SERVER_NAME does not implicitly enable it. It can be enabled by +passing subdomain_matching=True to the Flask constructor. +#2635

  • +
  • A single trailing slash is stripped from the blueprint +url_prefix when it is registered with the app. #2629

  • +
  • Request.get_json doesn’t cache the result if parsing fails when +silent is true. #2651

  • +
  • Request.get_json no longer accepts arbitrary encodings. Incoming +JSON should be encoded using UTF-8 per RFC 8259, but Flask will +autodetect UTF-8, -16, or -32. #2691

  • +
  • Added MAX_COOKIE_SIZE and Response.max_cookie_size to +control when Werkzeug warns about large cookies that browsers may +ignore. #2693

  • +
  • Updated documentation theme to make docs look better in small +windows. #2709

  • +
  • Rewrote the tutorial docs and example project to take a more +structured approach to help new users avoid common pitfalls. +#2676

  • +
+
+
+

Version 0.12.5

+

Released 2020-02-10

+
    +
  • Pin Werkzeug to < 1.0.0. #3497

  • +
+
+
+

Version 0.12.4

+

Released 2018-04-29

+
    +
  • Repackage 0.12.3 to fix package layout issue. #2728

  • +
+
+
+

Version 0.12.3

+

Released 2018-04-26

+
    +
  • Request.get_json no longer accepts arbitrary encodings. +Incoming JSON should be encoded using UTF-8 per RFC 8259, but +Flask will autodetect UTF-8, -16, or -32. #2692

  • +
  • Fix a Python warning about imports when using python -m flask. +#2666

  • +
  • Fix a ValueError caused by invalid Range requests in some +cases.

  • +
+
+
+

Version 0.12.2

+

Released 2017-05-16

+
    +
  • Fix a bug in safe_join on Windows.

  • +
+
+
+

Version 0.12.1

+

Released 2017-03-31

+
    +
  • Prevent flask run from showing a NoAppException when an +ImportError occurs within the imported application module.

  • +
  • Fix encoding behavior of app.config.from_pyfile for Python 3. +#2118

  • +
  • Use the SERVER_NAME config if it is present as default values +for app.run. #2109, #2152

  • +
  • Call ctx.auto_pop with the exception object instead of None, +in the event that a BaseException such as KeyboardInterrupt +is raised in a request handler.

  • +
+
+
+

Version 0.12

+

Released 2016-12-21, codename Punsch

+
    +
  • The cli command now responds to --version.

  • +
  • Mimetype guessing and ETag generation for file-like objects in +send_file has been removed. #104, :pr`1849`

  • +
  • Mimetype guessing in send_file now fails loudly and doesn’t fall +back to application/octet-stream. #1988

  • +
  • Make flask.safe_join able to join multiple paths like +os.path.join #1730

  • +
  • Revert a behavior change that made the dev server crash instead of +returning an Internal Server Error. #2006

  • +
  • Correctly invoke response handlers for both regular request +dispatching as well as error handlers.

  • +
  • Disable logger propagation by default for the app logger.

  • +
  • Add support for range requests in send_file.

  • +
  • app.test_client includes preset default environment, which can +now be directly set, instead of per client.get.

  • +
  • Fix crash when running under PyPy3. #1814

  • +
+
+
+

Version 0.11.1

+

Released 2016-06-07

+
    +
  • Fixed a bug that prevented FLASK_APP=foobar/__init__.py from +working. #1872

  • +
+
+
+

Version 0.11

+

Released 2016-05-29, codename Absinthe

+
    +
  • Added support to serializing top-level arrays to jsonify. This +introduces a security risk in ancient browsers.

  • +
  • Added before_render_template signal.

  • +
  • Added **kwargs to Flask.test_client to support passing +additional keyword arguments to the constructor of +Flask.test_client_class.

  • +
  • Added SESSION_REFRESH_EACH_REQUEST config key that controls the +set-cookie behavior. If set to True a permanent session will be +refreshed each request and get their lifetime extended, if set to +False it will only be modified if the session actually modifies. +Non permanent sessions are not affected by this and will always +expire if the browser window closes.

  • +
  • Made Flask support custom JSON mimetypes for incoming data.

  • +
  • Added support for returning tuples in the form (response, +headers) from a view function.

  • +
  • Added Config.from_json.

  • +
  • Added Flask.config_class.

  • +
  • Added Config.get_namespace.

  • +
  • Templates are no longer automatically reloaded outside of debug +mode. This can be configured with the new TEMPLATES_AUTO_RELOAD +config key.

  • +
  • Added a workaround for a limitation in Python 3.3’s namespace +loader.

  • +
  • Added support for explicit root paths when using Python 3.3’s +namespace packages.

  • +
  • Added flask and the flask.cli module to start the +local debug server through the click CLI system. This is recommended +over the old flask.run() method as it works faster and more +reliable due to a different design and also replaces +Flask-Script.

  • +
  • Error handlers that match specific classes are now checked first, +thereby allowing catching exceptions that are subclasses of HTTP +exceptions (in werkzeug.exceptions). This makes it possible for +an extension author to create exceptions that will by default result +in the HTTP error of their choosing, but may be caught with a custom +error handler if desired.

  • +
  • Added Config.from_mapping.

  • +
  • Flask will now log by default even if debug is disabled. The log +format is now hardcoded but the default log handling can be disabled +through the LOGGER_HANDLER_POLICY configuration key.

  • +
  • Removed deprecated module functionality.

  • +
  • Added the EXPLAIN_TEMPLATE_LOADING config flag which when +enabled will instruct Flask to explain how it locates templates. +This should help users debug when the wrong templates are loaded.

  • +
  • Enforce blueprint handling in the order they were registered for +template loading.

  • +
  • Ported test suite to py.test.

  • +
  • Deprecated request.json in favour of request.get_json().

  • +
  • Add “pretty” and “compressed” separators definitions in jsonify() +method. Reduces JSON response size when +JSONIFY_PRETTYPRINT_REGULAR=False by removing unnecessary white +space included by default after separators.

  • +
  • JSON responses are now terminated with a newline character, because +it is a convention that UNIX text files end with a newline and some +clients don’t deal well when this newline is missing. #1262

  • +
  • The automatically provided OPTIONS method is now correctly +disabled if the user registered an overriding rule with the +lowercase-version options. #1288

  • +
  • flask.json.jsonify now supports the datetime.date type. +#1326

  • +
  • Don’t leak exception info of already caught exceptions to context +teardown handlers. #1393

  • +
  • Allow custom Jinja environment subclasses. #1422

  • +
  • Updated extension dev guidelines.

  • +
  • flask.g now has pop() and setdefault methods.

  • +
  • Turn on autoescape for flask.templating.render_template_string +by default. #1515

  • +
  • flask.ext is now deprecated. #1484

  • +
  • send_from_directory now raises BadRequest if the filename is +invalid on the server OS. #1763

  • +
  • Added the JSONIFY_MIMETYPE configuration variable. #1728

  • +
  • Exceptions during teardown handling will no longer leave bad +application contexts lingering around.

  • +
  • Fixed broken test_appcontext_signals() test case.

  • +
  • Raise an AttributeError in helpers.find_package with a +useful message explaining why it is raised when a PEP 302 import +hook is used without an is_package() method.

  • +
  • Fixed an issue causing exceptions raised before entering a request +or app context to be passed to teardown handlers.

  • +
  • Fixed an issue with query parameters getting removed from requests +in the test client when absolute URLs were requested.

  • +
  • Made @before_first_request into a decorator as intended.

  • +
  • Fixed an etags bug when sending a file streams with a name.

  • +
  • Fixed send_from_directory not expanding to the application root +path correctly.

  • +
  • Changed logic of before first request handlers to flip the flag +after invoking. This will allow some uses that are potentially +dangerous but should probably be permitted.

  • +
  • Fixed Python 3 bug when a handler from +app.url_build_error_handlers reraises the BuildError.

  • +
+
+
+

Version 0.10.1

+

Released 2013-06-14

+
    +
  • Fixed an issue where |tojson was not quoting single quotes which +made the filter not work properly in HTML attributes. Now it’s +possible to use that filter in single quoted attributes. This should +make using that filter with angular.js easier.

  • +
  • Added support for byte strings back to the session system. This +broke compatibility with the common case of people putting binary +data for token verification into the session.

  • +
  • Fixed an issue where registering the same method twice for the same +endpoint would trigger an exception incorrectly.

  • +
+
+
+

Version 0.10

+

Released 2013-06-13, codename Limoncello

+
    +
  • Changed default cookie serialization format from pickle to JSON to +limit the impact an attacker can do if the secret key leaks.

  • +
  • Added template_test methods in addition to the already existing +template_filter method family.

  • +
  • Added template_global methods in addition to the already +existing template_filter method family.

  • +
  • Set the content-length header for x-sendfile.

  • +
  • tojson filter now does not escape script blocks in HTML5 +parsers.

  • +
  • tojson used in templates is now safe by default. This was +allowed due to the different escaping behavior.

  • +
  • Flask will now raise an error if you attempt to register a new +function on an already used endpoint.

  • +
  • Added wrapper module around simplejson and added default +serialization of datetime objects. This allows much easier +customization of how JSON is handled by Flask or any Flask +extension.

  • +
  • Removed deprecated internal flask.session module alias. Use +flask.sessions instead to get the session module. This is not to +be confused with flask.session the session proxy.

  • +
  • Templates can now be rendered without request context. The behavior +is slightly different as the request, session and g +objects will not be available and blueprint’s context processors are +not called.

  • +
  • The config object is now available to the template as a real global +and not through a context processor which makes it available even in +imported templates by default.

  • +
  • Added an option to generate non-ascii encoded JSON which should +result in less bytes being transmitted over the network. It’s +disabled by default to not cause confusion with existing libraries +that might expect flask.json.dumps to return bytes by default.

  • +
  • flask.g is now stored on the app context instead of the request +context.

  • +
  • flask.g now gained a get() method for not erroring out on +non existing items.

  • +
  • flask.g now can be used with the in operator to see what’s +defined and it now is iterable and will yield all attributes stored.

  • +
  • flask.Flask.request_globals_class got renamed to +flask.Flask.app_ctx_globals_class which is a better name to what +it does since 0.10.

  • +
  • request, session and g are now also added as proxies to +the template context which makes them available in imported +templates. One has to be very careful with those though because +usage outside of macros might cause caching.

  • +
  • Flask will no longer invoke the wrong error handlers if a proxy +exception is passed through.

  • +
  • Added a workaround for chrome’s cookies in localhost not working as +intended with domain names.

  • +
  • Changed logic for picking defaults for cookie values from sessions +to work better with Google Chrome.

  • +
  • Added message_flashed signal that simplifies flashing testing.

  • +
  • Added support for copying of request contexts for better working +with greenlets.

  • +
  • Removed custom JSON HTTP exception subclasses. If you were relying +on them you can reintroduce them again yourself trivially. Using +them however is strongly discouraged as the interface was flawed.

  • +
  • Python requirements changed: requiring Python 2.6 or 2.7 now to +prepare for Python 3.3 port.

  • +
  • Changed how the teardown system is informed about exceptions. This +is now more reliable in case something handles an exception halfway +through the error handling process.

  • +
  • Request context preservation in debug mode now keeps the exception +information around which means that teardown handlers are able to +distinguish error from success cases.

  • +
  • Added the JSONIFY_PRETTYPRINT_REGULAR configuration variable.

  • +
  • Flask now orders JSON keys by default to not trash HTTP caches due +to different hash seeds between different workers.

  • +
  • Added appcontext_pushed and appcontext_popped signals.

  • +
  • The builtin run method now takes the SERVER_NAME into account +when picking the default port to run on.

  • +
  • Added flask.request.get_json() as a replacement for the old +flask.request.json property.

  • +
+
+
+

Version 0.9

+

Released 2012-07-01, codename Campari

+
    +
  • The Request.on_json_loading_failed now returns a JSON formatted +response by default.

  • +
  • The url_for function now can generate anchors to the generated +links.

  • +
  • The url_for function now can also explicitly generate URL rules +specific to a given HTTP method.

  • +
  • Logger now only returns the debug log setting if it was not set +explicitly.

  • +
  • Unregister a circular dependency between the WSGI environment and +the request object when shutting down the request. This means that +environ werkzeug.request will be None after the response was +returned to the WSGI server but has the advantage that the garbage +collector is not needed on CPython to tear down the request unless +the user created circular dependencies themselves.

  • +
  • Session is now stored after callbacks so that if the session payload +is stored in the session you can still modify it in an after request +callback.

  • +
  • The Flask class will avoid importing the provided import name if +it can (the required first parameter), to benefit tools which build +Flask instances programmatically. The Flask class will fall back to +using import on systems with custom module hooks, e.g. Google App +Engine, or when the import name is inside a zip archive (usually an +egg) prior to Python 2.7.

  • +
  • Blueprints now have a decorator to add custom template filters +application wide, Blueprint.app_template_filter.

  • +
  • The Flask and Blueprint classes now have a non-decorator method for +adding custom template filters application wide, +Flask.add_template_filter and +Blueprint.add_app_template_filter.

  • +
  • The get_flashed_messages function now allows rendering flashed +message categories in separate blocks, through a category_filter +argument.

  • +
  • The Flask.run method now accepts None for host and +port arguments, using default values when None. This allows +for calling run using configuration values, e.g. +app.run(app.config.get('MYHOST'), app.config.get('MYPORT')), +with proper behavior whether or not a config file is provided.

  • +
  • The render_template method now accepts a either an iterable of +template names or a single template name. Previously, it only +accepted a single template name. On an iterable, the first template +found is rendered.

  • +
  • Added Flask.app_context which works very similar to the request +context but only provides access to the current application. This +also adds support for URL generation without an active request +context.

  • +
  • View functions can now return a tuple with the first instance being +an instance of Response. This allows for returning +jsonify(error="error msg"), 400 from a view function.

  • +
  • Flask and Blueprint now provide a get_send_file_max_age +hook for subclasses to override behavior of serving static files +from Flask when using Flask.send_static_file (used for the +default static file handler) and helpers.send_file. This hook is +provided a filename, which for example allows changing cache +controls by file extension. The default max-age for send_file +and static files can be configured through a new +SEND_FILE_MAX_AGE_DEFAULT configuration variable, which is used +in the default get_send_file_max_age implementation.

  • +
  • Fixed an assumption in sessions implementation which could break +message flashing on sessions implementations which use external +storage.

  • +
  • Changed the behavior of tuple return values from functions. They are +no longer arguments to the response object, they now have a defined +meaning.

  • +
  • Added Flask.request_globals_class to allow a specific class to +be used on creation of the g instance of each request.

  • +
  • Added required_methods attribute to view functions to force-add +methods on registration.

  • +
  • Added flask.after_this_request.

  • +
  • Added flask.stream_with_context and the ability to push contexts +multiple times without producing unexpected behavior.

  • +
+
+
+

Version 0.8.1

+

Released 2012-07-01

+
    +
  • Fixed an issue with the undocumented flask.session module to not +work properly on Python 2.5. It should not be used but did cause +some problems for package managers.

  • +
+
+
+

Version 0.8

+

Released 2011-09-29, codename Rakija

+
    +
  • Refactored session support into a session interface so that the +implementation of the sessions can be changed without having to +override the Flask class.

  • +
  • Empty session cookies are now deleted properly automatically.

  • +
  • View functions can now opt out of getting the automatic OPTIONS +implementation.

  • +
  • HTTP exceptions and Bad Request errors can now be trapped so that +they show up normally in the traceback.

  • +
  • Flask in debug mode is now detecting some common problems and tries +to warn you about them.

  • +
  • Flask in debug mode will now complain with an assertion error if a +view was attached after the first request was handled. This gives +earlier feedback when users forget to import view code ahead of +time.

  • +
  • Added the ability to register callbacks that are only triggered once +at the beginning of the first request with +Flask.before_first_request.

  • +
  • Malformed JSON data will now trigger a bad request HTTP exception +instead of a value error which usually would result in a 500 +internal server error if not handled. This is a backwards +incompatible change.

  • +
  • Applications now not only have a root path where the resources and +modules are located but also an instance path which is the +designated place to drop files that are modified at runtime (uploads +etc.). Also this is conceptually only instance depending and outside +version control so it’s the perfect place to put configuration files +etc.

  • +
  • Added the APPLICATION_ROOT configuration variable.

  • +
  • Implemented TestClient.session_transaction to easily modify +sessions from the test environment.

  • +
  • Refactored test client internally. The APPLICATION_ROOT +configuration variable as well as SERVER_NAME are now properly +used by the test client as defaults.

  • +
  • Added View.decorators to support simpler decorating of pluggable +(class-based) views.

  • +
  • Fixed an issue where the test client if used with the “with” +statement did not trigger the execution of the teardown handlers.

  • +
  • Added finer control over the session cookie parameters.

  • +
  • HEAD requests to a method view now automatically dispatch to the +get method if no handler was implemented.

  • +
  • Implemented the virtual flask.ext package to import extensions +from.

  • +
  • The context preservation on exceptions is now an integral component +of Flask itself and no longer of the test client. This cleaned up +some internal logic and lowers the odds of runaway request contexts +in unittests.

  • +
  • Fixed the Jinja2 environment’s list_templates method not +returning the correct names when blueprints or modules were +involved.

  • +
+
+
+

Version 0.7.2

+

Released 2011-07-06

+
    +
  • Fixed an issue with URL processors not properly working on +blueprints.

  • +
+
+
+

Version 0.7.1

+

Released 2011-06-29

+
    +
  • Added missing future import that broke 2.5 compatibility.

  • +
  • Fixed an infinite redirect issue with blueprints.

  • +
+
+
+

Version 0.7

+

Released 2011-06-28, codename Grappa

+
    +
  • Added Flask.make_default_options_response which can be used by +subclasses to alter the default behavior for OPTIONS responses.

  • +
  • Unbound locals now raise a proper RuntimeError instead of an +AttributeError.

  • +
  • Mimetype guessing and etag support based on file objects is now +deprecated for send_file because it was unreliable. Pass +filenames instead or attach your own etags and provide a proper +mimetype by hand.

  • +
  • Static file handling for modules now requires the name of the static +folder to be supplied explicitly. The previous autodetection was not +reliable and caused issues on Google’s App Engine. Until 1.0 the old +behavior will continue to work but issue dependency warnings.

  • +
  • Fixed a problem for Flask to run on jython.

  • +
  • Added a PROPAGATE_EXCEPTIONS configuration variable that can be +used to flip the setting of exception propagation which previously +was linked to DEBUG alone and is now linked to either DEBUG +or TESTING.

  • +
  • Flask no longer internally depends on rules being added through the +add_url_rule function and can now also accept regular werkzeug +rules added to the url map.

  • +
  • Added an endpoint method to the flask application object which +allows one to register a callback to an arbitrary endpoint with a +decorator.

  • +
  • Use Last-Modified for static file sending instead of Date which was +incorrectly introduced in 0.6.

  • +
  • Added create_jinja_loader to override the loader creation +process.

  • +
  • Implemented a silent flag for config.from_pyfile.

  • +
  • Added teardown_request decorator, for functions that should run +at the end of a request regardless of whether an exception occurred. +Also the behavior for after_request was changed. It’s now no +longer executed when an exception is raised.

  • +
  • Implemented has_request_context.

  • +
  • Deprecated init_jinja_globals. Override the +Flask.create_jinja_environment method instead to achieve the +same functionality.

  • +
  • Added safe_join.

  • +
  • The automatic JSON request data unpacking now looks at the charset +mimetype parameter.

  • +
  • Don’t modify the session on get_flashed_messages if there are no +messages in the session.

  • +
  • before_request handlers are now able to abort requests with +errors.

  • +
  • It is not possible to define user exception handlers. That way you +can provide custom error messages from a central hub for certain +errors that might occur during request processing (for instance +database connection errors, timeouts from remote resources etc.).

  • +
  • Blueprints can provide blueprint specific error handlers.

  • +
  • Implemented generic class-based views.

  • +
+
+
+

Version 0.6.1

+

Released 2010-12-31

+
    +
  • Fixed an issue where the default OPTIONS response was not +exposing all valid methods in the Allow header.

  • +
  • Jinja2 template loading syntax now allows “./” in front of a +template load path. Previously this caused issues with module +setups.

  • +
  • Fixed an issue where the subdomain setting for modules was ignored +for the static folder.

  • +
  • Fixed a security problem that allowed clients to download arbitrary +files if the host server was a windows based operating system and +the client uses backslashes to escape the directory the files where +exposed from.

  • +
+
+
+

Version 0.6

+

Released 2010-07-27, codename Whisky

+
    +
  • After request functions are now called in reverse order of +registration.

  • +
  • OPTIONS is now automatically implemented by Flask unless the +application explicitly adds ‘OPTIONS’ as method to the URL rule. In +this case no automatic OPTIONS handling kicks in.

  • +
  • Static rules are now even in place if there is no static folder for +the module. This was implemented to aid GAE which will remove the +static folder if it’s part of a mapping in the .yml file.

  • +
  • Flask.config is now available in the templates as config.

  • +
  • Context processors will no longer override values passed directly to +the render function.

  • +
  • Added the ability to limit the incoming request data with the new +MAX_CONTENT_LENGTH configuration value.

  • +
  • The endpoint for the Module.add_url_rule method is now optional +to be consistent with the function of the same name on the +application object.

  • +
  • Added a make_response function that simplifies creating response +object instances in views.

  • +
  • Added signalling support based on blinker. This feature is currently +optional and supposed to be used by extensions and applications. If +you want to use it, make sure to have blinker installed.

  • +
  • Refactored the way URL adapters are created. This process is now +fully customizable with the Flask.create_url_adapter method.

  • +
  • Modules can now register for a subdomain instead of just an URL +prefix. This makes it possible to bind a whole module to a +configurable subdomain.

  • +
+
+
+

Version 0.5.2

+

Released 2010-07-15

+
    +
  • Fixed another issue with loading templates from directories when +modules were used.

  • +
+
+
+

Version 0.5.1

+

Released 2010-07-06

+
    +
  • Fixes an issue with template loading from directories when modules +where used.

  • +
+
+
+

Version 0.5

+

Released 2010-07-06, codename Calvados

+
    +
  • Fixed a bug with subdomains that was caused by the inability to +specify the server name. The server name can now be set with the +SERVER_NAME config key. This key is now also used to set the +session cookie cross-subdomain wide.

  • +
  • Autoescaping is no longer active for all templates. Instead it is +only active for .html, .htm, .xml and .xhtml. Inside +templates this behavior can be changed with the autoescape tag.

  • +
  • Refactored Flask internally. It now consists of more than a single +file.

  • +
  • send_file now emits etags and has the ability to do conditional +responses builtin.

  • +
  • (temporarily) dropped support for zipped applications. This was a +rarely used feature and led to some confusing behavior.

  • +
  • Added support for per-package template and static-file directories.

  • +
  • Removed support for create_jinja_loader which is no longer used +in 0.5 due to the improved module support.

  • +
  • Added a helper function to expose files from any directory.

  • +
+
+
+

Version 0.4

+

Released 2010-06-18, codename Rakia

+
    +
  • Added the ability to register application wide error handlers from +modules.

  • +
  • Flask.after_request handlers are now also invoked if the request +dies with an exception and an error handling page kicks in.

  • +
  • Test client has not the ability to preserve the request context for +a little longer. This can also be used to trigger custom requests +that do not pop the request stack for testing.

  • +
  • Because the Python standard library caches loggers, the name of the +logger is configurable now to better support unittests.

  • +
  • Added TESTING switch that can activate unittesting helpers.

  • +
  • The logger switches to DEBUG mode now if debug is enabled.

  • +
+
+
+

Version 0.3.1

+

Released 2010-05-28

+
    +
  • Fixed a error reporting bug with Config.from_envvar.

  • +
  • Removed some unused code.

  • +
  • Release does no longer include development leftover files (.git +folder for themes, built documentation in zip and pdf file and some +.pyc files)

  • +
+
+
+

Version 0.3

+

Released 2010-05-28, codename Schnaps

+
    +
  • Added support for categories for flashed messages.

  • +
  • The application now configures a logging.Handler and will log +request handling exceptions to that logger when not in debug mode. +This makes it possible to receive mails on server errors for +example.

  • +
  • Added support for context binding that does not require the use of +the with statement for playing in the console.

  • +
  • The request context is now available within the with statement +making it possible to further push the request context or pop it.

  • +
  • Added support for configurations.

  • +
+
+
+

Version 0.2

+

Released 2010-05-12, codename J?germeister

+
    +
  • Various bugfixes

  • +
  • Integrated JSON support

  • +
  • Added get_template_attribute helper function.

  • +
  • Flask.add_url_rule can now also register a view function.

  • +
  • Refactored internal request dispatching.

  • +
  • Server listens on 127.0.0.1 by default now to fix issues with +chrome.

  • +
  • Added external URL support.

  • +
  • Added support for send_file.

  • +
  • Module support and internal request handling refactoring to better +support pluggable applications.

  • +
  • Sessions can be set to be permanent now on a per-session basis.

  • +
  • Better error reporting on missing secret keys.

  • +
  • Added support for Google Appengine.

  • +
+
+
+

Version 0.1

+

Released 2010-04-16

+
    +
  • First public preview release.

  • +
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/cli/index.html b/_build/cli/index.html new file mode 100644 index 00000000..592f47eb --- /dev/null +++ b/_build/cli/index.html @@ -0,0 +1,550 @@ + + + + + + + + Command Line Interface — Flask Documentation (3.1.x) + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Command Line Interface

+

Installing Flask installs the flask script, a Click command line +interface, in your virtualenv. Executed from the terminal, this script gives +access to built-in, extension, and application-defined commands. The --help +option will give more information about any commands and options.

+
+

Application Discovery

+

The flask command is installed by Flask, not your application; it must be +told where to find your application in order to use it. The --app +option is used to specify how to load the application.

+

While --app supports a variety of options for specifying your +application, most use cases should be simple. Here are the typical values:

+
+
(nothing)

The name “app” or “wsgi” is imported (as a “.py” file, or package), +automatically detecting an app (app or application) or +factory (create_app or make_app).

+
+
--app hello

The given name is imported, automatically detecting an app (app +or application) or factory (create_app or make_app).

+
+
+
+

--app has three parts: an optional path that sets the current working +directory, a Python file or dotted import path, and an optional variable +name of the instance or factory. If the name is a factory, it can optionally +be followed by arguments in parentheses. The following values demonstrate these +parts:

+
+
--app src/hello

Sets the current working directory to src then imports hello.

+
+
--app hello.web

Imports the path hello.web.

+
+
--app hello:app2

Uses the app2 Flask instance in hello.

+
+
--app 'hello:create_app("dev")'

The create_app factory in hello is called with the string 'dev' +as the argument.

+
+
+

If --app is not set, the command will try to import “app” or +“wsgi” (as a “.py” file, or package) and try to detect an application +instance or factory.

+

Within the given import, the command looks for an application instance named +app or application, then any application instance. If no instance is +found, the command looks for a factory function named create_app or +make_app that returns an instance.

+

If parentheses follow the factory name, their contents are parsed as +Python literals and passed as arguments and keyword arguments to the +function. This means that strings must still be in quotes.

+
+
+

Run the Development Server

+

The run command will start the development server. It +replaces the Flask.run() method in most cases.

+
$ flask --app hello run
+ * Serving Flask app "hello"
+ * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
+
+
+
+

Warning

+

Do not use this command to run your application in production. +Only use the development server during development. The development server +is provided for convenience, but is not designed to be particularly secure, +stable, or efficient. See Deploying to Production for how to run in production.

+
+

If another program is already using port 5000, you’ll see +OSError: [Errno 98] or OSError: [WinError 10013] when the +server tries to start. See Address already in use for how to +handle that.

+
+

Debug Mode

+

In debug mode, the flask run command will enable the interactive debugger and the +reloader by default, and make errors easier to see and debug. To enable debug mode, use +the --debug option.

+
$ flask --app hello run --debug
+ * Serving Flask app "hello"
+ * Debug mode: on
+ * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
+ * Restarting with inotify reloader
+ * Debugger is active!
+ * Debugger PIN: 223-456-919
+
+
+

The --debug option can also be passed to the top level flask command to enable +debug mode for any command. The following two run calls are equivalent.

+
$ flask --app hello --debug run
+$ flask --app hello run --debug
+
+
+
+
+

Watch and Ignore Files with the Reloader

+

When using debug mode, the reloader will trigger whenever your Python code or imported +modules change. The reloader can watch additional files with the --extra-files +option. Multiple paths are separated with :, or ; on Windows.

+
$ flask run --extra-files file1:dirA/file2:dirB/
+ * Running on http://127.0.0.1:8000/
+ * Detected change in '/path/to/file1', reloading
+
+
+

The reloader can also ignore files using fnmatch patterns with the +--exclude-patterns option. Multiple patterns are separated with :, or ; on +Windows.

+
+
+
+

Open a Shell

+

To explore the data in your application, you can start an interactive Python +shell with the shell command. An application +context will be active, and the app instance will be imported.

+
$ flask shell
+Python 3.10.0 (default, Oct 27 2021, 06:59:51) [GCC 11.1.0] on linux
+App: example [production]
+Instance: /home/david/Projects/pallets/flask/instance
+>>>
+
+
+

Use shell_context_processor() to add other automatic imports.

+
+
+

Environment Variables From dotenv

+

The flask command supports setting any option for any command with +environment variables. The variables are named like FLASK_OPTION or +FLASK_COMMAND_OPTION, for example FLASK_APP or +FLASK_RUN_PORT.

+

Rather than passing options every time you run a command, or environment +variables every time you open a new terminal, you can use Flask’s dotenv +support to set environment variables automatically.

+

If python-dotenv is installed, running the flask command will set +environment variables defined in the files .env and .flaskenv. +You can also specify an extra file to load with the --env-file +option. Dotenv files can be used to avoid having to set --app or +FLASK_APP manually, and to set configuration using environment +variables similar to how some deployment services work.

+

Variables set on the command line are used over those set in .env, +which are used over those set in .flaskenv. .flaskenv should be +used for public variables, such as FLASK_APP, while .env should not +be committed to your repository so that it can set private variables.

+

Directories are scanned upwards from the directory you call flask +from to locate the files.

+

The files are only loaded by the flask command or calling +run(). If you would like to load these files when running in +production, you should call load_dotenv() manually.

+
+

Setting Command Options

+

Click is configured to load default values for command options from +environment variables. The variables use the pattern +FLASK_COMMAND_OPTION. For example, to set the port for the run +command, instead of flask run --port 8000:

+
+
$ export FLASK_RUN_PORT=8000
+$ flask run
+ * Running on http://127.0.0.1:8000/
+
+
+
+

These can be added to the .flaskenv file just like FLASK_APP to +control default command options.

+
+
+

Disable dotenv

+

The flask command will show a message if it detects dotenv files but +python-dotenv is not installed.

+
$ flask run
+ * Tip: There are .env files present. Do "pip install python-dotenv" to use them.
+
+
+

You can tell Flask not to load dotenv files even when python-dotenv is +installed by setting the FLASK_SKIP_DOTENV environment variable. +This can be useful if you want to load them manually, or if you’re using +a project runner that loads them already. Keep in mind that the +environment variables must be set before the app loads or it won’t +configure as expected.

+
+
$ export FLASK_SKIP_DOTENV=1
+$ flask run
+
+
+
+
+
+
+

Environment Variables From virtualenv

+

If you do not want to install dotenv support, you can still set environment +variables by adding them to the end of the virtualenv’s activate +script. Activating the virtualenv will set the variables.

+
+

Unix Bash, .venv/bin/activate:

+
$ export FLASK_APP=hello
+
+
+
+

It is preferred to use dotenv support over this, since .flaskenv can be +committed to the repository so that it works automatically wherever the project +is checked out.

+
+
+

Custom Commands

+

The flask command is implemented using Click. See that project’s +documentation for full information about writing commands.

+

This example adds the command create-user that takes the argument +name.

+
import click
+from flask import Flask
+
+app = Flask(__name__)
+
+@app.cli.command("create-user")
+@click.argument("name")
+def create_user(name):
+    ...
+
+
+
$ flask create-user admin
+
+
+

This example adds the same command, but as user create, a command in a +group. This is useful if you want to organize multiple related commands.

+
import click
+from flask import Flask
+from flask.cli import AppGroup
+
+app = Flask(__name__)
+user_cli = AppGroup('user')
+
+@user_cli.command('create')
+@click.argument('name')
+def create_user(name):
+    ...
+
+app.cli.add_command(user_cli)
+
+
+
$ flask user create demo
+
+
+

See Running Commands with the CLI Runner for an overview of how to test your custom +commands.

+
+

Registering Commands with Blueprints

+

If your application uses blueprints, you can optionally register CLI +commands directly onto them. When your blueprint is registered onto your +application, the associated commands will be available to the flask +command. By default, those commands will be nested in a group matching +the name of the blueprint.

+
from flask import Blueprint
+
+bp = Blueprint('students', __name__)
+
+@bp.cli.command('create')
+@click.argument('name')
+def create(name):
+    ...
+
+app.register_blueprint(bp)
+
+
+
$ flask students create alice
+
+
+

You can alter the group name by specifying the cli_group parameter +when creating the Blueprint object, or later with +app.register_blueprint(bp, cli_group='...'). +The following are equivalent:

+
bp = Blueprint('students', __name__, cli_group='other')
+# or
+app.register_blueprint(bp, cli_group='other')
+
+
+
$ flask other create alice
+
+
+

Specifying cli_group=None will remove the nesting and merge the +commands directly to the application’s level:

+
bp = Blueprint('students', __name__, cli_group=None)
+# or
+app.register_blueprint(bp, cli_group=None)
+
+
+
$ flask create alice
+
+
+
+
+

Application Context

+

Commands added using the Flask app’s cli or +FlaskGroup command() decorator +will be executed with an application context pushed, so your custom +commands and parameters have access to the app and its configuration. The +with_appcontext() decorator can be used to get the same +behavior, but is not needed in most cases.

+
import click
+from flask.cli import with_appcontext
+
+@click.command()
+@with_appcontext
+def do_work():
+    ...
+
+app.cli.add_command(do_work)
+
+
+
+
+
+

Plugins

+

Flask will automatically load commands specified in the flask.commands +entry point. This is useful for extensions that want to add commands when +they are installed. Entry points are specified in pyproject.toml:

+
[project.entry-points."flask.commands"]
+my-command = "my_extension.commands:cli"
+
+
+

Inside my_extension/commands.py you can then export a Click +object:

+
import click
+
+@click.command()
+def cli():
+    ...
+
+
+

Once that package is installed in the same virtualenv as your Flask project, +you can run flask my-command to invoke the command.

+
+
+

Custom Scripts

+

When you are using the app factory pattern, it may be more convenient to define +your own Click script. Instead of using --app and letting Flask load +your application, you can create your own Click object and export it as a +console script entry point.

+

Create an instance of FlaskGroup and pass it the factory:

+
import click
+from flask import Flask
+from flask.cli import FlaskGroup
+
+def create_app():
+    app = Flask('wiki')
+    # other setup
+    return app
+
+@click.group(cls=FlaskGroup, create_app=create_app)
+def cli():
+    """Management script for the Wiki application."""
+
+
+

Define the entry point in pyproject.toml:

+
[project.scripts]
+wiki = "wiki:cli"
+
+
+

Install the application in the virtualenv in editable mode and the custom +script is available. Note that you don’t need to set --app.

+
$ pip install -e .
+$ wiki run
+
+
+
+

Errors in Custom Scripts

+

When using a custom script, if you introduce an error in your +module-level code, the reloader will fail because it can no longer +load the entry point.

+

The flask command, being separate from your code, does not have +this issue and is recommended in most cases.

+
+
+
+

PyCharm Integration

+

PyCharm Professional provides a special Flask run configuration to run the development +server. For the Community Edition, and for other commands besides run, you need to +create a custom run configuration. These instructions should be similar for any other +IDE you use.

+

In PyCharm, with your project open, click on Run from the menu bar and go to Edit +Configurations. You’ll see a screen similar to this:

+Screenshot of PyCharm run configuration. +

Once you create a configuration for the flask run, you can copy and change it to +call any other command.

+

Click the + (Add New Configuration) button and select Python. Give the configuration +a name such as “flask run”.

+

Click the Script path dropdown and change it to Module name, then input flask.

+

The Parameters field is set to the CLI command to execute along with any arguments. +This example uses --app hello run --debug, which will run the development server in +debug mode. --app hello should be the import or file with your Flask app.

+

If you installed your project as a package in your virtualenv, you may uncheck the +PYTHONPATH options. This will more accurately match how you deploy later.

+

Click OK to save and close the configuration. Select the configuration in the main +PyCharm window and click the play button next to it to run the server.

+

Now that you have a configuration for flask run, you can copy that configuration and +change the Parameters argument to run a different CLI command.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/config/index.html b/_build/config/index.html new file mode 100644 index 00000000..752a62f6 --- /dev/null +++ b/_build/config/index.html @@ -0,0 +1,930 @@ + + + + + + + + Configuration Handling — Flask Documentation (3.1.x) + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Configuration Handling

+

Applications need some kind of configuration. There are different settings +you might want to change depending on the application environment like +toggling the debug mode, setting the secret key, and other such +environment-specific things.

+

The way Flask is designed usually requires the configuration to be +available when the application starts up. You can hard code the +configuration in the code, which for many small applications is not +actually that bad, but there are better ways.

+

Independent of how you load your config, there is a config object +available which holds the loaded configuration values: +The config attribute of the Flask +object. This is the place where Flask itself puts certain configuration +values and also where extensions can put their configuration values. But +this is also where you can have your own configuration.

+
+

Configuration Basics

+

The config is actually a subclass of a dictionary and +can be modified just like any dictionary:

+
app = Flask(__name__)
+app.config['TESTING'] = True
+
+
+

Certain configuration values are also forwarded to the +Flask object so you can read and write them from there:

+
app.testing = True
+
+
+

To update multiple keys at once you can use the dict.update() +method:

+
app.config.update(
+    TESTING=True,
+    SECRET_KEY='192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'
+)
+
+
+
+
+

Debug Mode

+

The DEBUG config value is special because it may behave inconsistently if +changed after the app has begun setting up. In order to set debug mode reliably, use the +--debug option on the flask or flask run command. flask run will use the +interactive debugger and reloader by default in debug mode.

+
$ flask --app hello run --debug
+
+
+

Using the option is recommended. While it is possible to set DEBUG in your +config or code, this is strongly discouraged. It can’t be read early by the +flask run command, and some systems or extensions may have already configured +themselves based on a previous value.

+
+
+

Builtin Configuration Values

+

The following configuration values are used internally by Flask:

+
+
+DEBUG
+

Whether debug mode is enabled. When using flask run to start the development +server, an interactive debugger will be shown for unhandled exceptions, and the +server will be reloaded when code changes. The debug attribute +maps to this config key. This is set with the FLASK_DEBUG environment variable. +It may not behave as expected if set in code.

+

Do not enable debug mode when deploying in production.

+

Default: False

+
+ +
+
+TESTING
+

Enable testing mode. Exceptions are propagated rather than handled by the +the app’s error handlers. Extensions may also change their behavior to +facilitate easier testing. You should enable this in your own tests.

+

Default: False

+
+ +
+
+PROPAGATE_EXCEPTIONS
+

Exceptions are re-raised rather than being handled by the app’s error +handlers. If not set, this is implicitly true if TESTING or DEBUG +is enabled.

+

Default: None

+
+ +
+
+TRAP_HTTP_EXCEPTIONS
+

If there is no handler for an HTTPException-type exception, re-raise it +to be handled by the interactive debugger instead of returning it as a +simple error response.

+

Default: False

+
+ +
+
+TRAP_BAD_REQUEST_ERRORS
+

Trying to access a key that doesn’t exist from request dicts like args +and form will return a 400 Bad Request error page. Enable this to treat +the error as an unhandled exception instead so that you get the interactive +debugger. This is a more specific version of TRAP_HTTP_EXCEPTIONS. If +unset, it is enabled in debug mode.

+

Default: None

+
+ +
+
+SECRET_KEY
+

A secret key that will be used for securely signing the session cookie +and can be used for any other security related needs by extensions or your +application. It should be a long random bytes or str. For +example, copy the output of this to your config:

+
$ python -c 'import secrets; print(secrets.token_hex())'
+'192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'
+
+
+

Do not reveal the secret key when posting questions or committing code.

+

Default: None

+
+ +
+
+SECRET_KEY_FALLBACKS
+

A list of old secret keys that can still be used for unsigning, most recent +first. This allows a project to implement key rotation without invalidating +active sessions or other recently-signed secrets.

+

Keys should be removed after an appropriate period of time, as checking each +additional key adds some overhead.

+

Flask’s built-in secure cookie session supports this. Extensions that use +SECRET_KEY may not support this yet.

+

Default: None

+
+

Added in version 3.1.

+
+
+ +
+ +

The name of the session cookie. Can be changed in case you already have a +cookie with the same name.

+

Default: 'session'

+
+ +
+ +

The value of the Domain parameter on the session cookie. If not set, browsers +will only send the cookie to the exact domain it was set from. Otherwise, they +will send it to any subdomain of the given value as well.

+

Not setting this value is more restricted and secure than setting it.

+

Default: None

+
+

Warning

+

If this is changed after the browser created a cookie is created with +one setting, it may result in another being created. Browsers may send +send both in an undefined order. In that case, you may want to change +SESSION_COOKIE_NAME as well or otherwise invalidate old sessions.

+
+
+Changelog
+

Changed in version 2.3: Not set by default, does not fall back to SERVER_NAME.

+
+
+ +
+ +

The path that the session cookie will be valid for. If not set, the cookie +will be valid underneath APPLICATION_ROOT or / if that is not set.

+

Default: None

+
+ +
+ +

Browsers will not allow JavaScript access to cookies marked as “HTTP only” +for security.

+

Default: True

+
+ +
+ +

Browsers will only send cookies with requests over HTTPS if the cookie is +marked “secure”. The application must be served over HTTPS for this to make +sense.

+

Default: False

+
+ +
+ +

Browsers will send cookies based on the top-level document’s domain, rather +than only the domain of the document setting the cookie. This prevents third +party cookies set in iframes from “leaking” between separate sites.

+

Browsers are beginning to disallow non-partitioned third party cookies, so +you need to mark your cookies partitioned if you expect them to work in such +embedded situations.

+

Enabling this implicitly enables SESSION_COOKIE_SECURE as well, as +it is only valid when served over HTTPS.

+

Default: False

+
+

Added in version 3.1.

+
+
+ +
+ +

Restrict how cookies are sent with requests from external sites. Can +be set to 'Lax' (recommended) or 'Strict'. +See Set-Cookie options.

+

Default: None

+
+Changelog
+

Added in version 1.0.

+
+
+ +
+
+PERMANENT_SESSION_LIFETIME
+

If session.permanent is true, the cookie’s expiration will be set this +number of seconds in the future. Can either be a +datetime.timedelta or an int.

+

Flask’s default cookie implementation validates that the cryptographic +signature is not older than this value.

+

Default: timedelta(days=31) (2678400 seconds)

+
+ +
+
+SESSION_REFRESH_EACH_REQUEST
+

Control whether the cookie is sent with every response when +session.permanent is true. Sending the cookie every time (the default) +can more reliably keep the session from expiring, but uses more bandwidth. +Non-permanent sessions are not affected.

+

Default: True

+
+ +
+
+USE_X_SENDFILE
+

When serving files, set the X-Sendfile header instead of serving the +data with Flask. Some web servers, such as Apache, recognize this and serve +the data more efficiently. This only makes sense when using such a server.

+

Default: False

+
+ +
+
+SEND_FILE_MAX_AGE_DEFAULT
+

When serving files, set the cache control max age to this number of +seconds. Can be a datetime.timedelta or an int. +Override this value on a per-file basis using +get_send_file_max_age() on the application or +blueprint.

+

If None, send_file tells the browser to use conditional +requests will be used instead of a timed cache, which is usually +preferable.

+

Default: None

+
+ +
+
+TRUSTED_HOSTS
+

Validate Request.host and other attributes that use it against +these trusted values. Raise a SecurityError if +the host is invalid, which results in a 400 error. If it is None, all +hosts are valid. Each value is either an exact match, or can start with +a dot . to match any subdomain.

+

Validation is done during routing against this value. before_request and +after_request callbacks will still be called.

+

Default: None

+
+

Added in version 3.1.

+
+
+ +
+
+SERVER_NAME
+

Inform the application what host and port it is bound to.

+

Must be set if subdomain_matching is enabled, to be able to extract the +subdomain from the request.

+

Must be set for url_for to generate external URLs outside of a +request context.

+

Default: None

+
+

Changed in version 3.1: Does not restrict requests to only this domain, for both +subdomain_matching and host_matching.

+
+
+Changelog
+

Changed in version 2.3: Does not affect SESSION_COOKIE_DOMAIN.

+
+
+

Changed in version 1.0: Does not implicitly enable subdomain_matching.

+
+
+ +
+
+APPLICATION_ROOT
+

Inform the application what path it is mounted under by the application / +web server. This is used for generating URLs outside the context of a +request (inside a request, the dispatcher is responsible for setting +SCRIPT_NAME instead; see Application Dispatching +for examples of dispatch configuration).

+

Will be used for the session cookie path if SESSION_COOKIE_PATH is not +set.

+

Default: '/'

+
+ +
+
+PREFERRED_URL_SCHEME
+

Use this scheme for generating external URLs when not in a request context.

+

Default: 'http'

+
+ +
+
+MAX_CONTENT_LENGTH
+

The maximum number of bytes that will be read during this request. If +this limit is exceeded, a 413 RequestEntityTooLarge +error is raised. If it is set to None, no limit is enforced at the +Flask application level. However, if it is None and the request has no +Content-Length header and the WSGI server does not indicate that it +terminates the stream, then no data is read to avoid an infinite stream.

+

Each request defaults to this config. It can be set on a specific +Request.max_content_length to apply the limit to that specific +view. This should be set appropriately based on an application’s or view’s +specific needs.

+

Default: None

+
+Changelog
+

Added in version 0.6.

+
+
+ +
+
+MAX_FORM_MEMORY_SIZE
+

The maximum size in bytes any non-file form field may be in a +multipart/form-data body. If this limit is exceeded, a 413 +RequestEntityTooLarge error is raised. If it is +set to None, no limit is enforced at the Flask application level.

+

Each request defaults to this config. It can be set on a specific +Request.max_form_memory_parts to apply the limit to that specific +view. This should be set appropriately based on an application’s or view’s +specific needs.

+

Default: 500_000

+
+

Added in version 3.1.

+
+
+ +
+
+MAX_FORM_PARTS
+

The maximum number of fields that may be present in a +multipart/form-data body. If this limit is exceeded, a 413 +RequestEntityTooLarge error is raised. If it +is set to None, no limit is enforced at the Flask application level.

+

Each request defaults to this config. It can be set on a specific +Request.max_form_parts to apply the limit to that specific view. +This should be set appropriately based on an application’s or view’s +specific needs.

+

Default: 1_000

+
+

Added in version 3.1.

+
+
+ +
+
+TEMPLATES_AUTO_RELOAD
+

Reload templates when they are changed. If not set, it will be enabled in +debug mode.

+

Default: None

+
+ +
+
+EXPLAIN_TEMPLATE_LOADING
+

Log debugging information tracing how a template file was loaded. This can +be useful to figure out why a template was not loaded or the wrong file +appears to be loaded.

+

Default: False

+
+ +
+ +

Warn if cookie headers are larger than this many bytes. Defaults to +4093. Larger cookies may be silently ignored by browsers. Set to +0 to disable the warning.

+
+ +
+
+PROVIDE_AUTOMATIC_OPTIONS
+

Set to False to disable the automatic addition of OPTIONS +responses. This can be overridden per route by altering the +provide_automatic_options attribute.

+
+ +
+

Added in version 3.10: Added PROVIDE_AUTOMATIC_OPTIONS to control the default +addition of autogenerated OPTIONS responses.

+
+
+Changelog
+

Changed in version 2.3: JSON_AS_ASCII, JSON_SORT_KEYS, JSONIFY_MIMETYPE, and +JSONIFY_PRETTYPRINT_REGULAR were removed. The default app.json provider has +equivalent attributes instead.

+
+
+

Changed in version 2.3: ENV was removed.

+
+
+

Changed in version 2.2: Removed PRESERVE_CONTEXT_ON_EXCEPTION.

+
+
+

Changed in version 1.0: LOGGER_NAME and LOGGER_HANDLER_POLICY were removed. See +Logging for information about configuration.

+

Added ENV to reflect the FLASK_ENV environment +variable.

+

Added SESSION_COOKIE_SAMESITE to control the session +cookie’s SameSite option.

+

Added MAX_COOKIE_SIZE to control a warning from Werkzeug.

+
+
+

Added in version 0.11: SESSION_REFRESH_EACH_REQUEST, TEMPLATES_AUTO_RELOAD, +LOGGER_HANDLER_POLICY, EXPLAIN_TEMPLATE_LOADING

+
+
+

Added in version 0.10: JSON_AS_ASCII, JSON_SORT_KEYS, JSONIFY_PRETTYPRINT_REGULAR

+
+
+

Added in version 0.9: PREFERRED_URL_SCHEME

+
+
+

Added in version 0.8: TRAP_BAD_REQUEST_ERRORS, TRAP_HTTP_EXCEPTIONS, +APPLICATION_ROOT, SESSION_COOKIE_DOMAIN, +SESSION_COOKIE_PATH, SESSION_COOKIE_HTTPONLY, +SESSION_COOKIE_SECURE

+
+
+

Added in version 0.7: PROPAGATE_EXCEPTIONS, PRESERVE_CONTEXT_ON_EXCEPTION

+
+
+

Added in version 0.6: MAX_CONTENT_LENGTH

+
+
+

Added in version 0.5: SERVER_NAME

+
+
+

Added in version 0.4: LOGGER_NAME

+
+
+
+

Configuring from Python Files

+

Configuration becomes more useful if you can store it in a separate file, ideally +located outside the actual application package. You can deploy your application, then +separately configure it for the specific deployment.

+

A common pattern is this:

+
app = Flask(__name__)
+app.config.from_object('yourapplication.default_settings')
+app.config.from_envvar('YOURAPPLICATION_SETTINGS')
+
+
+

This first loads the configuration from the +yourapplication.default_settings module and then overrides the values +with the contents of the file the YOURAPPLICATION_SETTINGS +environment variable points to. This environment variable can be set +in the shell before starting the server:

+
+
$ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg
+$ flask run
+ * Running on http://127.0.0.1:5000/
+
+
+
+

The configuration files themselves are actual Python files. Only values +in uppercase are actually stored in the config object later on. So make +sure to use uppercase letters for your config keys.

+

Here is an example of a configuration file:

+
# Example configuration
+SECRET_KEY = '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'
+
+
+

Make sure to load the configuration very early on, so that extensions have +the ability to access the configuration when starting up. There are other +methods on the config object as well to load from individual files. For a +complete reference, read the Config object’s +documentation.

+
+
+

Configuring from Data Files

+

It is also possible to load configuration from a file in a format of +your choice using from_file(). For example to load +from a TOML file:

+
import tomllib
+app.config.from_file("config.toml", load=tomllib.load, text=False)
+
+
+

Or from a JSON file:

+
import json
+app.config.from_file("config.json", load=json.load)
+
+
+
+
+

Configuring from Environment Variables

+

In addition to pointing to configuration files using environment +variables, you may find it useful (or necessary) to control your +configuration values directly from the environment. Flask can be +instructed to load all environment variables starting with a specific +prefix into the config using from_prefixed_env().

+

Environment variables can be set in the shell before starting the +server:

+
+
$ export FLASK_SECRET_KEY="5f352379324c22463451387a0aec5d2f"
+$ export FLASK_MAIL_ENABLED=false
+$ flask run
+ * Running on http://127.0.0.1:5000/
+
+
+
+

The variables can then be loaded and accessed via the config with a key +equal to the environment variable name without the prefix i.e.

+
app.config.from_prefixed_env()
+app.config["SECRET_KEY"]  # Is "5f352379324c22463451387a0aec5d2f"
+
+
+

The prefix is FLASK_ by default. This is configurable via the +prefix argument of from_prefixed_env().

+

Values will be parsed to attempt to convert them to a more specific type +than strings. By default json.loads() is used, so any valid JSON +value is possible, including lists and dicts. This is configurable via +the loads argument of from_prefixed_env().

+

When adding a boolean value with the default JSON parsing, only “true” +and “false”, lowercase, are valid values. Keep in mind that any +non-empty string is considered True by Python.

+

It is possible to set keys in nested dictionaries by separating the +keys with double underscore (__). Any intermediate keys that don’t +exist on the parent dict will be initialized to an empty dict.

+
$ export FLASK_MYAPI__credentials__username=user123
+
+
+
app.config["MYAPI"]["credentials"]["username"]  # Is "user123"
+
+
+

On Windows, environment variable keys are always uppercase, therefore +the above example would end up as MYAPI__CREDENTIALS__USERNAME.

+

For even more config loading features, including merging and +case-insensitive Windows support, try a dedicated library such as +Dynaconf, which includes integration with Flask.

+
+
+

Configuration Best Practices

+

The downside with the approach mentioned earlier is that it makes testing +a little harder. There is no single 100% solution for this problem in +general, but there are a couple of things you can keep in mind to improve +that experience:

+
    +
  1. Create your application in a function and register blueprints on it. +That way you can create multiple instances of your application with +different configurations attached which makes unit testing a lot +easier. You can use this to pass in configuration as needed.

  2. +
  3. Do not write code that needs the configuration at import time. If you +limit yourself to request-only accesses to the configuration you can +reconfigure the object later on as needed.

  4. +
  5. Make sure to load the configuration very early on, so that +extensions can access the configuration when calling init_app.

  6. +
+
+
+

Development / Production

+

Most applications need more than one configuration. There should be at +least separate configurations for the production server and the one used +during development. The easiest way to handle this is to use a default +configuration that is always loaded and part of the version control, and a +separate configuration that overrides the values as necessary as mentioned +in the example above:

+
app = Flask(__name__)
+app.config.from_object('yourapplication.default_settings')
+app.config.from_envvar('YOURAPPLICATION_SETTINGS')
+
+
+

Then you just have to add a separate config.py file and export +YOURAPPLICATION_SETTINGS=/path/to/config.py and you are done. However +there are alternative ways as well. For example you could use imports or +subclassing.

+

What is very popular in the Django world is to make the import explicit in +the config file by adding from yourapplication.default_settings +import * to the top of the file and then overriding the changes by hand. +You could also inspect an environment variable like +YOURAPPLICATION_MODE and set that to production, development etc +and import different hard-coded files based on that.

+

An interesting pattern is also to use classes and inheritance for +configuration:

+
class Config(object):
+    TESTING = False
+
+class ProductionConfig(Config):
+    DATABASE_URI = 'mysql://user@localhost/foo'
+
+class DevelopmentConfig(Config):
+    DATABASE_URI = "sqlite:////tmp/foo.db"
+
+class TestingConfig(Config):
+    DATABASE_URI = 'sqlite:///:memory:'
+    TESTING = True
+
+
+

To enable such a config you just have to call into +from_object():

+
app.config.from_object('configmodule.ProductionConfig')
+
+
+

Note that from_object() does not instantiate the class +object. If you need to instantiate the class, such as to access a property, +then you must do so before calling from_object():

+
from configmodule import ProductionConfig
+app.config.from_object(ProductionConfig())
+
+# Alternatively, import via string:
+from werkzeug.utils import import_string
+cfg = import_string('configmodule.ProductionConfig')()
+app.config.from_object(cfg)
+
+
+

Instantiating the configuration object allows you to use @property in +your configuration classes:

+
class Config(object):
+    """Base config, uses staging database server."""
+    TESTING = False
+    DB_SERVER = '192.168.1.56'
+
+    @property
+    def DATABASE_URI(self):  # Note: all caps
+        return f"mysql://user@{self.DB_SERVER}/foo"
+
+class ProductionConfig(Config):
+    """Uses production database server."""
+    DB_SERVER = '192.168.19.32'
+
+class DevelopmentConfig(Config):
+    DB_SERVER = 'localhost'
+
+class TestingConfig(Config):
+    DB_SERVER = 'localhost'
+    DATABASE_URI = 'sqlite:///:memory:'
+
+
+

There are many different ways and it’s up to you how you want to manage +your configuration files. However here a list of good recommendations:

+
    +
  • Keep a default configuration in version control. Either populate the +config with this default configuration or import it in your own +configuration files before overriding values.

  • +
  • Use an environment variable to switch between the configurations. +This can be done from outside the Python interpreter and makes +development and deployment much easier because you can quickly and +easily switch between different configs without having to touch the +code at all. If you are working often on different projects you can +even create your own script for sourcing that activates a virtualenv +and exports the development configuration for you.

  • +
  • Use a tool like fabric to push code and configuration separately +to the production server(s).

  • +
+
+
+

Instance Folders

+
+Changelog
+

Added in version 0.8.

+
+

Flask 0.8 introduces instance folders. Flask for a long time made it +possible to refer to paths relative to the application’s folder directly +(via Flask.root_path). This was also how many developers loaded +configurations stored next to the application. Unfortunately however this +only works well if applications are not packages in which case the root +path refers to the contents of the package.

+

With Flask 0.8 a new attribute was introduced: +Flask.instance_path. It refers to a new concept called the +“instance folder”. The instance folder is designed to not be under +version control and be deployment specific. It’s the perfect place to +drop things that either change at runtime or configuration files.

+

You can either explicitly provide the path of the instance folder when +creating the Flask application or you can let Flask autodetect the +instance folder. For explicit configuration use the instance_path +parameter:

+
app = Flask(__name__, instance_path='/path/to/instance/folder')
+
+
+

Please keep in mind that this path must be absolute when provided.

+

If the instance_path parameter is not provided the following default +locations are used:

+
    +
  • Uninstalled module:

    +
    /myapp.py
    +/instance
    +
    +
    +
  • +
  • Uninstalled package:

    +
    /myapp
    +    /__init__.py
    +/instance
    +
    +
    +
  • +
  • Installed module or package:

    +
    $PREFIX/lib/pythonX.Y/site-packages/myapp
    +$PREFIX/var/myapp-instance
    +
    +
    +

    $PREFIX is the prefix of your Python installation. This can be +/usr or the path to your virtualenv. You can print the value of +sys.prefix to see what the prefix is set to.

    +
  • +
+

Since the config object provided loading of configuration files from +relative filenames we made it possible to change the loading via filenames +to be relative to the instance path if wanted. The behavior of relative +paths in config files can be flipped between “relative to the application +root” (the default) to “relative to instance folder” via the +instance_relative_config switch to the application constructor:

+
app = Flask(__name__, instance_relative_config=True)
+
+
+

Here is a full example of how to configure Flask to preload the config +from a module and then override the config from a file in the instance +folder if it exists:

+
app = Flask(__name__, instance_relative_config=True)
+app.config.from_object('yourapplication.default_settings')
+app.config.from_pyfile('application.cfg', silent=True)
+
+
+

The path to the instance folder can be found via the +Flask.instance_path. Flask also provides a shortcut to open a +file from the instance folder with Flask.open_instance_resource().

+

Example usage for both:

+
filename = os.path.join(app.instance_path, 'application.cfg')
+with open(filename) as f:
+    config = f.read()
+
+# or via open_instance_resource:
+with app.open_instance_resource('application.cfg') as f:
+    config = f.read()
+
+
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/contributing/index.html b/_build/contributing/index.html new file mode 100644 index 00000000..ed0173ed --- /dev/null +++ b/_build/contributing/index.html @@ -0,0 +1,95 @@ + + + + + + + + Contributing — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Contributing

+

See the Pallets detailed contributing documentation for many ways +to contribute, including reporting issues, requesting features, asking or +answering questions, and making PRs.

+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/debugging/index.html b/_build/debugging/index.html new file mode 100644 index 00000000..9ad11729 --- /dev/null +++ b/_build/debugging/index.html @@ -0,0 +1,178 @@ + + + + + + + + Debugging Application Errors — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Debugging Application Errors

+
+

In Production

+

Do not run the development server, or enable the built-in debugger, in +a production environment. The debugger allows executing arbitrary +Python code from the browser. It’s protected by a pin, but that should +not be relied on for security.

+

Use an error logging tool, such as Sentry, as described in +Error Logging Tools, or enable logging and notifications as +described in Logging.

+

If you have access to the server, you could add some code to start an +external debugger if request.remote_addr matches your IP. Some IDE +debuggers also have a remote mode so breakpoints on the server can be +interacted with locally. Only enable a debugger temporarily.

+
+
+

The Built-In Debugger

+

The built-in Werkzeug development server provides a debugger which shows +an interactive traceback in the browser when an unhandled error occurs +during a request. This debugger should only be used during development.

+screenshot of debugger in action +
+

Warning

+

The debugger allows executing arbitrary Python code from the +browser. It is protected by a pin, but still represents a major +security risk. Do not run the development server or debugger in a +production environment.

+
+

The debugger is enabled by default when the development server is run in debug mode.

+
$ flask --app hello run --debug
+
+
+

When running from Python code, passing debug=True enables debug mode, which is +mostly equivalent.

+
app.run(debug=True)
+
+
+

Development Server and Command Line Interface have more information about running the debugger and +debug mode. More information about the debugger can be found in the Werkzeug +documentation.

+
+
+

External Debuggers

+

External debuggers, such as those provided by IDEs, can offer a more +powerful debugging experience than the built-in debugger. They can also +be used to step through code during a request before an error is raised, +or if no error is raised. Some even have a remote mode so you can debug +code running on another machine.

+

When using an external debugger, the app should still be in debug mode, otherwise Flask +turns unhandled errors into generic 500 error pages. However, the built-in debugger and +reloader should be disabled so they don’t interfere with the external debugger.

+
$ flask --app hello run --debug --no-debugger --no-reload
+
+
+

When running from Python:

+
app.run(debug=True, use_debugger=False, use_reloader=False)
+
+
+

Disabling these isn’t required, an external debugger will continue to work with the +following caveats.

+
    +
  • If the built-in debugger is not disabled, it will catch unhandled exceptions before +the external debugger can.

  • +
  • If the reloader is not disabled, it could cause an unexpected reload if code changes +during a breakpoint.

  • +
  • The development server will still catch unhandled exceptions if the built-in +debugger is disabled, otherwise it would crash on any error. If you want that (and +usually you don’t) pass passthrough_errors=True to app.run.

    +
    app.run(
    +    debug=True, passthrough_errors=True,
    +    use_debugger=False, use_reloader=False
    +)
    +
    +
    +
  • +
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/deploying/apache-httpd/index.html b/_build/deploying/apache-httpd/index.html new file mode 100644 index 00000000..f11353c1 --- /dev/null +++ b/_build/deploying/apache-httpd/index.html @@ -0,0 +1,158 @@ + + + + + + + + Apache httpd — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Apache httpd

+

Apache httpd is a fast, production level HTTP server. When serving +your application with one of the WSGI servers listed in Deploying to Production, it +is often good or necessary to put a dedicated HTTP server in front of +it. This “reverse proxy” can handle incoming requests, TLS, and other +security and performance concerns better than the WSGI server.

+

httpd can be installed using your system package manager, or a pre-built +executable for Windows. Installing and running httpd itself is outside +the scope of this doc. This page outlines the basics of configuring +httpd to proxy your application. Be sure to read its documentation to +understand what features are available.

+
+

Domain Name

+

Acquiring and configuring a domain name is outside the scope of this +doc. In general, you will buy a domain name from a registrar, pay for +server space with a hosting provider, and then point your registrar +at the hosting provider’s name servers.

+

To simulate this, you can also edit your hosts file, located at +/etc/hosts on Linux. Add a line that associates a name with the +local IP.

+

Modern Linux systems may be configured to treat any domain name that +ends with .localhost like this without adding it to the hosts +file.

+
+
/etc/hosts
+
127.0.0.1 hello.localhost
+
+
+
+
+
+

Configuration

+

The httpd configuration is located at /etc/httpd/conf/httpd.conf on +Linux. It may be different depending on your operating system. Check the +docs and look for httpd.conf.

+

Remove or comment out any existing DocumentRoot directive. Add the +config lines below. We’ll assume the WSGI server is listening locally at +http://127.0.0.1:8000.

+
+
/etc/httpd/conf/httpd.conf
+
LoadModule proxy_module modules/mod_proxy.so
+LoadModule proxy_http_module modules/mod_proxy_http.so
+ProxyPass / http://127.0.0.1:8000/
+RequestHeader set X-Forwarded-Proto http
+RequestHeader set X-Forwarded-Prefix /
+
+
+
+

The LoadModule lines might already exist. If so, make sure they are +uncommented instead of adding them manually.

+

Then Tell Flask it is Behind a Proxy so that your application uses the X-Forwarded +headers. X-Forwarded-For and X-Forwarded-Host are automatically +set by ProxyPass.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/deploying/asgi/index.html b/_build/deploying/asgi/index.html new file mode 100644 index 00000000..0f84d871 --- /dev/null +++ b/_build/deploying/asgi/index.html @@ -0,0 +1,117 @@ + + + + + + + + ASGI — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

ASGI

+

If you’d like to use an ASGI server you will need to utilise WSGI to +ASGI middleware. The asgiref +WsgiToAsgi +adapter is recommended as it integrates with the event loop used for +Flask’s Using async and await support. You can use the adapter by +wrapping the Flask app,

+
from asgiref.wsgi import WsgiToAsgi
+from flask import Flask
+
+app = Flask(__name__)
+
+...
+
+asgi_app = WsgiToAsgi(app)
+
+
+

and then serving the asgi_app with the ASGI server, e.g. using +Hypercorn,

+
$ hypercorn module:asgi_app
+
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/deploying/eventlet/index.html b/_build/deploying/eventlet/index.html new file mode 100644 index 00000000..d1f8a1b5 --- /dev/null +++ b/_build/deploying/eventlet/index.html @@ -0,0 +1,167 @@ + + + + + + + + eventlet — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

eventlet

+

Prefer using Gunicorn with eventlet workers rather than using +eventlet directly. Gunicorn provides a much more configurable and +production-tested server.

+

eventlet allows writing asynchronous, coroutine-based code that looks +like standard synchronous Python. It uses greenlet to enable task +switching without writing async/await or using asyncio.

+

gevent is another library that does the same thing. Certain +dependencies you have, or other considerations, may affect which of the +two you choose to use.

+

eventlet provides a WSGI server that can handle many connections at once +instead of one per worker process. You must actually use eventlet in +your own code to see any benefit to using the server.

+
+

Installing

+

When using eventlet, greenlet>=1.0 is required, otherwise context locals +such as request will not work as expected. When using PyPy, +PyPy>=7.3.7 is required.

+

Create a virtualenv, install your application, then install +eventlet.

+
$ cd hello-app
+$ python -m venv .venv
+$ . .venv/bin/activate
+$ pip install .  # install your application
+$ pip install eventlet
+
+
+
+
+

Running

+

To use eventlet to serve your application, write a script that imports +its wsgi.server, as well as your app or app factory.

+
+
wsgi.py
+
import eventlet
+from eventlet import wsgi
+from hello import create_app
+
+app = create_app()
+wsgi.server(eventlet.listen(("127.0.0.1", 8000)), app)
+
+
+
+
$ python wsgi.py
+(x) wsgi starting up on http://127.0.0.1:8000
+
+
+
+
+

Binding Externally

+

eventlet should not be run as root because it would cause your +application code to run as root, which is not secure. However, this +means it will not be possible to bind to port 80 or 443. Instead, a +reverse proxy such as nginx or Apache httpd should be used +in front of eventlet.

+

You can bind to all external IPs on a non-privileged port by using +0.0.0.0 in the server arguments shown in the previous section. +Don’t do this when using a reverse proxy setup, otherwise it will be +possible to bypass the proxy.

+

0.0.0.0 is not a valid address to navigate to, you’d use a specific +IP address in your browser.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/deploying/gevent/index.html b/_build/deploying/gevent/index.html new file mode 100644 index 00000000..246b7ff3 --- /dev/null +++ b/_build/deploying/gevent/index.html @@ -0,0 +1,166 @@ + + + + + + + + gevent — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

gevent

+

Prefer using Gunicorn or uWSGI with gevent workers rather +than using gevent directly. Gunicorn and uWSGI provide much more +configurable and production-tested servers.

+

gevent allows writing asynchronous, coroutine-based code that looks +like standard synchronous Python. It uses greenlet to enable task +switching without writing async/await or using asyncio.

+

eventlet is another library that does the same thing. Certain +dependencies you have, or other considerations, may affect which of the +two you choose to use.

+

gevent provides a WSGI server that can handle many connections at once +instead of one per worker process. You must actually use gevent in your +own code to see any benefit to using the server.

+
+

Installing

+

When using gevent, greenlet>=1.0 is required, otherwise context locals +such as request will not work as expected. When using PyPy, +PyPy>=7.3.7 is required.

+

Create a virtualenv, install your application, then install gevent.

+
$ cd hello-app
+$ python -m venv .venv
+$ . .venv/bin/activate
+$ pip install .  # install your application
+$ pip install gevent
+
+
+
+
+

Running

+

To use gevent to serve your application, write a script that imports its +WSGIServer, as well as your app or app factory.

+
+
wsgi.py
+
from gevent.pywsgi import WSGIServer
+from hello import create_app
+
+app = create_app()
+http_server = WSGIServer(("127.0.0.1", 8000), app)
+http_server.serve_forever()
+
+
+
+
$ python wsgi.py
+
+
+

No output is shown when the server starts.

+
+
+

Binding Externally

+

gevent should not be run as root because it would cause your +application code to run as root, which is not secure. However, this +means it will not be possible to bind to port 80 or 443. Instead, a +reverse proxy such as nginx or Apache httpd should be used +in front of gevent.

+

You can bind to all external IPs on a non-privileged port by using +0.0.0.0 in the server arguments shown in the previous section. Don’t +do this when using a reverse proxy setup, otherwise it will be possible +to bypass the proxy.

+

0.0.0.0 is not a valid address to navigate to, you’d use a specific +IP address in your browser.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/deploying/gunicorn/index.html b/_build/deploying/gunicorn/index.html new file mode 100644 index 00000000..6b285abb --- /dev/null +++ b/_build/deploying/gunicorn/index.html @@ -0,0 +1,207 @@ + + + + + + + + Gunicorn — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Gunicorn

+

Gunicorn is a pure Python WSGI server with simple configuration and +multiple worker implementations for performance tuning.

+
    +
  • It tends to integrate easily with hosting platforms.

  • +
  • It does not support Windows (but does run on WSL).

  • +
  • It is easy to install as it does not require additional dependencies +or compilation.

  • +
  • It has built-in async worker support using gevent or eventlet.

  • +
+

This page outlines the basics of running Gunicorn. Be sure to read its +documentation and use gunicorn --help to understand what features +are available.

+
+

Installing

+

Gunicorn is easy to install, as it does not require external +dependencies or compilation. It runs on Windows only under WSL.

+

Create a virtualenv, install your application, then install +gunicorn.

+
$ cd hello-app
+$ python -m venv .venv
+$ . .venv/bin/activate
+$ pip install .  # install your application
+$ pip install gunicorn
+
+
+
+
+

Running

+

The only required argument to Gunicorn tells it how to load your Flask +application. The syntax is {module_import}:{app_variable}. +module_import is the dotted import name to the module with your +application. app_variable is the variable with the application. It +can also be a function call (with any arguments) if you’re using the +app factory pattern.

+
# equivalent to 'from hello import app'
+$ gunicorn -w 4 'hello:app'
+
+# equivalent to 'from hello import create_app; create_app()'
+$ gunicorn -w 4 'hello:create_app()'
+
+Starting gunicorn 20.1.0
+Listening at: http://127.0.0.1:8000 (x)
+Using worker: sync
+Booting worker with pid: x
+Booting worker with pid: x
+Booting worker with pid: x
+Booting worker with pid: x
+
+
+

The -w option specifies the number of processes to run; a starting +value could be CPU * 2. The default is only 1 worker, which is +probably not what you want for the default worker type.

+

Logs for each request aren’t shown by default, only worker info and +errors are shown. To show access logs on stdout, use the +--access-logfile=- option.

+
+
+

Binding Externally

+

Gunicorn should not be run as root because it would cause your +application code to run as root, which is not secure. However, this +means it will not be possible to bind to port 80 or 443. Instead, a +reverse proxy such as nginx or Apache httpd should be used +in front of Gunicorn.

+

You can bind to all external IPs on a non-privileged port using the +-b 0.0.0.0 option. Don’t do this when using a reverse proxy setup, +otherwise it will be possible to bypass the proxy.

+
$ gunicorn -w 4 -b 0.0.0.0 'hello:create_app()'
+Listening at: http://0.0.0.0:8000 (x)
+
+
+

0.0.0.0 is not a valid address to navigate to, you’d use a specific +IP address in your browser.

+
+
+

Async with gevent or eventlet

+

The default sync worker is appropriate for many use cases. If you need +asynchronous support, Gunicorn provides workers using either gevent +or eventlet. This is not the same as Python’s async/await, or the +ASGI server spec. You must actually use gevent/eventlet in your own code +to see any benefit to using the workers.

+

When using either gevent or eventlet, greenlet>=1.0 is required, +otherwise context locals such as request will not work as expected. +When using PyPy, PyPy>=7.3.7 is required.

+

To use gevent:

+
$ gunicorn -k gevent 'hello:create_app()'
+Starting gunicorn 20.1.0
+Listening at: http://127.0.0.1:8000 (x)
+Using worker: gevent
+Booting worker with pid: x
+
+
+

To use eventlet:

+
$ gunicorn -k eventlet 'hello:create_app()'
+Starting gunicorn 20.1.0
+Listening at: http://127.0.0.1:8000 (x)
+Using worker: eventlet
+Booting worker with pid: x
+
+
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/deploying/index.html b/_build/deploying/index.html new file mode 100644 index 00000000..ed6dd3a0 --- /dev/null +++ b/_build/deploying/index.html @@ -0,0 +1,171 @@ + + + + + + + + Deploying to Production — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Deploying to Production

+

After developing your application, you’ll want to make it available +publicly to other users. When you’re developing locally, you’re probably +using the built-in development server, debugger, and reloader. These +should not be used in production. Instead, you should use a dedicated +WSGI server or hosting platform, some of which will be described here.

+

“Production” means “not development”, which applies whether you’re +serving your application publicly to millions of users or privately / +locally to a single user. Do not use the development server when +deploying to production. It is intended for use only during local +development. It is not designed to be particularly secure, stable, or +efficient.

+
+

Self-Hosted Options

+

Flask is a WSGI application. A WSGI server is used to run the +application, converting incoming HTTP requests to the standard WSGI +environ, and converting outgoing WSGI responses to HTTP responses.

+

The primary goal of these docs is to familiarize you with the concepts +involved in running a WSGI application using a production WSGI server +and HTTP server. There are many WSGI servers and HTTP servers, with many +configuration possibilities. The pages below discuss the most common +servers, and show the basics of running each one. The next section +discusses platforms that can manage this for you.

+ +

WSGI servers have HTTP servers built-in. However, a dedicated HTTP +server may be safer, more efficient, or more capable. Putting an HTTP +server in front of the WSGI server is called a “reverse proxy.”

+ +

This list is not exhaustive, and you should evaluate these and other +servers based on your application’s needs. Different servers will have +different capabilities, configuration, and support.

+
+
+

Hosting Platforms

+

There are many services available for hosting web applications without +needing to maintain your own server, networking, domain, etc. Some +services may have a free tier up to a certain time or bandwidth. Many of +these services use one of the WSGI servers described above, or a similar +interface. The links below are for some of the most common platforms, +which have instructions for Flask, WSGI, or Python.

+ +

This list is not exhaustive, and you should evaluate these and other +services based on your application’s needs. Different services will have +different capabilities, configuration, pricing, and support.

+

You’ll probably need to Tell Flask it is Behind a Proxy when using most hosting +platforms.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/deploying/mod_wsgi/index.html b/_build/deploying/mod_wsgi/index.html new file mode 100644 index 00000000..994faba8 --- /dev/null +++ b/_build/deploying/mod_wsgi/index.html @@ -0,0 +1,181 @@ + + + + + + + + mod_wsgi — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

mod_wsgi

+

mod_wsgi is a WSGI server integrated with the Apache httpd server. +The modern mod_wsgi-express command makes it easy to configure and +start the server without needing to write Apache httpd configuration.

+
    +
  • Tightly integrated with Apache httpd.

  • +
  • Supports Windows directly.

  • +
  • Requires a compiler and the Apache development headers to install.

  • +
  • Does not require a reverse proxy setup.

  • +
+

This page outlines the basics of running mod_wsgi-express, not the more +complex installation and configuration with httpd. Be sure to read the +mod_wsgi-express, mod_wsgi, and Apache httpd documentation to +understand what features are available.

+
+

Installing

+

Installing mod_wsgi requires a compiler and the Apache server and +development headers installed. You will get an error if they are not. +How to install them depends on the OS and package manager that you use.

+

Create a virtualenv, install your application, then install +mod_wsgi.

+
$ cd hello-app
+$ python -m venv .venv
+$ . .venv/bin/activate
+$ pip install .  # install your application
+$ pip install mod_wsgi
+
+
+
+
+

Running

+

The only argument to mod_wsgi-express specifies a script containing +your Flask application, which must be called application. You can +write a small script to import your app with this name, or to create it +if using the app factory pattern.

+
+
wsgi.py
+
from hello import app
+
+application = app
+
+
+
+
+
wsgi.py
+
from hello import create_app
+
+application = create_app()
+
+
+
+

Now run the mod_wsgi-express start-server command.

+
$ mod_wsgi-express start-server wsgi.py --processes 4
+
+
+

The --processes option specifies the number of worker processes to +run; a starting value could be CPU * 2.

+

Logs for each request aren’t show in the terminal. If an error occurs, +its information is written to the error log file shown when starting the +server.

+
+
+

Binding Externally

+

Unlike the other WSGI servers in these docs, mod_wsgi can be run as +root to bind to privileged ports like 80 and 443. However, it must be +configured to drop permissions to a different user and group for the +worker processes.

+

For example, if you created a hello user and group, you should +install your virtualenv and application as that user, then tell +mod_wsgi to drop to that user after starting.

+
$ sudo /home/hello/.venv/bin/mod_wsgi-express start-server \
+    /home/hello/wsgi.py \
+    --user hello --group hello --port 80 --processes 4
+
+
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/deploying/nginx/index.html b/_build/deploying/nginx/index.html new file mode 100644 index 00000000..400904f4 --- /dev/null +++ b/_build/deploying/nginx/index.html @@ -0,0 +1,162 @@ + + + + + + + + nginx — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

nginx

+

nginx is a fast, production level HTTP server. When serving your +application with one of the WSGI servers listed in Deploying to Production, it is +often good or necessary to put a dedicated HTTP server in front of it. +This “reverse proxy” can handle incoming requests, TLS, and other +security and performance concerns better than the WSGI server.

+

Nginx can be installed using your system package manager, or a pre-built +executable for Windows. Installing and running Nginx itself is outside +the scope of this doc. This page outlines the basics of configuring +Nginx to proxy your application. Be sure to read its documentation to +understand what features are available.

+
+

Domain Name

+

Acquiring and configuring a domain name is outside the scope of this +doc. In general, you will buy a domain name from a registrar, pay for +server space with a hosting provider, and then point your registrar +at the hosting provider’s name servers.

+

To simulate this, you can also edit your hosts file, located at +/etc/hosts on Linux. Add a line that associates a name with the +local IP.

+

Modern Linux systems may be configured to treat any domain name that +ends with .localhost like this without adding it to the hosts +file.

+
+
/etc/hosts
+
127.0.0.1 hello.localhost
+
+
+
+
+
+

Configuration

+

The nginx configuration is located at /etc/nginx/nginx.conf on +Linux. It may be different depending on your operating system. Check the +docs and look for nginx.conf.

+

Remove or comment out any existing server section. Add a server +section and use the proxy_pass directive to point to the address the +WSGI server is listening on. We’ll assume the WSGI server is listening +locally at http://127.0.0.1:8000.

+
+
/etc/nginx.conf
+
server {
+    listen 80;
+    server_name _;
+
+    location / {
+        proxy_pass http://127.0.0.1:8000/;
+        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+        proxy_set_header X-Forwarded-Proto $scheme;
+        proxy_set_header X-Forwarded-Host $host;
+        proxy_set_header X-Forwarded-Prefix /;
+    }
+}
+
+
+
+

Then Tell Flask it is Behind a Proxy so that your application uses these headers.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/deploying/proxy_fix/index.html b/_build/deploying/proxy_fix/index.html new file mode 100644 index 00000000..04342c2e --- /dev/null +++ b/_build/deploying/proxy_fix/index.html @@ -0,0 +1,121 @@ + + + + + + + + Tell Flask it is Behind a Proxy — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Tell Flask it is Behind a Proxy

+

When using a reverse proxy, or many Python hosting platforms, the proxy +will intercept and forward all external requests to the local WSGI +server.

+

From the WSGI server and Flask application’s perspectives, requests are +now coming from the HTTP server to the local address, rather than from +the remote address to the external server address.

+

HTTP servers should set X-Forwarded- headers to pass on the real +values to the application. The application can then be told to trust and +use those values by wrapping it with the +X-Forwarded-For Proxy Fix middleware provided by Werkzeug.

+

This middleware should only be used if the application is actually +behind a proxy, and should be configured with the number of proxies that +are chained in front of it. Not all proxies set all the headers. Since +incoming headers can be faked, you must set how many proxies are setting +each header so the middleware knows what to trust.

+
from werkzeug.middleware.proxy_fix import ProxyFix
+
+app.wsgi_app = ProxyFix(
+    app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1
+)
+
+
+

Remember, only apply this middleware if you are behind a proxy, and set +the correct number of proxies that set each header. It can be a security +issue if you get this configuration wrong.

+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/deploying/uwsgi/index.html b/_build/deploying/uwsgi/index.html new file mode 100644 index 00000000..82df015e --- /dev/null +++ b/_build/deploying/uwsgi/index.html @@ -0,0 +1,220 @@ + + + + + + + + uWSGI — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

uWSGI

+

uWSGI is a fast, compiled server suite with extensive configuration +and capabilities beyond a basic server.

+
    +
  • It can be very performant due to being a compiled program.

  • +
  • It is complex to configure beyond the basic application, and has so +many options that it can be difficult for beginners to understand.

  • +
  • It does not support Windows (but does run on WSL).

  • +
  • It requires a compiler to install in some cases.

  • +
+

This page outlines the basics of running uWSGI. Be sure to read its +documentation to understand what features are available.

+
+

Installing

+

uWSGI has multiple ways to install it. The most straightforward is to +install the pyuwsgi package, which provides precompiled wheels for +common platforms. However, it does not provide SSL support, which can be +provided with a reverse proxy instead.

+

Create a virtualenv, install your application, then install pyuwsgi.

+
$ cd hello-app
+$ python -m venv .venv
+$ . .venv/bin/activate
+$ pip install .  # install your application
+$ pip install pyuwsgi
+
+
+

If you have a compiler available, you can install the uwsgi package +instead. Or install the pyuwsgi package from sdist instead of wheel. +Either method will include SSL support.

+
$ pip install uwsgi
+
+# or
+$ pip install --no-binary pyuwsgi pyuwsgi
+
+
+
+
+

Running

+

The most basic way to run uWSGI is to tell it to start an HTTP server +and import your application.

+
$ uwsgi --http 127.0.0.1:8000 --master -p 4 -w hello:app
+
+*** Starting uWSGI 2.0.20 (64bit) on [x] ***
+*** Operational MODE: preforking ***
+mounting hello:app on /
+spawned uWSGI master process (pid: x)
+spawned uWSGI worker 1 (pid: x, cores: 1)
+spawned uWSGI worker 2 (pid: x, cores: 1)
+spawned uWSGI worker 3 (pid: x, cores: 1)
+spawned uWSGI worker 4 (pid: x, cores: 1)
+spawned uWSGI http 1 (pid: x)
+
+
+

If you’re using the app factory pattern, you’ll need to create a small +Python file to create the app, then point uWSGI at that.

+
+
wsgi.py
+
from hello import create_app
+
+app = create_app()
+
+
+
+
$ uwsgi --http 127.0.0.1:8000 --master -p 4 -w wsgi:app
+
+
+

The --http option starts an HTTP server at 127.0.0.1 port 8000. The +--master option specifies the standard worker manager. The -p +option starts 4 worker processes; a starting value could be CPU * 2. +The -w option tells uWSGI how to import your application

+
+
+

Binding Externally

+

uWSGI should not be run as root with the configuration shown in this doc +because it would cause your application code to run as root, which is +not secure. However, this means it will not be possible to bind to port +80 or 443. Instead, a reverse proxy such as nginx or +Apache httpd should be used in front of uWSGI. It is possible to +run uWSGI as root securely, but that is beyond the scope of this doc.

+

uWSGI has optimized integration with Nginx uWSGI and +Apache mod_proxy_uwsgi, and possibly other servers, instead of using +a standard HTTP proxy. That configuration is beyond the scope of this +doc, see the links for more information.

+

You can bind to all external IPs on a non-privileged port using the +--http 0.0.0.0:8000 option. Don’t do this when using a reverse proxy +setup, otherwise it will be possible to bypass the proxy.

+
$ uwsgi --http 0.0.0.0:8000 --master -p 4 -w wsgi:app
+
+
+

0.0.0.0 is not a valid address to navigate to, you’d use a specific +IP address in your browser.

+
+
+

Async with gevent

+

The default sync worker is appropriate for many use cases. If you need +asynchronous support, uWSGI provides a gevent worker. This is not the +same as Python’s async/await, or the ASGI server spec. You must +actually use gevent in your own code to see any benefit to using the +worker.

+

When using gevent, greenlet>=1.0 is required, otherwise context locals +such as request will not work as expected. When using PyPy, +PyPy>=7.3.7 is required.

+
$ uwsgi --http 127.0.0.1:8000 --master --gevent 100 -w wsgi:app
+
+*** Starting uWSGI 2.0.20 (64bit) on [x] ***
+*** Operational MODE: async ***
+mounting hello:app on /
+spawned uWSGI master process (pid: x)
+spawned uWSGI worker 1 (pid: x, cores: 100)
+spawned uWSGI http 1 (pid: x)
+*** running gevent loop engine [addr:x] ***
+
+
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/deploying/waitress/index.html b/_build/deploying/waitress/index.html new file mode 100644 index 00000000..3d3e9b80 --- /dev/null +++ b/_build/deploying/waitress/index.html @@ -0,0 +1,164 @@ + + + + + + + + Waitress — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Waitress

+

Waitress is a pure Python WSGI server.

+
    +
  • It is easy to configure.

  • +
  • It supports Windows directly.

  • +
  • It is easy to install as it does not require additional dependencies +or compilation.

  • +
  • It does not support streaming requests, full request data is always +buffered.

  • +
  • It uses a single process with multiple thread workers.

  • +
+

This page outlines the basics of running Waitress. Be sure to read its +documentation and waitress-serve --help to understand what features +are available.

+
+

Installing

+

Create a virtualenv, install your application, then install +waitress.

+
$ cd hello-app
+$ python -m venv .venv
+$ . .venv/bin/activate
+$ pip install .  # install your application
+$ pip install waitress
+
+
+
+
+

Running

+

The only required argument to waitress-serve tells it how to load +your Flask application. The syntax is {module}:{app}. module is +the dotted import name to the module with your application. app is +the variable with the application. If you’re using the app factory +pattern, use --call {module}:{factory} instead.

+
# equivalent to 'from hello import app'
+$ waitress-serve --host 127.0.0.1 hello:app
+
+# equivalent to 'from hello import create_app; create_app()'
+$ waitress-serve --host 127.0.0.1 --call hello:create_app
+
+Serving on http://127.0.0.1:8080
+
+
+

The --host option binds the server to local 127.0.0.1 only.

+

Logs for each request aren’t shown, only errors are shown. Logging can +be configured through the Python interface instead of the command line.

+
+
+

Binding Externally

+

Waitress should not be run as root because it would cause your +application code to run as root, which is not secure. However, this +means it will not be possible to bind to port 80 or 443. Instead, a +reverse proxy such as nginx or Apache httpd should be used +in front of Waitress.

+

You can bind to all external IPs on a non-privileged port by not +specifying the --host option. Don’t do this when using a reverse +proxy setup, otherwise it will be possible to bypass the proxy.

+

0.0.0.0 is not a valid address to navigate to, you’d use a specific +IP address in your browser.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/design/index.html b/_build/design/index.html new file mode 100644 index 00000000..ede4b16d --- /dev/null +++ b/_build/design/index.html @@ -0,0 +1,298 @@ + + + + + + + + Design Decisions in Flask — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Design Decisions in Flask

+

If you are curious why Flask does certain things the way it does and not +differently, this section is for you. This should give you an idea about +some of the design decisions that may appear arbitrary and surprising at +first, especially in direct comparison with other frameworks.

+
+

The Explicit Application Object

+

A Python web application based on WSGI has to have one central callable +object that implements the actual application. In Flask this is an +instance of the Flask class. Each Flask application has +to create an instance of this class itself and pass it the name of the +module, but why can’t Flask do that itself?

+

Without such an explicit application object the following code:

+
from flask import Flask
+app = Flask(__name__)
+
+@app.route('/')
+def index():
+    return 'Hello World!'
+
+
+

Would look like this instead:

+
from hypothetical_flask import route
+
+@route('/')
+def index():
+    return 'Hello World!'
+
+
+

There are three major reasons for this. The most important one is that +implicit application objects require that there may only be one instance at +the time. There are ways to fake multiple applications with a single +application object, like maintaining a stack of applications, but this +causes some problems I won’t outline here in detail. Now the question is: +when does a microframework need more than one application at the same +time? A good example for this is unit testing. When you want to test +something it can be very helpful to create a minimal application to test +specific behavior. When the application object is deleted everything it +allocated will be freed again.

+

Another thing that becomes possible when you have an explicit object lying +around in your code is that you can subclass the base class +(Flask) to alter specific behavior. This would not be +possible without hacks if the object were created ahead of time for you +based on a class that is not exposed to you.

+

But there is another very important reason why Flask depends on an +explicit instantiation of that class: the package name. Whenever you +create a Flask instance you usually pass it __name__ as package name. +Flask depends on that information to properly load resources relative +to your module. With Python’s outstanding support for reflection it can +then access the package to figure out where the templates and static files +are stored (see open_resource()). Now obviously there +are frameworks around that do not need any configuration and will still be +able to load templates relative to your application module. But they have +to use the current working directory for that, which is a very unreliable +way to determine where the application is. The current working directory +is process-wide and if you are running multiple applications in one +process (which could happen in a webserver without you knowing) the paths +will be off. Worse: many webservers do not set the working directory to +the directory of your application but to the document root which does not +have to be the same folder.

+

The third reason is “explicit is better than implicit”. That object is +your WSGI application, you don’t have to remember anything else. If you +want to apply a WSGI middleware, just wrap it and you’re done (though +there are better ways to do that so that you do not lose the reference +to the application object wsgi_app()).

+

Furthermore this design makes it possible to use a factory function to +create the application which is very helpful for unit testing and similar +things (Application Factories).

+
+
+

The Routing System

+

Flask uses the Werkzeug routing system which was designed to +automatically order routes by complexity. This means that you can declare +routes in arbitrary order and they will still work as expected. This is a +requirement if you want to properly implement decorator based routing +since decorators could be fired in undefined order when the application is +split into multiple modules.

+

Another design decision with the Werkzeug routing system is that routes +in Werkzeug try to ensure that URLs are unique. Werkzeug will go quite far +with that in that it will automatically redirect to a canonical URL if a route +is ambiguous.

+
+
+

One Template Engine

+

Flask decides on one template engine: Jinja2. Why doesn’t Flask have a +pluggable template engine interface? You can obviously use a different +template engine, but Flask will still configure Jinja2 for you. While +that limitation that Jinja2 is always configured will probably go away, +the decision to bundle one template engine and use that will not.

+

Template engines are like programming languages and each of those engines +has a certain understanding about how things work. On the surface they +all work the same: you tell the engine to evaluate a template with a set +of variables and take the return value as string.

+

But that’s about where similarities end. Jinja2 for example has an +extensive filter system, a certain way to do template inheritance, +support for reusable blocks (macros) that can be used from inside +templates and also from Python code, supports iterative template +rendering, configurable syntax and more. On the other hand an engine +like Genshi is based on XML stream evaluation, template inheritance by +taking the availability of XPath into account and more. Mako on the +other hand treats templates similar to Python modules.

+

When it comes to connecting a template engine with an application or +framework there is more than just rendering templates. For instance, +Flask uses Jinja2’s extensive autoescaping support. Also it provides +ways to access macros from Jinja2 templates.

+

A template abstraction layer that would not take the unique features of +the template engines away is a science on its own and a too large +undertaking for a microframework like Flask.

+

Furthermore extensions can then easily depend on one template language +being present. You can easily use your own templating language, but an +extension could still depend on Jinja itself.

+
+
+

What does “micro” mean?

+

“Micro” does not mean that your whole web application has to fit into a single +Python file (although it certainly can), nor does it mean that Flask is lacking +in functionality. The “micro” in microframework means Flask aims to keep the +core simple but extensible. Flask won’t make many decisions for you, such as +what database to use. Those decisions that it does make, such as what +templating engine to use, are easy to change. Everything else is up to you, so +that Flask can be everything you need and nothing you don’t.

+

By default, Flask does not include a database abstraction layer, form +validation or anything else where different libraries already exist that can +handle that. Instead, Flask supports extensions to add such functionality to +your application as if it was implemented in Flask itself. Numerous extensions +provide database integration, form validation, upload handling, various open +authentication technologies, and more. Flask may be “micro”, but it’s ready for +production use on a variety of needs.

+

Why does Flask call itself a microframework and yet it depends on two +libraries (namely Werkzeug and Jinja2). Why shouldn’t it? If we look +over to the Ruby side of web development there we have a protocol very +similar to WSGI. Just that it’s called Rack there, but besides that it +looks very much like a WSGI rendition for Ruby. But nearly all +applications in Ruby land do not work with Rack directly, but on top of a +library with the same name. This Rack library has two equivalents in +Python: WebOb (formerly Paste) and Werkzeug. Paste is still around but +from my understanding it’s sort of deprecated in favour of WebOb. The +development of WebOb and Werkzeug started side by side with similar ideas +in mind: be a good implementation of WSGI for other applications to take +advantage.

+

Flask is a framework that takes advantage of the work already done by +Werkzeug to properly interface WSGI (which can be a complex task at +times). Thanks to recent developments in the Python package +infrastructure, packages with dependencies are no longer an issue and +there are very few reasons against having libraries that depend on others.

+
+
+

Thread Locals

+

Flask uses thread local objects (context local objects in fact, they +support greenlet contexts as well) for request, session and an extra +object you can put your own things on (g). Why is that and +isn’t that a bad idea?

+

Yes it is usually not such a bright idea to use thread locals. They cause +troubles for servers that are not based on the concept of threads and make +large applications harder to maintain. However Flask is just not designed +for large applications or asynchronous servers. Flask wants to make it +quick and easy to write a traditional web application.

+
+
+

Async/await and ASGI support

+

Flask supports async coroutines for view functions by executing the +coroutine on a separate thread instead of using an event loop on the +main thread as an async-first (ASGI) framework would. This is necessary +for Flask to remain backwards compatible with extensions and code built +before async was introduced into Python. This compromise introduces +a performance cost compared with the ASGI frameworks, due to the +overhead of the threads.

+

Due to how tied to WSGI Flask’s code is, it’s not clear if it’s possible +to make the Flask class support ASGI and WSGI at the same time. Work +is currently being done in Werkzeug to work with ASGI, which may +eventually enable support in Flask as well.

+

See Using async and await for more discussion.

+
+
+

What Flask is, What Flask is Not

+

Flask will never have a database layer. It will not have a form library +or anything else in that direction. Flask itself just bridges to Werkzeug +to implement a proper WSGI application and to Jinja2 to handle templating. +It also binds to a few common standard library packages such as logging. +Everything else is up for extensions.

+

Why is this the case? Because people have different preferences and +requirements and Flask could not meet those if it would force any of this +into the core. The majority of web applications will need a template +engine in some sort. However not every application needs a SQL database.

+

As your codebase grows, you are free to make the design decisions appropriate +for your project. Flask will continue to provide a very simple glue layer to +the best that Python has to offer. You can implement advanced patterns in +SQLAlchemy or another database tool, introduce non-relational data persistence +as appropriate, and take advantage of framework-agnostic tools built for WSGI, +the Python web interface.

+

The idea of Flask is to build a good foundation for all applications. +Everything else is up to you or extensions.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/errorhandling/index.html b/_build/errorhandling/index.html new file mode 100644 index 00000000..918f72b6 --- /dev/null +++ b/_build/errorhandling/index.html @@ -0,0 +1,552 @@ + + + + + + + + Handling Application Errors — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Handling Application Errors

+

Applications fail, servers fail. Sooner or later you will see an exception +in production. Even if your code is 100% correct, you will still see +exceptions from time to time. Why? Because everything else involved will +fail. Here are some situations where perfectly fine code can lead to server +errors:

+
    +
  • the client terminated the request early and the application was still +reading from the incoming data

  • +
  • the database server was overloaded and could not handle the query

  • +
  • a filesystem is full

  • +
  • a harddrive crashed

  • +
  • a backend server overloaded

  • +
  • a programming error in a library you are using

  • +
  • network connection of the server to another system failed

  • +
+

And that’s just a small sample of issues you could be facing. So how do we +deal with that sort of problem? By default if your application runs in +production mode, and an exception is raised Flask will display a very simple +page for you and log the exception to the logger.

+

But there is more you can do, and we will cover some better setups to deal +with errors including custom exceptions and 3rd party tools.

+
+

Error Logging Tools

+

Sending error mails, even if just for critical ones, can become +overwhelming if enough users are hitting the error and log files are +typically never looked at. This is why we recommend using Sentry for dealing with application errors. It’s +available as a source-available project on GitHub and is also available as a hosted version which you can try for free. Sentry +aggregates duplicate errors, captures the full stack trace and local +variables for debugging, and sends you mails based on new errors or +frequency thresholds.

+

To use Sentry you need to install the sentry-sdk client with extra +flask dependencies.

+
$ pip install sentry-sdk[flask]
+
+
+

And then add this to your Flask app:

+
import sentry_sdk
+from sentry_sdk.integrations.flask import FlaskIntegration
+
+sentry_sdk.init('YOUR_DSN_HERE', integrations=[FlaskIntegration()])
+
+
+

The YOUR_DSN_HERE value needs to be replaced with the DSN value you +get from your Sentry installation.

+

After installation, failures leading to an Internal Server Error +are automatically reported to Sentry and from there you can +receive error notifications.

+

See also:

+ +
+
+

Error Handlers

+

When an error occurs in Flask, an appropriate HTTP status code will be +returned. 400-499 indicate errors with the client’s request data, or +about the data requested. 500-599 indicate errors with the server or +application itself.

+

You might want to show custom error pages to the user when an error occurs. +This can be done by registering error handlers.

+

An error handler is a function that returns a response when a type of error is +raised, similar to how a view is a function that returns a response when a +request URL is matched. It is passed the instance of the error being handled, +which is most likely a HTTPException.

+

The status code of the response will not be set to the handler’s code. Make +sure to provide the appropriate HTTP status code when returning a response from +a handler.

+
+

Registering

+

Register handlers by decorating a function with +errorhandler(). Or use +register_error_handler() to register the function later. +Remember to set the error code when returning the response.

+
@app.errorhandler(werkzeug.exceptions.BadRequest)
+def handle_bad_request(e):
+    return 'bad request!', 400
+
+# or, without the decorator
+app.register_error_handler(400, handle_bad_request)
+
+
+

werkzeug.exceptions.HTTPException subclasses like +BadRequest and their HTTP codes are interchangeable +when registering handlers. (BadRequest.code == 400)

+

Non-standard HTTP codes cannot be registered by code because they are not known +by Werkzeug. Instead, define a subclass of +HTTPException with the appropriate code and +register and raise that exception class.

+
class InsufficientStorage(werkzeug.exceptions.HTTPException):
+    code = 507
+    description = 'Not enough storage space.'
+
+app.register_error_handler(InsufficientStorage, handle_507)
+
+raise InsufficientStorage()
+
+
+

Handlers can be registered for any exception class, not just +HTTPException subclasses or HTTP status +codes. Handlers can be registered for a specific class, or for all subclasses +of a parent class.

+
+
+

Handling

+

When building a Flask application you will run into exceptions. If some part +of your code breaks while handling a request (and you have no error handlers +registered), a “500 Internal Server Error” +(InternalServerError) will be returned by default. +Similarly, “404 Not Found” +(NotFound) error will occur if a request is sent to an unregistered route. +If a route receives an unallowed request method, a “405 Method Not Allowed” +(MethodNotAllowed) will be raised. These are all +subclasses of HTTPException and are provided by +default in Flask.

+

Flask gives you the ability to raise any HTTP exception registered by +Werkzeug. However, the default HTTP exceptions return simple exception +pages. You might want to show custom error pages to the user when an error occurs. +This can be done by registering error handlers.

+

When Flask catches an exception while handling a request, it is first looked up by code. +If no handler is registered for the code, Flask looks up the error by its class hierarchy; the most specific handler is chosen. +If no handler is registered, HTTPException subclasses show a +generic message about their code, while other exceptions are converted to a +generic “500 Internal Server Error”.

+

For example, if an instance of ConnectionRefusedError is raised, +and a handler is registered for ConnectionError and +ConnectionRefusedError, the more specific ConnectionRefusedError +handler is called with the exception instance to generate the response.

+

Handlers registered on the blueprint take precedence over those registered +globally on the application, assuming a blueprint is handling the request that +raises the exception. However, the blueprint cannot handle 404 routing errors +because the 404 occurs at the routing level before the blueprint can be +determined.

+
+
+

Generic Exception Handlers

+

It is possible to register error handlers for very generic base classes +such as HTTPException or even Exception. However, be aware that +these will catch more than you might expect.

+

For example, an error handler for HTTPException might be useful for turning +the default HTML errors pages into JSON. However, this +handler will trigger for things you don’t cause directly, such as 404 +and 405 errors during routing. Be sure to craft your handler carefully +so you don’t lose information about the HTTP error.

+
from flask import json
+from werkzeug.exceptions import HTTPException
+
+@app.errorhandler(HTTPException)
+def handle_exception(e):
+    """Return JSON instead of HTML for HTTP errors."""
+    # start with the correct headers and status code from the error
+    response = e.get_response()
+    # replace the body with JSON
+    response.data = json.dumps({
+        "code": e.code,
+        "name": e.name,
+        "description": e.description,
+    })
+    response.content_type = "application/json"
+    return response
+
+
+

An error handler for Exception might seem useful for changing how +all errors, even unhandled ones, are presented to the user. However, +this is similar to doing except Exception: in Python, it will +capture all otherwise unhandled errors, including all HTTP status +codes.

+

In most cases it will be safer to register handlers for more +specific exceptions. Since HTTPException instances are valid WSGI +responses, you could also pass them through directly.

+
from werkzeug.exceptions import HTTPException
+
+@app.errorhandler(Exception)
+def handle_exception(e):
+    # pass through HTTP errors
+    if isinstance(e, HTTPException):
+        return e
+
+    # now you're handling non-HTTP exceptions only
+    return render_template("500_generic.html", e=e), 500
+
+
+

Error handlers still respect the exception class hierarchy. If you +register handlers for both HTTPException and Exception, the +Exception handler will not handle HTTPException subclasses +because the HTTPException handler is more specific.

+
+
+

Unhandled Exceptions

+

When there is no error handler registered for an exception, a 500 +Internal Server Error will be returned instead. See +flask.Flask.handle_exception() for information about this +behavior.

+

If there is an error handler registered for InternalServerError, +this will be invoked. As of Flask 1.1.0, this error handler will always +be passed an instance of InternalServerError, not the original +unhandled error.

+

The original error is available as e.original_exception.

+

An error handler for “500 Internal Server Error” will be passed uncaught +exceptions in addition to explicit 500 errors. In debug mode, a handler +for “500 Internal Server Error” will not be used. Instead, the +interactive debugger will be shown.

+
+
+
+

Custom Error Pages

+

Sometimes when building a Flask application, you might want to raise a +HTTPException to signal to the user that +something is wrong with the request. Fortunately, Flask comes with a handy +abort() function that aborts a request with a HTTP error from +werkzeug as desired. It will also provide a plain black and white error page +for you with a basic description, but nothing fancy.

+

Depending on the error code it is less or more likely for the user to +actually see such an error.

+

Consider the code below, we might have a user profile route, and if the user +fails to pass a username we can raise a “400 Bad Request”. If the user passes a +username and we can’t find it, we raise a “404 Not Found”.

+
from flask import abort, render_template, request
+
+# a username needs to be supplied in the query args
+# a successful request would be like /profile?username=jack
+@app.route("/profile")
+def user_profile():
+    username = request.arg.get("username")
+    # if a username isn't supplied in the request, return a 400 bad request
+    if username is None:
+        abort(400)
+
+    user = get_user(username=username)
+    # if a user can't be found by their username, return 404 not found
+    if user is None:
+        abort(404)
+
+    return render_template("profile.html", user=user)
+
+
+

Here is another example implementation for a “404 Page Not Found” exception:

+
from flask import render_template
+
+@app.errorhandler(404)
+def page_not_found(e):
+    # note that we set the 404 status explicitly
+    return render_template('404.html'), 404
+
+
+

When using Application Factories:

+
from flask import Flask, render_template
+
+def page_not_found(e):
+  return render_template('404.html'), 404
+
+def create_app(config_filename):
+    app = Flask(__name__)
+    app.register_error_handler(404, page_not_found)
+    return app
+
+
+

An example template might be this:

+
{% extends "layout.html" %}
+{% block title %}Page Not Found{% endblock %}
+{% block body %}
+  <h1>Page Not Found</h1>
+  <p>What you were looking for is just not there.
+  <p><a href="{{ url_for('index') }}">go somewhere nice</a>
+{% endblock %}
+
+
+
+

Further Examples

+

The above examples wouldn’t actually be an improvement on the default +exception pages. We can create a custom 500.html template like this:

+
{% extends "layout.html" %}
+{% block title %}Internal Server Error{% endblock %}
+{% block body %}
+  <h1>Internal Server Error</h1>
+  <p>Oops... we seem to have made a mistake, sorry!</p>
+  <p><a href="{{ url_for('index') }}">Go somewhere nice instead</a>
+{% endblock %}
+
+
+

It can be implemented by rendering the template on “500 Internal Server Error”:

+
from flask import render_template
+
+@app.errorhandler(500)
+def internal_server_error(e):
+    # note that we set the 500 status explicitly
+    return render_template('500.html'), 500
+
+
+

When using Application Factories:

+
from flask import Flask, render_template
+
+def internal_server_error(e):
+  return render_template('500.html'), 500
+
+def create_app():
+    app = Flask(__name__)
+    app.register_error_handler(500, internal_server_error)
+    return app
+
+
+

When using Modular Applications with Blueprints:

+
from flask import Blueprint
+
+blog = Blueprint('blog', __name__)
+
+# as a decorator
+@blog.errorhandler(500)
+def internal_server_error(e):
+    return render_template('500.html'), 500
+
+# or with register_error_handler
+blog.register_error_handler(500, internal_server_error)
+
+
+
+
+
+

Blueprint Error Handlers

+

In Modular Applications with Blueprints, most error handlers will work as expected. +However, there is a caveat concerning handlers for 404 and 405 +exceptions. These error handlers are only invoked from an appropriate +raise statement or a call to abort in another of the blueprint’s +view functions; they are not invoked by, e.g., an invalid URL access.

+

This is because the blueprint does not “own” a certain URL space, so +the application instance has no way of knowing which blueprint error +handler it should run if given an invalid URL. If you would like to +execute different handling strategies for these errors based on URL +prefixes, they may be defined at the application level using the +request proxy object.

+
from flask import jsonify, render_template
+
+# at the application level
+# not the blueprint level
+@app.errorhandler(404)
+def page_not_found(e):
+    # if a request is in our blog URL space
+    if request.path.startswith('/blog/'):
+        # we return a custom blog 404 page
+        return render_template("blog/404.html"), 404
+    else:
+        # otherwise we return our generic site-wide 404 page
+        return render_template("404.html"), 404
+
+@app.errorhandler(405)
+def method_not_allowed(e):
+    # if a request has the wrong method to our API
+    if request.path.startswith('/api/'):
+        # we return a json saying so
+        return jsonify(message="Method Not Allowed"), 405
+    else:
+        # otherwise we return a generic site-wide 405 page
+        return render_template("405.html"), 405
+
+
+
+
+

Returning API Errors as JSON

+

When building APIs in Flask, some developers realise that the built-in +exceptions are not expressive enough for APIs and that the content type of +text/html they are emitting is not very useful for API consumers.

+

Using the same techniques as above and jsonify() we can return JSON +responses to API errors. abort() is called +with a description parameter. The error handler will +use that as the JSON error message, and set the status code to 404.

+
from flask import abort, jsonify
+
+@app.errorhandler(404)
+def resource_not_found(e):
+    return jsonify(error=str(e)), 404
+
+@app.route("/cheese")
+def get_one_cheese():
+    resource = get_resource()
+
+    if resource is None:
+        abort(404, description="Resource not found")
+
+    return jsonify(resource)
+
+
+

We can also create custom exception classes. For instance, we can +introduce a new custom exception for an API that can take a proper human readable message, +a status code for the error and some optional payload to give more context +for the error.

+

This is a simple example:

+
from flask import jsonify, request
+
+class InvalidAPIUsage(Exception):
+    status_code = 400
+
+    def __init__(self, message, status_code=None, payload=None):
+        super().__init__()
+        self.message = message
+        if status_code is not None:
+            self.status_code = status_code
+        self.payload = payload
+
+    def to_dict(self):
+        rv = dict(self.payload or ())
+        rv['message'] = self.message
+        return rv
+
+@app.errorhandler(InvalidAPIUsage)
+def invalid_api_usage(e):
+    return jsonify(e.to_dict()), e.status_code
+
+# an API app route for getting user information
+# a correct request might be /api/user?user_id=420
+@app.route("/api/user")
+def user_api(user_id):
+    user_id = request.arg.get("user_id")
+    if not user_id:
+        raise InvalidAPIUsage("No user id provided!")
+
+    user = get_user(user_id=user_id)
+    if not user:
+        raise InvalidAPIUsage("No such user!", status_code=404)
+
+    return jsonify(user.to_dict())
+
+
+

A view can now raise that exception with an error message. Additionally +some extra payload can be provided as a dictionary through the payload +parameter.

+
+
+

Logging

+

See Logging for information about how to log exceptions, such as +by emailing them to admins.

+
+
+

Debugging

+

See Debugging Application Errors for information about how to debug errors in +development and production.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/extensiondev/index.html b/_build/extensiondev/index.html new file mode 100644 index 00000000..720a9769 --- /dev/null +++ b/_build/extensiondev/index.html @@ -0,0 +1,364 @@ + + + + + + + + Flask Extension Development — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Flask Extension Development

+

Extensions are extra packages that add functionality to a Flask +application. While PyPI contains many Flask extensions, you may not +find one that fits your need. If this is the case, you can create your +own, and publish it for others to use as well.

+

This guide will show how to create a Flask extension, and some of the +common patterns and requirements involved. Since extensions can do +anything, this guide won’t be able to cover every possibility.

+

The best ways to learn about extensions are to look at how other +extensions you use are written, and discuss with others. Discuss your +design ideas with others on our Discord Chat or +GitHub Discussions.

+

The best extensions share common patterns, so that anyone familiar with +using one extension won’t feel completely lost with another. This can +only work if collaboration happens early.

+
+

Naming

+

A Flask extension typically has flask in its name as a prefix or +suffix. If it wraps another library, it should include the library name +as well. This makes it easy to search for extensions, and makes their +purpose clearer.

+

A general Python packaging recommendation is that the install name from +the package index and the name used in import statements should be +related. The import name is lowercase, with words separated by +underscores (_). The install name is either lower case or title +case, with words separated by dashes (-). If it wraps another +library, prefer using the same case as that library’s name.

+

Here are some example install and import names:

+
    +
  • Flask-Name imported as flask_name

  • +
  • flask-name-lower imported as flask_name_lower

  • +
  • Flask-ComboName imported as flask_comboname

  • +
  • Name-Flask imported as name_flask

  • +
+
+
+

The Extension Class and Initialization

+

All extensions will need some entry point that initializes the +extension with the application. The most common pattern is to create a +class that represents the extension’s configuration and behavior, with +an init_app method to apply the extension instance to the given +application instance.

+
class HelloExtension:
+    def __init__(self, app=None):
+        if app is not None:
+            self.init_app(app)
+
+    def init_app(self, app):
+        app.before_request(...)
+
+
+

It is important that the app is not stored on the extension, don’t do +self.app = app. The only time the extension should have direct +access to an app is during init_app, otherwise it should use +current_app.

+

This allows the extension to support the application factory pattern, +avoids circular import issues when importing the extension instance +elsewhere in a user’s code, and makes testing with different +configurations easier.

+
hello = HelloExtension()
+
+def create_app():
+    app = Flask(__name__)
+    hello.init_app(app)
+    return app
+
+
+

Above, the hello extension instance exists independently of the +application. This means that other modules in a user’s project can do +from project import hello and use the extension in blueprints before +the app exists.

+

The Flask.extensions dict can be used to store a reference to +the extension on the application, or some other state specific to the +application. Be aware that this is a single namespace, so use a name +unique to your extension, such as the extension’s name without the +“flask” prefix.

+
+
+

Adding Behavior

+

There are many ways that an extension can add behavior. Any setup +methods that are available on the Flask object can be used +during an extension’s init_app method.

+

A common pattern is to use before_request() to initialize +some data or a connection at the beginning of each request, then +teardown_request() to clean it up at the end. This can be +stored on g, discussed more below.

+

A more lazy approach is to provide a method that initializes and caches +the data or connection. For example, a ext.get_db method could +create a database connection the first time it’s called, so that a view +that doesn’t use the database doesn’t create a connection.

+

Besides doing something before and after every view, your extension +might want to add some specific views as well. In this case, you could +define a Blueprint, then call register_blueprint() +during init_app to add the blueprint to the app.

+
+
+

Configuration Techniques

+

There can be multiple levels and sources of configuration for an +extension. You should consider what parts of your extension fall into +each one.

+
    +
  • Configuration per application instance, through app.config +values. This is configuration that could reasonably change for each +deployment of an application. A common example is a URL to an +external resource, such as a database. Configuration keys should +start with the extension’s name so that they don’t interfere with +other extensions.

  • +
  • Configuration per extension instance, through __init__ +arguments. This configuration usually affects how the extension +is used, such that it wouldn’t make sense to change it per +deployment.

  • +
  • Configuration per extension instance, through instance attributes +and decorator methods. It might be more ergonomic to assign to +ext.value, or use a @ext.register decorator to register a +function, after the extension instance has been created.

  • +
  • Global configuration through class attributes. Changing a class +attribute like Ext.connection_class can customize default +behavior without making a subclass. This could be combined +per-extension configuration to override defaults.

  • +
  • Subclassing and overriding methods and attributes. Making the API of +the extension itself something that can be overridden provides a +very powerful tool for advanced customization.

  • +
+

The Flask object itself uses all of these techniques.

+

It’s up to you to decide what configuration is appropriate for your +extension, based on what you need and what you want to support.

+

Configuration should not be changed after the application setup phase is +complete and the server begins handling requests. Configuration is +global, any changes to it are not guaranteed to be visible to other +workers.

+
+
+

Data During a Request

+

When writing a Flask application, the g object is used to +store information during a request. For example the +tutorial stores a connection to a SQLite +database as g.db. Extensions can also use this, with some care. +Since g is a single global namespace, extensions must use unique +names that won’t collide with user data. For example, use the extension +name as a prefix, or as a namespace.

+
# an internal prefix with the extension name
+g._hello_user_id = 2
+
+# or an internal prefix as a namespace
+from types import SimpleNamespace
+g._hello = SimpleNamespace()
+g._hello.user_id = 2
+
+
+

The data in g lasts for an application context. An application +context is active when a request context is, or when a CLI command is +run. If you’re storing something that should be closed, use +teardown_appcontext() to ensure that it gets closed +when the application context ends. If it should only be valid during a +request, or would not be used in the CLI outside a request, use +teardown_request().

+
+
+

Views and Models

+

Your extension views might want to interact with specific models in your +database, or some other extension or data connected to your application. +For example, let’s consider a Flask-SimpleBlog extension that works +with Flask-SQLAlchemy to provide a Post model and views to write +and read posts.

+

The Post model needs to subclass the Flask-SQLAlchemy db.Model +object, but that’s only available once you’ve created an instance of +that extension, not when your extension is defining its views. So how +can the view code, defined before the model exists, access the model?

+

One method could be to use Class-based Views. During __init__, create +the model, then create the views by passing the model to the view +class’s as_view() method.

+
class PostAPI(MethodView):
+    def __init__(self, model):
+        self.model = model
+
+    def get(self, id):
+        post = self.model.query.get(id)
+        return jsonify(post.to_json())
+
+class BlogExtension:
+    def __init__(self, db):
+        class Post(db.Model):
+            id = db.Column(primary_key=True)
+            title = db.Column(db.String, nullable=False)
+
+        self.post_model = Post
+
+    def init_app(self, app):
+        api_view = PostAPI.as_view(model=self.post_model)
+
+db = SQLAlchemy()
+blog = BlogExtension(db)
+db.init_app(app)
+blog.init_app(app)
+
+
+

Another technique could be to use an attribute on the extension, such as +self.post_model from above. Add the extension to app.extensions +in init_app, then access +current_app.extensions["simple_blog"].post_model from views.

+

You may also want to provide base classes so that users can provide +their own Post model that conforms to the API your extension +expects. So they could implement class Post(blog.BasePost), then +set it as blog.post_model.

+

As you can see, this can get a bit complex. Unfortunately, there’s no +perfect solution here, only different strategies and tradeoffs depending +on your needs and how much customization you want to offer. Luckily, +this sort of resource dependency is not a common need for most +extensions. Remember, if you need help with design, ask on our +Discord Chat or GitHub Discussions.

+
+ +
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/extensions/index.html b/_build/extensions/index.html new file mode 100644 index 00000000..0b4d985b --- /dev/null +++ b/_build/extensions/index.html @@ -0,0 +1,139 @@ + + + + + + + + Extensions — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Extensions

+

Extensions are extra packages that add functionality to a Flask +application. For example, an extension might add support for sending +email or connecting to a database. Some extensions add entire new +frameworks to help build certain types of applications, like a REST API.

+
+

Finding Extensions

+

Flask extensions are usually named “Flask-Foo” or “Foo-Flask”. You can +search PyPI for packages tagged with Framework :: Flask.

+
+
+

Using Extensions

+

Consult each extension’s documentation for installation, configuration, +and usage instructions. Generally, extensions pull their own +configuration from app.config and are +passed an application instance during initialization. For example, +an extension called “Flask-Foo” might be used like this:

+
from flask_foo import Foo
+
+foo = Foo()
+
+app = Flask(__name__)
+app.config.update(
+    FOO_BAR='baz',
+    FOO_SPAM='eggs',
+)
+
+foo.init_app(app)
+
+
+
+
+

Building Extensions

+

While PyPI contains many Flask extensions, you may not find +an extension that fits your need. If this is the case, you can create +your own, and publish it for others to use as well. Read +Flask Extension Development to develop your own Flask extension.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/genindex/index.html b/_build/genindex/index.html new file mode 100644 index 00000000..1821e126 --- /dev/null +++ b/_build/genindex/index.html @@ -0,0 +1,1550 @@ + + + + + + + + Index — Flask Documentation (3.1.x) + + + + + + + + + + + + +
+
+
+
+ + +

Index

+ +
+ _ + | A + | B + | C + | D + | E + | F + | G + | H + | I + | J + | K + | L + | M + | N + | O + | P + | Q + | R + | S + | T + | U + | V + | W + | Y + +
+

_

+ + +
+ +

A

+ + + +
+ +

B

+ + + +
+ +

C

+ + + +
+ +

D

+ + + +
+ +

E

+ + + +
+ +

F

+ + + +
+ +

G

+ + + +
+ +

H

+ + + +
+ +

I

+ + + +
+ +

J

+ + + +
+ +

K

+ + + +
+ +

L

+ + + +
+ +

M

+ + + +
+ +

N

+ + + +
+ +

O

+ + + +
+ +

P

+ + + +
+ +

Q

+ + +
+ +

R

+ + + +
+ +

S

+ + + +
+ +

T

+ + + +
+ +

U

+ + + +
+ +

V

+ + + +
+ +

W

+ + + +
+ +

Y

+ + +
+ + + +
+
+
+
+ + +
+
+ + + diff --git a/_build/index.html b/_build/index.html new file mode 100644 index 00000000..5e283a05 --- /dev/null +++ b/_build/index.html @@ -0,0 +1,470 @@ + + + + + + + + Welcome to Flask — Flask Documentation (3.1.x) + + + + + + + + + + + + + +
+
+
+
+ +
+

Welcome to Flask

+_images/flask-horizontal.png +

Welcome to Flask’s documentation. Flask is a lightweight WSGI web application framework. +It is designed to make getting started quick and easy, with the ability to scale up to +complex applications.

+

Get started with Installation +and then get an overview with the Quickstart. There is also a +more detailed Tutorial that shows how to create a small but +complete application with Flask. Common patterns are described in the +Patterns for Flask section. The rest of the docs describe each +component of Flask in detail, with a full reference in the API +section.

+

Flask depends on the Werkzeug WSGI toolkit, the Jinja template engine, and the +Click CLI toolkit. Be sure to check their documentation as well as Flask’s when +looking for information.

+
+

User’s Guide

+

Flask provides configuration and conventions, with sensible defaults, to get started. +This section of the documentation explains the different parts of the Flask framework +and how they can be used, customized, and extended. Beyond Flask itself, look for +community-maintained extensions to add even more functionality.

+
+ +
+
+
+

API Reference

+

If you are looking for information on a specific function, class or +method, this part of the documentation is for you.

+ +
+
+

Additional Notes

+ +
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/installation/index.html b/_build/installation/index.html new file mode 100644 index 00000000..075ae1ce --- /dev/null +++ b/_build/installation/index.html @@ -0,0 +1,208 @@ + + + + + + + + Installation — Flask Documentation (3.1.x) + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Installation

+
+

Python Version

+

We recommend using the latest version of Python. Flask supports Python 3.9 and newer.

+
+
+

Dependencies

+

These distributions will be installed automatically when installing Flask.

+
    +
  • Werkzeug implements WSGI, the standard Python interface between +applications and servers.

  • +
  • Jinja is a template language that renders the pages your application +serves.

  • +
  • MarkupSafe comes with Jinja. It escapes untrusted input when rendering +templates to avoid injection attacks.

  • +
  • ItsDangerous securely signs data to ensure its integrity. This is used +to protect Flask’s session cookie.

  • +
  • Click is a framework for writing command line applications. It provides +the flask command and allows adding custom management commands.

  • +
  • Blinker provides support for Signals.

  • +
+
+

Optional dependencies

+

These distributions will not be installed automatically. Flask will detect and +use them if you install them.

+ +
+
+

greenlet

+

You may choose to use gevent or eventlet with your application. In this +case, greenlet>=1.0 is required. When using PyPy, PyPy>=7.3.7 is +required.

+

These are not minimum supported versions, they only indicate the first +versions that added necessary features. You should use the latest +versions of each.

+
+
+
+

Virtual environments

+

Use a virtual environment to manage the dependencies for your project, both in +development and in production.

+

What problem does a virtual environment solve? The more Python projects you +have, the more likely it is that you need to work with different versions of +Python libraries, or even Python itself. Newer versions of libraries for one +project can break compatibility in another project.

+

Virtual environments are independent groups of Python libraries, one for each +project. Packages installed for one project will not affect other projects or +the operating system’s packages.

+

Python comes bundled with the venv module to create virtual +environments.

+
+

Create an environment

+

Create a project folder and a .venv folder within:

+
+
$ mkdir myproject
+$ cd myproject
+$ python3 -m venv .venv
+
+
+
+
+
+

Activate the environment

+

Before you work on your project, activate the corresponding environment:

+
+
$ . .venv/bin/activate
+
+
+
+

Your shell prompt will change to show the name of the activated +environment.

+
+
+
+

Install Flask

+

Within the activated environment, use the following command to install +Flask:

+
$ pip install Flask
+
+
+

Flask is now installed. Check out the Quickstart or go to the +Documentation Overview.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/license/index.html b/_build/license/index.html new file mode 100644 index 00000000..4ff055cb --- /dev/null +++ b/_build/license/index.html @@ -0,0 +1,122 @@ + + + + + + + + BSD-3-Clause License — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

BSD-3-Clause License

+
Copyright 2010 Pallets
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+1.  Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+
+2.  Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in the
+    documentation and/or other materials provided with the distribution.
+
+3.  Neither the name of the copyright holder nor the names of its
+    contributors may be used to endorse or promote products derived from
+    this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/lifecycle/index.html b/_build/lifecycle/index.html new file mode 100644 index 00000000..779334d7 --- /dev/null +++ b/_build/lifecycle/index.html @@ -0,0 +1,257 @@ + + + + + + + + Application Structure and Lifecycle — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Application Structure and Lifecycle

+

Flask makes it pretty easy to write a web application. But there are quite a few +different parts to an application and to each request it handles. Knowing what happens +during application setup, serving, and handling requests will help you know what’s +possible in Flask and how to structure your application.

+
+

Application Setup

+

The first step in creating a Flask application is creating the application object. Each +Flask application is an instance of the Flask class, which collects all +configuration, extensions, and views.

+
from flask import Flask
+
+app = Flask(__name__)
+app.config.from_mapping(
+    SECRET_KEY="dev",
+)
+app.config.from_prefixed_env()
+
+@app.route("/")
+def index():
+    return "Hello, World!"
+
+
+

This is known as the “application setup phase”, it’s the code you write that’s outside +any view functions or other handlers. It can be split up between different modules and +sub-packages, but all code that you want to be part of your application must be imported +in order for it to be registered.

+

All application setup must be completed before you start serving your application and +handling requests. This is because WSGI servers divide work between multiple workers, or +can be distributed across multiple machines. If the configuration changed in one worker, +there’s no way for Flask to ensure consistency between other workers.

+

Flask tries to help developers catch some of these setup ordering issues by showing an +error if setup-related methods are called after requests are handled. In that case +you’ll see this error:

+
+

The setup method ‘route’ can no longer be called on the application. It has already +handled its first request, any changes will not be applied consistently. +Make sure all imports, decorators, functions, etc. needed to set up the application +are done before running it.

+
+

However, it is not possible for Flask to detect all cases of out-of-order setup. In +general, don’t do anything to modify the Flask app object and Blueprint objects +from within view functions that run during requests. This includes:

+
    +
  • Adding routes, view functions, and other request handlers with @app.route, +@app.errorhandler, @app.before_request, etc.

  • +
  • Registering blueprints.

  • +
  • Loading configuration with app.config.

  • +
  • Setting up the Jinja template environment with app.jinja_env.

  • +
  • Setting a session interface, instead of the default itsdangerous cookie.

  • +
  • Setting a JSON provider with app.json, instead of the default provider.

  • +
  • Creating and initializing Flask extensions.

  • +
+
+
+

Serving the Application

+

Flask is a WSGI application framework. The other half of WSGI is the WSGI server. During +development, Flask, through Werkzeug, provides a development WSGI server with the +flask run CLI command. When you are done with development, use a production server +to serve your application, see Deploying to Production.

+

Regardless of what server you’re using, it will follow the PEP 3333 WSGI spec. The +WSGI server will be told how to access your Flask application object, which is the WSGI +application. Then it will start listening for HTTP requests, translate the request data +into a WSGI environ, and call the WSGI application with that data. The WSGI application +will return data that is translated into an HTTP response.

+
    +
  1. Browser or other client makes HTTP request.

  2. +
  3. WSGI server receives request.

  4. +
  5. WSGI server converts HTTP data to WSGI environ dict.

  6. +
  7. WSGI server calls WSGI application with the environ.

  8. +
  9. Flask, the WSGI application, does all its internal processing to route the request +to a view function, handle errors, etc.

  10. +
  11. Flask translates View function return into WSGI response data, passes it to WSGI +server.

  12. +
  13. WSGI server creates and send an HTTP response.

  14. +
  15. Client receives the HTTP response.

  16. +
+
+

Middleware

+

The WSGI application above is a callable that behaves in a certain way. Middleware +is a WSGI application that wraps another WSGI application. It’s a similar concept to +Python decorators. The outermost middleware will be called by the server. It can modify +the data passed to it, then call the WSGI application (or further middleware) that it +wraps, and so on. And it can take the return value of that call and modify it further.

+

From the WSGI server’s perspective, there is one WSGI application, the one it calls +directly. Typically, Flask is the “real” application at the end of the chain of +middleware. But even Flask can call further WSGI applications, although that’s an +advanced, uncommon use case.

+

A common middleware you’ll see used with Flask is Werkzeug’s +ProxyFix, which modifies the request to look +like it came directly from a client even if it passed through HTTP proxies on the way. +There are other middleware that can handle serving static files, authentication, etc.

+
+
+
+

How a Request is Handled

+

For us, the interesting part of the steps above is when Flask gets called by the WSGI +server (or middleware). At that point, it will do quite a lot to handle the request and +generate the response. At the most basic, it will match the URL to a view function, call +the view function, and pass the return value back to the server. But there are many more +parts that you can use to customize its behavior.

+
    +
  1. WSGI server calls the Flask object, which calls Flask.wsgi_app().

  2. +
  3. A RequestContext object is created. This converts the WSGI environ +dict into a Request object. It also creates an AppContext object.

  4. +
  5. The app context is pushed, which makes current_app and +g available.

  6. +
  7. The appcontext_pushed signal is sent.

  8. +
  9. The request context is pushed, which makes request and +session available.

  10. +
  11. The session is opened, loading any existing session data using the app’s +session_interface, an instance of SessionInterface.

  12. +
  13. The URL is matched against the URL rules registered with the route() +decorator during application setup. If there is no match, the error - usually a 404, +405, or redirect - is stored to be handled later.

  14. +
  15. The request_started signal is sent.

  16. +
  17. Any url_value_preprocessor() decorated functions are called.

  18. +
  19. Any before_request() decorated functions are called. If any of +these function returns a value it is treated as the response immediately.

  20. +
  21. If the URL didn’t match a route a few steps ago, that error is raised now.

  22. +
  23. The route() decorated view function associated with the matched URL +is called and returns a value to be used as the response.

  24. +
  25. If any step so far raised an exception, and there is an errorhandler() +decorated function that matches the exception class or HTTP error code, it is +called to handle the error and return a response.

  26. +
  27. Whatever returned a response value - a before request function, the view, or an +error handler, that value is converted to a Response object.

  28. +
  29. Any after_this_request() decorated functions are called, then cleared.

  30. +
  31. Any after_request() decorated functions are called, which can modify +the response object.

  32. +
  33. The session is saved, persisting any modified session data using the app’s +session_interface.

  34. +
  35. The request_finished signal is sent.

  36. +
  37. If any step so far raised an exception, and it was not handled by an error handler +function, it is handled now. HTTP exceptions are treated as responses with their +corresponding status code, other exceptions are converted to a generic 500 response. +The got_request_exception signal is sent.

  38. +
  39. The response object’s status, headers, and body are returned to the WSGI server.

  40. +
  41. Any teardown_request() decorated functions are called.

  42. +
  43. The request_tearing_down signal is sent.

  44. +
  45. The request context is popped, request and session are no longer +available.

  46. +
  47. Any teardown_appcontext() decorated functions are called.

  48. +
  49. The appcontext_tearing_down signal is sent.

  50. +
  51. The app context is popped, current_app and g are no longer +available.

  52. +
  53. The appcontext_popped signal is sent.

  54. +
+

There are even more decorators and customization points than this, but that aren’t part +of every request lifecycle. They’re more specific to certain things you might use during +a request, such as templates, building URLs, or handling JSON data. See the rest of this +documentation, as well as the API to explore further.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/logging/index.html b/_build/logging/index.html new file mode 100644 index 00000000..df0b0ef9 --- /dev/null +++ b/_build/logging/index.html @@ -0,0 +1,275 @@ + + + + + + + + Logging — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Logging

+

Flask uses standard Python logging. Messages about your Flask +application are logged with app.logger, +which takes the same name as app.name. This +logger can also be used to log your own messages.

+
@app.route('/login', methods=['POST'])
+def login():
+    user = get_user(request.form['username'])
+
+    if user.check_password(request.form['password']):
+        login_user(user)
+        app.logger.info('%s logged in successfully', user.username)
+        return redirect(url_for('index'))
+    else:
+        app.logger.info('%s failed to log in', user.username)
+        abort(401)
+
+
+

If you don’t configure logging, Python’s default log level is usually +‘warning’. Nothing below the configured level will be visible.

+
+

Basic Configuration

+

When you want to configure logging for your project, you should do it as soon +as possible when the program starts. If app.logger +is accessed before logging is configured, it will add a default handler. If +possible, configure logging before creating the application object.

+

This example uses dictConfig() to create a logging +configuration similar to Flask’s default, except for all logs:

+
from logging.config import dictConfig
+
+dictConfig({
+    'version': 1,
+    'formatters': {'default': {
+        'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
+    }},
+    'handlers': {'wsgi': {
+        'class': 'logging.StreamHandler',
+        'stream': 'ext://flask.logging.wsgi_errors_stream',
+        'formatter': 'default'
+    }},
+    'root': {
+        'level': 'INFO',
+        'handlers': ['wsgi']
+    }
+})
+
+app = Flask(__name__)
+
+
+
+

Default Configuration

+

If you do not configure logging yourself, Flask will add a +StreamHandler to app.logger +automatically. During requests, it will write to the stream specified by the +WSGI server in environ['wsgi.errors'] (which is usually +sys.stderr). Outside a request, it will log to sys.stderr.

+
+
+

Removing the Default Handler

+

If you configured logging after accessing +app.logger, and need to remove the default +handler, you can import and remove it:

+
from flask.logging import default_handler
+
+app.logger.removeHandler(default_handler)
+
+
+
+
+
+

Email Errors to Admins

+

When running the application on a remote server for production, you probably +won’t be looking at the log messages very often. The WSGI server will probably +send log messages to a file, and you’ll only check that file if a user tells +you something went wrong.

+

To be proactive about discovering and fixing bugs, you can configure a +logging.handlers.SMTPHandler to send an email when errors and higher +are logged.

+
import logging
+from logging.handlers import SMTPHandler
+
+mail_handler = SMTPHandler(
+    mailhost='127.0.0.1',
+    fromaddr='server-error@example.com',
+    toaddrs=['admin@example.com'],
+    subject='Application Error'
+)
+mail_handler.setLevel(logging.ERROR)
+mail_handler.setFormatter(logging.Formatter(
+    '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'
+))
+
+if not app.debug:
+    app.logger.addHandler(mail_handler)
+
+
+

This requires that you have an SMTP server set up on the same server. See the +Python docs for more information about configuring the handler.

+
+
+

Injecting Request Information

+

Seeing more information about the request, such as the IP address, may help +debugging some errors. You can subclass logging.Formatter to inject +your own fields that can be used in messages. You can change the formatter for +Flask’s default handler, the mail handler defined above, or any other +handler.

+
from flask import has_request_context, request
+from flask.logging import default_handler
+
+class RequestFormatter(logging.Formatter):
+    def format(self, record):
+        if has_request_context():
+            record.url = request.url
+            record.remote_addr = request.remote_addr
+        else:
+            record.url = None
+            record.remote_addr = None
+
+        return super().format(record)
+
+formatter = RequestFormatter(
+    '[%(asctime)s] %(remote_addr)s requested %(url)s\n'
+    '%(levelname)s in %(module)s: %(message)s'
+)
+default_handler.setFormatter(formatter)
+mail_handler.setFormatter(formatter)
+
+
+
+
+

Other Libraries

+

Other libraries may use logging extensively, and you want to see relevant +messages from those logs too. The simplest way to do this is to add handlers +to the root logger instead of only the app logger.

+
from flask.logging import default_handler
+
+root = logging.getLogger()
+root.addHandler(default_handler)
+root.addHandler(mail_handler)
+
+
+

Depending on your project, it may be more useful to configure each logger you +care about separately, instead of configuring only the root logger.

+
for logger in (
+    logging.getLogger(app.name),
+    logging.getLogger('sqlalchemy'),
+    logging.getLogger('other_package'),
+):
+    logger.addHandler(default_handler)
+    logger.addHandler(mail_handler)
+
+
+
+

Werkzeug

+

Werkzeug logs basic request/response information to the 'werkzeug' logger. +If the root logger has no handlers configured, Werkzeug adds a +StreamHandler to its logger.

+
+
+

Flask Extensions

+

Depending on the situation, an extension may choose to log to +app.logger or its own named logger. Consult each +extension’s documentation for details.

+
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/objects.inv b/_build/objects.inv new file mode 100644 index 00000000..d5f96467 Binary files /dev/null and b/_build/objects.inv differ diff --git a/_build/patterns/appdispatch/index.html b/_build/patterns/appdispatch/index.html new file mode 100644 index 00000000..9bd10a85 --- /dev/null +++ b/_build/patterns/appdispatch/index.html @@ -0,0 +1,272 @@ + + + + + + + + Application Dispatching — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Application Dispatching

+

Application dispatching is the process of combining multiple Flask +applications on the WSGI level. You can combine not only Flask +applications but any WSGI application. This would allow you to run a +Django and a Flask application in the same interpreter side by side if +you want. The usefulness of this depends on how the applications work +internally.

+

The fundamental difference from Large Applications as Packages is that in this case you +are running the same or different Flask applications that are entirely +isolated from each other. They run different configurations and are +dispatched on the WSGI level.

+
+

Working with this Document

+

Each of the techniques and examples below results in an application +object that can be run with any WSGI server. For development, use the +flask run command to start a development server. For production, see +Deploying to Production.

+
from flask import Flask
+
+app = Flask(__name__)
+
+@app.route('/')
+def hello_world():
+    return 'Hello World!'
+
+
+
+
+

Combining Applications

+

If you have entirely separated applications and you want them to work next +to each other in the same Python interpreter process you can take +advantage of the werkzeug.wsgi.DispatcherMiddleware. The idea +here is that each Flask application is a valid WSGI application and they +are combined by the dispatcher middleware into a larger one that is +dispatched based on prefix.

+

For example you could have your main application run on / and your +backend interface on /backend.

+
from werkzeug.middleware.dispatcher import DispatcherMiddleware
+from frontend_app import application as frontend
+from backend_app import application as backend
+
+application = DispatcherMiddleware(frontend, {
+    '/backend': backend
+})
+
+
+
+
+

Dispatch by Subdomain

+

Sometimes you might want to use multiple instances of the same application +with different configurations. Assuming the application is created inside +a function and you can call that function to instantiate it, that is +really easy to implement. In order to develop your application to support +creating new instances in functions have a look at the +Application Factories pattern.

+

A very common example would be creating applications per subdomain. For +instance you configure your webserver to dispatch all requests for all +subdomains to your application and you then use the subdomain information +to create user-specific instances. Once you have your server set up to +listen on all subdomains you can use a very simple WSGI application to do +the dynamic application creation.

+

The perfect level for abstraction in that regard is the WSGI layer. You +write your own WSGI application that looks at the request that comes and +delegates it to your Flask application. If that application does not +exist yet, it is dynamically created and remembered.

+
from threading import Lock
+
+class SubdomainDispatcher:
+
+    def __init__(self, domain, create_app):
+        self.domain = domain
+        self.create_app = create_app
+        self.lock = Lock()
+        self.instances = {}
+
+    def get_application(self, host):
+        host = host.split(':')[0]
+        assert host.endswith(self.domain), 'Configuration error'
+        subdomain = host[:-len(self.domain)].rstrip('.')
+        with self.lock:
+            app = self.instances.get(subdomain)
+            if app is None:
+                app = self.create_app(subdomain)
+                self.instances[subdomain] = app
+            return app
+
+    def __call__(self, environ, start_response):
+        app = self.get_application(environ['HTTP_HOST'])
+        return app(environ, start_response)
+
+
+

This dispatcher can then be used like this:

+
from myapplication import create_app, get_user_for_subdomain
+from werkzeug.exceptions import NotFound
+
+def make_app(subdomain):
+    user = get_user_for_subdomain(subdomain)
+    if user is None:
+        # if there is no user for that subdomain we still have
+        # to return a WSGI application that handles that request.
+        # We can then just return the NotFound() exception as
+        # application which will render a default 404 page.
+        # You might also redirect the user to the main page then
+        return NotFound()
+
+    # otherwise create the application for the specific user
+    return create_app(user)
+
+application = SubdomainDispatcher('example.com', make_app)
+
+
+
+
+

Dispatch by Path

+

Dispatching by a path on the URL is very similar. Instead of looking at +the Host header to figure out the subdomain one simply looks at the +request path up to the first slash.

+
from threading import Lock
+from wsgiref.util import shift_path_info
+
+class PathDispatcher:
+
+    def __init__(self, default_app, create_app):
+        self.default_app = default_app
+        self.create_app = create_app
+        self.lock = Lock()
+        self.instances = {}
+
+    def get_application(self, prefix):
+        with self.lock:
+            app = self.instances.get(prefix)
+            if app is None:
+                app = self.create_app(prefix)
+                if app is not None:
+                    self.instances[prefix] = app
+            return app
+
+    def __call__(self, environ, start_response):
+        app = self.get_application(_peek_path_info(environ))
+        if app is not None:
+            shift_path_info(environ)
+        else:
+            app = self.default_app
+        return app(environ, start_response)
+
+def _peek_path_info(environ):
+    segments = environ.get("PATH_INFO", "").lstrip("/").split("/", 1)
+    if segments:
+        return segments[0]
+
+    return None
+
+
+

The big difference between this and the subdomain one is that this one +falls back to another application if the creator function returns None.

+
from myapplication import create_app, default_app, get_user_for_prefix
+
+def make_app(prefix):
+    user = get_user_for_prefix(prefix)
+    if user is not None:
+        return create_app(user)
+
+application = PathDispatcher(default_app, make_app)
+
+
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/patterns/appfactories/index.html b/_build/patterns/appfactories/index.html new file mode 100644 index 00000000..f882d17c --- /dev/null +++ b/_build/patterns/appfactories/index.html @@ -0,0 +1,213 @@ + + + + + + + + Application Factories — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Application Factories

+

If you are already using packages and blueprints for your application +(Modular Applications with Blueprints) there are a couple of really nice ways to further improve +the experience. A common pattern is creating the application object when +the blueprint is imported. But if you move the creation of this object +into a function, you can then create multiple instances of this app later.

+

So why would you want to do this?

+
    +
  1. Testing. You can have instances of the application with different +settings to test every case.

  2. +
  3. Multiple instances. Imagine you want to run different versions of the +same application. Of course you could have multiple instances with +different configs set up in your webserver, but if you use factories, +you can have multiple instances of the same application running in the +same application process which can be handy.

  4. +
+

So how would you then actually implement that?

+
+

Basic Factories

+

The idea is to set up the application in a function. Like this:

+
def create_app(config_filename):
+    app = Flask(__name__)
+    app.config.from_pyfile(config_filename)
+
+    from yourapplication.model import db
+    db.init_app(app)
+
+    from yourapplication.views.admin import admin
+    from yourapplication.views.frontend import frontend
+    app.register_blueprint(admin)
+    app.register_blueprint(frontend)
+
+    return app
+
+
+

The downside is that you cannot use the application object in the blueprints +at import time. You can however use it from within a request. How do you +get access to the application with the config? Use +current_app:

+
from flask import current_app, Blueprint, render_template
+admin = Blueprint('admin', __name__, url_prefix='/admin')
+
+@admin.route('/')
+def index():
+    return render_template(current_app.config['INDEX_TEMPLATE'])
+
+
+

Here we look up the name of a template in the config.

+
+
+

Factories & Extensions

+

It’s preferable to create your extensions and app factories so that the +extension object does not initially get bound to the application.

+

Using Flask-SQLAlchemy, +as an example, you should not do something along those lines:

+
def create_app(config_filename):
+    app = Flask(__name__)
+    app.config.from_pyfile(config_filename)
+
+    db = SQLAlchemy(app)
+
+
+

But, rather, in model.py (or equivalent):

+
db = SQLAlchemy()
+
+
+

and in your application.py (or equivalent):

+
def create_app(config_filename):
+    app = Flask(__name__)
+    app.config.from_pyfile(config_filename)
+
+    from yourapplication.model import db
+    db.init_app(app)
+
+
+

Using this design pattern, no application-specific state is stored on the +extension object, so one extension object can be used for multiple apps. +For more information about the design of extensions refer to Flask Extension Development.

+
+
+

Using Applications

+

To run such an application, you can use the flask command:

+
$ flask --app hello run
+
+
+

Flask will automatically detect the factory if it is named +create_app or make_app in hello. You can also pass arguments +to the factory like this:

+
$ flask --app hello:create_app(local_auth=True) run
+
+
+

Then the create_app factory in myapp is called with the keyword +argument local_auth=True. See Command Line Interface for more detail.

+
+
+

Factory Improvements

+

The factory function above is not very clever, but you can improve it. +The following changes are straightforward to implement:

+
    +
  1. Make it possible to pass in configuration values for unit tests so that +you don’t have to create config files on the filesystem.

  2. +
  3. Call a function from a blueprint when the application is setting up so +that you have a place to modify attributes of the application (like +hooking in before/after request handlers etc.)

  4. +
  5. Add in WSGI middlewares when the application is being created if necessary.

  6. +
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/patterns/caching/index.html b/_build/patterns/caching/index.html new file mode 100644 index 00000000..75d1651f --- /dev/null +++ b/_build/patterns/caching/index.html @@ -0,0 +1,105 @@ + + + + + + + + Caching — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Caching

+

When your application runs slow, throw some caches in. Well, at least +it’s the easiest way to speed up things. What does a cache do? Say you +have a function that takes some time to complete but the results would +still be good enough if they were 5 minutes old. So then the idea is that +you actually put the result of that calculation into a cache for some +time.

+

Flask itself does not provide caching for you, but Flask-Caching, an +extension for Flask does. Flask-Caching supports various backends, and it is +even possible to develop your own caching backend.

+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/patterns/celery/index.html b/_build/patterns/celery/index.html new file mode 100644 index 00000000..58077fa9 --- /dev/null +++ b/_build/patterns/celery/index.html @@ -0,0 +1,301 @@ + + + + + + + + Background Tasks with Celery — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Background Tasks with Celery

+

If your application has a long running task, such as processing some uploaded data or +sending email, you don’t want to wait for it to finish during a request. Instead, use a +task queue to send the necessary data to another process that will run the task in the +background while the request returns immediately.

+

Celery is a powerful task queue that can be used for simple background tasks as well +as complex multi-stage programs and schedules. This guide will show you how to configure +Celery using Flask. Read Celery’s First Steps with Celery guide to learn how to use +Celery itself.

+

The Flask repository contains an example +based on the information on this page, which also shows how to use JavaScript to submit +tasks and poll for progress and results.

+
+

Install

+

Install Celery from PyPI, for example using pip:

+
$ pip install celery
+
+
+
+
+

Integrate Celery with Flask

+

You can use Celery without any integration with Flask, but it’s convenient to configure +it through Flask’s config, and to let tasks access the Flask application.

+

Celery uses similar ideas to Flask, with a Celery app object that has configuration +and registers tasks. While creating a Flask app, use the following code to create and +configure a Celery app as well.

+
from celery import Celery, Task
+
+def celery_init_app(app: Flask) -> Celery:
+    class FlaskTask(Task):
+        def __call__(self, *args: object, **kwargs: object) -> object:
+            with app.app_context():
+                return self.run(*args, **kwargs)
+
+    celery_app = Celery(app.name, task_cls=FlaskTask)
+    celery_app.config_from_object(app.config["CELERY"])
+    celery_app.set_default()
+    app.extensions["celery"] = celery_app
+    return celery_app
+
+
+

This creates and returns a Celery app object. Celery configuration is taken from +the CELERY key in the Flask configuration. The Celery app is set as the default, so +that it is seen during each request. The Task subclass automatically runs task +functions with a Flask app context active, so that services like your database +connections are available.

+

Here’s a basic example.py that configures Celery to use Redis for communication. We +enable a result backend, but ignore results by default. This allows us to store results +only for tasks where we care about the result.

+
from flask import Flask
+
+app = Flask(__name__)
+app.config.from_mapping(
+    CELERY=dict(
+        broker_url="redis://localhost",
+        result_backend="redis://localhost",
+        task_ignore_result=True,
+    ),
+)
+celery_app = celery_init_app(app)
+
+
+

Point the celery worker command at this and it will find the celery_app object.

+
$ celery -A example worker --loglevel INFO
+
+
+

You can also run the celery beat command to run tasks on a schedule. See Celery’s +docs for more information about defining schedules.

+
$ celery -A example beat --loglevel INFO
+
+
+
+
+

Application Factory

+

When using the Flask application factory pattern, call the celery_init_app function +inside the factory. It sets app.extensions["celery"] to the Celery app object, which +can be used to get the Celery app from the Flask app returned by the factory.

+
def create_app() -> Flask:
+    app = Flask(__name__)
+    app.config.from_mapping(
+        CELERY=dict(
+            broker_url="redis://localhost",
+            result_backend="redis://localhost",
+            task_ignore_result=True,
+        ),
+    )
+    app.config.from_prefixed_env()
+    celery_init_app(app)
+    return app
+
+
+

To use celery commands, Celery needs an app object, but that’s no longer directly +available. Create a make_celery.py file that calls the Flask app factory and gets +the Celery app from the returned Flask app.

+
from example import create_app
+
+flask_app = create_app()
+celery_app = flask_app.extensions["celery"]
+
+
+

Point the celery command to this file.

+
$ celery -A make_celery worker --loglevel INFO
+$ celery -A make_celery beat --loglevel INFO
+
+
+
+
+

Defining Tasks

+

Using @celery_app.task to decorate task functions requires access to the +celery_app object, which won’t be available when using the factory pattern. It also +means that the decorated tasks are tied to the specific Flask and Celery app instances, +which could be an issue during testing if you change configuration for a test.

+

Instead, use Celery’s @shared_task decorator. This creates task objects that will +access whatever the “current app” is, which is a similar concept to Flask’s blueprints +and app context. This is why we called celery_app.set_default() above.

+

Here’s an example task that adds two numbers together and returns the result.

+
from celery import shared_task
+
+@shared_task(ignore_result=False)
+def add_together(a: int, b: int) -> int:
+    return a + b
+
+
+

Earlier, we configured Celery to ignore task results by default. Since we want to know +the return value of this task, we set ignore_result=False. On the other hand, a task +that didn’t need a result, such as sending an email, wouldn’t set this.

+
+
+

Calling Tasks

+

The decorated function becomes a task object with methods to call it in the background. +The simplest way is to use the delay(*args, **kwargs) method. See Celery’s docs for +more methods.

+

A Celery worker must be running to run the task. Starting a worker is shown in the +previous sections.

+
from flask import request
+
+@app.post("/add")
+def start_add() -> dict[str, object]:
+    a = request.form.get("a", type=int)
+    b = request.form.get("b", type=int)
+    result = add_together.delay(a, b)
+    return {"result_id": result.id}
+
+
+

The route doesn’t get the task’s result immediately. That would defeat the purpose by +blocking the response. Instead, we return the running task’s result id, which we can use +later to get the result.

+
+
+

Getting Results

+

To fetch the result of the task we started above, we’ll add another route that takes the +result id we returned before. We return whether the task is finished (ready), whether it +finished successfully, and what the return value (or error) was if it is finished.

+
from celery.result import AsyncResult
+
+@app.get("/result/<id>")
+def task_result(id: str) -> dict[str, object]:
+    result = AsyncResult(id)
+    return {
+        "ready": result.ready(),
+        "successful": result.successful(),
+        "value": result.result if result.ready() else None,
+    }
+
+
+

Now you can start the task using the first route, then poll for the result using the +second route. This keeps the Flask request workers from being blocked waiting for tasks +to finish.

+

The Flask repository contains an example +using JavaScript to submit tasks and poll for progress and results.

+
+
+

Passing Data to Tasks

+

The “add” task above took two integers as arguments. To pass arguments to tasks, Celery +has to serialize them to a format that it can pass to other processes. Therefore, +passing complex objects is not recommended. For example, it would be impossible to pass +a SQLAlchemy model object, since that object is probably not serializable and is tied to +the session that queried it.

+

Pass the minimal amount of data necessary to fetch or recreate any complex data within +the task. Consider a task that will run when the logged in user asks for an archive of +their data. The Flask request knows the logged in user, and has the user object queried +from the database. It got that by querying the database for a given id, so the task can +do the same thing. Pass the user’s id rather than the user object.

+
@shared_task
+def generate_user_archive(user_id: str) -> None:
+    user = db.session.get(User, user_id)
+    ...
+
+generate_user_archive.delay(current_user.id)
+
+
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/patterns/deferredcallbacks/index.html b/_build/patterns/deferredcallbacks/index.html new file mode 100644 index 00000000..bfb19459 --- /dev/null +++ b/_build/patterns/deferredcallbacks/index.html @@ -0,0 +1,134 @@ + + + + + + + + Deferred Request Callbacks — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Deferred Request Callbacks

+

One of the design principles of Flask is that response objects are created and +passed down a chain of potential callbacks that can modify them or replace +them. When the request handling starts, there is no response object yet. It is +created as necessary either by a view function or by some other component in +the system.

+

What happens if you want to modify the response at a point where the response +does not exist yet? A common example for that would be a +before_request() callback that wants to set a cookie on the +response object.

+

One way is to avoid the situation. Very often that is possible. For instance +you can try to move that logic into a after_request() +callback instead. However, sometimes moving code there makes it +more complicated or awkward to reason about.

+

As an alternative, you can use after_this_request() to register +callbacks that will execute after only the current request. This way you can +defer code execution from anywhere in the application, based on the current +request.

+

At any time during a request, we can register a function to be called at the +end of the request. For example you can remember the current language of the +user in a cookie in a before_request() callback:

+
from flask import request, after_this_request
+
+@app.before_request
+def detect_user_language():
+    language = request.cookies.get('user_lang')
+
+    if language is None:
+        language = guess_language_from_request()
+
+        # when the response exists, set a cookie with the language
+        @after_this_request
+        def remember_language(response):
+            response.set_cookie('user_lang', language)
+            return response
+
+    g.language = language
+
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/patterns/favicon/index.html b/_build/patterns/favicon/index.html new file mode 100644 index 00000000..355b5c1e --- /dev/null +++ b/_build/patterns/favicon/index.html @@ -0,0 +1,150 @@ + + + + + + + + Adding a favicon — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Adding a favicon

+

A “favicon” is an icon used by browsers for tabs and bookmarks. This helps +to distinguish your website and to give it a unique brand.

+

A common question is how to add a favicon to a Flask application. First, of +course, you need an icon. It should be 16 × 16 pixels and in the ICO file +format. This is not a requirement but a de-facto standard supported by all +relevant browsers. Put the icon in your static directory as +favicon.ico.

+

Now, to get browsers to find your icon, the correct way is to add a link +tag in your HTML. So, for example:

+
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
+
+
+

That’s all you need for most browsers, however some really old ones do not +support this standard. The old de-facto standard is to serve this file, +with this name, at the website root. If your application is not mounted at +the root path of the domain you either need to configure the web server to +serve the icon at the root or if you can’t do that you’re out of luck. If +however your application is the root you can simply route a redirect:

+
app.add_url_rule('/favicon.ico',
+                 redirect_to=url_for('static', filename='favicon.ico'))
+
+
+

If you want to save the extra redirect request you can also write a view +using send_from_directory():

+
import os
+from flask import send_from_directory
+
+@app.route('/favicon.ico')
+def favicon():
+    return send_from_directory(os.path.join(app.root_path, 'static'),
+                               'favicon.ico', mimetype='image/vnd.microsoft.icon')
+
+
+

We can leave out the explicit mimetype and it will be guessed, but we may +as well specify it to avoid the extra guessing, as it will always be the +same.

+

The above will serve the icon via your application and if possible it’s +better to configure your dedicated web server to serve it; refer to the +web server’s documentation.

+
+

See also

+
    +
  • The Favicon article on +Wikipedia

  • +
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/patterns/fileuploads/index.html b/_build/patterns/fileuploads/index.html new file mode 100644 index 00000000..74cf5d74 --- /dev/null +++ b/_build/patterns/fileuploads/index.html @@ -0,0 +1,273 @@ + + + + + + + + Uploading Files — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Uploading Files

+

Ah yes, the good old problem of file uploads. The basic idea of file +uploads is actually quite simple. It basically works like this:

+
    +
  1. A <form> tag is marked with enctype=multipart/form-data +and an <input type=file> is placed in that form.

  2. +
  3. The application accesses the file from the files +dictionary on the request object.

  4. +
  5. use the save() method of the file to save +the file permanently somewhere on the filesystem.

  6. +
+
+

A Gentle Introduction

+

Let’s start with a very basic application that uploads a file to a +specific upload folder and displays a file to the user. Let’s look at the +bootstrapping code for our application:

+
import os
+from flask import Flask, flash, request, redirect, url_for
+from werkzeug.utils import secure_filename
+
+UPLOAD_FOLDER = '/path/to/the/uploads'
+ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
+
+app = Flask(__name__)
+app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
+
+
+

So first we need a couple of imports. Most should be straightforward, the +werkzeug.secure_filename() is explained a little bit later. The +UPLOAD_FOLDER is where we will store the uploaded files and the +ALLOWED_EXTENSIONS is the set of allowed file extensions.

+

Why do we limit the extensions that are allowed? You probably don’t want +your users to be able to upload everything there if the server is directly +sending out the data to the client. That way you can make sure that users +are not able to upload HTML files that would cause XSS problems (see +Cross-Site Scripting (XSS)). Also make sure to disallow .php files if the server +executes them, but who has PHP installed on their server, right? :)

+

Next the functions that check if an extension is valid and that uploads +the file and redirects the user to the URL for the uploaded file:

+
def allowed_file(filename):
+    return '.' in filename and \
+           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
+
+@app.route('/', methods=['GET', 'POST'])
+def upload_file():
+    if request.method == 'POST':
+        # check if the post request has the file part
+        if 'file' not in request.files:
+            flash('No file part')
+            return redirect(request.url)
+        file = request.files['file']
+        # If the user does not select a file, the browser submits an
+        # empty file without a filename.
+        if file.filename == '':
+            flash('No selected file')
+            return redirect(request.url)
+        if file and allowed_file(file.filename):
+            filename = secure_filename(file.filename)
+            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
+            return redirect(url_for('download_file', name=filename))
+    return '''
+    <!doctype html>
+    <title>Upload new File</title>
+    <h1>Upload new File</h1>
+    <form method=post enctype=multipart/form-data>
+      <input type=file name=file>
+      <input type=submit value=Upload>
+    </form>
+    '''
+
+
+

So what does that secure_filename() function actually do? +Now the problem is that there is that principle called “never trust user +input”. This is also true for the filename of an uploaded file. All +submitted form data can be forged, and filenames can be dangerous. For +the moment just remember: always use that function to secure a filename +before storing it directly on the filesystem.

+
+

Information for the Pros

+

So you’re interested in what that secure_filename() +function does and what the problem is if you’re not using it? So just +imagine someone would send the following information as filename to +your application:

+
filename = "../../../../home/username/.bashrc"
+
+
+

Assuming the number of ../ is correct and you would join this with +the UPLOAD_FOLDER the user might have the ability to modify a file on +the server’s filesystem he or she should not modify. This does require some +knowledge about how the application looks like, but trust me, hackers +are patient :)

+

Now let’s look how that function works:

+
>>> secure_filename('../../../../home/username/.bashrc')
+'home_username_.bashrc'
+
+
+
+

We want to be able to serve the uploaded files so they can be downloaded +by users. We’ll define a download_file view to serve files in the +upload folder by name. url_for("download_file", name=name) generates +download URLs.

+
from flask import send_from_directory
+
+@app.route('/uploads/<name>')
+def download_file(name):
+    return send_from_directory(app.config["UPLOAD_FOLDER"], name)
+
+
+

If you’re using middleware or the HTTP server to serve files, you can +register the download_file endpoint as build_only so url_for +will work without a view function.

+
app.add_url_rule(
+    "/uploads/<name>", endpoint="download_file", build_only=True
+)
+
+
+
+
+

Improving Uploads

+
+Changelog
+

Added in version 0.6.

+
+

So how exactly does Flask handle uploads? Well it will store them in the +webserver’s memory if the files are reasonably small, otherwise in a +temporary location (as returned by tempfile.gettempdir()). But how +do you specify the maximum file size after which an upload is aborted? By +default Flask will happily accept file uploads with an unlimited amount of +memory, but you can limit that by setting the MAX_CONTENT_LENGTH +config key:

+
from flask import Flask, Request
+
+app = Flask(__name__)
+app.config['MAX_CONTENT_LENGTH'] = 16 * 1000 * 1000
+
+
+

The code above will limit the maximum allowed payload to 16 megabytes. +If a larger file is transmitted, Flask will raise a +RequestEntityTooLarge exception.

+
+

Connection Reset Issue

+

When using the local development server, you may get a connection +reset error instead of a 413 response. You will get the correct +status response when running the app with a production WSGI server.

+
+

This feature was added in Flask 0.6 but can be achieved in older versions +as well by subclassing the request object. For more information on that +consult the Werkzeug documentation on file handling.

+
+
+

Upload Progress Bars

+

A while ago many developers had the idea to read the incoming file in +small chunks and store the upload progress in the database to be able to +poll the progress with JavaScript from the client. The client asks the +server every 5 seconds how much it has transmitted, but this is +something it should already know.

+
+
+

An Easier Solution

+

Now there are better solutions that work faster and are more reliable. There +are JavaScript libraries like jQuery that have form plugins to ease the +construction of progress bar.

+

Because the common pattern for file uploads exists almost unchanged in all +applications dealing with uploads, there are also some Flask extensions that +implement a full fledged upload mechanism that allows controlling which +file extensions are allowed to be uploaded.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/patterns/flashing/index.html b/_build/patterns/flashing/index.html new file mode 100644 index 00000000..0e49f8ef --- /dev/null +++ b/_build/patterns/flashing/index.html @@ -0,0 +1,243 @@ + + + + + + + + Message Flashing — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Message Flashing

+

Good applications and user interfaces are all about feedback. If the user +does not get enough feedback they will probably end up hating the +application. Flask provides a really simple way to give feedback to a +user with the flashing system. The flashing system basically makes it +possible to record a message at the end of a request and access it next +request and only next request. This is usually combined with a layout +template that does this. Note that browsers and sometimes web servers enforce +a limit on cookie sizes. This means that flashing messages that are too +large for session cookies causes message flashing to fail silently.

+
+

Simple Flashing

+

So here is a full example:

+
from flask import Flask, flash, redirect, render_template, \
+     request, url_for
+
+app = Flask(__name__)
+app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
+
+@app.route('/')
+def index():
+    return render_template('index.html')
+
+@app.route('/login', methods=['GET', 'POST'])
+def login():
+    error = None
+    if request.method == 'POST':
+        if request.form['username'] != 'admin' or \
+                request.form['password'] != 'secret':
+            error = 'Invalid credentials'
+        else:
+            flash('You were successfully logged in')
+            return redirect(url_for('index'))
+    return render_template('login.html', error=error)
+
+
+

And here is the layout.html template which does the magic:

+
<!doctype html>
+<title>My Application</title>
+{% with messages = get_flashed_messages() %}
+  {% if messages %}
+    <ul class=flashes>
+    {% for message in messages %}
+      <li>{{ message }}</li>
+    {% endfor %}
+    </ul>
+  {% endif %}
+{% endwith %}
+{% block body %}{% endblock %}
+
+
+

Here is the index.html template which inherits from layout.html:

+
{% extends "layout.html" %}
+{% block body %}
+  <h1>Overview</h1>
+  <p>Do you want to <a href="{{ url_for('login') }}">log in?</a>
+{% endblock %}
+
+
+

And here is the login.html template which also inherits from +layout.html:

+
{% extends "layout.html" %}
+{% block body %}
+  <h1>Login</h1>
+  {% if error %}
+    <p class=error><strong>Error:</strong> {{ error }}
+  {% endif %}
+  <form method=post>
+    <dl>
+      <dt>Username:
+      <dd><input type=text name=username value="{{
+          request.form.username }}">
+      <dt>Password:
+      <dd><input type=password name=password>
+    </dl>
+    <p><input type=submit value=Login>
+  </form>
+{% endblock %}
+
+
+
+
+

Flashing With Categories

+
+Changelog
+

Added in version 0.3.

+
+

It is also possible to provide categories when flashing a message. The +default category if nothing is provided is 'message'. Alternative +categories can be used to give the user better feedback. For example +error messages could be displayed with a red background.

+

To flash a message with a different category, just use the second argument +to the flash() function:

+
flash('Invalid password provided', 'error')
+
+
+

Inside the template you then have to tell the +get_flashed_messages() function to also return the +categories. The loop looks slightly different in that situation then:

+
{% with messages = get_flashed_messages(with_categories=true) %}
+  {% if messages %}
+    <ul class=flashes>
+    {% for category, message in messages %}
+      <li class="{{ category }}">{{ message }}</li>
+    {% endfor %}
+    </ul>
+  {% endif %}
+{% endwith %}
+
+
+

This is just one example of how to render these flashed messages. One +might also use the category to add a prefix such as +<strong>Error:</strong> to the message.

+
+
+

Filtering Flash Messages

+
+Changelog
+

Added in version 0.9.

+
+

Optionally you can pass a list of categories which filters the results of +get_flashed_messages(). This is useful if you wish to +render each category in a separate block.

+
{% with errors = get_flashed_messages(category_filter=["error"]) %}
+{% if errors %}
+<div class="alert-message block-message error">
+  <a class="close" href="#">×</a>
+  <ul>
+    {%- for msg in errors %}
+    <li>{{ msg }}</li>
+    {% endfor -%}
+  </ul>
+</div>
+{% endif %}
+{% endwith %}
+
+
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/patterns/index.html b/_build/patterns/index.html new file mode 100644 index 00000000..df8c42d8 --- /dev/null +++ b/_build/patterns/index.html @@ -0,0 +1,222 @@ + + + + + + + + Patterns for Flask — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Patterns for Flask

+

Certain features and interactions are common enough that you will find +them in most web applications. For example, many applications use a +relational database and user authentication. They will open a database +connection at the beginning of the request and get the information for +the logged in user. At the end of the request, the database connection +is closed.

+

These types of patterns may be a bit outside the scope of Flask itself, +but Flask makes it easy to implement them. Some common patterns are +collected in the following pages.

+
+ +
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/patterns/javascript/index.html b/_build/patterns/javascript/index.html new file mode 100644 index 00000000..0690dfb1 --- /dev/null +++ b/_build/patterns/javascript/index.html @@ -0,0 +1,314 @@ + + + + + + + + JavaScript, fetch, and JSON — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

JavaScript, fetch, and JSON

+

You may want to make your HTML page dynamic, by changing data without +reloading the entire page. Instead of submitting an HTML <form> and +performing a redirect to re-render the template, you can add +JavaScript that calls fetch() and replaces content on the page.

+

fetch() is the modern, built-in JavaScript solution to making +requests from a page. You may have heard of other “AJAX” methods and +libraries, such as XMLHttpRequest() or jQuery. These are no longer needed in +modern browsers, although you may choose to use them or another library +depending on your application’s requirements. These docs will only focus +on built-in JavaScript features.

+
+

Rendering Templates

+

It is important to understand the difference between templates and +JavaScript. Templates are rendered on the server, before the response is +sent to the user’s browser. JavaScript runs in the user’s browser, after +the template is rendered and sent. Therefore, it is impossible to use +JavaScript to affect how the Jinja template is rendered, but it is +possible to render data into the JavaScript that will run.

+

To provide data to JavaScript when rendering the template, use the +tojson() filter in a <script> block. This will +convert the data to a valid JavaScript object, and ensure that any +unsafe HTML characters are rendered safely. If you do not use the +tojson filter, you will get a SyntaxError in the browser +console.

+
data = generate_report()
+return render_template("report.html", chart_data=data)
+
+
+
<script>
+    const chart_data = {{ chart_data|tojson }}
+    chartLib.makeChart(chart_data)
+</script>
+
+
+

A less common pattern is to add the data to a data- attribute on an +HTML tag. In this case, you must use single quotes around the value, not +double quotes, otherwise you will produce invalid or unsafe HTML.

+
<div data-chart='{{ chart_data|tojson }}'></div>
+
+
+
+
+

Generating URLs

+

The other way to get data from the server to JavaScript is to make a +request for it. First, you need to know the URL to request.

+

The simplest way to generate URLs is to continue to use +url_for() when rendering the template. For example:

+
const user_url = {{ url_for("user", id=current_user.id)|tojson }}
+fetch(user_url).then(...)
+
+
+

However, you might need to generate a URL based on information you only +know in JavaScript. As discussed above, JavaScript runs in the user’s +browser, not as part of the template rendering, so you can’t use +url_for at that point.

+

In this case, you need to know the “root URL” under which your +application is served. In simple setups, this is /, but it might +also be something else, like https://example.com/myapp/.

+

A simple way to tell your JavaScript code about this root is to set it +as a global variable when rendering the template. Then you can use it +when generating URLs from JavaScript.

+
const SCRIPT_ROOT = {{ request.script_root|tojson }}
+let user_id = ...  // do something to get a user id from the page
+let user_url = `${SCRIPT_ROOT}/user/${user_id}`
+fetch(user_url).then(...)
+
+
+
+
+

Making a Request with fetch

+

fetch() takes two arguments, a URL and an object with other options, +and returns a Promise. We won’t cover all the available options, and +will only use then() on the promise, not other callbacks or +await syntax. Read the linked MDN docs for more information about +those features.

+

By default, the GET method is used. If the response contains JSON, it +can be used with a then() callback chain.

+
const room_url = {{ url_for("room_detail", id=room.id)|tojson }}
+fetch(room_url)
+    .then(response => response.json())
+    .then(data => {
+        // data is a parsed JSON object
+    })
+
+
+

To send data, use a data method such as POST, and pass the body +option. The most common types for data are form data or JSON data.

+

To send form data, pass a populated FormData object. This uses the +same format as an HTML form, and would be accessed with request.form +in a Flask view.

+
let data = new FormData()
+data.append("name", "Flask Room")
+data.append("description", "Talk about Flask here.")
+fetch(room_url, {
+    "method": "POST",
+    "body": data,
+}).then(...)
+
+
+

In general, prefer sending request data as form data, as would be used +when submitting an HTML form. JSON can represent more complex data, but +unless you need that it’s better to stick with the simpler format. When +sending JSON data, the Content-Type: application/json header must be +sent as well, otherwise Flask will return a 400 error.

+
let data = {
+    "name": "Flask Room",
+    "description": "Talk about Flask here.",
+}
+fetch(room_url, {
+    "method": "POST",
+    "headers": {"Content-Type": "application/json"},
+    "body": JSON.stringify(data),
+}).then(...)
+
+
+
+
+

Following Redirects

+

A response might be a redirect, for example if you logged in with +JavaScript instead of a traditional HTML form, and your view returned +a redirect instead of JSON. JavaScript requests do follow redirects, but +they don’t change the page. If you want to make the page change you can +inspect the response and apply the redirect manually.

+
fetch("/login", {"body": ...}).then(
+    response => {
+        if (response.redirected) {
+            window.location = response.url
+        } else {
+            showLoginError()
+        }
+    }
+)
+
+
+
+
+

Replacing Content

+

A response might be new HTML, either a new section of the page to add or +replace, or an entirely new page. In general, if you’re returning the +entire page, it would be better to handle that with a redirect as shown +in the previous section. The following example shows how to replace a +<div> with the HTML returned by a request.

+
<div id="geology-fact">
+    {{ include "geology_fact.html" }}
+</div>
+<script>
+    const geology_url = {{ url_for("geology_fact")|tojson }}
+    const geology_div = getElementById("geology-fact")
+    fetch(geology_url)
+        .then(response => response.text)
+        .then(text => geology_div.innerHTML = text)
+</script>
+
+
+
+
+

Return JSON from Views

+

To return a JSON object from your API view, you can directly return a +dict from the view. It will be serialized to JSON automatically.

+
@app.route("/user/<int:id>")
+def user_detail(id):
+    user = User.query.get_or_404(id)
+    return {
+        "username": User.username,
+        "email": User.email,
+        "picture": url_for("static", filename=f"users/{id}/profile.png"),
+    }
+
+
+

If you want to return another JSON type, use the +jsonify() function, which creates a response object +with the given data serialized to JSON.

+
from flask import jsonify
+
+@app.route("/users")
+def user_list():
+    users = User.query.order_by(User.name).all()
+    return jsonify([u.to_json() for u in users])
+
+
+

It is usually not a good idea to return file data in a JSON response. +JSON cannot represent binary data directly, so it must be base64 +encoded, which can be slow, takes more bandwidth to send, and is not as +easy to cache. Instead, serve files using one view, and generate a URL +to the desired file to include in the JSON. Then the client can make a +separate request to get the linked resource after getting the JSON.

+
+
+

Receiving JSON in Views

+

Use the json property of the +request object to decode the request’s body as JSON. If +the body is not valid JSON, or the Content-Type header is not set to +application/json, a 400 Bad Request error will be raised.

+
from flask import request
+
+@app.post("/user/<int:id>")
+def user_update(id):
+    user = User.query.get_or_404(id)
+    user.update_from_json(request.json)
+    db.session.commit()
+    return user.to_json()
+
+
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/patterns/jquery/index.html b/_build/patterns/jquery/index.html new file mode 100644 index 00000000..ecb42036 --- /dev/null +++ b/_build/patterns/jquery/index.html @@ -0,0 +1,82 @@ + + + + + + + + AJAX with jQuery — Flask Documentation (3.1.x) + + + + + + + + + + + + +
+
+
+
+ +
+

AJAX with jQuery

+

Obsolete, see JavaScript, fetch, and JSON instead.

+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/patterns/lazyloading/index.html b/_build/patterns/lazyloading/index.html new file mode 100644 index 00000000..a9ac2036 --- /dev/null +++ b/_build/patterns/lazyloading/index.html @@ -0,0 +1,207 @@ + + + + + + + + Lazily Loading Views — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Lazily Loading Views

+

Flask is usually used with the decorators. Decorators are simple and you +have the URL right next to the function that is called for that specific +URL. However there is a downside to this approach: it means all your code +that uses decorators has to be imported upfront or Flask will never +actually find your function.

+

This can be a problem if your application has to import quick. It might +have to do that on systems like Google’s App Engine or other systems. So +if you suddenly notice that your application outgrows this approach you +can fall back to a centralized URL mapping.

+

The system that enables having a central URL map is the +add_url_rule() function. Instead of using decorators, +you have a file that sets up the application with all URLs.

+
+

Converting to Centralized URL Map

+

Imagine the current application looks somewhat like this:

+
from flask import Flask
+app = Flask(__name__)
+
+@app.route('/')
+def index():
+    pass
+
+@app.route('/user/<username>')
+def user(username):
+    pass
+
+
+

Then, with the centralized approach you would have one file with the views +(views.py) but without any decorator:

+
def index():
+    pass
+
+def user(username):
+    pass
+
+
+

And then a file that sets up an application which maps the functions to +URLs:

+
from flask import Flask
+from yourapplication import views
+app = Flask(__name__)
+app.add_url_rule('/', view_func=views.index)
+app.add_url_rule('/user/<username>', view_func=views.user)
+
+
+
+
+

Loading Late

+

So far we only split up the views and the routing, but the module is still +loaded upfront. The trick is to actually load the view function as needed. +This can be accomplished with a helper class that behaves just like a +function but internally imports the real function on first use:

+
from werkzeug.utils import import_string, cached_property
+
+class LazyView(object):
+
+    def __init__(self, import_name):
+        self.__module__, self.__name__ = import_name.rsplit('.', 1)
+        self.import_name = import_name
+
+    @cached_property
+    def view(self):
+        return import_string(self.import_name)
+
+    def __call__(self, *args, **kwargs):
+        return self.view(*args, **kwargs)
+
+
+

What’s important here is is that __module__ and __name__ are properly +set. This is used by Flask internally to figure out how to name the +URL rules in case you don’t provide a name for the rule yourself.

+

Then you can define your central place to combine the views like this:

+
from flask import Flask
+from yourapplication.helpers import LazyView
+app = Flask(__name__)
+app.add_url_rule('/',
+                 view_func=LazyView('yourapplication.views.index'))
+app.add_url_rule('/user/<username>',
+                 view_func=LazyView('yourapplication.views.user'))
+
+
+

You can further optimize this in terms of amount of keystrokes needed to +write this by having a function that calls into +add_url_rule() by prefixing a string with the project +name and a dot, and by wrapping view_func in a LazyView as needed.

+
def url(import_name, url_rules=[], **options):
+    view = LazyView(f"yourapplication.{import_name}")
+    for url_rule in url_rules:
+        app.add_url_rule(url_rule, view_func=view, **options)
+
+# add a single route to the index view
+url('views.index', ['/'])
+
+# add two routes to a single function endpoint
+url_rules = ['/user/','/user/<username>']
+url('views.user', url_rules)
+
+
+

One thing to keep in mind is that before and after request handlers have +to be in a file that is imported upfront to work properly on the first +request. The same goes for any kind of remaining decorator.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/patterns/methodoverrides/index.html b/_build/patterns/methodoverrides/index.html new file mode 100644 index 00000000..430ea134 --- /dev/null +++ b/_build/patterns/methodoverrides/index.html @@ -0,0 +1,134 @@ + + + + + + + + Adding HTTP Method Overrides — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Adding HTTP Method Overrides

+

Some HTTP proxies do not support arbitrary HTTP methods or newer HTTP +methods (such as PATCH). In that case it’s possible to “proxy” HTTP +methods through another HTTP method in total violation of the protocol.

+

The way this works is by letting the client do an HTTP POST request and +set the X-HTTP-Method-Override header. Then the method is replaced +with the header value before being passed to Flask.

+

This can be accomplished with an HTTP middleware:

+
class HTTPMethodOverrideMiddleware(object):
+    allowed_methods = frozenset([
+        'GET',
+        'HEAD',
+        'POST',
+        'DELETE',
+        'PUT',
+        'PATCH',
+        'OPTIONS'
+    ])
+    bodyless_methods = frozenset(['GET', 'HEAD', 'OPTIONS', 'DELETE'])
+
+    def __init__(self, app):
+        self.app = app
+
+    def __call__(self, environ, start_response):
+        method = environ.get('HTTP_X_HTTP_METHOD_OVERRIDE', '').upper()
+        if method in self.allowed_methods:
+            environ['REQUEST_METHOD'] = method
+        if method in self.bodyless_methods:
+            environ['CONTENT_LENGTH'] = '0'
+        return self.app(environ, start_response)
+
+
+

To use this with Flask, wrap the app object with the middleware:

+
from flask import Flask
+
+app = Flask(__name__)
+app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)
+
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/patterns/mongoengine/index.html b/_build/patterns/mongoengine/index.html new file mode 100644 index 00000000..eedc1234 --- /dev/null +++ b/_build/patterns/mongoengine/index.html @@ -0,0 +1,197 @@ + + + + + + + + MongoDB with MongoEngine — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

MongoDB with MongoEngine

+

Using a document database like MongoDB is a common alternative to +relational SQL databases. This pattern shows how to use +MongoEngine, a document mapper library, to integrate with MongoDB.

+

A running MongoDB server and Flask-MongoEngine are required.

+
pip install flask-mongoengine
+
+
+
+

Configuration

+

Basic setup can be done by defining MONGODB_SETTINGS on +app.config and creating a MongoEngine instance.

+
from flask import Flask
+from flask_mongoengine import MongoEngine
+
+app = Flask(__name__)
+app.config['MONGODB_SETTINGS'] = {
+    "db": "myapp",
+}
+db = MongoEngine(app)
+
+
+
+
+

Mapping Documents

+

To declare a model that represents a Mongo document, create a class that +inherits from Document and declare each of the fields.

+
import mongoengine as me
+
+class Movie(me.Document):
+    title = me.StringField(required=True)
+    year = me.IntField()
+    rated = me.StringField()
+    director = me.StringField()
+    actors = me.ListField()
+
+
+

If the document has nested fields, use EmbeddedDocument to +defined the fields of the embedded document and +EmbeddedDocumentField to declare it on the parent document.

+
class Imdb(me.EmbeddedDocument):
+    imdb_id = me.StringField()
+    rating = me.DecimalField()
+    votes = me.IntField()
+
+class Movie(me.Document):
+    ...
+    imdb = me.EmbeddedDocumentField(Imdb)
+
+
+
+
+

Creating Data

+

Instantiate your document class with keyword arguments for the fields. +You can also assign values to the field attributes after instantiation. +Then call doc.save().

+
bttf = Movie(title="Back To The Future", year=1985)
+bttf.actors = [
+    "Michael J. Fox",
+    "Christopher Lloyd"
+]
+bttf.imdb = Imdb(imdb_id="tt0088763", rating=8.5)
+bttf.save()
+
+
+
+
+

Queries

+

Use the class objects attribute to make queries. A keyword argument +looks for an equal value on the field.

+
bttf = Movies.objects(title="Back To The Future").get_or_404()
+
+
+

Query operators may be used by concatenating them with the field name +using a double-underscore. objects, and queries returned by +calling it, are iterable.

+
some_theron_movie = Movie.objects(actors__in=["Charlize Theron"]).first()
+
+for recents in Movie.objects(year__gte=2017):
+    print(recents.title)
+
+
+
+
+

Documentation

+

There are many more ways to define and query documents with MongoEngine. +For more information, check out the official documentation.

+

Flask-MongoEngine adds helpful utilities on top of MongoEngine. Check +out their documentation as well.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/patterns/packages/index.html b/_build/patterns/packages/index.html new file mode 100644 index 00000000..c723d1a2 --- /dev/null +++ b/_build/patterns/packages/index.html @@ -0,0 +1,226 @@ + + + + + + + + Large Applications as Packages — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Large Applications as Packages

+

Imagine a simple flask application structure that looks like this:

+
/yourapplication
+    yourapplication.py
+    /static
+        style.css
+    /templates
+        layout.html
+        index.html
+        login.html
+        ...
+
+
+

While this is fine for small applications, for larger applications +it’s a good idea to use a package instead of a module. +The Tutorial is structured to use the package pattern, +see the example code.

+
+

Simple Packages

+

To convert that into a larger one, just create a new folder +yourapplication inside the existing one and move everything below it. +Then rename yourapplication.py to __init__.py. (Make sure to delete +all .pyc files first, otherwise things would most likely break)

+

You should then end up with something like that:

+
/yourapplication
+    /yourapplication
+        __init__.py
+        /static
+            style.css
+        /templates
+            layout.html
+            index.html
+            login.html
+            ...
+
+
+

But how do you run your application now? The naive python +yourapplication/__init__.py will not work. Let’s just say that Python +does not want modules in packages to be the startup file. But that is not +a big problem, just add a new file called pyproject.toml next to the inner +yourapplication folder with the following contents:

+
[project]
+name = "yourapplication"
+dependencies = [
+    "flask",
+]
+
+[build-system]
+requires = ["flit_core<4"]
+build-backend = "flit_core.buildapi"
+
+
+

Install your application so it is importable:

+
$ pip install -e .
+
+
+

To use the flask command and run your application you need to set +the --app option that tells Flask where to find the application +instance:

+
$ flask --app yourapplication run
+
+
+

What did we gain from this? Now we can restructure the application a bit +into multiple modules. The only thing you have to remember is the +following quick checklist:

+
    +
  1. the Flask application object creation has to be in the +__init__.py file. That way each module can import it safely and the +__name__ variable will resolve to the correct package.

  2. +
  3. all the view functions (the ones with a route() +decorator on top) have to be imported in the __init__.py file. +Not the object itself, but the module it is in. Import the view module +after the application object is created.

  4. +
+

Here’s an example __init__.py:

+
from flask import Flask
+app = Flask(__name__)
+
+import yourapplication.views
+
+
+

And this is what views.py would look like:

+
from yourapplication import app
+
+@app.route('/')
+def index():
+    return 'Hello World!'
+
+
+

You should then end up with something like that:

+
/yourapplication
+    pyproject.toml
+    /yourapplication
+        __init__.py
+        views.py
+        /static
+            style.css
+        /templates
+            layout.html
+            index.html
+            login.html
+            ...
+
+
+
+

Circular Imports

+

Every Python programmer hates them, and yet we just added some: +circular imports (That’s when two modules depend on each other. In this +case views.py depends on __init__.py). Be advised that this is a +bad idea in general but here it is actually fine. The reason for this is +that we are not actually using the views in __init__.py and just +ensuring the module is imported and we are doing that at the bottom of +the file.

+
+
+
+

Working with Blueprints

+

If you have larger applications it’s recommended to divide them into +smaller groups where each group is implemented with the help of a +blueprint. For a gentle introduction into this topic refer to the +Modular Applications with Blueprints chapter of the documentation.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/patterns/requestchecksum/index.html b/_build/patterns/requestchecksum/index.html new file mode 100644 index 00000000..84ac1563 --- /dev/null +++ b/_build/patterns/requestchecksum/index.html @@ -0,0 +1,146 @@ + + + + + + + + Request Content Checksums — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Request Content Checksums

+

Various pieces of code can consume the request data and preprocess it. +For instance JSON data ends up on the request object already read and +processed, form data ends up there as well but goes through a different +code path. This seems inconvenient when you want to calculate the +checksum of the incoming request data. This is necessary sometimes for +some APIs.

+

Fortunately this is however very simple to change by wrapping the input +stream.

+

The following example calculates the SHA1 checksum of the incoming data as +it gets read and stores it in the WSGI environment:

+
import hashlib
+
+class ChecksumCalcStream(object):
+
+    def __init__(self, stream):
+        self._stream = stream
+        self._hash = hashlib.sha1()
+
+    def read(self, bytes):
+        rv = self._stream.read(bytes)
+        self._hash.update(rv)
+        return rv
+
+    def readline(self, size_hint):
+        rv = self._stream.readline(size_hint)
+        self._hash.update(rv)
+        return rv
+
+def generate_checksum(request):
+    env = request.environ
+    stream = ChecksumCalcStream(env['wsgi.input'])
+    env['wsgi.input'] = stream
+    return stream._hash
+
+
+

To use this, all you need to do is to hook the calculating stream in +before the request starts consuming data. (Eg: be careful accessing +request.form or anything of that nature. before_request_handlers +for instance should be careful not to access it).

+

Example usage:

+
@app.route('/special-api', methods=['POST'])
+def special_api():
+    hash = generate_checksum(request)
+    # Accessing this parses the input stream
+    files = request.files
+    # At this point the hash is fully constructed.
+    checksum = hash.hexdigest()
+    return f"Hash was: {checksum}"
+
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/patterns/singlepageapplications/index.html b/_build/patterns/singlepageapplications/index.html new file mode 100644 index 00000000..3499e732 --- /dev/null +++ b/_build/patterns/singlepageapplications/index.html @@ -0,0 +1,117 @@ + + + + + + + + Single-Page Applications — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Single-Page Applications

+

Flask can be used to serve Single-Page Applications (SPA) by placing static +files produced by your frontend framework in a subfolder inside of your +project. You will also need to create a catch-all endpoint that routes all +requests to your SPA.

+

The following example demonstrates how to serve an SPA along with an API:

+
from flask import Flask, jsonify
+
+app = Flask(__name__, static_folder='app', static_url_path="/app")
+
+
+@app.route("/heartbeat")
+def heartbeat():
+    return jsonify({"status": "healthy"})
+
+
+@app.route('/', defaults={'path': ''})
+@app.route('/<path:path>')
+def catch_all(path):
+    return app.send_static_file("index.html")
+
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/patterns/sqlalchemy/index.html b/_build/patterns/sqlalchemy/index.html new file mode 100644 index 00000000..85cd3a8f --- /dev/null +++ b/_build/patterns/sqlalchemy/index.html @@ -0,0 +1,301 @@ + + + + + + + + SQLAlchemy in Flask — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

SQLAlchemy in Flask

+

Many people prefer SQLAlchemy for database access. In this case it’s +encouraged to use a package instead of a module for your flask application +and drop the models into a separate module (Large Applications as Packages). While that +is not necessary, it makes a lot of sense.

+

There are four very common ways to use SQLAlchemy. I will outline each +of them here:

+
+

Flask-SQLAlchemy Extension

+

Because SQLAlchemy is a common database abstraction layer and object +relational mapper that requires a little bit of configuration effort, +there is a Flask extension that handles that for you. This is recommended +if you want to get started quickly.

+

You can download Flask-SQLAlchemy from PyPI.

+
+
+

Declarative

+

The declarative extension in SQLAlchemy is the most recent method of using +SQLAlchemy. It allows you to define tables and models in one go, similar +to how Django works. In addition to the following text I recommend the +official documentation on the declarative extension.

+

Here’s the example database.py module for your application:

+
from sqlalchemy import create_engine
+from sqlalchemy.orm import scoped_session, sessionmaker, declarative_base
+
+engine = create_engine('sqlite:////tmp/test.db')
+db_session = scoped_session(sessionmaker(autocommit=False,
+                                         autoflush=False,
+                                         bind=engine))
+Base = declarative_base()
+Base.query = db_session.query_property()
+
+def init_db():
+    # import all modules here that might define models so that
+    # they will be registered properly on the metadata.  Otherwise
+    # you will have to import them first before calling init_db()
+    import yourapplication.models
+    Base.metadata.create_all(bind=engine)
+
+
+

To define your models, just subclass the Base class that was created by +the code above. If you are wondering why we don’t have to care about +threads here (like we did in the SQLite3 example above with the +g object): that’s because SQLAlchemy does that for us +already with the scoped_session.

+

To use SQLAlchemy in a declarative way with your application, you just +have to put the following code into your application module. Flask will +automatically remove database sessions at the end of the request or +when the application shuts down:

+
from yourapplication.database import db_session
+
+@app.teardown_appcontext
+def shutdown_session(exception=None):
+    db_session.remove()
+
+
+

Here is an example model (put this into models.py, e.g.):

+
from sqlalchemy import Column, Integer, String
+from yourapplication.database import Base
+
+class User(Base):
+    __tablename__ = 'users'
+    id = Column(Integer, primary_key=True)
+    name = Column(String(50), unique=True)
+    email = Column(String(120), unique=True)
+
+    def __init__(self, name=None, email=None):
+        self.name = name
+        self.email = email
+
+    def __repr__(self):
+        return f'<User {self.name!r}>'
+
+
+

To create the database you can use the init_db function:

+
>>> from yourapplication.database import init_db
+>>> init_db()
+
+
+

You can insert entries into the database like this:

+
>>> from yourapplication.database import db_session
+>>> from yourapplication.models import User
+>>> u = User('admin', 'admin@localhost')
+>>> db_session.add(u)
+>>> db_session.commit()
+
+
+

Querying is simple as well:

+
>>> User.query.all()
+[<User 'admin'>]
+>>> User.query.filter(User.name == 'admin').first()
+<User 'admin'>
+
+
+
+
+

Manual Object Relational Mapping

+

Manual object relational mapping has a few upsides and a few downsides +versus the declarative approach from above. The main difference is that +you define tables and classes separately and map them together. It’s more +flexible but a little more to type. In general it works like the +declarative approach, so make sure to also split up your application into +multiple modules in a package.

+

Here is an example database.py module for your application:

+
from sqlalchemy import create_engine, MetaData
+from sqlalchemy.orm import scoped_session, sessionmaker
+
+engine = create_engine('sqlite:////tmp/test.db')
+metadata = MetaData()
+db_session = scoped_session(sessionmaker(autocommit=False,
+                                         autoflush=False,
+                                         bind=engine))
+def init_db():
+    metadata.create_all(bind=engine)
+
+
+

As in the declarative approach, you need to close the session after +each request or application context shutdown. Put this into your +application module:

+
from yourapplication.database import db_session
+
+@app.teardown_appcontext
+def shutdown_session(exception=None):
+    db_session.remove()
+
+
+

Here is an example table and model (put this into models.py):

+
from sqlalchemy import Table, Column, Integer, String
+from sqlalchemy.orm import mapper
+from yourapplication.database import metadata, db_session
+
+class User(object):
+    query = db_session.query_property()
+
+    def __init__(self, name=None, email=None):
+        self.name = name
+        self.email = email
+
+    def __repr__(self):
+        return f'<User {self.name!r}>'
+
+users = Table('users', metadata,
+    Column('id', Integer, primary_key=True),
+    Column('name', String(50), unique=True),
+    Column('email', String(120), unique=True)
+)
+mapper(User, users)
+
+
+

Querying and inserting works exactly the same as in the example above.

+
+
+

SQL Abstraction Layer

+

If you just want to use the database system (and SQL) abstraction layer +you basically only need the engine:

+
from sqlalchemy import create_engine, MetaData, Table
+
+engine = create_engine('sqlite:////tmp/test.db')
+metadata = MetaData(bind=engine)
+
+
+

Then you can either declare the tables in your code like in the examples +above, or automatically load them:

+
from sqlalchemy import Table
+
+users = Table('users', metadata, autoload=True)
+
+
+

To insert data you can use the insert method. We have to get a +connection first so that we can use a transaction:

+
>>> con = engine.connect()
+>>> con.execute(users.insert(), name='admin', email='admin@localhost')
+
+
+

SQLAlchemy will automatically commit for us.

+

To query your database, you use the engine directly or use a connection:

+
>>> users.select(users.c.id == 1).execute().first()
+(1, 'admin', 'admin@localhost')
+
+
+

These results are also dict-like tuples:

+
>>> r = users.select(users.c.id == 1).execute().first()
+>>> r['name']
+'admin'
+
+
+

You can also pass strings of SQL statements to the +execute() method:

+
>>> engine.execute('select * from users where id = :1', [1]).first()
+(1, 'admin', 'admin@localhost')
+
+
+

For more information about SQLAlchemy, head over to the +website.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/patterns/sqlite3/index.html b/_build/patterns/sqlite3/index.html new file mode 100644 index 00000000..148cdb90 --- /dev/null +++ b/_build/patterns/sqlite3/index.html @@ -0,0 +1,244 @@ + + + + + + + + Using SQLite 3 with Flask — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Using SQLite 3 with Flask

+

In Flask you can easily implement the opening of database connections on +demand and closing them when the context dies (usually at the end of the +request).

+

Here is a simple example of how you can use SQLite 3 with Flask:

+
import sqlite3
+from flask import g
+
+DATABASE = '/path/to/database.db'
+
+def get_db():
+    db = getattr(g, '_database', None)
+    if db is None:
+        db = g._database = sqlite3.connect(DATABASE)
+    return db
+
+@app.teardown_appcontext
+def close_connection(exception):
+    db = getattr(g, '_database', None)
+    if db is not None:
+        db.close()
+
+
+

Now, to use the database, the application must either have an active +application context (which is always true if there is a request in flight) +or create an application context itself. At that point the get_db +function can be used to get the current database connection. Whenever the +context is destroyed the database connection will be terminated.

+

Example:

+
@app.route('/')
+def index():
+    cur = get_db().cursor()
+    ...
+
+
+
+

Note

+

Please keep in mind that the teardown request and appcontext functions +are always executed, even if a before-request handler failed or was +never executed. Because of this we have to make sure here that the +database is there before we close it.

+
+
+

Connect on Demand

+

The upside of this approach (connecting on first use) is that this will +only open the connection if truly necessary. If you want to use this +code outside a request context you can use it in a Python shell by opening +the application context by hand:

+
with app.app_context():
+    # now you can use get_db()
+
+
+
+
+

Easy Querying

+

Now in each request handling function you can access get_db() to get the +current open database connection. To simplify working with SQLite, a +row factory function is useful. It is executed for every result returned +from the database to convert the result. For instance, in order to get +dictionaries instead of tuples, this could be inserted into the get_db +function we created above:

+
def make_dicts(cursor, row):
+    return dict((cursor.description[idx][0], value)
+                for idx, value in enumerate(row))
+
+db.row_factory = make_dicts
+
+
+

This will make the sqlite3 module return dicts for this database connection, which are much nicer to deal with. Even more simply, we could place this in get_db instead:

+
db.row_factory = sqlite3.Row
+
+
+

This would use Row objects rather than dicts to return the results of queries. These are namedtuple s, so we can access them either by index or by key. For example, assuming we have a sqlite3.Row called r for the rows id, FirstName, LastName, and MiddleInitial:

+
>>> # You can get values based on the row's name
+>>> r['FirstName']
+John
+>>> # Or, you can get them based on index
+>>> r[1]
+John
+# Row objects are also iterable:
+>>> for value in r:
+...     print(value)
+1
+John
+Doe
+M
+
+
+

Additionally, it is a good idea to provide a query function that combines +getting the cursor, executing and fetching the results:

+
def query_db(query, args=(), one=False):
+    cur = get_db().execute(query, args)
+    rv = cur.fetchall()
+    cur.close()
+    return (rv[0] if rv else None) if one else rv
+
+
+

This handy little function, in combination with a row factory, makes +working with the database much more pleasant than it is by just using the +raw cursor and connection objects.

+

Here is how you can use it:

+
for user in query_db('select * from users'):
+    print(user['username'], 'has the id', user['user_id'])
+
+
+

Or if you just want a single result:

+
user = query_db('select * from users where username = ?',
+                [the_username], one=True)
+if user is None:
+    print('No such user')
+else:
+    print(the_username, 'has the id', user['user_id'])
+
+
+

To pass variable parts to the SQL statement, use a question mark in the +statement and pass in the arguments as a list. Never directly add them to +the SQL statement with string formatting because this makes it possible +to attack the application using SQL Injections.

+
+
+

Initial Schemas

+

Relational databases need schemas, so applications often ship a +schema.sql file that creates the database. It’s a good idea to provide +a function that creates the database based on that schema. This function +can do that for you:

+
def init_db():
+    with app.app_context():
+        db = get_db()
+        with app.open_resource('schema.sql', mode='r') as f:
+            db.cursor().executescript(f.read())
+        db.commit()
+
+
+

You can then create such a database from the Python shell:

+
>>> from yourapplication import init_db
+>>> init_db()
+
+
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/patterns/streaming/index.html b/_build/patterns/streaming/index.html new file mode 100644 index 00000000..758eb5c0 --- /dev/null +++ b/_build/patterns/streaming/index.html @@ -0,0 +1,176 @@ + + + + + + + + Streaming Contents — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Streaming Contents

+

Sometimes you want to send an enormous amount of data to the client, much +more than you want to keep in memory. When you are generating the data on +the fly though, how do you send that back to the client without the +roundtrip to the filesystem?

+

The answer is by using generators and direct responses.

+
+

Basic Usage

+

This is a basic view function that generates a lot of CSV data on the fly. +The trick is to have an inner function that uses a generator to generate +data and to then invoke that function and pass it to a response object:

+
@app.route('/large.csv')
+def generate_large_csv():
+    def generate():
+        for row in iter_all_rows():
+            yield f"{','.join(row)}\n"
+    return generate(), {"Content-Type": "text/csv"}
+
+
+

Each yield expression is directly sent to the browser. Note though +that some WSGI middlewares might break streaming, so be careful there in +debug environments with profilers and other things you might have enabled.

+
+
+

Streaming from Templates

+

The Jinja2 template engine supports rendering a template piece by +piece, returning an iterator of strings. Flask provides the +stream_template() and stream_template_string() +functions to make this easier to use.

+
from flask import stream_template
+
+@app.get("/timeline")
+def timeline():
+    return stream_template("timeline.html")
+
+
+

The parts yielded by the render stream tend to match statement blocks in +the template.

+
+
+

Streaming with Context

+

The request will not be active while the generator is +running, because the view has already returned at that point. If you try +to access request, you’ll get a RuntimeError.

+

If your generator function relies on data in request, use the +stream_with_context() wrapper. This will keep the request +context active during the generator.

+
from flask import stream_with_context, request
+from markupsafe import escape
+
+@app.route('/stream')
+def streamed_response():
+    def generate():
+        yield '<p>Hello '
+        yield escape(request.args['name'])
+        yield '!</p>'
+    return stream_with_context(generate())
+
+
+

It can also be used as a decorator.

+
@stream_with_context
+def generate():
+    ...
+
+return generate()
+
+
+

The stream_template() and +stream_template_string() functions automatically +use stream_with_context() if a request is active.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/patterns/subclassing/index.html b/_build/patterns/subclassing/index.html new file mode 100644 index 00000000..7963daff --- /dev/null +++ b/_build/patterns/subclassing/index.html @@ -0,0 +1,109 @@ + + + + + + + + Subclassing Flask — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Subclassing Flask

+

The Flask class is designed for subclassing.

+

For example, you may want to override how request parameters are handled to preserve their order:

+
from flask import Flask, Request
+from werkzeug.datastructures import ImmutableOrderedMultiDict
+class MyRequest(Request):
+    """Request subclass to override request parameter storage"""
+    parameter_storage_class = ImmutableOrderedMultiDict
+class MyFlask(Flask):
+    """Flask subclass using the custom request class"""
+    request_class = MyRequest
+
+
+

This is the recommended approach for overriding or augmenting Flask’s internal functionality.

+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/patterns/templateinheritance/index.html b/_build/patterns/templateinheritance/index.html new file mode 100644 index 00000000..fc48f9e4 --- /dev/null +++ b/_build/patterns/templateinheritance/index.html @@ -0,0 +1,162 @@ + + + + + + + + Template Inheritance — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Template Inheritance

+

The most powerful part of Jinja is template inheritance. Template inheritance +allows you to build a base “skeleton” template that contains all the common +elements of your site and defines blocks that child templates can override.

+

Sounds complicated but is very basic. It’s easiest to understand it by starting +with an example.

+
+

Base Template

+

This template, which we’ll call layout.html, defines a simple HTML skeleton +document that you might use for a simple two-column page. It’s the job of +“child” templates to fill the empty blocks with content:

+
<!doctype html>
+<html>
+  <head>
+    {% block head %}
+    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
+    <title>{% block title %}{% endblock %} - My Webpage</title>
+    {% endblock %}
+  </head>
+  <body>
+    <div id="content">{% block content %}{% endblock %}</div>
+    <div id="footer">
+      {% block footer %}
+      &copy; Copyright 2010 by <a href="http://domain.invalid/">you</a>.
+      {% endblock %}
+    </div>
+  </body>
+</html>
+
+
+

In this example, the {% block %} tags define four blocks that child templates +can fill in. All the block tag does is tell the template engine that a +child template may override those portions of the template.

+
+
+

Child Template

+

A child template might look like this:

+
{% extends "layout.html" %}
+{% block title %}Index{% endblock %}
+{% block head %}
+  {{ super() }}
+  <style type="text/css">
+    .important { color: #336699; }
+  </style>
+{% endblock %}
+{% block content %}
+  <h1>Index</h1>
+  <p class="important">
+    Welcome on my awesome homepage.
+{% endblock %}
+
+
+

The {% extends %} tag is the key here. It tells the template engine that +this template “extends” another template. When the template system evaluates +this template, first it locates the parent. The extends tag must be the +first tag in the template. To render the contents of a block defined in +the parent template, use {{ super() }}.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/patterns/urlprocessors/index.html b/_build/patterns/urlprocessors/index.html new file mode 100644 index 00000000..ada40a8a --- /dev/null +++ b/_build/patterns/urlprocessors/index.html @@ -0,0 +1,227 @@ + + + + + + + + Using URL Processors — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Using URL Processors

+
+Changelog
+

Added in version 0.7.

+
+

Flask 0.7 introduces the concept of URL processors. The idea is that you +might have a bunch of resources with common parts in the URL that you +don’t always explicitly want to provide. For instance you might have a +bunch of URLs that have the language code in it but you don’t want to have +to handle it in every single function yourself.

+

URL processors are especially helpful when combined with blueprints. We +will handle both application specific URL processors here as well as +blueprint specifics.

+
+

Internationalized Application URLs

+

Consider an application like this:

+
from flask import Flask, g
+
+app = Flask(__name__)
+
+@app.route('/<lang_code>/')
+def index(lang_code):
+    g.lang_code = lang_code
+    ...
+
+@app.route('/<lang_code>/about')
+def about(lang_code):
+    g.lang_code = lang_code
+    ...
+
+
+

This is an awful lot of repetition as you have to handle the language code +setting on the g object yourself in every single function. +Sure, a decorator could be used to simplify this, but if you want to +generate URLs from one function to another you would have to still provide +the language code explicitly which can be annoying.

+

For the latter, this is where url_defaults() functions +come in. They can automatically inject values into a call to +url_for(). The code below checks if the +language code is not yet in the dictionary of URL values and if the +endpoint wants a value named 'lang_code':

+
@app.url_defaults
+def add_language_code(endpoint, values):
+    if 'lang_code' in values or not g.lang_code:
+        return
+    if app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):
+        values['lang_code'] = g.lang_code
+
+
+

The method is_endpoint_expecting() of the URL +map can be used to figure out if it would make sense to provide a language +code for the given endpoint.

+

The reverse of that function are +url_value_preprocessor()s. They are executed right +after the request was matched and can execute code based on the URL +values. The idea is that they pull information out of the values +dictionary and put it somewhere else:

+
@app.url_value_preprocessor
+def pull_lang_code(endpoint, values):
+    g.lang_code = values.pop('lang_code', None)
+
+
+

That way you no longer have to do the lang_code assignment to +g in every function. You can further improve that by +writing your own decorator that prefixes URLs with the language code, but +the more beautiful solution is using a blueprint. Once the +'lang_code' is popped from the values dictionary and it will no longer +be forwarded to the view function reducing the code to this:

+
from flask import Flask, g
+
+app = Flask(__name__)
+
+@app.url_defaults
+def add_language_code(endpoint, values):
+    if 'lang_code' in values or not g.lang_code:
+        return
+    if app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):
+        values['lang_code'] = g.lang_code
+
+@app.url_value_preprocessor
+def pull_lang_code(endpoint, values):
+    g.lang_code = values.pop('lang_code', None)
+
+@app.route('/<lang_code>/')
+def index():
+    ...
+
+@app.route('/<lang_code>/about')
+def about():
+    ...
+
+
+
+
+

Internationalized Blueprint URLs

+

Because blueprints can automatically prefix all URLs with a common string +it’s easy to automatically do that for every function. Furthermore +blueprints can have per-blueprint URL processors which removes a whole lot +of logic from the url_defaults() function because it no +longer has to check if the URL is really interested in a 'lang_code' +parameter:

+
from flask import Blueprint, g
+
+bp = Blueprint('frontend', __name__, url_prefix='/<lang_code>')
+
+@bp.url_defaults
+def add_language_code(endpoint, values):
+    values.setdefault('lang_code', g.lang_code)
+
+@bp.url_value_preprocessor
+def pull_lang_code(endpoint, values):
+    g.lang_code = values.pop('lang_code')
+
+@bp.route('/')
+def index():
+    ...
+
+@bp.route('/about')
+def about():
+    ...
+
+
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/patterns/viewdecorators/index.html b/_build/patterns/viewdecorators/index.html new file mode 100644 index 00000000..d1664250 --- /dev/null +++ b/_build/patterns/viewdecorators/index.html @@ -0,0 +1,269 @@ + + + + + + + + View Decorators — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

View Decorators

+

Python has a really interesting feature called function decorators. This +allows some really neat things for web applications. Because each view in +Flask is a function, decorators can be used to inject additional +functionality to one or more functions. The route() +decorator is the one you probably used already. But there are use cases +for implementing your own decorator. For instance, imagine you have a +view that should only be used by people that are logged in. If a user +goes to the site and is not logged in, they should be redirected to the +login page. This is a good example of a use case where a decorator is an +excellent solution.

+
+

Login Required Decorator

+

So let’s implement such a decorator. A decorator is a function that +wraps and replaces another function. Since the original function is +replaced, you need to remember to copy the original function’s information +to the new function. Use functools.wraps() to handle this for you.

+

This example assumes that the login page is called 'login' and that +the current user is stored in g.user and is None if there is no-one +logged in.

+
from functools import wraps
+from flask import g, request, redirect, url_for
+
+def login_required(f):
+    @wraps(f)
+    def decorated_function(*args, **kwargs):
+        if g.user is None:
+            return redirect(url_for('login', next=request.url))
+        return f(*args, **kwargs)
+    return decorated_function
+
+
+

To use the decorator, apply it as innermost decorator to a view function. +When applying further decorators, always remember +that the route() decorator is the outermost.

+
@app.route('/secret_page')
+@login_required
+def secret_page():
+    pass
+
+
+
+

Note

+

The next value will exist in request.args after a GET request for +the login page. You’ll have to pass it along when sending the POST request +from the login form. You can do this with a hidden input tag, then retrieve it +from request.form when logging the user in.

+
<input type="hidden" value="{{ request.args.get('next', '') }}"/>
+
+
+
+
+
+

Caching Decorator

+

Imagine you have a view function that does an expensive calculation and +because of that you would like to cache the generated results for a +certain amount of time. A decorator would be nice for that. We’re +assuming you have set up a cache like mentioned in Caching.

+

Here is an example cache function. It generates the cache key from a +specific prefix (actually a format string) and the current path of the +request. Notice that we are using a function that first creates the +decorator that then decorates the function. Sounds awful? Unfortunately +it is a little bit more complex, but the code should still be +straightforward to read.

+

The decorated function will then work as follows

+
    +
  1. get the unique cache key for the current request based on the current +path.

  2. +
  3. get the value for that key from the cache. If the cache returned +something we will return that value.

  4. +
  5. otherwise the original function is called and the return value is +stored in the cache for the timeout provided (by default 5 minutes).

  6. +
+

Here the code:

+
from functools import wraps
+from flask import request
+
+def cached(timeout=5 * 60, key='view/{}'):
+    def decorator(f):
+        @wraps(f)
+        def decorated_function(*args, **kwargs):
+            cache_key = key.format(request.path)
+            rv = cache.get(cache_key)
+            if rv is not None:
+                return rv
+            rv = f(*args, **kwargs)
+            cache.set(cache_key, rv, timeout=timeout)
+            return rv
+        return decorated_function
+    return decorator
+
+
+

Notice that this assumes an instantiated cache object is available, see +Caching.

+
+
+

Templating Decorator

+

A common pattern invented by the TurboGears guys a while back is a +templating decorator. The idea of that decorator is that you return a +dictionary with the values passed to the template from the view function +and the template is automatically rendered. With that, the following +three examples do exactly the same:

+
@app.route('/')
+def index():
+    return render_template('index.html', value=42)
+
+@app.route('/')
+@templated('index.html')
+def index():
+    return dict(value=42)
+
+@app.route('/')
+@templated()
+def index():
+    return dict(value=42)
+
+
+

As you can see, if no template name is provided it will use the endpoint +of the URL map with dots converted to slashes + '.html'. Otherwise +the provided template name is used. When the decorated function returns, +the dictionary returned is passed to the template rendering function. If +None is returned, an empty dictionary is assumed, if something else than +a dictionary is returned we return it from the function unchanged. That +way you can still use the redirect function or return simple strings.

+

Here is the code for that decorator:

+
from functools import wraps
+from flask import request, render_template
+
+def templated(template=None):
+    def decorator(f):
+        @wraps(f)
+        def decorated_function(*args, **kwargs):
+            template_name = template
+            if template_name is None:
+                template_name = f"{request.endpoint.replace('.', '/')}.html"
+            ctx = f(*args, **kwargs)
+            if ctx is None:
+                ctx = {}
+            elif not isinstance(ctx, dict):
+                return ctx
+            return render_template(template_name, **ctx)
+        return decorated_function
+    return decorator
+
+
+
+
+

Endpoint Decorator

+

When you want to use the werkzeug routing system for more flexibility you +need to map the endpoint as defined in the Rule +to a view function. This is possible with this decorator. For example:

+
from flask import Flask
+from werkzeug.routing import Rule
+
+app = Flask(__name__)
+app.url_map.add(Rule('/', endpoint='index'))
+
+@app.endpoint('index')
+def my_index():
+    return "Hello world"
+
+
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/patterns/wtforms/index.html b/_build/patterns/wtforms/index.html new file mode 100644 index 00000000..c167eb20 --- /dev/null +++ b/_build/patterns/wtforms/index.html @@ -0,0 +1,214 @@ + + + + + + + + Form Validation with WTForms — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Form Validation with WTForms

+

When you have to work with form data submitted by a browser view, code +quickly becomes very hard to read. There are libraries out there designed +to make this process easier to manage. One of them is WTForms which we +will handle here. If you find yourself in the situation of having many +forms, you might want to give it a try.

+

When you are working with WTForms you have to define your forms as classes +first. I recommend breaking up the application into multiple modules +(Large Applications as Packages) for that and adding a separate module for the +forms.

+
+

Getting the most out of WTForms with an Extension

+

The Flask-WTF extension expands on this pattern and adds a +few little helpers that make working with forms and Flask more +fun. You can get it from PyPI.

+
+
+

The Forms

+

This is an example form for a typical registration page:

+
from wtforms import Form, BooleanField, StringField, PasswordField, validators
+
+class RegistrationForm(Form):
+    username = StringField('Username', [validators.Length(min=4, max=25)])
+    email = StringField('Email Address', [validators.Length(min=6, max=35)])
+    password = PasswordField('New Password', [
+        validators.DataRequired(),
+        validators.EqualTo('confirm', message='Passwords must match')
+    ])
+    confirm = PasswordField('Repeat Password')
+    accept_tos = BooleanField('I accept the TOS', [validators.DataRequired()])
+
+
+
+
+

In the View

+

In the view function, the usage of this form looks like this:

+
@app.route('/register', methods=['GET', 'POST'])
+def register():
+    form = RegistrationForm(request.form)
+    if request.method == 'POST' and form.validate():
+        user = User(form.username.data, form.email.data,
+                    form.password.data)
+        db_session.add(user)
+        flash('Thanks for registering')
+        return redirect(url_for('login'))
+    return render_template('register.html', form=form)
+
+
+

Notice we’re implying that the view is using SQLAlchemy here +(SQLAlchemy in Flask), but that’s not a requirement, of course. Adapt +the code as necessary.

+

Things to remember:

+
    +
  1. create the form from the request form value if +the data is submitted via the HTTP POST method and +args if the data is submitted as GET.

  2. +
  3. to validate the data, call the validate() +method, which will return True if the data validates, False +otherwise.

  4. +
  5. to access individual values from the form, access form.<NAME>.data.

  6. +
+
+
+

Forms in Templates

+

Now to the template side. When you pass the form to the templates, you can +easily render them there. Look at the following example template to see +how easy this is. WTForms does half the form generation for us already. +To make it even nicer, we can write a macro that renders a field with +label and a list of errors if there are any.

+

Here’s an example _formhelpers.html template with such a macro:

+
{% macro render_field(field) %}
+  <dt>{{ field.label }}
+  <dd>{{ field(**kwargs)|safe }}
+  {% if field.errors %}
+    <ul class=errors>
+    {% for error in field.errors %}
+      <li>{{ error }}</li>
+    {% endfor %}
+    </ul>
+  {% endif %}
+  </dd>
+{% endmacro %}
+
+
+

This macro accepts a couple of keyword arguments that are forwarded to +WTForm’s field function, which renders the field for us. The keyword +arguments will be inserted as HTML attributes. So, for example, you can +call render_field(form.username, class='username') to add a class to +the input element. Note that WTForms returns standard Python strings, +so we have to tell Jinja2 that this data is already HTML-escaped with +the |safe filter.

+

Here is the register.html template for the function we used above, which +takes advantage of the _formhelpers.html template:

+
{% from "_formhelpers.html" import render_field %}
+<form method=post>
+  <dl>
+    {{ render_field(form.username) }}
+    {{ render_field(form.email) }}
+    {{ render_field(form.password) }}
+    {{ render_field(form.confirm) }}
+    {{ render_field(form.accept_tos) }}
+  </dl>
+  <p><input type=submit value=Register>
+</form>
+
+
+

For more information about WTForms, head over to the WTForms +website.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/py-modindex/index.html b/_build/py-modindex/index.html new file mode 100644 index 00000000..2cc2d0bb --- /dev/null +++ b/_build/py-modindex/index.html @@ -0,0 +1,109 @@ + + + + + + + + Python Module Index — Flask Documentation (3.1.x) + + + + + + + + + + + + + + + +
+
+
+
+ + +

Python Module Index

+ +
+ f +
+ + + + + + + + + + + + + +
 
+ f
+ flask +
    + flask.json +
    + flask.json.tag +
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/quickstart/index.html b/_build/quickstart/index.html new file mode 100644 index 00000000..5e4d5cd0 --- /dev/null +++ b/_build/quickstart/index.html @@ -0,0 +1,940 @@ + + + + + + + + Quickstart — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Quickstart

+

Eager to get started? This page gives a good introduction to Flask. +Follow Installation to set up a project and install Flask first.

+
+

A Minimal Application

+

A minimal Flask application looks something like this:

+
from flask import Flask
+
+app = Flask(__name__)
+
+@app.route("/")
+def hello_world():
+    return "<p>Hello, World!</p>"
+
+
+

So what did that code do?

+
    +
  1. First we imported the Flask class. An instance of +this class will be our WSGI application.

  2. +
  3. Next we create an instance of this class. The first argument is the +name of the application’s module or package. __name__ is a +convenient shortcut for this that is appropriate for most cases. +This is needed so that Flask knows where to look for resources such +as templates and static files.

  4. +
  5. We then use the route() decorator to tell Flask +what URL should trigger our function.

  6. +
  7. The function returns the message we want to display in the user’s +browser. The default content type is HTML, so HTML in the string +will be rendered by the browser.

  8. +
+

Save it as hello.py or something similar. Make sure to not call +your application flask.py because this would conflict with Flask +itself.

+

To run the application, use the flask command or +python -m flask. You need to tell the Flask where your application +is with the --app option.

+
$ flask --app hello run
+ * Serving Flask app 'hello'
+ * Running on http://127.0.0.1:5000 (Press CTRL+C to quit)
+
+
+
+

Application Discovery Behavior

+

As a shortcut, if the file is named app.py or wsgi.py, you +don’t have to use --app. See Command Line Interface for more details.

+
+

This launches a very simple builtin server, which is good enough for +testing but probably not what you want to use in production. For +deployment options see Deploying to Production.

+

Now head over to http://127.0.0.1:5000/, and you should see your hello +world greeting.

+

If another program is already using port 5000, you’ll see +OSError: [Errno 98] or OSError: [WinError 10013] when the +server tries to start. See Address already in use for how to +handle that.

+
+

Externally Visible Server

+

If you run the server you will notice that the server is only accessible +from your own computer, not from any other in the network. This is the +default because in debugging mode a user of the application can execute +arbitrary Python code on your computer.

+

If you have the debugger disabled or trust the users on your network, +you can make the server publicly available simply by adding +--host=0.0.0.0 to the command line:

+
$ flask run --host=0.0.0.0
+
+
+

This tells your operating system to listen on all public IPs.

+
+
+
+

Debug Mode

+

The flask run command can do more than just start the development +server. By enabling debug mode, the server will automatically reload if +code changes, and will show an interactive debugger in the browser if an +error occurs during a request.

+The interactive debugger in action. +
+

Warning

+

The debugger allows executing arbitrary Python code from the +browser. It is protected by a pin, but still represents a major +security risk. Do not run the development server or debugger in a +production environment.

+
+

To enable debug mode, use the --debug option.

+
$ flask --app hello run --debug
+ * Serving Flask app 'hello'
+ * Debug mode: on
+ * Running on http://127.0.0.1:5000 (Press CTRL+C to quit)
+ * Restarting with stat
+ * Debugger is active!
+ * Debugger PIN: nnn-nnn-nnn
+
+
+

See also:

+ +
+
+

HTML Escaping

+

When returning HTML (the default response type in Flask), any +user-provided values rendered in the output must be escaped to protect +from injection attacks. HTML templates rendered with Jinja, introduced +later, will do this automatically.

+

escape(), shown here, can be used manually. It is +omitted in most examples for brevity, but you should always be aware of +how you’re using untrusted data.

+
from markupsafe import escape
+
+@app.route("/<name>")
+def hello(name):
+    return f"Hello, {escape(name)}!"
+
+
+

If a user managed to submit the name <script>alert("bad")</script>, +escaping causes it to be rendered as text, rather than running the +script in the user’s browser.

+

<name> in the route captures a value from the URL and passes it to +the view function. These variable rules are explained below.

+
+
+

Routing

+

Modern web applications use meaningful URLs to help users. Users are more +likely to like a page and come back if the page uses a meaningful URL they can +remember and use to directly visit a page.

+

Use the route() decorator to bind a function to a URL.

+
@app.route('/')
+def index():
+    return 'Index Page'
+
+@app.route('/hello')
+def hello():
+    return 'Hello, World'
+
+
+

You can do more! You can make parts of the URL dynamic and attach multiple +rules to a function.

+
+

Variable Rules

+

You can add variable sections to a URL by marking sections with +<variable_name>. Your function then receives the <variable_name> +as a keyword argument. Optionally, you can use a converter to specify the type +of the argument like <converter:variable_name>.

+
from markupsafe import escape
+
+@app.route('/user/<username>')
+def show_user_profile(username):
+    # show the user profile for that user
+    return f'User {escape(username)}'
+
+@app.route('/post/<int:post_id>')
+def show_post(post_id):
+    # show the post with the given id, the id is an integer
+    return f'Post {post_id}'
+
+@app.route('/path/<path:subpath>')
+def show_subpath(subpath):
+    # show the subpath after /path/
+    return f'Subpath {escape(subpath)}'
+
+
+

Converter types:

+ + + + + + + + + + + + + + + + + + +

string

(default) accepts any text without a slash

int

accepts positive integers

float

accepts positive floating point values

path

like string but also accepts slashes

uuid

accepts UUID strings

+
+
+

Unique URLs / Redirection Behavior

+

The following two rules differ in their use of a trailing slash.

+
@app.route('/projects/')
+def projects():
+    return 'The project page'
+
+@app.route('/about')
+def about():
+    return 'The about page'
+
+
+

The canonical URL for the projects endpoint has a trailing slash. +It’s similar to a folder in a file system. If you access the URL without +a trailing slash (/projects), Flask redirects you to the canonical URL +with the trailing slash (/projects/).

+

The canonical URL for the about endpoint does not have a trailing +slash. It’s similar to the pathname of a file. Accessing the URL with a +trailing slash (/about/) produces a 404 “Not Found” error. This helps +keep URLs unique for these resources, which helps search engines avoid +indexing the same page twice.

+
+
+

URL Building

+

To build a URL to a specific function, use the url_for() function. +It accepts the name of the function as its first argument and any number of +keyword arguments, each corresponding to a variable part of the URL rule. +Unknown variable parts are appended to the URL as query parameters.

+

Why would you want to build URLs using the URL reversing function +url_for() instead of hard-coding them into your templates?

+
    +
  1. Reversing is often more descriptive than hard-coding the URLs.

  2. +
  3. You can change your URLs in one go instead of needing to remember to +manually change hard-coded URLs.

  4. +
  5. URL building handles escaping of special characters transparently.

  6. +
  7. The generated paths are always absolute, avoiding unexpected behavior +of relative paths in browsers.

  8. +
  9. If your application is placed outside the URL root, for example, in +/myapplication instead of /, url_for() properly +handles that for you.

  10. +
+

For example, here we use the test_request_context() method +to try out url_for(). test_request_context() +tells Flask to behave as though it’s handling a request even while we use a +Python shell. See Context Locals.

+
from flask import url_for
+
+@app.route('/')
+def index():
+    return 'index'
+
+@app.route('/login')
+def login():
+    return 'login'
+
+@app.route('/user/<username>')
+def profile(username):
+    return f'{username}\'s profile'
+
+with app.test_request_context():
+    print(url_for('index'))
+    print(url_for('login'))
+    print(url_for('login', next='/'))
+    print(url_for('profile', username='John Doe'))
+
+
+
/
+/login
+/login?next=/
+/user/John%20Doe
+
+
+
+
+

HTTP Methods

+

Web applications use different HTTP methods when accessing URLs. You should +familiarize yourself with the HTTP methods as you work with Flask. By default, +a route only answers to GET requests. You can use the methods argument +of the route() decorator to handle different HTTP methods.

+
from flask import request
+
+@app.route('/login', methods=['GET', 'POST'])
+def login():
+    if request.method == 'POST':
+        return do_the_login()
+    else:
+        return show_the_login_form()
+
+
+

The example above keeps all methods for the route within one function, +which can be useful if each part uses some common data.

+

You can also separate views for different methods into different +functions. Flask provides a shortcut for decorating such routes with +get(), post(), etc. for each +common HTTP method.

+
@app.get('/login')
+def login_get():
+    return show_the_login_form()
+
+@app.post('/login')
+def login_post():
+    return do_the_login()
+
+
+

If GET is present, Flask automatically adds support for the HEAD method +and handles HEAD requests according to the HTTP RFC. Likewise, +OPTIONS is automatically implemented for you.

+
+
+
+

Static Files

+

Dynamic web applications also need static files. That’s usually where +the CSS and JavaScript files are coming from. Ideally your web server is +configured to serve them for you, but during development Flask can do that +as well. Just create a folder called static in your package or next to +your module and it will be available at /static on the application.

+

To generate URLs for static files, use the special 'static' endpoint name:

+
url_for('static', filename='style.css')
+
+
+

The file has to be stored on the filesystem as static/style.css.

+
+
+

Rendering Templates

+

Generating HTML from within Python is not fun, and actually pretty +cumbersome because you have to do the HTML escaping on your own to keep +the application secure. Because of that Flask configures the Jinja2 template engine for you automatically.

+

Templates can be used to generate any type of text file. For web applications, you’ll +primarily be generating HTML pages, but you can also generate markdown, plain text for +emails, and anything else.

+

For a reference to HTML, CSS, and other web APIs, use the MDN Web Docs.

+

To render a template you can use the render_template() +method. All you have to do is provide the name of the template and the +variables you want to pass to the template engine as keyword arguments. +Here’s a simple example of how to render a template:

+
from flask import render_template
+
+@app.route('/hello/')
+@app.route('/hello/<name>')
+def hello(name=None):
+    return render_template('hello.html', person=name)
+
+
+

Flask will look for templates in the templates folder. So if your +application is a module, this folder is next to that module, if it’s a +package it’s actually inside your package:

+

Case 1: a module:

+
/application.py
+/templates
+    /hello.html
+
+
+

Case 2: a package:

+
/application
+    /__init__.py
+    /templates
+        /hello.html
+
+
+

For templates you can use the full power of Jinja2 templates. Head over +to the official Jinja2 Template Documentation for more information.

+

Here is an example template:

+
<!doctype html>
+<title>Hello from Flask</title>
+{% if person %}
+  <h1>Hello {{ person }}!</h1>
+{% else %}
+  <h1>Hello, World!</h1>
+{% endif %}
+
+
+

Inside templates you also have access to the config, +request, session and g [1] objects +as well as the url_for() and get_flashed_messages() functions.

+

Templates are especially useful if inheritance is used. If you want to +know how that works, see Template Inheritance. Basically +template inheritance makes it possible to keep certain elements on each +page (like header, navigation and footer).

+

Automatic escaping is enabled, so if person contains HTML it will be escaped +automatically. If you can trust a variable and you know that it will be +safe HTML (for example because it came from a module that converts wiki +markup to HTML) you can mark it as safe by using the +Markup class or by using the |safe filter in the +template. Head over to the Jinja 2 documentation for more examples.

+

Here is a basic introduction to how the Markup class works:

+
>>> from markupsafe import Markup
+>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'
+Markup('<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')
+>>> Markup.escape('<blink>hacker</blink>')
+Markup('&lt;blink&gt;hacker&lt;/blink&gt;')
+>>> Markup('<em>Marked up</em> &raquo; HTML').striptags()
+'Marked up » HTML'
+
+
+
+Changelog
+

Changed in version 0.5: Autoescaping is no longer enabled for all templates. The following +extensions for templates trigger autoescaping: .html, .htm, +.xml, .xhtml. Templates loaded from a string will have +autoescaping disabled.

+
+
+
+
+

Accessing Request Data

+

For web applications it’s crucial to react to the data a client sends to +the server. In Flask this information is provided by the global +request object. If you have some experience with Python +you might be wondering how that object can be global and how Flask +manages to still be threadsafe. The answer is context locals:

+
+

Context Locals

+
+

Insider Information

+

If you want to understand how that works and how you can implement +tests with context locals, read this section, otherwise just skip it.

+
+

Certain objects in Flask are global objects, but not of the usual kind. +These objects are actually proxies to objects that are local to a specific +context. What a mouthful. But that is actually quite easy to understand.

+

Imagine the context being the handling thread. A request comes in and the +web server decides to spawn a new thread (or something else, the +underlying object is capable of dealing with concurrency systems other +than threads). When Flask starts its internal request handling it +figures out that the current thread is the active context and binds the +current application and the WSGI environments to that context (thread). +It does that in an intelligent way so that one application can invoke another +application without breaking.

+

So what does this mean to you? Basically you can completely ignore that +this is the case unless you are doing something like unit testing. You +will notice that code which depends on a request object will suddenly break +because there is no request object. The solution is creating a request +object yourself and binding it to the context. The easiest solution for +unit testing is to use the test_request_context() +context manager. In combination with the with statement it will bind a +test request so that you can interact with it. Here is an example:

+
from flask import request
+
+with app.test_request_context('/hello', method='POST'):
+    # now you can do something with the request until the
+    # end of the with block, such as basic assertions:
+    assert request.path == '/hello'
+    assert request.method == 'POST'
+
+
+

The other possibility is passing a whole WSGI environment to the +request_context() method:

+
with app.request_context(environ):
+    assert request.method == 'POST'
+
+
+
+
+

The Request Object

+

The request object is documented in the API section and we will not cover +it here in detail (see Request). Here is a broad overview of +some of the most common operations. First of all you have to import it from +the flask module:

+
from flask import request
+
+
+

The current request method is available by using the +method attribute. To access form data (data +transmitted in a POST or PUT request) you can use the +form attribute. Here is a full example of the two +attributes mentioned above:

+
@app.route('/login', methods=['POST', 'GET'])
+def login():
+    error = None
+    if request.method == 'POST':
+        if valid_login(request.form['username'],
+                       request.form['password']):
+            return log_the_user_in(request.form['username'])
+        else:
+            error = 'Invalid username/password'
+    # the code below is executed if the request method
+    # was GET or the credentials were invalid
+    return render_template('login.html', error=error)
+
+
+

What happens if the key does not exist in the form attribute? In that +case a special KeyError is raised. You can catch it like a +standard KeyError but if you don’t do that, a HTTP 400 Bad Request +error page is shown instead. So for many situations you don’t have to +deal with that problem.

+

To access parameters submitted in the URL (?key=value) you can use the +args attribute:

+
searchword = request.args.get('key', '')
+
+
+

We recommend accessing URL parameters with get or by catching the +KeyError because users might change the URL and presenting them a 400 +bad request page in that case is not user friendly.

+

For a full list of methods and attributes of the request object, head over +to the Request documentation.

+
+
+

File Uploads

+

You can handle uploaded files with Flask easily. Just make sure not to +forget to set the enctype="multipart/form-data" attribute on your HTML +form, otherwise the browser will not transmit your files at all.

+

Uploaded files are stored in memory or at a temporary location on the +filesystem. You can access those files by looking at the +files attribute on the request object. Each +uploaded file is stored in that dictionary. It behaves just like a +standard Python file object, but it also has a +save() method that +allows you to store that file on the filesystem of the server. +Here is a simple example showing how that works:

+
from flask import request
+
+@app.route('/upload', methods=['GET', 'POST'])
+def upload_file():
+    if request.method == 'POST':
+        f = request.files['the_file']
+        f.save('/var/www/uploads/uploaded_file.txt')
+    ...
+
+
+

If you want to know how the file was named on the client before it was +uploaded to your application, you can access the +filename attribute. +However please keep in mind that this value can be forged +so never ever trust that value. If you want to use the filename +of the client to store the file on the server, pass it through the +secure_filename() function that +Werkzeug provides for you:

+
from werkzeug.utils import secure_filename
+
+@app.route('/upload', methods=['GET', 'POST'])
+def upload_file():
+    if request.method == 'POST':
+        file = request.files['the_file']
+        file.save(f"/var/www/uploads/{secure_filename(file.filename)}")
+    ...
+
+
+

For some better examples, see Uploading Files.

+
+
+

Cookies

+

To access cookies you can use the cookies +attribute. To set cookies you can use the +set_cookie method of response objects. The +cookies attribute of request objects is a +dictionary with all the cookies the client transmits. If you want to use +sessions, do not use the cookies directly but instead use the +Sessions in Flask that add some security on top of cookies for you.

+

Reading cookies:

+
from flask import request
+
+@app.route('/')
+def index():
+    username = request.cookies.get('username')
+    # use cookies.get(key) instead of cookies[key] to not get a
+    # KeyError if the cookie is missing.
+
+
+

Storing cookies:

+
from flask import make_response
+
+@app.route('/')
+def index():
+    resp = make_response(render_template(...))
+    resp.set_cookie('username', 'the username')
+    return resp
+
+
+

Note that cookies are set on response objects. Since you normally +just return strings from the view functions Flask will convert them into +response objects for you. If you explicitly want to do that you can use +the make_response() function and then modify it.

+

Sometimes you might want to set a cookie at a point where the response +object does not exist yet. This is possible by utilizing the +Deferred Request Callbacks pattern.

+

For this also see About Responses.

+
+
+
+

Redirects and Errors

+

To redirect a user to another endpoint, use the redirect() +function; to abort a request early with an error code, use the +abort() function:

+
from flask import abort, redirect, url_for
+
+@app.route('/')
+def index():
+    return redirect(url_for('login'))
+
+@app.route('/login')
+def login():
+    abort(401)
+    this_is_never_executed()
+
+
+

This is a rather pointless example because a user will be redirected from +the index to a page they cannot access (401 means access denied) but it +shows how that works.

+

By default a black and white error page is shown for each error code. If +you want to customize the error page, you can use the +errorhandler() decorator:

+
from flask import render_template
+
+@app.errorhandler(404)
+def page_not_found(error):
+    return render_template('page_not_found.html'), 404
+
+
+

Note the 404 after the render_template() call. This +tells Flask that the status code of that page should be 404 which means +not found. By default 200 is assumed which translates to: all went well.

+

See Handling Application Errors for more details.

+
+
+

About Responses

+

The return value from a view function is automatically converted into +a response object for you. If the return value is a string it’s +converted into a response object with the string as response body, a +200 OK status code and a text/html mimetype. If the +return value is a dict or list, jsonify() is called to produce a +response. The logic that Flask applies to converting return values into +response objects is as follows:

+
    +
  1. If a response object of the correct type is returned it’s directly +returned from the view.

  2. +
  3. If it’s a string, a response object is created with that data and +the default parameters.

  4. +
  5. If it’s an iterator or generator returning strings or bytes, it is +treated as a streaming response.

  6. +
  7. If it’s a dict or list, a response object is created using +jsonify().

  8. +
  9. If a tuple is returned the items in the tuple can provide extra +information. Such tuples have to be in the form +(response, status), (response, headers), or +(response, status, headers). The status value will override +the status code and headers can be a list or dictionary of +additional header values.

  10. +
  11. If none of that works, Flask will assume the return value is a +valid WSGI application and convert that into a response object.

  12. +
+

If you want to get hold of the resulting response object inside the view +you can use the make_response() function.

+

Imagine you have a view like this:

+
from flask import render_template
+
+@app.errorhandler(404)
+def not_found(error):
+    return render_template('error.html'), 404
+
+
+

You just need to wrap the return expression with +make_response() and get the response object to modify it, then +return it:

+
from flask import make_response
+
+@app.errorhandler(404)
+def not_found(error):
+    resp = make_response(render_template('error.html'), 404)
+    resp.headers['X-Something'] = 'A value'
+    return resp
+
+
+
+

APIs with JSON

+

A common response format when writing an API is JSON. It’s easy to get +started writing such an API with Flask. If you return a dict or +list from a view, it will be converted to a JSON response.

+
@app.route("/me")
+def me_api():
+    user = get_current_user()
+    return {
+        "username": user.username,
+        "theme": user.theme,
+        "image": url_for("user_image", filename=user.image),
+    }
+
+@app.route("/users")
+def users_api():
+    users = get_all_users()
+    return [user.to_json() for user in users]
+
+
+

This is a shortcut to passing the data to the +jsonify() function, which will serialize any supported +JSON data type. That means that all the data in the dict or list must be +JSON serializable.

+

For complex types such as database models, you’ll want to use a +serialization library to convert the data to valid JSON types first. +There are many serialization libraries and Flask API extensions +maintained by the community that support more complex applications.

+
+
+
+

Sessions

+

In addition to the request object there is also a second object called +session which allows you to store information specific to a +user from one request to the next. This is implemented on top of cookies +for you and signs the cookies cryptographically. What this means is that +the user could look at the contents of your cookie but not modify it, +unless they know the secret key used for signing.

+

In order to use sessions you have to set a secret key. Here is how +sessions work:

+
from flask import session
+
+# Set the secret key to some random bytes. Keep this really secret!
+app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
+
+@app.route('/')
+def index():
+    if 'username' in session:
+        return f'Logged in as {session["username"]}'
+    return 'You are not logged in'
+
+@app.route('/login', methods=['GET', 'POST'])
+def login():
+    if request.method == 'POST':
+        session['username'] = request.form['username']
+        return redirect(url_for('index'))
+    return '''
+        <form method="post">
+            <p><input type=text name=username>
+            <p><input type=submit value=Login>
+        </form>
+    '''
+
+@app.route('/logout')
+def logout():
+    # remove the username from the session if it's there
+    session.pop('username', None)
+    return redirect(url_for('index'))
+
+
+
+

How to generate good secret keys

+

A secret key should be as random as possible. Your operating system has +ways to generate pretty random data based on a cryptographic random +generator. Use the following command to quickly generate a value for +Flask.secret_key (or SECRET_KEY):

+
$ python -c 'import secrets; print(secrets.token_hex())'
+'192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'
+
+
+
+

A note on cookie-based sessions: Flask will take the values you put into the +session object and serialize them into a cookie. If you are finding some +values do not persist across requests, cookies are indeed enabled, and you are +not getting a clear error message, check the size of the cookie in your page +responses compared to the size supported by web browsers.

+

Besides the default client-side based sessions, if you want to handle +sessions on the server-side instead, there are several +Flask extensions that support this.

+
+
+

Message Flashing

+

Good applications and user interfaces are all about feedback. If the user +does not get enough feedback they will probably end up hating the +application. Flask provides a really simple way to give feedback to a +user with the flashing system. The flashing system basically makes it +possible to record a message at the end of a request and access it on the next +(and only the next) request. This is usually combined with a layout +template to expose the message.

+

To flash a message use the flash() method, to get hold of the +messages you can use get_flashed_messages() which is also +available in the templates. See Message Flashing for a full +example.

+
+
+

Logging

+
+Changelog
+

Added in version 0.3.

+
+

Sometimes you might be in a situation where you deal with data that +should be correct, but actually is not. For example you may have +some client-side code that sends an HTTP request to the server +but it’s obviously malformed. This might be caused by a user tampering +with the data, or the client code failing. Most of the time it’s okay +to reply with 400 Bad Request in that situation, but sometimes +that won’t do and the code has to continue working.

+

You may still want to log that something fishy happened. This is where +loggers come in handy. As of Flask 0.3 a logger is preconfigured for you +to use.

+

Here are some example log calls:

+
app.logger.debug('A value for debugging')
+app.logger.warning('A warning occurred (%d apples)', 42)
+app.logger.error('An error occurred')
+
+
+

The attached logger is a standard logging +Logger, so head over to the official logging +docs for more information.

+

See Handling Application Errors.

+
+
+

Hooking in WSGI Middleware

+

To add WSGI middleware to your Flask application, wrap the application’s +wsgi_app attribute. For example, to apply Werkzeug’s +ProxyFix middleware for running +behind Nginx:

+
from werkzeug.middleware.proxy_fix import ProxyFix
+app.wsgi_app = ProxyFix(app.wsgi_app)
+
+
+

Wrapping app.wsgi_app instead of app means that app still +points at your Flask application, not at the middleware, so you can +continue to use and configure app directly.

+
+
+

Using Flask Extensions

+

Extensions are packages that help you accomplish common tasks. For +example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple +and easy to use with Flask.

+

For more on Flask extensions, see Extensions.

+
+
+

Deploying to a Web Server

+

Ready to deploy your new Flask app? See Deploying to Production.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/reqcontext/index.html b/_build/reqcontext/index.html new file mode 100644 index 00000000..69f7e5b2 --- /dev/null +++ b/_build/reqcontext/index.html @@ -0,0 +1,312 @@ + + + + + + + + The Request Context — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

The Request Context

+

The request context keeps track of the request-level data during a +request. Rather than passing the request object to each function that +runs during a request, the request and session proxies +are accessed instead.

+

This is similar to The Application Context, which keeps track of the +application-level data independent of a request. A corresponding +application context is pushed when a request context is pushed.

+
+

Purpose of the Context

+

When the Flask application handles a request, it creates a +Request object based on the environment it received from the +WSGI server. Because a worker (thread, process, or coroutine depending +on the server) handles only one request at a time, the request data can +be considered global to that worker during that request. Flask uses the +term context local for this.

+

Flask automatically pushes a request context when handling a request. +View functions, error handlers, and other functions that run during a +request will have access to the request proxy, which points to +the request object for the current request.

+
+
+

Lifetime of the Context

+

When a Flask application begins handling a request, it pushes a request +context, which also pushes an app context. When the +request ends it pops the request context then the application context.

+

The context is unique to each thread (or other worker type). +request cannot be passed to another thread, the other thread has +a different context space and will not know about the request the parent +thread was pointing to.

+

Context locals are implemented using Python’s contextvars and +Werkzeug’s LocalProxy. Python manages the +lifetime of context vars automatically, and local proxy wraps that +low-level interface to make the data easier to work with.

+
+
+

Manually Push a Context

+

If you try to access request, or anything that uses it, outside +a request context, you’ll get this error message:

+
RuntimeError: Working outside of request context.
+
+This typically means that you attempted to use functionality that
+needed an active HTTP request. Consult the documentation on testing
+for information about how to avoid this problem.
+
+
+

This should typically only happen when testing code that expects an +active request. One option is to use the +test client to simulate a full request. Or +you can use test_request_context() in a with block, and +everything that runs in the block will have access to request, +populated with your test data.

+
def generate_report(year):
+    format = request.args.get("format")
+    ...
+
+with app.test_request_context(
+    "/make_report/2017", query_string={"format": "short"}
+):
+    generate_report()
+
+
+

If you see that error somewhere else in your code not related to +testing, it most likely indicates that you should move that code into a +view function.

+

For information on how to use the request context from the interactive +Python shell, see Working with the Shell.

+
+
+

How the Context Works

+

The Flask.wsgi_app() method is called to handle each request. It +manages the contexts during the request. Internally, the request and +application contexts work like stacks. When contexts are pushed, the +proxies that depend on them are available and point at information from +the top item.

+

When the request starts, a RequestContext is created and +pushed, which creates and pushes an AppContext first if +a context for that application is not already the top context. While +these contexts are pushed, the current_app, g, +request, and session proxies are available to the +original thread handling the request.

+

Other contexts may be pushed to change the proxies during a request. +While this is not a common pattern, it can be used in advanced +applications to, for example, do internal redirects or chain different +applications together.

+

After the request is dispatched and a response is generated and sent, +the request context is popped, which then pops the application context. +Immediately before they are popped, the teardown_request() +and teardown_appcontext() functions are executed. These +execute even if an unhandled exception occurred during dispatch.

+
+
+

Callbacks and Errors

+

Flask dispatches a request in multiple stages which can affect the +request, response, and how errors are handled. The contexts are active +during all of these stages.

+

A Blueprint can add handlers for these events that are specific +to the blueprint. The handlers for a blueprint will run if the blueprint +owns the route that matches the request.

+
    +
  1. Before each request, before_request() functions are +called. If one of these functions return a value, the other +functions are skipped. The return value is treated as the response +and the view function is not called.

  2. +
  3. If the before_request() functions did not return a +response, the view function for the matched route is called and +returns a response.

  4. +
  5. The return value of the view is converted into an actual response +object and passed to the after_request() +functions. Each function returns a modified or new response object.

  6. +
  7. After the response is returned, the contexts are popped, which calls +the teardown_request() and +teardown_appcontext() functions. These functions are +called even if an unhandled exception was raised at any point above.

  8. +
+

If an exception is raised before the teardown functions, Flask tries to +match it with an errorhandler() function to handle the +exception and return a response. If no error handler is found, or the +handler itself raises an exception, Flask returns a generic +500 Internal Server Error response. The teardown functions are still +called, and are passed the exception object.

+

If debug mode is enabled, unhandled exceptions are not converted to a +500 response and instead are propagated to the WSGI server. This +allows the development server to present the interactive debugger with +the traceback.

+
+

Teardown Callbacks

+

The teardown callbacks are independent of the request dispatch, and are +instead called by the contexts when they are popped. The functions are +called even if there is an unhandled exception during dispatch, and for +manually pushed contexts. This means there is no guarantee that any +other parts of the request dispatch have run first. Be sure to write +these functions in a way that does not depend on other callbacks and +will not fail.

+

During testing, it can be useful to defer popping the contexts after the +request ends, so that their data can be accessed in the test function. +Use the test_client() as a with block to preserve the +contexts until the with block exits.

+
from flask import Flask, request
+
+app = Flask(__name__)
+
+@app.route('/')
+def hello():
+    print('during view')
+    return 'Hello, World!'
+
+@app.teardown_request
+def show_teardown(exception):
+    print('after with block')
+
+with app.test_request_context():
+    print('during with block')
+
+# teardown functions are called after the context with block exits
+
+with app.test_client() as client:
+    client.get('/')
+    # the contexts are not popped even though the request ended
+    print(request.path)
+
+# the contexts are popped and teardown functions are called after
+# the client with block exits
+
+
+
+
+

Signals

+

The following signals are sent:

+
    +
  1. request_started is sent before the before_request() functions +are called.

  2. +
  3. request_finished is sent after the after_request() functions +are called.

  4. +
  5. got_request_exception is sent when an exception begins to be handled, but +before an errorhandler() is looked up or called.

  6. +
  7. request_tearing_down is sent after the teardown_request() +functions are called.

  8. +
+
+
+
+

Notes On Proxies

+

Some of the objects provided by Flask are proxies to other objects. The +proxies are accessed in the same way for each worker thread, but +point to the unique object bound to each worker behind the scenes as +described on this page.

+

Most of the time you don’t have to care about that, but there are some +exceptions where it is good to know that this object is actually a proxy:

+
    +
  • The proxy objects cannot fake their type as the actual object types. +If you want to perform instance checks, you have to do that on the +object being proxied.

  • +
  • The reference to the proxied object is needed in some situations, +such as sending Signals or passing data to a background +thread.

  • +
+

If you need to access the underlying object that is proxied, use the +_get_current_object() method:

+
app = current_app._get_current_object()
+my_signal.send(app)
+
+
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/search/index.html b/_build/search/index.html new file mode 100644 index 00000000..a9b6b51a --- /dev/null +++ b/_build/search/index.html @@ -0,0 +1,101 @@ + + + + + + + + Search — Flask Documentation (3.1.x) + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +

Search

+ + + + +

+ Searching for multiple words only shows matches that contain + all words. +

+ + +
+ + + +
+ + +
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/searchindex.js b/_build/searchindex.js new file mode 100644 index 00000000..e73e466f --- /dev/null +++ b/_build/searchindex.js @@ -0,0 +1 @@ +Search.setIndex({"alltitles": {"A Gentle Introduction": [[35, "a-gentle-introduction"]], "A Minimal Application": [[54, "a-minimal-application"]], "AJAX with jQuery": [[39, null]], "API": [[0, null]], "API Reference": [[24, "api-reference"]], "APIs with JSON": [[54, "apis-with-json"]], "ASGI": [[10, null]], "About Responses": [[54, "about-responses"]], "About the First Parameter": [[0, null]], "Accessing Request Data": [[54, "accessing-request-data"]], "Accessing and Modifying the Session": [[60, "accessing-and-modifying-the-session"]], "Activate the environment": [[25, "activate-the-environment"]], "Adding Behavior": [[22, "adding-behavior"]], "Adding HTTP Method Overrides": [[41, null]], "Adding a favicon": [[34, null]], "Additional Notes": [[24, "additional-notes"]], "Address already in use": [[56, "address-already-in-use"]], "An Easier Solution": [[35, "an-easier-solution"]], "Apache httpd": [[9, null]], "Application Context": [[5, "application-context"]], "Application Discovery": [[5, "application-discovery"]], "Application Discovery Behavior": [[54, null]], "Application Dispatching": [[29, null]], "Application Factories": [[30, null]], "Application Factory": [[32, "application-factory"]], "Application Globals": [[0, "application-globals"]], "Application Object": [[0, "application-object"]], "Application Setup": [[27, "application-setup"], [64, null]], "Application Structure and Lifecycle": [[27, null]], "Async with gevent": [[18, "async-with-gevent"]], "Async with gevent or eventlet": [[13, "async-with-gevent-or-eventlet"]], "Async/await and ASGI support": [[20, "async-await-and-asgi-support"]], "Authentication": [[71, "authentication"]], "BSD-3-Clause License": [[26, null]], "Background Tasks with Celery": [[32, null]], "Background tasks": [[2, "background-tasks"]], "Base Template": [[50, "base-template"]], "Basic Configuration": [[28, "basic-configuration"]], "Basic Factories": [[30, "basic-factories"]], "Basic Reusable View": [[73, "basic-reusable-view"]], "Basic Usage": [[48, "basic-usage"]], "Binding Externally": [[11, "binding-externally"], [12, "binding-externally"], [13, "binding-externally"], [15, "binding-externally"], [18, "binding-externally"], [19, "binding-externally"]], "Blog": [[71, "blog"]], "Blog Blueprint": [[61, null]], "Blueprint Error Handlers": [[3, "blueprint-error-handlers"], [21, "blueprint-error-handlers"]], "Blueprint Objects": [[0, "blueprint-objects"]], "Blueprint Resource Folder": [[3, "blueprint-resource-folder"]], "Blueprint Resources": [[3, "blueprint-resources"]], "Blueprints and Views": [[72, null]], "Build and Install": [[63, "build-and-install"]], "Building Extensions": [[23, "building-extensions"]], "Building URLs": [[3, "building-urls"]], "Builtin Configuration Values": [[6, "builtin-configuration-values"]], "Caching": [[31, null]], "Caching Decorator": [[52, "caching-decorator"]], "Callbacks and Errors": [[55, "callbacks-and-errors"]], "Calling Tasks": [[32, "calling-tasks"]], "Changes": [[4, null]], "Child Template": [[50, "child-template"]], "Circular Imports": [[43, null]], "Class-Based Views": [[0, "class-based-views"]], "Class-based Views": [[73, null]], "Combining Applications": [[29, "combining-applications"]], "Command Line": [[56, "command-line"]], "Command Line Interface": [[0, "command-line-interface"], [5, null], [57, "command-line-interface"]], "Configuration": [[0, "configuration"], [9, "configuration"], [16, "configuration"], [42, "configuration"]], "Configuration Basics": [[6, "configuration-basics"]], "Configuration Best Practices": [[6, "configuration-best-practices"]], "Configuration Handling": [[6, null]], "Configuration Techniques": [[22, "configuration-techniques"]], "Configure the Secret Key": [[63, "configure-the-secret-key"]], "Configuring from Data Files": [[6, "configuring-from-data-files"]], "Configuring from Environment Variables": [[6, "configuring-from-environment-variables"]], "Configuring from Python Files": [[6, "configuring-from-python-files"]], "Connect on Demand": [[47, "connect-on-demand"]], "Connect to the Database": [[62, "connect-to-the-database"]], "Connection Reset Issue": [[35, null]], "Content Security Policy (CSP)": [[74, "content-security-policy-csp"]], "Contents:": [[65, null]], "Context Locals": [[54, "context-locals"]], "Context Processors": [[59, "context-processors"]], "Contributing": [[7, null]], "Controlling Autoescaping": [[59, "controlling-autoescaping"]], "Converting to Centralized URL Map": [[40, "converting-to-centralized-url-map"]], "Cookies": [[54, "cookies"]], "Copy/Paste to Terminal": [[74, "copy-paste-to-terminal"]], "Core Signals": [[58, "core-signals"]], "Create": [[61, "create"]], "Create a Blueprint": [[72, "create-a-blueprint"]], "Create an environment": [[25, "create-an-environment"]], "Create the Tables": [[62, "create-the-tables"]], "Creating Data": [[42, "creating-data"]], "Creating Signals": [[58, "creating-signals"]], "Creating a Request Context": [[57, "creating-a-request-context"]], "Cross-Site Request Forgery (CSRF)": [[74, "cross-site-request-forgery-csrf"]], "Cross-Site Scripting (XSS)": [[74, "cross-site-scripting-xss"]], "Custom Commands": [[5, "custom-commands"]], "Custom Error Pages": [[21, "custom-error-pages"]], "Custom Scripts": [[5, "custom-scripts"]], "Data During a Request": [[22, "data-during-a-request"]], "Database": [[71, "database"]], "Debug Mode": [[5, "debug-mode"], [6, "debug-mode"], [54, "debug-mode"]], "Debugging": [[21, "debugging"]], "Debugging Application Errors": [[8, null]], "Declarative": [[46, "declarative"]], "Decorator Based Signal Subscriptions": [[58, "decorator-based-signal-subscriptions"]], "Default Configuration": [[28, "default-configuration"]], "Deferred Errors on Reload": [[56, "deferred-errors-on-reload"]], "Deferred Request Callbacks": [[33, null]], "Define and Access the Database": [[62, null]], "Defining Tasks": [[32, "defining-tasks"]], "Delete": [[61, "delete"]], "Dependencies": [[25, "dependencies"]], "Deploy to Production": [[63, null]], "Deploying to Production": [[14, null]], "Deploying to a Web Server": [[54, "deploying-to-a-web-server"]], "Describe the Project": [[66, "describe-the-project"]], "Design Decisions in Flask": [[20, null]], "Development / Production": [[6, "development-production"]], "Development Server": [[56, null]], "Disable dotenv": [[5, "disable-dotenv"]], "Dispatch by Path": [[29, "dispatch-by-path"]], "Dispatch by Subdomain": [[29, "dispatch-by-subdomain"]], "Documentation": [[42, "documentation"]], "Domain Name": [[9, "domain-name"], [16, "domain-name"]], "Easy Querying": [[47, "easy-querying"]], "Email Errors to Admins": [[28, "email-errors-to-admins"]], "Endpoint Decorator": [[52, "endpoint-decorator"]], "Endpoints and URLs": [[72, "endpoints-and-urls"]], "Environment Variables From dotenv": [[5, "environment-variables-from-dotenv"]], "Environment Variables From virtualenv": [[5, "environment-variables-from-virtualenv"]], "Error Handlers": [[21, "error-handlers"]], "Error Logging Tools": [[21, "error-logging-tools"]], "Errors in Custom Scripts": [[5, null]], "Events and Signals": [[1, "events-and-signals"]], "Extensions": [[2, "extensions"], [23, null]], "External Debuggers": [[8, "external-debuggers"]], "Externally Visible Server": [[54, "public-server"]], "Factories & Extensions": [[30, "factories-extensions"]], "Factory": [[71, "factory"]], "Factory Improvements": [[30, "factory-improvements"]], "File Uploads": [[54, "file-uploads"]], "Filtering Flash Messages": [[36, "filtering-flash-messages"]], "Finding Extensions": [[23, "finding-extensions"]], "Firing Before/After Request": [[57, "firing-before-after-request"]], "Fixtures": [[60, "fixtures"]], "Flashing With Categories": [[36, "flashing-with-categories"]], "Flask Extension Development": [[22, null]], "Flask Extensions": [[28, "flask-extensions"]], "Flask-SQLAlchemy Extension": [[46, "flask-sqlalchemy-extension"]], "Following Redirects": [[38, "following-redirects"], [60, "following-redirects"]], "Form Data": [[60, "form-data"]], "Form Validation with WTForms": [[53, null]], "Forms in Templates": [[53, "forms-in-templates"]], "Further Examples": [[21, "further-examples"]], "Further Improving the Shell Experience": [[57, "further-improving-the-shell-experience"]], "Generating URLs": [[38, "generating-urls"]], "Generic Exception Handlers": [[21, "generic-exception-handlers"]], "Getting Results": [[32, "getting-results"]], "Getting the most out of WTForms with an Extension": [[53, null]], "Gunicorn": [[13, null]], "HTML Escaping": [[54, "html-escaping"]], "HTTP Methods": [[54, "http-methods"]], "HTTP Public Key Pinning (HPKP)": [[74, "http-public-key-pinning-hpkp"]], "HTTP Strict Transport Security (HSTS)": [[74, "http-strict-transport-security-hsts"]], "Handling": [[21, "handling"]], "Handling Application Errors": [[21, null]], "Hooking in WSGI Middleware": [[54, "hooking-in-wsgi-middleware"]], "Hosting Platforms": [[14, "hosting-platforms"]], "How a Request is Handled": [[27, "how-a-request-is-handled"]], "How the Context Works": [[55, "how-the-context-works"]], "How to generate good secret keys": [[54, null]], "Identifying Tests": [[60, "identifying-tests"]], "Improving Uploads": [[35, "improving-uploads"]], "In Code": [[56, "in-code"]], "In Production": [[8, "in-production"]], "In the View": [[53, "in-the-view"]], "Incoming Request Data": [[0, "incoming-request-data"]], "Index": [[61, "index"]], "Information for the Pros": [[35, null]], "Initial Schemas": [[47, "initial-schemas"]], "Initialize the Database File": [[62, "initialize-the-database-file"]], "Injecting Request Information": [[28, "injecting-request-information"]], "Insider Information": [[54, null]], "Install": [[32, "install"]], "Install Flask": [[25, "install-flask"]], "Install the Project": [[66, "install-the-project"]], "Installation": [[25, null]], "Installing": [[11, "installing"], [12, "installing"], [13, "installing"], [15, "installing"], [18, "installing"], [19, "installing"]], "Instance Folders": [[6, "instance-folders"]], "Integrate Celery with Flask": [[32, "integrate-celery-with-flask"]], "Internationalized Application URLs": [[51, "internationalized-application-urls"]], "Internationalized Blueprint URLs": [[51, "internationalized-blueprint-urls"]], "JSON Data": [[60, "json-data"]], "JSON Security": [[74, "json-security"]], "JSON Support": [[0, "module-flask.json"]], "JavaScript, fetch, and JSON": [[38, null]], "Jinja Setup": [[59, "jinja-setup"]], "Keep Developing!": [[68, null]], "Keep in Mind": [[0, null]], "Large Applications as Packages": [[43, null]], "Lazily Loading Views": [[40, null]], "Lifetime of the Context": [[1, "lifetime-of-the-context"], [55, "lifetime-of-the-context"]], "Loading Late": [[40, "loading-late"]], "Log In": [[70, "log-in"]], "Logging": [[21, "logging"], [28, null], [54, "logging"]], "Login": [[72, "login"]], "Login Required Decorator": [[52, "login-required-decorator"]], "Logout": [[72, "logout"]], "Make the Project Installable": [[66, null]], "Making a Request with fetch": [[38, "making-a-request-with-fetch"]], "Manual Object Relational Mapping": [[46, "manual-object-relational-mapping"]], "Manually Push a Context": [[1, "manually-push-a-context"], [55, "manually-push-a-context"]], "Mapping Documents": [[42, "mapping-documents"]], "Message Flashing": [[0, "message-flashing"], [36, null], [54, "message-flashing"]], "Method Dispatching and APIs": [[73, "method-dispatching-and-apis"]], "Method Hints": [[73, "method-hints"]], "Middleware": [[27, "middleware"]], "Modular Applications with Blueprints": [[3, null]], "MongoDB with MongoEngine": [[42, null]], "My First Blueprint": [[3, "my-first-blueprint"]], "Naming": [[22, "naming"]], "Nesting Blueprints": [[3, "nesting-blueprints"]], "Notes On Proxies": [[55, "notes-on-proxies"]], "Notice": [[0, null]], "One Template Engine": [[20, "one-template-engine"]], "Open a Shell": [[5, "open-a-shell"]], "Optional dependencies": [[25, "optional-dependencies"]], "Other Libraries": [[28, "other-libraries"]], "Other event loops": [[2, "other-event-loops"]], "Passing Data to Tasks": [[32, "passing-data-to-tasks"]], "Passing Proxies as Senders": [[58, null]], "Patterns for Flask": [[37, null]], "Performance": [[2, "performance"]], "Plugins": [[5, "plugins"]], "Project Layout": [[67, null]], "Purpose of the Context": [[1, "purpose-of-the-context"], [55, "purpose-of-the-context"]], "PyCharm Integration": [[5, "pycharm-integration"]], "Python Version": [[25, "python-version"]], "Queries": [[42, "queries"]], "Quickstart": [[54, null]], "Receiving JSON in Views": [[38, "receiving-json-in-views"]], "Recommended Extension Guidelines": [[22, "recommended-extension-guidelines"]], "Redirects and Errors": [[54, "redirects-and-errors"]], "Register": [[70, "register"]], "Register A User": [[70, "register-a-user"]], "Register with the Application": [[62, "register-with-the-application"]], "Registering": [[21, "registering"]], "Registering Blueprints": [[3, "registering-blueprints"]], "Registering Commands with Blueprints": [[5, "registering-commands-with-blueprints"]], "Registering Filters": [[59, "registering-filters"]], "Removing the Default Handler": [[28, "removing-the-default-handler"]], "Rendering Templates": [[38, "rendering-templates"], [54, "rendering-templates"]], "Replacing Content": [[38, "replacing-content"]], "Request Content Checksums": [[44, null]], "Require Authentication in Other Views": [[72, "require-authentication-in-other-views"]], "Resource Use": [[74, "resource-use"]], "Response Objects": [[0, "response-objects"]], "Return JSON from Views": [[38, "return-json-from-views"]], "Returning API Errors as JSON": [[21, "returning-api-errors-as-json"]], "Routing": [[54, "routing"]], "Run The Application": [[64, "run-the-application"]], "Run the Development Server": [[5, "run-the-development-server"]], "Run with a Production Server": [[63, "run-with-a-production-server"]], "Running": [[11, "running"], [12, "running"], [13, "running"], [15, "running"], [18, "running"], [19, "running"]], "Running Commands with the CLI Runner": [[60, "running-commands-with-the-cli-runner"]], "Running the Tests": [[71, "running-the-tests"]], "SQL Abstraction Layer": [[46, "sql-abstraction-layer"]], "SQLAlchemy in Flask": [[46, null]], "Security Considerations": [[74, null]], "Security Headers": [[74, "security-headers"]], "See also": [[34, "see-also"]], "Self-Hosted Options": [[14, "self-hosted-options"]], "Sending Requests with the Test Client": [[60, "sending-requests-with-the-test-client"]], "Sending Signals": [[58, "sending-signals"]], "Serving the Application": [[27, "serving-the-application"]], "Session Interface": [[0, "session-interface"]], "Sessions": [[0, "sessions"], [54, "sessions"]], "Set-Cookie options": [[74, "set-cookie-options"]], "Setting Command Options": [[5, "setting-command-options"]], "Setup and Fixtures": [[71, "setup-and-fixtures"]], "Signals": [[0, "signals"], [55, "signals"], [58, null]], "Signals and Flask\u2019s Request Context": [[58, "signals-and-flask-s-request-context"]], "Simple Flashing": [[36, "simple-flashing"]], "Simple Packages": [[43, "simple-packages"]], "Single-Page Applications": [[45, null]], "Standard Context": [[59, "standard-context"]], "Static Files": [[3, "static-files"], [54, "static-files"], [69, null]], "Storing Data": [[1, "storing-data"]], "Stream Helpers": [[0, "stream-helpers"]], "Streaming": [[59, "streaming"]], "Streaming Contents": [[48, null]], "Streaming from Templates": [[48, "streaming-from-templates"]], "Streaming with Context": [[48, "streaming-with-context"]], "Subclassing Flask": [[49, null]], "Subscribing to Signals": [[58, "subscribing-to-signals"]], "Tagged JSON": [[0, "tagged-json"]], "Teardown Callbacks": [[55, "teardown-callbacks"]], "Tell Flask it is Behind a Proxy": [[17, null]], "Template Inheritance": [[50, null]], "Template Rendering": [[0, "template-rendering"]], "Templates": [[3, "templates"], [59, null], [70, null]], "Templating Decorator": [[52, "templating-decorator"]], "Test CLI Runner": [[0, "test-cli-runner"]], "Test Client": [[0, "test-client"]], "Test Coverage": [[71, null]], "Testing Flask Applications": [[60, null]], "Tests that depend on an Active Context": [[60, "tests-that-depend-on-an-active-context"]], "The Application Context": [[1, null]], "The Application Factory": [[64, "the-application-factory"]], "The Base Layout": [[70, "the-base-layout"]], "The Blueprint": [[61, "the-blueprint"]], "The Built-In Debugger": [[8, "the-built-in-debugger"]], "The Concept of Blueprints": [[3, "the-concept-of-blueprints"]], "The Explicit Application Object": [[20, "the-explicit-application-object"]], "The Extension Class and Initialization": [[22, "the-extension-class-and-initialization"]], "The First View: Register": [[72, "the-first-view-register"]], "The Forms": [[53, "the-forms"]], "The Jinja Context Behavior": [[59, null]], "The Request Context": [[55, null]], "The Request Object": [[54, "the-request-object"]], "The Routing System": [[20, "the-routing-system"]], "Thread Locals": [[20, "thread-locals"]], "Tutorial": [[65, null]], "URL Building": [[54, "url-building"]], "URL Route Registrations": [[0, "url-route-registrations"]], "URL Variables": [[73, "url-variables"]], "Unhandled Exceptions": [[21, "unhandled-exceptions"]], "Unique URLs / Redirection Behavior": [[54, "unique-urls-redirection-behavior"]], "Update": [[61, "update"]], "Upload Progress Bars": [[35, "upload-progress-bars"]], "Uploading Files": [[35, null]], "Useful Functions and Classes": [[0, "useful-functions-and-classes"]], "Useful Internals": [[0, "useful-internals"]], "User\u2019s Guide": [[24, "user-s-guide"]], "Using Applications": [[30, "using-applications"]], "Using Extensions": [[23, "using-extensions"]], "Using Flask Extensions": [[54, "using-flask-extensions"]], "Using SQLite 3 with Flask": [[47, null]], "Using URL Processors": [[51, null]], "Using async and await": [[2, null]], "Using async with greenlet": [[2, null]], "Variable Rules": [[54, "variable-rules"]], "Version 0.1": [[4, "version-0-1"]], "Version 0.10": [[4, "version-0-10"]], "Version 0.10.1": [[4, "version-0-10-1"]], "Version 0.11": [[4, "version-0-11"]], "Version 0.11.1": [[4, "version-0-11-1"]], "Version 0.12": [[4, "version-0-12"]], "Version 0.12.1": [[4, "version-0-12-1"]], "Version 0.12.2": [[4, "version-0-12-2"]], "Version 0.12.3": [[4, "version-0-12-3"]], "Version 0.12.4": [[4, "version-0-12-4"]], "Version 0.12.5": [[4, "version-0-12-5"]], "Version 0.2": [[4, "version-0-2"]], "Version 0.3": [[4, "version-0-3"]], "Version 0.3.1": [[4, "version-0-3-1"]], "Version 0.4": [[4, "version-0-4"]], "Version 0.5": [[4, "version-0-5"]], "Version 0.5.1": [[4, "version-0-5-1"]], "Version 0.5.2": [[4, "version-0-5-2"]], "Version 0.6": [[4, "version-0-6"]], "Version 0.6.1": [[4, "version-0-6-1"]], "Version 0.7": [[4, "version-0-7"]], "Version 0.7.1": [[4, "version-0-7-1"]], "Version 0.7.2": [[4, "version-0-7-2"]], "Version 0.8": [[4, "version-0-8"]], "Version 0.8.1": [[4, "version-0-8-1"]], "Version 0.9": [[4, "version-0-9"]], "Version 1.0": [[4, "version-1-0"]], "Version 1.0.1": [[4, "version-1-0-1"]], "Version 1.0.2": [[4, "version-1-0-2"]], "Version 1.0.3": [[4, "version-1-0-3"]], "Version 1.0.4": [[4, "version-1-0-4"]], "Version 1.1.0": [[4, "version-1-1-0"]], "Version 1.1.1": [[4, "version-1-1-1"]], "Version 1.1.2": [[4, "version-1-1-2"]], "Version 1.1.3": [[4, "version-1-1-3"]], "Version 1.1.4": [[4, "version-1-1-4"]], "Version 2.0.0": [[4, "version-2-0-0"]], "Version 2.0.1": [[4, "version-2-0-1"]], "Version 2.0.2": [[4, "version-2-0-2"]], "Version 2.0.3": [[4, "version-2-0-3"]], "Version 2.1.0": [[4, "version-2-1-0"]], "Version 2.1.1": [[4, "version-2-1-1"]], "Version 2.1.2": [[4, "version-2-1-2"]], "Version 2.1.3": [[4, "version-2-1-3"]], "Version 2.2.0": [[4, "version-2-2-0"]], "Version 2.2.1": [[4, "version-2-2-1"]], "Version 2.2.2": [[4, "version-2-2-2"]], "Version 2.2.3": [[4, "version-2-2-3"]], "Version 2.2.4": [[4, "version-2-2-4"]], "Version 2.2.5": [[4, "version-2-2-5"]], "Version 2.3.0": [[4, "version-2-3-0"]], "Version 2.3.1": [[4, "version-2-3-1"]], "Version 2.3.2": [[4, "version-2-3-2"]], "Version 2.3.3": [[4, "version-2-3-3"]], "Version 3.0.0": [[4, "version-3-0-0"]], "Version 3.0.1": [[4, "version-3-0-1"]], "Version 3.0.2": [[4, "version-3-0-2"]], "Version 3.0.3": [[4, "version-3-0-3"]], "Version 3.1.0": [[4, "version-3-1-0"]], "Version 3.1.1": [[4, "version-3-1-1"]], "View Decorators": [[52, null], [73, "view-decorators"]], "View Function Options": [[0, "view-function-options"]], "View Lifetime and self": [[73, "view-lifetime-and-self"]], "Views and Models": [[22, "views-and-models"]], "Virtual environments": [[25, "virtual-environments"]], "Waitress": [[19, null]], "Watch and Ignore Files with the Reloader": [[5, "watch-and-ignore-files-with-the-reloader"]], "Welcome to Flask": [[24, null]], "Werkzeug": [[28, "werkzeug"]], "What Flask is, What Flask is Not": [[20, "what-flask-is-what-flask-is-not"]], "What does \u201cmicro\u201d mean?": [[20, "what-does-micro-mean"]], "When to use Quart instead": [[2, "when-to-use-quart-instead"]], "Why Blueprints?": [[3, "why-blueprints"]], "Working with Blueprints": [[43, "working-with-blueprints"]], "Working with the Shell": [[57, null]], "Working with this Document": [[29, "working-with-this-document"]], "X-Content-Type-Options": [[74, "x-content-type-options"]], "X-Frame-Options": [[74, "x-frame-options"]], "eventlet": [[11, null]], "gevent": [[12, null]], "greenlet": [[25, "greenlet"]], "mod_wsgi": [[15, null]], "nginx": [[16, null]], "uWSGI": [[18, null]]}, "docnames": ["api", "appcontext", "async-await", "blueprints", "changes", "cli", "config", "contributing", "debugging", "deploying/apache-httpd", "deploying/asgi", "deploying/eventlet", "deploying/gevent", "deploying/gunicorn", "deploying/index", "deploying/mod_wsgi", "deploying/nginx", "deploying/proxy_fix", "deploying/uwsgi", "deploying/waitress", "design", "errorhandling", "extensiondev", "extensions", "index", "installation", "license", "lifecycle", "logging", "patterns/appdispatch", "patterns/appfactories", "patterns/caching", "patterns/celery", "patterns/deferredcallbacks", "patterns/favicon", "patterns/fileuploads", "patterns/flashing", "patterns/index", "patterns/javascript", "patterns/jquery", "patterns/lazyloading", "patterns/methodoverrides", "patterns/mongoengine", "patterns/packages", "patterns/requestchecksum", "patterns/singlepageapplications", "patterns/sqlalchemy", "patterns/sqlite3", "patterns/streaming", "patterns/subclassing", "patterns/templateinheritance", "patterns/urlprocessors", "patterns/viewdecorators", "patterns/wtforms", "quickstart", "reqcontext", "server", "shell", "signals", "templating", "testing", "tutorial/blog", "tutorial/database", "tutorial/deploy", "tutorial/factory", "tutorial/index", "tutorial/install", "tutorial/layout", "tutorial/next", "tutorial/static", "tutorial/templates", "tutorial/tests", "tutorial/views", "views", "web-security"], "envversion": {"sphinx": 64, "sphinx.domains.c": 3, "sphinx.domains.changeset": 1, "sphinx.domains.citation": 1, "sphinx.domains.cpp": 9, "sphinx.domains.index": 1, "sphinx.domains.javascript": 3, "sphinx.domains.math": 2, "sphinx.domains.python": 4, "sphinx.domains.rst": 2, "sphinx.domains.std": 2, "sphinx.ext.intersphinx": 1}, "filenames": ["api.rst", "appcontext.rst", "async-await.rst", "blueprints.rst", "changes.rst", "cli.rst", "config.rst", "contributing.rst", "debugging.rst", "deploying/apache-httpd.rst", "deploying/asgi.rst", "deploying/eventlet.rst", "deploying/gevent.rst", "deploying/gunicorn.rst", "deploying/index.rst", "deploying/mod_wsgi.rst", "deploying/nginx.rst", "deploying/proxy_fix.rst", "deploying/uwsgi.rst", "deploying/waitress.rst", "design.rst", "errorhandling.rst", "extensiondev.rst", "extensions.rst", "index.rst", "installation.rst", "license.rst", "lifecycle.rst", "logging.rst", "patterns/appdispatch.rst", "patterns/appfactories.rst", "patterns/caching.rst", "patterns/celery.rst", "patterns/deferredcallbacks.rst", "patterns/favicon.rst", "patterns/fileuploads.rst", "patterns/flashing.rst", "patterns/index.rst", "patterns/javascript.rst", "patterns/jquery.rst", "patterns/lazyloading.rst", "patterns/methodoverrides.rst", "patterns/mongoengine.rst", "patterns/packages.rst", "patterns/requestchecksum.rst", "patterns/singlepageapplications.rst", "patterns/sqlalchemy.rst", "patterns/sqlite3.rst", "patterns/streaming.rst", "patterns/subclassing.rst", "patterns/templateinheritance.rst", "patterns/urlprocessors.rst", "patterns/viewdecorators.rst", "patterns/wtforms.rst", "quickstart.rst", "reqcontext.rst", "server.rst", "shell.rst", "signals.rst", "templating.rst", "testing.rst", "tutorial/blog.rst", "tutorial/database.rst", "tutorial/deploy.rst", "tutorial/factory.rst", "tutorial/index.rst", "tutorial/install.rst", "tutorial/layout.rst", "tutorial/next.rst", "tutorial/static.rst", "tutorial/templates.rst", "tutorial/tests.rst", "tutorial/views.rst", "views.rst", "web-security.rst"], "indexentries": {"_appctxglobals (class in flask.ctx)": [[0, "flask.ctx._AppCtxGlobals", false]], "abort() (in module flask)": [[0, "flask.abort", false]], "aborter (flask.flask attribute)": [[0, "flask.Flask.aborter", false]], "aborter_class (flask.flask attribute)": [[0, "flask.Flask.aborter_class", false]], "accept_charsets (flask.request property)": [[0, "flask.Request.accept_charsets", false]], "accept_encodings (flask.request property)": [[0, "flask.Request.accept_encodings", false]], "accept_languages (flask.request property)": [[0, "flask.Request.accept_languages", false]], "accept_mimetypes (flask.request property)": [[0, "flask.Request.accept_mimetypes", false]], "accept_ranges (flask.response attribute)": [[0, "flask.Response.accept_ranges", false]], "access_control_allow_credentials (flask.response property)": [[0, "flask.Response.access_control_allow_credentials", false]], "access_control_allow_headers (flask.response attribute)": [[0, "flask.Response.access_control_allow_headers", false]], "access_control_allow_methods (flask.response attribute)": [[0, "flask.Response.access_control_allow_methods", false]], "access_control_allow_origin (flask.response attribute)": [[0, "flask.Response.access_control_allow_origin", false]], "access_control_expose_headers (flask.response attribute)": [[0, "flask.Response.access_control_expose_headers", false]], "access_control_max_age (flask.response attribute)": [[0, "flask.Response.access_control_max_age", false]], "access_control_request_headers (flask.request attribute)": [[0, "flask.Request.access_control_request_headers", false]], "access_control_request_method (flask.request attribute)": [[0, "flask.Request.access_control_request_method", false]], "access_route (flask.request property)": [[0, "flask.Request.access_route", false]], "accessed (flask.sessions.securecookiesession attribute)": [[0, "flask.sessions.SecureCookieSession.accessed", false]], "accessed (flask.sessions.sessionmixin attribute)": [[0, "flask.sessions.SessionMixin.accessed", false]], "add_app_template_filter() (flask.blueprint method)": [[0, "flask.Blueprint.add_app_template_filter", false]], "add_app_template_global() (flask.blueprint method)": [[0, "flask.Blueprint.add_app_template_global", false]], "add_app_template_test() (flask.blueprint method)": [[0, "flask.Blueprint.add_app_template_test", false]], "add_etag() (flask.response method)": [[0, "flask.Response.add_etag", false]], "add_template_filter() (flask.flask method)": [[0, "flask.Flask.add_template_filter", false]], "add_template_global() (flask.flask method)": [[0, "flask.Flask.add_template_global", false]], "add_template_test() (flask.flask method)": [[0, "flask.Flask.add_template_test", false]], "add_url_rule() (flask.blueprint method)": [[0, "flask.Blueprint.add_url_rule", false]], "add_url_rule() (flask.blueprints.blueprintsetupstate method)": [[0, "flask.blueprints.BlueprintSetupState.add_url_rule", false]], "add_url_rule() (flask.flask method)": [[0, "flask.Flask.add_url_rule", false]], "after_app_request() (flask.blueprint method)": [[0, "flask.Blueprint.after_app_request", false]], "after_request() (flask.blueprint method)": [[0, "flask.Blueprint.after_request", false]], "after_request() (flask.flask method)": [[0, "flask.Flask.after_request", false]], "after_request_funcs (flask.blueprint attribute)": [[0, "flask.Blueprint.after_request_funcs", false]], "after_request_funcs (flask.flask attribute)": [[0, "flask.Flask.after_request_funcs", false]], "after_this_request() (in module flask)": [[0, "flask.after_this_request", false]], "age (flask.response attribute)": [[0, "flask.Response.age", false]], "allow (flask.response property)": [[0, "flask.Response.allow", false]], "app (flask.blueprints.blueprintsetupstate attribute)": [[0, "flask.blueprints.BlueprintSetupState.app", false]], "app_context() (flask.flask method)": [[0, "flask.Flask.app_context", false]], "app_context_processor() (flask.blueprint method)": [[0, "flask.Blueprint.app_context_processor", false]], "app_ctx_globals_class (flask.flask attribute)": [[0, "flask.Flask.app_ctx_globals_class", false]], "app_errorhandler() (flask.blueprint method)": [[0, "flask.Blueprint.app_errorhandler", false]], "app_import_path (flask.cli.scriptinfo attribute)": [[0, "flask.cli.ScriptInfo.app_import_path", false]], "app_template_filter() (flask.blueprint method)": [[0, "flask.Blueprint.app_template_filter", false]], "app_template_global() (flask.blueprint method)": [[0, "flask.Blueprint.app_template_global", false]], "app_template_test() (flask.blueprint method)": [[0, "flask.Blueprint.app_template_test", false]], "app_url_defaults() (flask.blueprint method)": [[0, "flask.Blueprint.app_url_defaults", false]], "app_url_value_preprocessor() (flask.blueprint method)": [[0, "flask.Blueprint.app_url_value_preprocessor", false]], "appcontext (class in flask.ctx)": [[0, "flask.ctx.AppContext", false]], "appcontext_popped (in module flask)": [[0, "flask.appcontext_popped", false]], "appcontext_pushed (in module flask)": [[0, "flask.appcontext_pushed", false]], "appcontext_tearing_down (in module flask)": [[0, "flask.appcontext_tearing_down", false]], "appgroup (class in flask.cli)": [[0, "flask.cli.AppGroup", false]], "application() (flask.request class method)": [[0, "flask.Request.application", false]], "application_root (built-in variable)": [[6, "APPLICATION_ROOT", false]], "args (flask.request property)": [[0, "flask.Request.args", false]], "as_view() (flask.views.view class method)": [[0, "flask.views.View.as_view", false]], "async_to_sync() (flask.flask method)": [[0, "flask.Flask.async_to_sync", false]], "authorization (flask.request property)": [[0, "flask.Request.authorization", false]], "auto_find_instance_path() (flask.flask method)": [[0, "flask.Flask.auto_find_instance_path", false]], "autocorrect_location_header (flask.response attribute)": [[0, "flask.Response.autocorrect_location_header", false]], "automatically_set_content_length (flask.response attribute)": [[0, "flask.Response.automatically_set_content_length", false]], "base_url (flask.request property)": [[0, "flask.Request.base_url", false]], "before_app_request() (flask.blueprint method)": [[0, "flask.Blueprint.before_app_request", false]], "before_request() (flask.blueprint method)": [[0, "flask.Blueprint.before_request", false]], "before_request() (flask.flask method)": [[0, "flask.Flask.before_request", false]], "before_request_funcs (flask.blueprint attribute)": [[0, "flask.Blueprint.before_request_funcs", false]], "before_request_funcs (flask.flask attribute)": [[0, "flask.Flask.before_request_funcs", false]], "blueprint (class in flask)": [[0, "flask.Blueprint", false]], "blueprint (flask.blueprints.blueprintsetupstate attribute)": [[0, "flask.blueprints.BlueprintSetupState.blueprint", false]], "blueprint (flask.request property)": [[0, "flask.Request.blueprint", false]], "blueprints (flask.flask attribute)": [[0, "flask.Flask.blueprints", false]], "blueprints (flask.request property)": [[0, "flask.Request.blueprints", false]], "blueprintsetupstate (class in flask.blueprints)": [[0, "flask.blueprints.BlueprintSetupState", false]], "cache_control (flask.request property)": [[0, "flask.Request.cache_control", false]], "cache_control (flask.response property)": [[0, "flask.Response.cache_control", false]], "calculate_content_length() (flask.response method)": [[0, "flask.Response.calculate_content_length", false]], "call_on_close() (flask.response method)": [[0, "flask.Response.call_on_close", false]], "check() (flask.json.tag.jsontag method)": [[0, "flask.json.tag.JSONTag.check", false]], "clear() (flask.sessions.nullsession method)": [[0, "flask.sessions.NullSession.clear", false]], "cli (flask.blueprint attribute)": [[0, "flask.Blueprint.cli", false]], "cli (flask.flask attribute)": [[0, "flask.Flask.cli", false]], "close() (flask.request method)": [[0, "flask.Request.close", false]], "close() (flask.response method)": [[0, "flask.Response.close", false]], "command() (flask.cli.appgroup method)": [[0, "flask.cli.AppGroup.command", false]], "compact (flask.json.provider.defaultjsonprovider attribute)": [[0, "flask.json.provider.DefaultJSONProvider.compact", false]], "config (class in flask)": [[0, "flask.Config", false]], "config (flask.flask attribute)": [[0, "flask.Flask.config", false]], "config_class (flask.flask attribute)": [[0, "flask.Flask.config_class", false]], "content_encoding (flask.request attribute)": [[0, "flask.Request.content_encoding", false]], "content_encoding (flask.response attribute)": [[0, "flask.Response.content_encoding", false]], "content_language (flask.response property)": [[0, "flask.Response.content_language", false]], "content_length (flask.request property)": [[0, "flask.Request.content_length", false]], "content_length (flask.response attribute)": [[0, "flask.Response.content_length", false]], "content_location (flask.response attribute)": [[0, "flask.Response.content_location", false]], "content_md5 (flask.request attribute)": [[0, "flask.Request.content_md5", false]], "content_md5 (flask.response attribute)": [[0, "flask.Response.content_md5", false]], "content_range (flask.response property)": [[0, "flask.Response.content_range", false]], "content_security_policy (flask.response property)": [[0, "flask.Response.content_security_policy", false]], "content_security_policy_report_only (flask.response property)": [[0, "flask.Response.content_security_policy_report_only", false]], "content_type (flask.request attribute)": [[0, "flask.Request.content_type", false]], "content_type (flask.response attribute)": [[0, "flask.Response.content_type", false]], "context_processor() (flask.blueprint method)": [[0, "flask.Blueprint.context_processor", false]], "context_processor() (flask.flask method)": [[0, "flask.Flask.context_processor", false]], "cookies (flask.request property)": [[0, "flask.Request.cookies", false]], "copy() (flask.ctx.requestcontext method)": [[0, "flask.ctx.RequestContext.copy", false]], "copy_current_request_context() (in module flask)": [[0, "flask.copy_current_request_context", false]], "create_app (flask.cli.scriptinfo attribute)": [[0, "flask.cli.ScriptInfo.create_app", false]], "create_global_jinja_loader() (flask.flask method)": [[0, "flask.Flask.create_global_jinja_loader", false]], "create_jinja_environment() (flask.flask method)": [[0, "flask.Flask.create_jinja_environment", false]], "create_url_adapter() (flask.flask method)": [[0, "flask.Flask.create_url_adapter", false]], "cross_origin_embedder_policy (flask.response attribute)": [[0, "flask.Response.cross_origin_embedder_policy", false]], "cross_origin_opener_policy (flask.response attribute)": [[0, "flask.Response.cross_origin_opener_policy", false]], "current_app (in module flask)": [[0, "flask.current_app", false]], "data (flask.cli.scriptinfo attribute)": [[0, "flask.cli.ScriptInfo.data", false]], "data (flask.request property)": [[0, "flask.Request.data", false]], "data (flask.response property)": [[0, "flask.Response.data", false]], "date (flask.request attribute)": [[0, "flask.Request.date", false]], "date (flask.response attribute)": [[0, "flask.Response.date", false]], "debug (built-in variable)": [[6, "DEBUG", false]], "debug (flask.flask property)": [[0, "flask.Flask.debug", false]], "decorators (flask.views.view attribute)": [[0, "flask.views.View.decorators", false]], "default() (flask.json.provider.defaultjsonprovider static method)": [[0, "flask.json.provider.DefaultJSONProvider.default", false]], "default_mimetype (flask.response attribute)": [[0, "flask.Response.default_mimetype", false]], "default_status (flask.response attribute)": [[0, "flask.Response.default_status", false]], "default_tags (flask.json.tag.taggedjsonserializer attribute)": [[0, "flask.json.tag.TaggedJSONSerializer.default_tags", false]], "defaultjsonprovider (class in flask.json.provider)": [[0, "flask.json.provider.DefaultJSONProvider", false]], "delete() (flask.blueprint method)": [[0, "flask.Blueprint.delete", false]], "delete() (flask.flask method)": [[0, "flask.Flask.delete", false]], "delete_cookie() (flask.response method)": [[0, "flask.Response.delete_cookie", false]], "dict_storage_class (flask.request attribute)": [[0, "flask.Request.dict_storage_class", false]], "digest_method() (flask.sessions.securecookiesessioninterface static method)": [[0, "flask.sessions.SecureCookieSessionInterface.digest_method", false]], "direct_passthrough (flask.response attribute)": [[0, "flask.Response.direct_passthrough", false]], "dispatch_request() (flask.flask method)": [[0, "flask.Flask.dispatch_request", false]], "dispatch_request() (flask.views.methodview method)": [[0, "flask.views.MethodView.dispatch_request", false]], "dispatch_request() (flask.views.view method)": [[0, "flask.views.View.dispatch_request", false]], "do_teardown_appcontext() (flask.flask method)": [[0, "flask.Flask.do_teardown_appcontext", false]], "do_teardown_request() (flask.flask method)": [[0, "flask.Flask.do_teardown_request", false]], "dump() (flask.json.provider.jsonprovider method)": [[0, "flask.json.provider.JSONProvider.dump", false]], "dump() (in module flask.json)": [[0, "flask.json.dump", false]], "dumps() (flask.json.provider.defaultjsonprovider method)": [[0, "flask.json.provider.DefaultJSONProvider.dumps", false]], "dumps() (flask.json.provider.jsonprovider method)": [[0, "flask.json.provider.JSONProvider.dumps", false]], "dumps() (flask.json.tag.taggedjsonserializer method)": [[0, "flask.json.tag.TaggedJSONSerializer.dumps", false]], "dumps() (in module flask.json)": [[0, "flask.json.dumps", false]], "endpoint (flask.request property)": [[0, "flask.Request.endpoint", false]], "endpoint() (flask.blueprint method)": [[0, "flask.Blueprint.endpoint", false]], "endpoint() (flask.flask method)": [[0, "flask.Flask.endpoint", false]], "ensure_ascii (flask.json.provider.defaultjsonprovider attribute)": [[0, "flask.json.provider.DefaultJSONProvider.ensure_ascii", false]], "ensure_sync() (flask.flask method)": [[0, "flask.Flask.ensure_sync", false]], "environ (flask.request attribute)": [[0, "flask.Request.environ", false]], "environment variable": [[0, "index-0", false], [6, "index-0", false], [6, "index-1", false]], "error_handler_spec (flask.blueprint attribute)": [[0, "flask.Blueprint.error_handler_spec", false]], "error_handler_spec (flask.flask attribute)": [[0, "flask.Flask.error_handler_spec", false]], "errorhandler() (flask.blueprint method)": [[0, "flask.Blueprint.errorhandler", false]], "errorhandler() (flask.flask method)": [[0, "flask.Flask.errorhandler", false]], "expires (flask.response attribute)": [[0, "flask.Response.expires", false]], "explain_template_loading (built-in variable)": [[6, "EXPLAIN_TEMPLATE_LOADING", false]], "extensions (flask.flask attribute)": [[0, "flask.Flask.extensions", false]], "files (flask.request property)": [[0, "flask.Request.files", false]], "first_registration (flask.blueprints.blueprintsetupstate attribute)": [[0, "flask.blueprints.BlueprintSetupState.first_registration", false]], "flash() (in module flask)": [[0, "flask.flash", false]], "flask": [[0, "module-flask", false]], "flask (class in flask)": [[0, "flask.Flask", false]], "flask.globals.app_ctx (in module flask)": [[0, "flask.flask.globals.app_ctx", false]], "flask.globals.request_ctx (in module flask)": [[0, "flask.flask.globals.request_ctx", false]], "flask.json": [[0, "module-flask.json", false]], "flask.json.tag": [[0, "module-flask.json.tag", false]], "flask_debug": [[0, "index-0", false]], "flask_env": [[6, "index-0", false]], "flaskclient (class in flask.testing)": [[0, "flask.testing.FlaskClient", false]], "flaskclirunner (class in flask.testing)": [[0, "flask.testing.FlaskCliRunner", false]], "flaskgroup (class in flask.cli)": [[0, "flask.cli.FlaskGroup", false]], "force_type() (flask.response class method)": [[0, "flask.Response.force_type", false]], "form (flask.request property)": [[0, "flask.Request.form", false]], "form_data_parser_class (flask.request attribute)": [[0, "flask.Request.form_data_parser_class", false]], "freeze() (flask.response method)": [[0, "flask.Response.freeze", false]], "from_app() (flask.response class method)": [[0, "flask.Response.from_app", false]], "from_envvar() (flask.config method)": [[0, "flask.Config.from_envvar", false]], "from_file() (flask.config method)": [[0, "flask.Config.from_file", false]], "from_mapping() (flask.config method)": [[0, "flask.Config.from_mapping", false]], "from_object() (flask.config method)": [[0, "flask.Config.from_object", false]], "from_prefixed_env() (flask.config method)": [[0, "flask.Config.from_prefixed_env", false]], "from_pyfile() (flask.config method)": [[0, "flask.Config.from_pyfile", false]], "from_values() (flask.request class method)": [[0, "flask.Request.from_values", false]], "full_dispatch_request() (flask.flask method)": [[0, "flask.Flask.full_dispatch_request", false]], "full_path (flask.request property)": [[0, "flask.Request.full_path", false]], "g (in module flask)": [[0, "flask.g", false]], "get() (flask.blueprint method)": [[0, "flask.Blueprint.get", false]], "get() (flask.ctx._appctxglobals method)": [[0, "flask.ctx._AppCtxGlobals.get", false]], "get() (flask.flask method)": [[0, "flask.Flask.get", false]], "get() (flask.sessions.securecookiesession method)": [[0, "flask.sessions.SecureCookieSession.get", false]], "get_app_iter() (flask.response method)": [[0, "flask.Response.get_app_iter", false]], "get_command() (flask.cli.flaskgroup method)": [[0, "flask.cli.FlaskGroup.get_command", false]], "get_cookie_domain() (flask.sessions.sessioninterface method)": [[0, "flask.sessions.SessionInterface.get_cookie_domain", false]], "get_cookie_httponly() (flask.sessions.sessioninterface method)": [[0, "flask.sessions.SessionInterface.get_cookie_httponly", false]], "get_cookie_name() (flask.sessions.sessioninterface method)": [[0, "flask.sessions.SessionInterface.get_cookie_name", false]], "get_cookie_partitioned() (flask.sessions.sessioninterface method)": [[0, "flask.sessions.SessionInterface.get_cookie_partitioned", false]], "get_cookie_path() (flask.sessions.sessioninterface method)": [[0, "flask.sessions.SessionInterface.get_cookie_path", false]], "get_cookie_samesite() (flask.sessions.sessioninterface method)": [[0, "flask.sessions.SessionInterface.get_cookie_samesite", false]], "get_cookie_secure() (flask.sessions.sessioninterface method)": [[0, "flask.sessions.SessionInterface.get_cookie_secure", false]], "get_data() (flask.request method)": [[0, "flask.Request.get_data", false]], "get_data() (flask.response method)": [[0, "flask.Response.get_data", false]], "get_etag() (flask.response method)": [[0, "flask.Response.get_etag", false]], "get_expiration_time() (flask.sessions.sessioninterface method)": [[0, "flask.sessions.SessionInterface.get_expiration_time", false]], "get_flashed_messages() (in module flask)": [[0, "flask.get_flashed_messages", false]], "get_json() (flask.request method)": [[0, "flask.Request.get_json", false]], "get_json() (flask.response method)": [[0, "flask.Response.get_json", false]], "get_namespace() (flask.config method)": [[0, "flask.Config.get_namespace", false]], "get_send_file_max_age() (flask.blueprint method)": [[0, "flask.Blueprint.get_send_file_max_age", false]], "get_send_file_max_age() (flask.flask method)": [[0, "flask.Flask.get_send_file_max_age", false]], "get_template_attribute() (in module flask)": [[0, "flask.get_template_attribute", false]], "get_wsgi_headers() (flask.response method)": [[0, "flask.Response.get_wsgi_headers", false]], "get_wsgi_response() (flask.response method)": [[0, "flask.Response.get_wsgi_response", false]], "got_request_exception (in module flask)": [[0, "flask.got_request_exception", false]], "group() (flask.cli.appgroup method)": [[0, "flask.cli.AppGroup.group", false]], "handle_exception() (flask.flask method)": [[0, "flask.Flask.handle_exception", false]], "handle_http_exception() (flask.flask method)": [[0, "flask.Flask.handle_http_exception", false]], "handle_url_build_error() (flask.flask method)": [[0, "flask.Flask.handle_url_build_error", false]], "handle_user_exception() (flask.flask method)": [[0, "flask.Flask.handle_user_exception", false]], "has_app_context() (in module flask)": [[0, "flask.has_app_context", false]], "has_request_context() (in module flask)": [[0, "flask.has_request_context", false]], "has_static_folder (flask.blueprint property)": [[0, "flask.Blueprint.has_static_folder", false]], "has_static_folder (flask.flask property)": [[0, "flask.Flask.has_static_folder", false]], "headers (flask.request attribute)": [[0, "flask.Request.headers", false]], "host (flask.request property)": [[0, "flask.Request.host", false]], "host_url (flask.request property)": [[0, "flask.Request.host_url", false]], "if_match (flask.request property)": [[0, "flask.Request.if_match", false]], "if_modified_since (flask.request property)": [[0, "flask.Request.if_modified_since", false]], "if_none_match (flask.request property)": [[0, "flask.Request.if_none_match", false]], "if_range (flask.request property)": [[0, "flask.Request.if_range", false]], "if_unmodified_since (flask.request property)": [[0, "flask.Request.if_unmodified_since", false]], "implicit_sequence_conversion (flask.response attribute)": [[0, "flask.Response.implicit_sequence_conversion", false]], "import_name (flask.blueprint attribute)": [[0, "flask.Blueprint.import_name", false]], "import_name (flask.flask attribute)": [[0, "flask.Flask.import_name", false]], "init_every_request (flask.views.view attribute)": [[0, "flask.views.View.init_every_request", false]], "inject_url_defaults() (flask.flask method)": [[0, "flask.Flask.inject_url_defaults", false]], "input_stream (flask.request attribute)": [[0, "flask.Request.input_stream", false]], "instance_path (flask.flask attribute)": [[0, "flask.Flask.instance_path", false]], "invoke() (flask.testing.flaskclirunner method)": [[0, "flask.testing.FlaskCliRunner.invoke", false]], "is_json (flask.request property)": [[0, "flask.Request.is_json", false]], "is_json (flask.response property)": [[0, "flask.Response.is_json", false]], "is_multiprocess (flask.request attribute)": [[0, "flask.Request.is_multiprocess", false]], "is_multithread (flask.request attribute)": [[0, "flask.Request.is_multithread", false]], "is_null_session() (flask.sessions.sessioninterface method)": [[0, "flask.sessions.SessionInterface.is_null_session", false]], "is_run_once (flask.request attribute)": [[0, "flask.Request.is_run_once", false]], "is_secure (flask.request property)": [[0, "flask.Request.is_secure", false]], "is_sequence (flask.response property)": [[0, "flask.Response.is_sequence", false]], "is_streamed (flask.response property)": [[0, "flask.Response.is_streamed", false]], "iter_blueprints() (flask.flask method)": [[0, "flask.Flask.iter_blueprints", false]], "iter_encoded() (flask.response method)": [[0, "flask.Response.iter_encoded", false]], "jinja_env (flask.flask property)": [[0, "flask.Flask.jinja_env", false]], "jinja_environment (flask.flask attribute)": [[0, "flask.Flask.jinja_environment", false]], "jinja_loader (flask.blueprint property)": [[0, "flask.Blueprint.jinja_loader", false]], "jinja_loader (flask.flask property)": [[0, "flask.Flask.jinja_loader", false]], "jinja_options (flask.flask attribute)": [[0, "flask.Flask.jinja_options", false]], "json (flask.flask attribute)": [[0, "flask.Flask.json", false]], "json (flask.request property)": [[0, "flask.Request.json", false]], "json (flask.response property)": [[0, "flask.Response.json", false]], "json_provider_class (flask.flask attribute)": [[0, "flask.Flask.json_provider_class", false]], "jsonify() (in module flask.json)": [[0, "flask.json.jsonify", false]], "jsonprovider (class in flask.json.provider)": [[0, "flask.json.provider.JSONProvider", false]], "jsontag (class in flask.json.tag)": [[0, "flask.json.tag.JSONTag", false]], "key (flask.json.tag.jsontag attribute)": [[0, "flask.json.tag.JSONTag.key", false]], "key_derivation (flask.sessions.securecookiesessioninterface attribute)": [[0, "flask.sessions.SecureCookieSessionInterface.key_derivation", false]], "last_modified (flask.response attribute)": [[0, "flask.Response.last_modified", false]], "list_commands() (flask.cli.flaskgroup method)": [[0, "flask.cli.FlaskGroup.list_commands", false]], "list_storage_class (flask.request attribute)": [[0, "flask.Request.list_storage_class", false]], "load() (flask.json.provider.jsonprovider method)": [[0, "flask.json.provider.JSONProvider.load", false]], "load() (in module flask.json)": [[0, "flask.json.load", false]], "load_app() (flask.cli.scriptinfo method)": [[0, "flask.cli.ScriptInfo.load_app", false]], "load_dotenv() (in module flask.cli)": [[0, "flask.cli.load_dotenv", false]], "load_dotenv_defaults (flask.cli.scriptinfo attribute)": [[0, "flask.cli.ScriptInfo.load_dotenv_defaults", false]], "loads() (flask.json.provider.defaultjsonprovider method)": [[0, "flask.json.provider.DefaultJSONProvider.loads", false]], "loads() (flask.json.provider.jsonprovider method)": [[0, "flask.json.provider.JSONProvider.loads", false]], "loads() (flask.json.tag.taggedjsonserializer method)": [[0, "flask.json.tag.TaggedJSONSerializer.loads", false]], "loads() (in module flask.json)": [[0, "flask.json.loads", false]], "location (flask.response attribute)": [[0, "flask.Response.location", false]], "log_exception() (flask.flask method)": [[0, "flask.Flask.log_exception", false]], "logger (flask.flask property)": [[0, "flask.Flask.logger", false]], "make_aborter() (flask.flask method)": [[0, "flask.Flask.make_aborter", false]], "make_conditional() (flask.response method)": [[0, "flask.Response.make_conditional", false]], "make_config() (flask.flask method)": [[0, "flask.Flask.make_config", false]], "make_context() (flask.cli.flaskgroup method)": [[0, "flask.cli.FlaskGroup.make_context", false]], "make_default_options_response() (flask.flask method)": [[0, "flask.Flask.make_default_options_response", false]], "make_form_data_parser() (flask.request method)": [[0, "flask.Request.make_form_data_parser", false]], "make_null_session() (flask.sessions.sessioninterface method)": [[0, "flask.sessions.SessionInterface.make_null_session", false]], "make_response() (flask.flask method)": [[0, "flask.Flask.make_response", false]], "make_response() (in module flask)": [[0, "flask.make_response", false]], "make_sequence() (flask.response method)": [[0, "flask.Response.make_sequence", false]], "make_setup_state() (flask.blueprint method)": [[0, "flask.Blueprint.make_setup_state", false]], "make_shell_context() (flask.flask method)": [[0, "flask.Flask.make_shell_context", false]], "match_request() (flask.ctx.requestcontext method)": [[0, "flask.ctx.RequestContext.match_request", false]], "max_content_length (built-in variable)": [[6, "MAX_CONTENT_LENGTH", false]], "max_content_length (flask.request property)": [[0, "flask.Request.max_content_length", false]], "max_cookie_size (built-in variable)": [[6, "MAX_COOKIE_SIZE", false]], "max_cookie_size (flask.response property)": [[0, "flask.Response.max_cookie_size", false]], "max_form_memory_size (built-in variable)": [[6, "MAX_FORM_MEMORY_SIZE", false]], "max_form_memory_size (flask.request property)": [[0, "flask.Request.max_form_memory_size", false]], "max_form_parts (built-in variable)": [[6, "MAX_FORM_PARTS", false]], "max_form_parts (flask.request property)": [[0, "flask.Request.max_form_parts", false]], "max_forwards (flask.request attribute)": [[0, "flask.Request.max_forwards", false]], "message_flashed (in module flask)": [[0, "flask.message_flashed", false]], "method (flask.request attribute)": [[0, "flask.Request.method", false]], "methods (flask.views.view attribute)": [[0, "flask.views.View.methods", false]], "methodview (class in flask.views)": [[0, "flask.views.MethodView", false]], "mimetype (flask.json.provider.defaultjsonprovider attribute)": [[0, "flask.json.provider.DefaultJSONProvider.mimetype", false]], "mimetype (flask.request property)": [[0, "flask.Request.mimetype", false]], "mimetype (flask.response property)": [[0, "flask.Response.mimetype", false]], "mimetype_params (flask.request property)": [[0, "flask.Request.mimetype_params", false]], "mimetype_params (flask.response property)": [[0, "flask.Response.mimetype_params", false]], "modified (flask.session attribute)": [[0, "flask.session.modified", false]], "modified (flask.sessions.securecookiesession attribute)": [[0, "flask.sessions.SecureCookieSession.modified", false]], "modified (flask.sessions.sessionmixin attribute)": [[0, "flask.sessions.SessionMixin.modified", false]], "module": [[0, "module-flask", false], [0, "module-flask.json", false], [0, "module-flask.json.tag", false]], "name (flask.flask property)": [[0, "flask.Flask.name", false]], "new (flask.session attribute)": [[0, "flask.session.new", false]], "null_session_class (flask.sessions.sessioninterface attribute)": [[0, "flask.sessions.SessionInterface.null_session_class", false]], "nullsession (class in flask.sessions)": [[0, "flask.sessions.NullSession", false]], "on_json_loading_failed() (flask.request method)": [[0, "flask.Request.on_json_loading_failed", false]], "open() (flask.testing.flaskclient method)": [[0, "flask.testing.FlaskClient.open", false]], "open_instance_resource() (flask.flask method)": [[0, "flask.Flask.open_instance_resource", false]], "open_resource() (flask.blueprint method)": [[0, "flask.Blueprint.open_resource", false]], "open_resource() (flask.flask method)": [[0, "flask.Flask.open_resource", false]], "open_session() (flask.sessions.securecookiesessioninterface method)": [[0, "flask.sessions.SecureCookieSessionInterface.open_session", false]], "open_session() (flask.sessions.sessioninterface method)": [[0, "flask.sessions.SessionInterface.open_session", false]], "options (flask.blueprints.blueprintsetupstate attribute)": [[0, "flask.blueprints.BlueprintSetupState.options", false]], "origin (flask.request attribute)": [[0, "flask.Request.origin", false]], "parameter_storage_class (flask.request attribute)": [[0, "flask.Request.parameter_storage_class", false]], "parse_args() (flask.cli.flaskgroup method)": [[0, "flask.cli.FlaskGroup.parse_args", false]], "pass_script_info() (in module flask.cli)": [[0, "flask.cli.pass_script_info", false]], "patch() (flask.blueprint method)": [[0, "flask.Blueprint.patch", false]], "patch() (flask.flask method)": [[0, "flask.Flask.patch", false]], "path (flask.request attribute)": [[0, "flask.Request.path", false]], "pep 302": [[4, "index-5", false]], "pep 3333": [[4, "index-2", false], [27, "index-0", false]], "pep 451": [[4, "index-1", false]], "pep 519": [[4, "index-0", false]], "permanent (flask.session attribute)": [[0, "flask.session.permanent", false]], "permanent (flask.sessions.sessionmixin property)": [[0, "flask.sessions.SessionMixin.permanent", false]], "permanent_session_lifetime (built-in variable)": [[6, "PERMANENT_SESSION_LIFETIME", false]], "permanent_session_lifetime (flask.flask attribute)": [[0, "flask.Flask.permanent_session_lifetime", false]], "pickle_based (flask.sessions.sessioninterface attribute)": [[0, "flask.sessions.SessionInterface.pickle_based", false]], "pop() (flask.ctx._appctxglobals method)": [[0, "flask.ctx._AppCtxGlobals.pop", false]], "pop() (flask.ctx.appcontext method)": [[0, "flask.ctx.AppContext.pop", false]], "pop() (flask.ctx.requestcontext method)": [[0, "flask.ctx.RequestContext.pop", false]], "pop() (flask.sessions.nullsession method)": [[0, "flask.sessions.NullSession.pop", false]], "popitem() (flask.sessions.nullsession method)": [[0, "flask.sessions.NullSession.popitem", false]], "post() (flask.blueprint method)": [[0, "flask.Blueprint.post", false]], "post() (flask.flask method)": [[0, "flask.Flask.post", false]], "pragma (flask.request property)": [[0, "flask.Request.pragma", false]], "preferred_url_scheme (built-in variable)": [[6, "PREFERRED_URL_SCHEME", false]], "preprocess_request() (flask.flask method)": [[0, "flask.Flask.preprocess_request", false]], "process_response() (flask.flask method)": [[0, "flask.Flask.process_response", false]], "propagate_exceptions (built-in variable)": [[6, "PROPAGATE_EXCEPTIONS", false]], "provide_automatic_options (built-in variable)": [[6, "PROVIDE_AUTOMATIC_OPTIONS", false]], "provide_automatic_options (flask.views.view attribute)": [[0, "flask.views.View.provide_automatic_options", false]], "push() (flask.ctx.appcontext method)": [[0, "flask.ctx.AppContext.push", false]], "put() (flask.blueprint method)": [[0, "flask.Blueprint.put", false]], "put() (flask.flask method)": [[0, "flask.Flask.put", false]], "python enhancement proposals": [[4, "index-0", false], [4, "index-1", false], [4, "index-2", false], [4, "index-5", false], [27, "index-0", false]], "query_string (flask.request attribute)": [[0, "flask.Request.query_string", false]], "range (flask.request property)": [[0, "flask.Request.range", false]], "record() (flask.blueprint method)": [[0, "flask.Blueprint.record", false]], "record_once() (flask.blueprint method)": [[0, "flask.Blueprint.record_once", false]], "redirect() (flask.flask method)": [[0, "flask.Flask.redirect", false]], "redirect() (in module flask)": [[0, "flask.redirect", false]], "referrer (flask.request attribute)": [[0, "flask.Request.referrer", false]], "register() (flask.blueprint method)": [[0, "flask.Blueprint.register", false]], "register() (flask.json.tag.taggedjsonserializer method)": [[0, "flask.json.tag.TaggedJSONSerializer.register", false]], "register_blueprint() (flask.blueprint method)": [[0, "flask.Blueprint.register_blueprint", false]], "register_blueprint() (flask.flask method)": [[0, "flask.Flask.register_blueprint", false]], "register_error_handler() (flask.blueprint method)": [[0, "flask.Blueprint.register_error_handler", false]], "register_error_handler() (flask.flask method)": [[0, "flask.Flask.register_error_handler", false]], "remote_addr (flask.request attribute)": [[0, "flask.Request.remote_addr", false]], "remote_user (flask.request attribute)": [[0, "flask.Request.remote_user", false]], "render_template() (in module flask)": [[0, "flask.render_template", false]], "render_template_string() (in module flask)": [[0, "flask.render_template_string", false]], "request (class in flask)": [[0, "flask.Request", false]], "request (in module flask)": [[0, "flask.request", false]], "request_class (flask.flask attribute)": [[0, "flask.Flask.request_class", false]], "request_context() (flask.flask method)": [[0, "flask.Flask.request_context", false]], "request_finished (in module flask)": [[0, "flask.request_finished", false]], "request_started (in module flask)": [[0, "flask.request_started", false]], "request_tearing_down (in module flask)": [[0, "flask.request_tearing_down", false]], "requestcontext (class in flask.ctx)": [[0, "flask.ctx.RequestContext", false]], "response (class in flask)": [[0, "flask.Response", false]], "response (flask.response attribute)": [[0, "flask.Response.response", false]], "response() (flask.json.provider.defaultjsonprovider method)": [[0, "flask.json.provider.DefaultJSONProvider.response", false]], "response() (flask.json.provider.jsonprovider method)": [[0, "flask.json.provider.JSONProvider.response", false]], "response_class (flask.flask attribute)": [[0, "flask.Flask.response_class", false]], "retry_after (flask.response property)": [[0, "flask.Response.retry_after", false]], "rfc": [[0, "index-1", false], [0, "index-2", false], [4, "index-3", false], [4, "index-4", false]], "rfc 2231": [[0, "index-1", false]], "rfc 822": [[0, "index-2", false]], "rfc 8259": [[4, "index-3", false], [4, "index-4", false]], "root_path (flask.blueprint attribute)": [[0, "flask.Blueprint.root_path", false]], "root_path (flask.flask attribute)": [[0, "flask.Flask.root_path", false]], "root_path (flask.request attribute)": [[0, "flask.Request.root_path", false]], "root_url (flask.request property)": [[0, "flask.Request.root_url", false]], "route() (flask.blueprint method)": [[0, "flask.Blueprint.route", false]], "route() (flask.flask method)": [[0, "flask.Flask.route", false]], "routing_exception (flask.request attribute)": [[0, "flask.Request.routing_exception", false]], "run() (flask.flask method)": [[0, "flask.Flask.run", false]], "run_command (in module flask.cli)": [[0, "flask.cli.run_command", false]], "salt (flask.sessions.securecookiesessioninterface attribute)": [[0, "flask.sessions.SecureCookieSessionInterface.salt", false]], "save_session() (flask.sessions.securecookiesessioninterface method)": [[0, "flask.sessions.SecureCookieSessionInterface.save_session", false]], "save_session() (flask.sessions.sessioninterface method)": [[0, "flask.sessions.SessionInterface.save_session", false]], "scheme (flask.request attribute)": [[0, "flask.Request.scheme", false]], "script_root (flask.request property)": [[0, "flask.Request.script_root", false]], "scriptinfo (class in flask.cli)": [[0, "flask.cli.ScriptInfo", false]], "secret_key (built-in variable)": [[6, "SECRET_KEY", false]], "secret_key (flask.flask attribute)": [[0, "flask.Flask.secret_key", false]], "secret_key_fallbacks (built-in variable)": [[6, "SECRET_KEY_FALLBACKS", false]], "securecookiesession (class in flask.sessions)": [[0, "flask.sessions.SecureCookieSession", false]], "securecookiesessioninterface (class in flask.sessions)": [[0, "flask.sessions.SecureCookieSessionInterface", false]], "select_jinja_autoescape() (flask.flask method)": [[0, "flask.Flask.select_jinja_autoescape", false]], "send_file() (in module flask)": [[0, "flask.send_file", false]], "send_file_max_age_default (built-in variable)": [[6, "SEND_FILE_MAX_AGE_DEFAULT", false]], "send_from_directory() (in module flask)": [[0, "flask.send_from_directory", false]], "send_static_file() (flask.blueprint method)": [[0, "flask.Blueprint.send_static_file", false]], "send_static_file() (flask.flask method)": [[0, "flask.Flask.send_static_file", false]], "serializer (flask.sessions.securecookiesessioninterface attribute)": [[0, "flask.sessions.SecureCookieSessionInterface.serializer", false]], "server (flask.request attribute)": [[0, "flask.Request.server", false]], "server_name (built-in variable)": [[6, "SERVER_NAME", false]], "session (class in flask)": [[0, "flask.session", false]], "session_class (flask.sessions.securecookiesessioninterface attribute)": [[0, "flask.sessions.SecureCookieSessionInterface.session_class", false]], "session_cookie_domain (built-in variable)": [[6, "SESSION_COOKIE_DOMAIN", false]], "session_cookie_httponly (built-in variable)": [[6, "SESSION_COOKIE_HTTPONLY", false]], "session_cookie_name (built-in variable)": [[6, "SESSION_COOKIE_NAME", false]], "session_cookie_partitioned (built-in variable)": [[6, "SESSION_COOKIE_PARTITIONED", false]], "session_cookie_path (built-in variable)": [[6, "SESSION_COOKIE_PATH", false]], "session_cookie_samesite (built-in variable)": [[6, "SESSION_COOKIE_SAMESITE", false]], "session_cookie_secure (built-in variable)": [[6, "SESSION_COOKIE_SECURE", false]], "session_interface (flask.flask attribute)": [[0, "flask.Flask.session_interface", false]], "session_refresh_each_request (built-in variable)": [[6, "SESSION_REFRESH_EACH_REQUEST", false]], "session_transaction() (flask.testing.flaskclient method)": [[0, "flask.testing.FlaskClient.session_transaction", false]], "sessioninterface (class in flask.sessions)": [[0, "flask.sessions.SessionInterface", false]], "sessionmixin (class in flask.sessions)": [[0, "flask.sessions.SessionMixin", false]], "set_cookie() (flask.response method)": [[0, "flask.Response.set_cookie", false]], "set_data() (flask.response method)": [[0, "flask.Response.set_data", false]], "set_etag() (flask.response method)": [[0, "flask.Response.set_etag", false]], "setdefault() (flask.ctx._appctxglobals method)": [[0, "flask.ctx._AppCtxGlobals.setdefault", false]], "setdefault() (flask.sessions.nullsession method)": [[0, "flask.sessions.NullSession.setdefault", false]], "setdefault() (flask.sessions.securecookiesession method)": [[0, "flask.sessions.SecureCookieSession.setdefault", false]], "shallow (flask.request attribute)": [[0, "flask.Request.shallow", false]], "shell_command (in module flask.cli)": [[0, "flask.cli.shell_command", false]], "shell_context_processor() (flask.flask method)": [[0, "flask.Flask.shell_context_processor", false]], "shell_context_processors (flask.flask attribute)": [[0, "flask.Flask.shell_context_processors", false]], "should_ignore_error() (flask.flask method)": [[0, "flask.Flask.should_ignore_error", false]], "should_set_cookie() (flask.sessions.sessioninterface method)": [[0, "flask.sessions.SessionInterface.should_set_cookie", false]], "sort_keys (flask.json.provider.defaultjsonprovider attribute)": [[0, "flask.json.provider.DefaultJSONProvider.sort_keys", false]], "static_folder (flask.blueprint property)": [[0, "flask.Blueprint.static_folder", false]], "static_folder (flask.flask property)": [[0, "flask.Flask.static_folder", false]], "static_url_path (flask.blueprint property)": [[0, "flask.Blueprint.static_url_path", false]], "static_url_path (flask.flask property)": [[0, "flask.Flask.static_url_path", false]], "status (flask.response property)": [[0, "flask.Response.status", false]], "status_code (flask.response property)": [[0, "flask.Response.status_code", false]], "stream (flask.request property)": [[0, "flask.Request.stream", false]], "stream (flask.response property)": [[0, "flask.Response.stream", false]], "stream_template() (in module flask)": [[0, "flask.stream_template", false]], "stream_template_string() (in module flask)": [[0, "flask.stream_template_string", false]], "stream_with_context() (in module flask)": [[0, "flask.stream_with_context", false]], "subdomain (flask.blueprints.blueprintsetupstate attribute)": [[0, "flask.blueprints.BlueprintSetupState.subdomain", false]], "tag() (flask.json.tag.jsontag method)": [[0, "flask.json.tag.JSONTag.tag", false]], "tag() (flask.json.tag.taggedjsonserializer method)": [[0, "flask.json.tag.TaggedJSONSerializer.tag", false]], "taggedjsonserializer (class in flask.json.tag)": [[0, "flask.json.tag.TaggedJSONSerializer", false]], "teardown_app_request() (flask.blueprint method)": [[0, "flask.Blueprint.teardown_app_request", false]], "teardown_appcontext() (flask.flask method)": [[0, "flask.Flask.teardown_appcontext", false]], "teardown_appcontext_funcs (flask.flask attribute)": [[0, "flask.Flask.teardown_appcontext_funcs", false]], "teardown_request() (flask.blueprint method)": [[0, "flask.Blueprint.teardown_request", false]], "teardown_request() (flask.flask method)": [[0, "flask.Flask.teardown_request", false]], "teardown_request_funcs (flask.blueprint attribute)": [[0, "flask.Blueprint.teardown_request_funcs", false]], "teardown_request_funcs (flask.flask attribute)": [[0, "flask.Flask.teardown_request_funcs", false]], "template_context_processors (flask.blueprint attribute)": [[0, "flask.Blueprint.template_context_processors", false]], "template_context_processors (flask.flask attribute)": [[0, "flask.Flask.template_context_processors", false]], "template_filter() (flask.flask method)": [[0, "flask.Flask.template_filter", false]], "template_folder (flask.blueprint attribute)": [[0, "flask.Blueprint.template_folder", false]], "template_folder (flask.flask attribute)": [[0, "flask.Flask.template_folder", false]], "template_global() (flask.flask method)": [[0, "flask.Flask.template_global", false]], "template_rendered (in module flask)": [[0, "flask.template_rendered", false]], "template_test() (flask.flask method)": [[0, "flask.Flask.template_test", false]], "templates_auto_reload (built-in variable)": [[6, "TEMPLATES_AUTO_RELOAD", false]], "test_cli_runner() (flask.flask method)": [[0, "flask.Flask.test_cli_runner", false]], "test_cli_runner_class (flask.flask attribute)": [[0, "flask.Flask.test_cli_runner_class", false]], "test_client() (flask.flask method)": [[0, "flask.Flask.test_client", false]], "test_client_class (flask.flask attribute)": [[0, "flask.Flask.test_client_class", false]], "test_request_context() (flask.flask method)": [[0, "flask.Flask.test_request_context", false]], "testing (built-in variable)": [[6, "TESTING", false]], "testing (flask.flask attribute)": [[0, "flask.Flask.testing", false]], "to_json() (flask.json.tag.jsontag method)": [[0, "flask.json.tag.JSONTag.to_json", false]], "to_python() (flask.json.tag.jsontag method)": [[0, "flask.json.tag.JSONTag.to_python", false]], "trap_bad_request_errors (built-in variable)": [[6, "TRAP_BAD_REQUEST_ERRORS", false]], "trap_http_exception() (flask.flask method)": [[0, "flask.Flask.trap_http_exception", false]], "trap_http_exceptions (built-in variable)": [[6, "TRAP_HTTP_EXCEPTIONS", false]], "trusted_hosts (built-in variable)": [[6, "TRUSTED_HOSTS", false]], "trusted_hosts (flask.request attribute)": [[0, "flask.Request.trusted_hosts", false]], "untag() (flask.json.tag.taggedjsonserializer method)": [[0, "flask.json.tag.TaggedJSONSerializer.untag", false]], "update() (flask.sessions.nullsession method)": [[0, "flask.sessions.NullSession.update", false]], "update_template_context() (flask.flask method)": [[0, "flask.Flask.update_template_context", false]], "url (flask.request property)": [[0, "flask.Request.url", false]], "url_build_error_handlers (flask.flask attribute)": [[0, "flask.Flask.url_build_error_handlers", false]], "url_default_functions (flask.blueprint attribute)": [[0, "flask.Blueprint.url_default_functions", false]], "url_default_functions (flask.flask attribute)": [[0, "flask.Flask.url_default_functions", false]], "url_defaults (flask.blueprints.blueprintsetupstate attribute)": [[0, "flask.blueprints.BlueprintSetupState.url_defaults", false]], "url_defaults() (flask.blueprint method)": [[0, "flask.Blueprint.url_defaults", false]], "url_defaults() (flask.flask method)": [[0, "flask.Flask.url_defaults", false]], "url_for() (flask.flask method)": [[0, "flask.Flask.url_for", false]], "url_for() (in module flask)": [[0, "flask.url_for", false]], "url_map (flask.flask attribute)": [[0, "flask.Flask.url_map", false]], "url_map_class (flask.flask attribute)": [[0, "flask.Flask.url_map_class", false]], "url_prefix (flask.blueprints.blueprintsetupstate attribute)": [[0, "flask.blueprints.BlueprintSetupState.url_prefix", false]], "url_root (flask.request property)": [[0, "flask.Request.url_root", false]], "url_rule (flask.request attribute)": [[0, "flask.Request.url_rule", false]], "url_rule_class (flask.flask attribute)": [[0, "flask.Flask.url_rule_class", false]], "url_value_preprocessor() (flask.blueprint method)": [[0, "flask.Blueprint.url_value_preprocessor", false]], "url_value_preprocessor() (flask.flask method)": [[0, "flask.Flask.url_value_preprocessor", false]], "url_value_preprocessors (flask.blueprint attribute)": [[0, "flask.Blueprint.url_value_preprocessors", false]], "url_value_preprocessors (flask.flask attribute)": [[0, "flask.Flask.url_value_preprocessors", false]], "use_x_sendfile (built-in variable)": [[6, "USE_X_SENDFILE", false]], "user_agent (flask.request property)": [[0, "flask.Request.user_agent", false]], "user_agent_class (flask.request attribute)": [[0, "flask.Request.user_agent_class", false]], "values (flask.request property)": [[0, "flask.Request.values", false]], "vary (flask.response property)": [[0, "flask.Response.vary", false]], "view (class in flask.views)": [[0, "flask.views.View", false]], "view_args (flask.request attribute)": [[0, "flask.Request.view_args", false]], "view_functions (flask.blueprint attribute)": [[0, "flask.Blueprint.view_functions", false]], "view_functions (flask.flask attribute)": [[0, "flask.Flask.view_functions", false]], "want_form_data_parsed (flask.request property)": [[0, "flask.Request.want_form_data_parsed", false]], "with_appcontext() (in module flask.cli)": [[0, "flask.cli.with_appcontext", false]], "wsgi_app() (flask.flask method)": [[0, "flask.Flask.wsgi_app", false]], "www_authenticate (flask.response property)": [[0, "flask.Response.www_authenticate", false]], "yourapplication_settings": [[6, "index-1", false]]}, "objects": {"": [[6, 0, 1, "", "APPLICATION_ROOT"], [6, 0, 1, "", "DEBUG"], [6, 0, 1, "", "EXPLAIN_TEMPLATE_LOADING"], [6, 0, 1, "", "MAX_CONTENT_LENGTH"], [6, 0, 1, "", "MAX_COOKIE_SIZE"], [6, 0, 1, "", "MAX_FORM_MEMORY_SIZE"], [6, 0, 1, "", "MAX_FORM_PARTS"], [6, 0, 1, "", "PERMANENT_SESSION_LIFETIME"], [6, 0, 1, "", "PREFERRED_URL_SCHEME"], [6, 0, 1, "", "PROPAGATE_EXCEPTIONS"], [6, 0, 1, "", "PROVIDE_AUTOMATIC_OPTIONS"], [6, 0, 1, "", "SECRET_KEY"], [6, 0, 1, "", "SECRET_KEY_FALLBACKS"], [6, 0, 1, "", "SEND_FILE_MAX_AGE_DEFAULT"], [6, 0, 1, "", "SERVER_NAME"], [6, 0, 1, "", "SESSION_COOKIE_DOMAIN"], [6, 0, 1, "", "SESSION_COOKIE_HTTPONLY"], [6, 0, 1, "", "SESSION_COOKIE_NAME"], [6, 0, 1, "", "SESSION_COOKIE_PARTITIONED"], [6, 0, 1, "", "SESSION_COOKIE_PATH"], [6, 0, 1, "", "SESSION_COOKIE_SAMESITE"], [6, 0, 1, "", "SESSION_COOKIE_SECURE"], [6, 0, 1, "", "SESSION_REFRESH_EACH_REQUEST"], [6, 0, 1, "", "TEMPLATES_AUTO_RELOAD"], [6, 0, 1, "", "TESTING"], [6, 0, 1, "", "TRAP_BAD_REQUEST_ERRORS"], [6, 0, 1, "", "TRAP_HTTP_EXCEPTIONS"], [6, 0, 1, "", "TRUSTED_HOSTS"], [6, 0, 1, "", "USE_X_SENDFILE"], [0, 1, 0, "-", "flask"]], "flask": [[0, 2, 1, "", "Blueprint"], [0, 2, 1, "", "Config"], [0, 2, 1, "", "Flask"], [0, 2, 1, "", "Request"], [0, 2, 1, "", "Response"], [0, 6, 1, "", "abort"], [0, 6, 1, "", "after_this_request"], [0, 0, 1, "", "appcontext_popped"], [0, 0, 1, "", "appcontext_pushed"], [0, 0, 1, "", "appcontext_tearing_down"], [0, 6, 1, "", "copy_current_request_context"], [0, 0, 1, "", "current_app"], [0, 6, 1, "", "flash"], [0, 0, 1, "", "g"], [0, 6, 1, "", "get_flashed_messages"], [0, 6, 1, "", "get_template_attribute"], [0, 0, 1, "", "got_request_exception"], [0, 6, 1, "", "has_app_context"], [0, 6, 1, "", "has_request_context"], [0, 1, 0, "-", "json"], [0, 6, 1, "", "make_response"], [0, 0, 1, "", "message_flashed"], [0, 6, 1, "", "redirect"], [0, 6, 1, "", "render_template"], [0, 6, 1, "", "render_template_string"], [0, 4, 1, "", "request"], [0, 0, 1, "", "request_finished"], [0, 0, 1, "", "request_started"], [0, 0, 1, "", "request_tearing_down"], [0, 6, 1, "", "send_file"], [0, 6, 1, "", "send_from_directory"], [0, 2, 1, "", "session"], [0, 6, 1, "", "stream_template"], [0, 6, 1, "", "stream_template_string"], [0, 6, 1, "", "stream_with_context"], [0, 0, 1, "", "template_rendered"], [0, 6, 1, "", "url_for"]], "flask.Blueprint": [[0, 3, 1, "", "add_app_template_filter"], [0, 3, 1, "", "add_app_template_global"], [0, 3, 1, "", "add_app_template_test"], [0, 3, 1, "", "add_url_rule"], [0, 3, 1, "", "after_app_request"], [0, 3, 1, "", "after_request"], [0, 4, 1, "", "after_request_funcs"], [0, 3, 1, "", "app_context_processor"], [0, 3, 1, "", "app_errorhandler"], [0, 3, 1, "", "app_template_filter"], [0, 3, 1, "", "app_template_global"], [0, 3, 1, "", "app_template_test"], [0, 3, 1, "", "app_url_defaults"], [0, 3, 1, "", "app_url_value_preprocessor"], [0, 3, 1, "", "before_app_request"], [0, 3, 1, "", "before_request"], [0, 4, 1, "", "before_request_funcs"], [0, 4, 1, "", "cli"], [0, 3, 1, "", "context_processor"], [0, 3, 1, "", "delete"], [0, 3, 1, "", "endpoint"], [0, 4, 1, "", "error_handler_spec"], [0, 3, 1, "", "errorhandler"], [0, 3, 1, "", "get"], [0, 3, 1, "", "get_send_file_max_age"], [0, 5, 1, "", "has_static_folder"], [0, 4, 1, "", "import_name"], [0, 5, 1, "", "jinja_loader"], [0, 3, 1, "", "make_setup_state"], [0, 3, 1, "", "open_resource"], [0, 3, 1, "", "patch"], [0, 3, 1, "", "post"], [0, 3, 1, "", "put"], [0, 3, 1, "", "record"], [0, 3, 1, "", "record_once"], [0, 3, 1, "", "register"], [0, 3, 1, "", "register_blueprint"], [0, 3, 1, "", "register_error_handler"], [0, 4, 1, "", "root_path"], [0, 3, 1, "", "route"], [0, 3, 1, "", "send_static_file"], [0, 5, 1, "", "static_folder"], [0, 5, 1, "", "static_url_path"], [0, 3, 1, "", "teardown_app_request"], [0, 3, 1, "", "teardown_request"], [0, 4, 1, "", "teardown_request_funcs"], [0, 4, 1, "", "template_context_processors"], [0, 4, 1, "", "template_folder"], [0, 4, 1, "", "url_default_functions"], [0, 3, 1, "", "url_defaults"], [0, 3, 1, "", "url_value_preprocessor"], [0, 4, 1, "", "url_value_preprocessors"], [0, 4, 1, "", "view_functions"]], "flask.Config": [[0, 3, 1, "", "from_envvar"], [0, 3, 1, "", "from_file"], [0, 3, 1, "", "from_mapping"], [0, 3, 1, "", "from_object"], [0, 3, 1, "", "from_prefixed_env"], [0, 3, 1, "", "from_pyfile"], [0, 3, 1, "", "get_namespace"]], "flask.Flask": [[0, 4, 1, "", "aborter"], [0, 4, 1, "", "aborter_class"], [0, 3, 1, "", "add_template_filter"], [0, 3, 1, "", "add_template_global"], [0, 3, 1, "", "add_template_test"], [0, 3, 1, "", "add_url_rule"], [0, 3, 1, "", "after_request"], [0, 4, 1, "", "after_request_funcs"], [0, 3, 1, "", "app_context"], [0, 4, 1, "", "app_ctx_globals_class"], [0, 3, 1, "", "async_to_sync"], [0, 3, 1, "", "auto_find_instance_path"], [0, 3, 1, "", "before_request"], [0, 4, 1, "", "before_request_funcs"], [0, 4, 1, "", "blueprints"], [0, 4, 1, "", "cli"], [0, 4, 1, "", "config"], [0, 4, 1, "", "config_class"], [0, 3, 1, "", "context_processor"], [0, 3, 1, "", "create_global_jinja_loader"], [0, 3, 1, "", "create_jinja_environment"], [0, 3, 1, "", "create_url_adapter"], [0, 5, 1, "", "debug"], [0, 3, 1, "", "delete"], [0, 3, 1, "", "dispatch_request"], [0, 3, 1, "", "do_teardown_appcontext"], [0, 3, 1, "", "do_teardown_request"], [0, 3, 1, "", "endpoint"], [0, 3, 1, "", "ensure_sync"], [0, 4, 1, "", "error_handler_spec"], [0, 3, 1, "", "errorhandler"], [0, 4, 1, "", "extensions"], [0, 3, 1, "", "full_dispatch_request"], [0, 3, 1, "", "get"], [0, 3, 1, "", "get_send_file_max_age"], [0, 3, 1, "", "handle_exception"], [0, 3, 1, "", "handle_http_exception"], [0, 3, 1, "", "handle_url_build_error"], [0, 3, 1, "", "handle_user_exception"], [0, 5, 1, "", "has_static_folder"], [0, 4, 1, "", "import_name"], [0, 3, 1, "", "inject_url_defaults"], [0, 4, 1, "", "instance_path"], [0, 3, 1, "", "iter_blueprints"], [0, 5, 1, "", "jinja_env"], [0, 4, 1, "", "jinja_environment"], [0, 5, 1, "", "jinja_loader"], [0, 4, 1, "", "jinja_options"], [0, 4, 1, "", "json"], [0, 4, 1, "", "json_provider_class"], [0, 3, 1, "", "log_exception"], [0, 5, 1, "", "logger"], [0, 3, 1, "", "make_aborter"], [0, 3, 1, "", "make_config"], [0, 3, 1, "", "make_default_options_response"], [0, 3, 1, "", "make_response"], [0, 3, 1, "", "make_shell_context"], [0, 5, 1, "", "name"], [0, 3, 1, "", "open_instance_resource"], [0, 3, 1, "", "open_resource"], [0, 3, 1, "", "patch"], [0, 4, 1, "", "permanent_session_lifetime"], [0, 3, 1, "", "post"], [0, 3, 1, "", "preprocess_request"], [0, 3, 1, "", "process_response"], [0, 3, 1, "", "put"], [0, 3, 1, "", "redirect"], [0, 3, 1, "", "register_blueprint"], [0, 3, 1, "", "register_error_handler"], [0, 4, 1, "", "request_class"], [0, 3, 1, "", "request_context"], [0, 4, 1, "", "response_class"], [0, 4, 1, "", "root_path"], [0, 3, 1, "", "route"], [0, 3, 1, "", "run"], [0, 4, 1, "", "secret_key"], [0, 3, 1, "", "select_jinja_autoescape"], [0, 3, 1, "", "send_static_file"], [0, 4, 1, "", "session_interface"], [0, 3, 1, "", "shell_context_processor"], [0, 4, 1, "", "shell_context_processors"], [0, 3, 1, "", "should_ignore_error"], [0, 5, 1, "", "static_folder"], [0, 5, 1, "", "static_url_path"], [0, 3, 1, "", "teardown_appcontext"], [0, 4, 1, "", "teardown_appcontext_funcs"], [0, 3, 1, "", "teardown_request"], [0, 4, 1, "", "teardown_request_funcs"], [0, 4, 1, "", "template_context_processors"], [0, 3, 1, "", "template_filter"], [0, 4, 1, "", "template_folder"], [0, 3, 1, "", "template_global"], [0, 3, 1, "", "template_test"], [0, 3, 1, "", "test_cli_runner"], [0, 4, 1, "", "test_cli_runner_class"], [0, 3, 1, "", "test_client"], [0, 4, 1, "", "test_client_class"], [0, 3, 1, "", "test_request_context"], [0, 4, 1, "", "testing"], [0, 3, 1, "", "trap_http_exception"], [0, 3, 1, "", "update_template_context"], [0, 4, 1, "", "url_build_error_handlers"], [0, 4, 1, "", "url_default_functions"], [0, 3, 1, "", "url_defaults"], [0, 3, 1, "", "url_for"], [0, 4, 1, "", "url_map"], [0, 4, 1, "", "url_map_class"], [0, 4, 1, "", "url_rule_class"], [0, 3, 1, "", "url_value_preprocessor"], [0, 4, 1, "", "url_value_preprocessors"], [0, 4, 1, "", "view_functions"], [0, 3, 1, "", "wsgi_app"]], "flask.Request": [[0, 5, 1, "", "accept_charsets"], [0, 5, 1, "", "accept_encodings"], [0, 5, 1, "", "accept_languages"], [0, 5, 1, "", "accept_mimetypes"], [0, 4, 1, "", "access_control_request_headers"], [0, 4, 1, "", "access_control_request_method"], [0, 5, 1, "", "access_route"], [0, 3, 1, "", "application"], [0, 5, 1, "", "args"], [0, 5, 1, "", "authorization"], [0, 5, 1, "", "base_url"], [0, 5, 1, "", "blueprint"], [0, 5, 1, "", "blueprints"], [0, 5, 1, "", "cache_control"], [0, 3, 1, "", "close"], [0, 4, 1, "", "content_encoding"], [0, 5, 1, "", "content_length"], [0, 4, 1, "", "content_md5"], [0, 4, 1, "", "content_type"], [0, 5, 1, "", "cookies"], [0, 5, 1, "", "data"], [0, 4, 1, "", "date"], [0, 4, 1, "", "dict_storage_class"], [0, 5, 1, "", "endpoint"], [0, 4, 1, "", "environ"], [0, 5, 1, "", "files"], [0, 5, 1, "", "form"], [0, 4, 1, "", "form_data_parser_class"], [0, 3, 1, "", "from_values"], [0, 5, 1, "", "full_path"], [0, 3, 1, "", "get_data"], [0, 3, 1, "", "get_json"], [0, 4, 1, "", "headers"], [0, 5, 1, "", "host"], [0, 5, 1, "", "host_url"], [0, 5, 1, "", "if_match"], [0, 5, 1, "", "if_modified_since"], [0, 5, 1, "", "if_none_match"], [0, 5, 1, "", "if_range"], [0, 5, 1, "", "if_unmodified_since"], [0, 4, 1, "", "input_stream"], [0, 5, 1, "", "is_json"], [0, 4, 1, "", "is_multiprocess"], [0, 4, 1, "", "is_multithread"], [0, 4, 1, "", "is_run_once"], [0, 5, 1, "", "is_secure"], [0, 5, 1, "", "json"], [0, 4, 1, "", "list_storage_class"], [0, 3, 1, "", "make_form_data_parser"], [0, 5, 1, "", "max_content_length"], [0, 5, 1, "", "max_form_memory_size"], [0, 5, 1, "", "max_form_parts"], [0, 4, 1, "", "max_forwards"], [0, 4, 1, "", "method"], [0, 5, 1, "", "mimetype"], [0, 5, 1, "", "mimetype_params"], [0, 3, 1, "", "on_json_loading_failed"], [0, 4, 1, "", "origin"], [0, 4, 1, "", "parameter_storage_class"], [0, 4, 1, "", "path"], [0, 5, 1, "", "pragma"], [0, 4, 1, "", "query_string"], [0, 5, 1, "", "range"], [0, 4, 1, "", "referrer"], [0, 4, 1, "", "remote_addr"], [0, 4, 1, "", "remote_user"], [0, 4, 1, "", "root_path"], [0, 5, 1, "", "root_url"], [0, 4, 1, "", "routing_exception"], [0, 4, 1, "", "scheme"], [0, 5, 1, "", "script_root"], [0, 4, 1, "", "server"], [0, 4, 1, "", "shallow"], [0, 5, 1, "", "stream"], [0, 4, 1, "", "trusted_hosts"], [0, 5, 1, "", "url"], [0, 5, 1, "", "url_root"], [0, 4, 1, "", "url_rule"], [0, 5, 1, "", "user_agent"], [0, 4, 1, "", "user_agent_class"], [0, 5, 1, "", "values"], [0, 4, 1, "", "view_args"], [0, 5, 1, "", "want_form_data_parsed"]], "flask.Response": [[0, 4, 1, "", "accept_ranges"], [0, 5, 1, "", "access_control_allow_credentials"], [0, 4, 1, "", "access_control_allow_headers"], [0, 4, 1, "", "access_control_allow_methods"], [0, 4, 1, "", "access_control_allow_origin"], [0, 4, 1, "", "access_control_expose_headers"], [0, 4, 1, "", "access_control_max_age"], [0, 3, 1, "", "add_etag"], [0, 4, 1, "", "age"], [0, 5, 1, "", "allow"], [0, 4, 1, "", "autocorrect_location_header"], [0, 4, 1, "", "automatically_set_content_length"], [0, 5, 1, "", "cache_control"], [0, 3, 1, "", "calculate_content_length"], [0, 3, 1, "", "call_on_close"], [0, 3, 1, "", "close"], [0, 4, 1, "", "content_encoding"], [0, 5, 1, "", "content_language"], [0, 4, 1, "", "content_length"], [0, 4, 1, "", "content_location"], [0, 4, 1, "", "content_md5"], [0, 5, 1, "", "content_range"], [0, 5, 1, "", "content_security_policy"], [0, 5, 1, "", "content_security_policy_report_only"], [0, 4, 1, "", "content_type"], [0, 4, 1, "", "cross_origin_embedder_policy"], [0, 4, 1, "", "cross_origin_opener_policy"], [0, 5, 1, "", "data"], [0, 4, 1, "", "date"], [0, 4, 1, "", "default_mimetype"], [0, 4, 1, "", "default_status"], [0, 3, 1, "", "delete_cookie"], [0, 4, 1, "", "direct_passthrough"], [0, 4, 1, "", "expires"], [0, 3, 1, "", "force_type"], [0, 3, 1, "", "freeze"], [0, 3, 1, "", "from_app"], [0, 3, 1, "", "get_app_iter"], [0, 3, 1, "", "get_data"], [0, 3, 1, "", "get_etag"], [0, 3, 1, "", "get_json"], [0, 3, 1, "", "get_wsgi_headers"], [0, 3, 1, "", "get_wsgi_response"], [0, 4, 1, "", "implicit_sequence_conversion"], [0, 5, 1, "", "is_json"], [0, 5, 1, "", "is_sequence"], [0, 5, 1, "", "is_streamed"], [0, 3, 1, "", "iter_encoded"], [0, 5, 1, "", "json"], [0, 4, 1, "", "last_modified"], [0, 4, 1, "", "location"], [0, 3, 1, "", "make_conditional"], [0, 3, 1, "", "make_sequence"], [0, 5, 1, "", "max_cookie_size"], [0, 5, 1, "", "mimetype"], [0, 5, 1, "", "mimetype_params"], [0, 4, 1, "", "response"], [0, 5, 1, "", "retry_after"], [0, 3, 1, "", "set_cookie"], [0, 3, 1, "", "set_data"], [0, 3, 1, "", "set_etag"], [0, 5, 1, "", "status"], [0, 5, 1, "", "status_code"], [0, 5, 1, "", "stream"], [0, 5, 1, "", "vary"], [0, 5, 1, "", "www_authenticate"]], "flask.blueprints": [[0, 2, 1, "", "BlueprintSetupState"]], "flask.blueprints.BlueprintSetupState": [[0, 3, 1, "", "add_url_rule"], [0, 4, 1, "", "app"], [0, 4, 1, "", "blueprint"], [0, 4, 1, "", "first_registration"], [0, 4, 1, "", "options"], [0, 4, 1, "", "subdomain"], [0, 4, 1, "", "url_defaults"], [0, 4, 1, "", "url_prefix"]], "flask.cli": [[0, 2, 1, "", "AppGroup"], [0, 2, 1, "", "FlaskGroup"], [0, 2, 1, "", "ScriptInfo"], [0, 6, 1, "", "load_dotenv"], [0, 6, 1, "", "pass_script_info"], [0, 0, 1, "", "run_command"], [0, 0, 1, "", "shell_command"], [0, 6, 1, "", "with_appcontext"]], "flask.cli.AppGroup": [[0, 3, 1, "", "command"], [0, 3, 1, "", "group"]], "flask.cli.FlaskGroup": [[0, 3, 1, "", "get_command"], [0, 3, 1, "", "list_commands"], [0, 3, 1, "", "make_context"], [0, 3, 1, "", "parse_args"]], "flask.cli.ScriptInfo": [[0, 4, 1, "", "app_import_path"], [0, 4, 1, "", "create_app"], [0, 4, 1, "", "data"], [0, 3, 1, "", "load_app"], [0, 4, 1, "", "load_dotenv_defaults"]], "flask.ctx": [[0, 2, 1, "", "AppContext"], [0, 2, 1, "", "RequestContext"], [0, 2, 1, "", "_AppCtxGlobals"]], "flask.ctx.AppContext": [[0, 3, 1, "", "pop"], [0, 3, 1, "", "push"]], "flask.ctx.RequestContext": [[0, 3, 1, "", "copy"], [0, 3, 1, "", "match_request"], [0, 3, 1, "", "pop"]], "flask.ctx._AppCtxGlobals": [[0, 3, 1, "", "get"], [0, 3, 1, "", "pop"], [0, 3, 1, "", "setdefault"]], "flask.flask.globals": [[0, 0, 1, "", "app_ctx"], [0, 0, 1, "", "request_ctx"]], "flask.json": [[0, 6, 1, "", "dump"], [0, 6, 1, "", "dumps"], [0, 6, 1, "", "jsonify"], [0, 6, 1, "", "load"], [0, 6, 1, "", "loads"], [0, 1, 0, "-", "tag"]], "flask.json.provider": [[0, 2, 1, "", "DefaultJSONProvider"], [0, 2, 1, "", "JSONProvider"]], "flask.json.provider.DefaultJSONProvider": [[0, 4, 1, "", "compact"], [0, 3, 1, "", "default"], [0, 3, 1, "", "dumps"], [0, 4, 1, "", "ensure_ascii"], [0, 3, 1, "", "loads"], [0, 4, 1, "", "mimetype"], [0, 3, 1, "", "response"], [0, 4, 1, "", "sort_keys"]], "flask.json.provider.JSONProvider": [[0, 3, 1, "", "dump"], [0, 3, 1, "", "dumps"], [0, 3, 1, "", "load"], [0, 3, 1, "", "loads"], [0, 3, 1, "", "response"]], "flask.json.tag": [[0, 2, 1, "", "JSONTag"], [0, 2, 1, "", "TaggedJSONSerializer"]], "flask.json.tag.JSONTag": [[0, 3, 1, "", "check"], [0, 4, 1, "", "key"], [0, 3, 1, "", "tag"], [0, 3, 1, "", "to_json"], [0, 3, 1, "", "to_python"]], "flask.json.tag.TaggedJSONSerializer": [[0, 4, 1, "", "default_tags"], [0, 3, 1, "", "dumps"], [0, 3, 1, "", "loads"], [0, 3, 1, "", "register"], [0, 3, 1, "", "tag"], [0, 3, 1, "", "untag"]], "flask.session": [[0, 4, 1, "", "modified"], [0, 4, 1, "", "new"], [0, 4, 1, "", "permanent"]], "flask.sessions": [[0, 2, 1, "", "NullSession"], [0, 2, 1, "", "SecureCookieSession"], [0, 2, 1, "", "SecureCookieSessionInterface"], [0, 2, 1, "", "SessionInterface"], [0, 2, 1, "", "SessionMixin"]], "flask.sessions.NullSession": [[0, 3, 1, "", "clear"], [0, 3, 1, "", "pop"], [0, 3, 1, "", "popitem"], [0, 3, 1, "", "setdefault"], [0, 3, 1, "", "update"]], "flask.sessions.SecureCookieSession": [[0, 4, 1, "", "accessed"], [0, 3, 1, "", "get"], [0, 4, 1, "", "modified"], [0, 3, 1, "", "setdefault"]], "flask.sessions.SecureCookieSessionInterface": [[0, 3, 1, "", "digest_method"], [0, 4, 1, "", "key_derivation"], [0, 3, 1, "", "open_session"], [0, 4, 1, "", "salt"], [0, 3, 1, "", "save_session"], [0, 4, 1, "", "serializer"], [0, 4, 1, "", "session_class"]], "flask.sessions.SessionInterface": [[0, 3, 1, "", "get_cookie_domain"], [0, 3, 1, "", "get_cookie_httponly"], [0, 3, 1, "", "get_cookie_name"], [0, 3, 1, "", "get_cookie_partitioned"], [0, 3, 1, "", "get_cookie_path"], [0, 3, 1, "", "get_cookie_samesite"], [0, 3, 1, "", "get_cookie_secure"], [0, 3, 1, "", "get_expiration_time"], [0, 3, 1, "", "is_null_session"], [0, 3, 1, "", "make_null_session"], [0, 4, 1, "", "null_session_class"], [0, 3, 1, "", "open_session"], [0, 4, 1, "", "pickle_based"], [0, 3, 1, "", "save_session"], [0, 3, 1, "", "should_set_cookie"]], "flask.sessions.SessionMixin": [[0, 4, 1, "", "accessed"], [0, 4, 1, "", "modified"], [0, 5, 1, "", "permanent"]], "flask.testing": [[0, 2, 1, "", "FlaskCliRunner"], [0, 2, 1, "", "FlaskClient"]], "flask.testing.FlaskCliRunner": [[0, 3, 1, "", "invoke"]], "flask.testing.FlaskClient": [[0, 3, 1, "", "open"], [0, 3, 1, "", "session_transaction"]], "flask.views": [[0, 2, 1, "", "MethodView"], [0, 2, 1, "", "View"]], "flask.views.MethodView": [[0, 3, 1, "", "dispatch_request"]], "flask.views.View": [[0, 3, 1, "", "as_view"], [0, 4, 1, "", "decorators"], [0, 3, 1, "", "dispatch_request"], [0, 4, 1, "", "init_every_request"], [0, 4, 1, "", "methods"], [0, 4, 1, "", "provide_automatic_options"]]}, "objnames": {"0": ["py", "data", "Python data"], "1": ["py", "module", "Python module"], "2": ["py", "class", "Python class"], "3": ["py", "method", "Python method"], "4": ["py", "attribute", "Python attribute"], "5": ["py", "property", "Python property"], "6": ["py", "function", "Python function"]}, "objtypes": {"0": "py:data", "1": "py:module", "2": "py:class", "3": "py:method", "4": "py:attribute", "5": "py:property", "6": "py:function"}, "terms": {"": [0, 2, 3, 4, 5, 6, 8, 9, 10, 13, 14, 16, 17, 18, 20, 21, 22, 23, 25, 27, 28, 30, 31, 32, 34, 35, 38, 40, 41, 43, 46, 47, 49, 50, 51, 52, 53, 54, 55, 57, 59, 60, 61, 63, 64, 65, 66, 68, 69, 70, 71, 72, 73, 74], "0": [0, 2, 3, 5, 6, 9, 11, 12, 13, 16, 18, 19, 21, 24, 25, 28, 29, 35, 36, 41, 47, 51, 54, 56, 57, 58, 59, 60, 63, 64, 66, 69, 70, 71, 74], "00": 71, "01": [4, 71], "02": 4, "03": 4, "04": 4, "05": 4, "06": [4, 5], "07": 4, "08": 4, "09": 4, "0a": 71, "0de171a4f4dac32e3364c7ddc7c14f3e2fa61f2d17574483f7ffbb431b4acb2f": 71, "1": [0, 2, 5, 6, 9, 11, 12, 13, 16, 17, 18, 19, 21, 22, 24, 25, 26, 28, 29, 35, 40, 46, 47, 54, 56, 58, 59, 60, 61, 63, 64, 66, 69, 70, 71], "10": [0, 5, 6, 24, 58, 59, 66, 74], "100": [6, 18, 21, 60, 71], "1000": [35, 74], "10013": [5, 54, 56, 64], "104": 4, "1091": 4, "10em": 69, "11": [0, 5, 6, 24, 57], "12": [0, 24], "120": 46, "1262": 4, "127": [0, 4, 5, 6, 9, 11, 12, 13, 16, 18, 19, 28, 54, 56, 64, 69, 70], "1288": 4, "12em": 69, "13": 4, "1326": 4, "1357": 4, "1393": 4, "14": [0, 4, 66], "1421": 4, "1422": 4, "1484": 4, "1489": 4, "15": 4, "1515": 4, "153": 71, "1548": 4, "1559": 4, "16": [4, 34, 35, 71], "1621": 4, "168": 6, "17": 4, "1728": 4, "1730": 4, "1763": 4, "18": 4, "1814": 4, "1849": 4, "1864": 0, "1872": 4, "1898": 4, "19": 6, "192": 6, "192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf": [6, 54, 63], "1936": 4, "1985": 42, "1988": 4, "1_000": [0, 6], "1em": 69, "1px": 69, "1rem": 69, "2": [0, 2, 6, 13, 15, 18, 22, 24, 26, 54, 60, 66, 71, 73], "20": [13, 18], "200": [0, 4, 54, 57, 58, 60, 71], "2006": 4, "2010": [4, 26, 50], "2011": 4, "2012": 4, "2013": 4, "2016": 4, "2017": [4, 42, 55], "2018": [4, 71], "2019": 4, "2020": 4, "2021": [4, 5], "2022": 4, "2023": 4, "2024": [4, 22], "204": 73, "20doe": 54, "21": [4, 71], "2109": 4, "2118": 4, "2152": 4, "2193": 4, "22": 71, "2223": 4, "223": 5, "2231": 0, "2254": 4, "2256": 4, "2259": 4, "2282": 4, "2288": 4, "2297": 4, "23": 71, "2314": 4, "2316": 4, "2319": 4, "2326": 4, "2348": 4, "2352": 4, "2354": 4, "2358": 4, "2362": 4, "2373": 4, "2374": 4, "2385": 4, "24": [4, 66, 71], "2410": 4, "2412": 4, "2414": 4, "2416": 4, "2430": 4, "2436": 4, "2450": 4, "25": [4, 53], "2520": 4, "2526": 4, "2529": 4, "2581": 4, "2586": 4, "25rem": 69, "26": 4, "2606": 4, "2607": 4, "2629": 4, "2635": 4, "2636": 4, "2651": 4, "2666": 4, "2676": 4, "2678400": 6, "2691": 4, "2692": 4, "2693": 4, "27": [4, 5], "2709": 4, "2722": 4, "2728": 4, "2730": 4, "2731": 4, "2735": 4, "2736": 4, "2741": 4, "2742": 4, "2748": 4, "2751": 4, "2765": 4, "2766": 4, "28": 4, "2825": 4, "2836": 4, "2866": 4, "2897": 4, "29": 4, "2900": 4, "2926": 4, "2933": 4, "2935": 4, "2937": 4, "2957": 4, "2986": 4, "2994": 4, "2f": 59, "3": [0, 2, 5, 6, 11, 12, 13, 18, 22, 24, 25, 36, 37, 54, 57, 66, 71, 74], "30": 4, "301": 0, "302": [0, 4], "3022": 4, "3059": 4, "3069": 4, "3074": 4, "3088": 4, "31": [0, 4, 6], "3108": 4, "3111": 4, "3124": 4, "3125": 4, "3134": 4, "3138": 4, "31536000": 74, "3157": 4, "3163": 4, "3190": 4, "3195": 4, "32": [4, 6], "3208": 4, "3211": 4, "3214": 4, "3215": 4, "3232": 4, "3249": 4, "3263": 4, "3266": 4, "3275": 4, "3285": 4, "3288": 4, "3297": 4, "33": 59, "3333": [4, 27], "3358": 4, "336699": 50, "3369": 4, "3396": 4, "3398": 4, "34": 71, "3412": 4, "3431": 4, "3452": 4, "3492": 4, "3497": 4, "35": 53, "3552": 4, "3553": 4, "3555": 4, "3560": 4, "3562": 4, "3579": 4, "3628": 4, "3726": 4, "3776": 4, "377ba8": 69, "3828": 4, "3881": 4, "3883": 4, "3898": 4, "3907": 4, "3923": 4, "3931": 4, "3941": 4, "3962": 4, "3973": 4, "3rd": [21, 74], "4": [0, 6, 13, 15, 18, 22, 24, 43, 53, 66, 71, 74], "400": [0, 4, 6, 21, 38, 54, 73], "4008": 4, "401": [28, 54, 61], "4019": 4, "4020": 4, "4024": 4, "4026": 4, "403": [61, 71], "4037": 4, "404": [0, 3, 21, 27, 29, 54, 61, 71], "4040": 4, "4041": 4, "4043": 4, "4044": 4, "405": [0, 3, 21, 27], "4050": 4, "4052": 4, "4053": 4, "4060": 4, "4069": 4, "4078": 4, "4093": [4, 6], "4095": 4, "4096": 4, "4098": 4, "4104": 4, "4112": 4, "4124": 4, "413": [0, 6, 35], "415": 0, "4150": 4, "4157": 4, "416": 0, "4170": 4, "4188": 4, "42": [0, 52, 54], "420": 21, "4229": 4, "4295": 4, "4297": 4, "4303": 4, "4307": 4, "4333": 4, "4335": 4, "4337": 4, "4341": 4, "4349": 4, "44": 71, "4417": 4, "4419": 4, "443": [11, 12, 13, 15, 18, 19], "4459": 4, "4460": 4, "4474": 4, "4479": 4, "4485": 4, "4496": 4, "4502": 4, "451": 4, "4519": 4, "4559": 4, "456": 5, "4567": 4, "4568": 4, "4569": 4, "4571": 4, "4600": 4, "4605": 4, "4606": 4, "4610": 4, "4629": 4, "4645": 4, "4666": 4, "4667": 4, "4672": 4, "4682": 4, "4692": 4, "4693": 4, "4695": 4, "4714": 4, "4715": 4, "4716": 4, "4732": 4, "4740": 4, "4754": 4, "4777": 4, "4831": 4, "4834": 4, "4892": 4, "4947": 4, "4989": 4, "499": 21, "4993": 4, "4995": 4, "4996": 4, "4997": 4, "5": [0, 6, 24, 31, 35, 42, 52, 54, 68, 71, 74], "50": 46, "500": [0, 4, 8, 21, 27, 55, 71], "5000": [0, 5, 6, 54, 56, 64, 69, 70], "50000": 71, "5001": 56, "5004": 4, "500_000": [0, 6], "500_gener": 21, "500kb": 74, "500mb": 74, "5010": 4, "503": 0, "5049": 4, "5051": 4, "5056": 4, "507": 21, "5071": 4, "5072": 4, "5084": 4, "51": 5, "5127": 4, "5160": 4, "519": 4, "5223": 4, "5230": 4, "5264": 4, "5270": 4, "5336": 4, "5344": 4, "5381": 4, "5383": 4, "5388": 4, "5391": 4, "54": 71, "5448": 4, "5472": 4, "5496": 4, "5504": 4, "5553": 4, "56": 6, "5621": 4, "5623": 4, "5624": 4, "5625": 4, "5628": 4, "5633": 4, "5636": 4, "5645": 4, "59": 5, "593": 4, "599": 21, "5em": 69, "5f352379324c22463451387a0aec5d2f": 6, "5rem": 69, "6": [0, 6, 24, 35, 53, 59, 66, 71], "60": 52, "600": 74, "64": 71, "64bit": 18, "6847": 56, "7": [0, 2, 3, 6, 11, 12, 13, 18, 24, 25, 51, 66], "8": [0, 6, 24, 42], "80": [11, 12, 13, 15, 16, 18, 19], "8000": [5, 9, 11, 12, 13, 16, 18], "8080": [19, 63], "822": 0, "8259": 4, "85em": 69, "86": 71, "8859": 4, "9": [0, 6, 22, 24, 25, 36, 66], "919": 5, "95": 71, "960px": 69, "98": [5, 54, 56, 64], "A": [0, 1, 3, 4, 6, 14, 20, 21, 22, 24, 26, 27, 29, 30, 32, 33, 34, 37, 38, 42, 50, 52, 55, 59, 60, 61, 64, 67, 68, 71, 72, 73, 74], "AND": 26, "AS": 26, "And": [0, 3, 21, 27, 36, 40, 43], "As": [0, 3, 20, 21, 22, 33, 38, 46, 52, 54, 61, 73], "At": [2, 27, 33, 37, 44, 47, 72], "BE": 26, "BUT": 26, "BY": [26, 61], "Be": [0, 4, 9, 13, 15, 16, 18, 19, 21, 22, 24, 43, 55, 74], "But": [0, 6, 20, 21, 27, 30, 35, 43, 52, 54, 57, 74], "By": [0, 3, 5, 6, 20, 21, 35, 38, 54, 57, 60, 67, 73], "FOR": 26, "For": [0, 1, 2, 3, 4, 5, 6, 9, 15, 16, 17, 20, 21, 22, 23, 27, 29, 30, 32, 33, 35, 36, 37, 38, 42, 43, 44, 46, 47, 49, 51, 52, 53, 54, 55, 57, 58, 60, 63, 64, 67, 71, 72, 73, 74], "IF": [26, 62], "IN": 26, "INTO": [61, 71, 72], "If": [0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 13, 15, 18, 19, 20, 21, 22, 23, 24, 27, 28, 29, 30, 32, 34, 35, 36, 38, 42, 43, 46, 47, 48, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 64, 67, 68, 69, 70, 71, 72, 73, 74], "In": [0, 3, 4, 5, 6, 9, 16, 20, 21, 22, 24, 25, 27, 29, 37, 38, 41, 43, 46, 47, 50, 54, 59, 61, 62, 63, 65, 67, 71, 72, 73, 74], "It": [0, 1, 2, 3, 4, 5, 6, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 24, 25, 27, 30, 32, 33, 34, 35, 36, 38, 40, 46, 47, 48, 50, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 70, 71, 73, 74], "Its": 0, "NO": 26, "NOT": [26, 62], "No": [0, 4, 12, 21, 35, 47], "Not": [0, 3, 6, 17, 21, 24, 43, 54, 59, 61, 71], "OF": 26, "ON": [26, 61], "OR": 26, "Of": 30, "On": [0, 3, 4, 6, 20, 24, 32, 71, 72], "One": [0, 4, 22, 24, 33, 36, 40, 53, 55, 57], "Or": [0, 6, 18, 21, 47, 55], "SUCH": 26, "Such": 54, "THE": 26, "TO": 26, "TOS": 53, "That": [0, 3, 4, 6, 18, 20, 32, 34, 35, 43, 51, 52, 54, 61, 70], "The": [0, 2, 4, 5, 6, 9, 10, 13, 14, 15, 16, 17, 18, 19, 21, 24, 25, 27, 28, 29, 30, 32, 34, 35, 36, 37, 38, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 56, 57, 58, 60, 62, 63, 65, 66, 67, 69, 71, 73, 74], "Then": [0, 6, 9, 16, 27, 30, 38, 40, 41, 42, 43, 46, 61, 67, 72, 73], "There": [0, 5, 6, 14, 20, 22, 24, 27, 35, 42, 46, 53, 54, 57, 59, 62, 63, 67, 68, 70, 71, 72, 74], "These": [0, 2, 3, 5, 14, 21, 25, 37, 38, 46, 47, 54, 55, 59, 62, 74], "To": [0, 1, 3, 4, 5, 6, 9, 11, 12, 13, 16, 21, 28, 30, 32, 36, 38, 41, 42, 43, 44, 46, 47, 50, 52, 53, 54, 57, 58, 59, 60, 61, 70, 71, 72, 73, 74], "Will": [0, 6], "With": [2, 6, 20, 37, 52, 61, 71], "_": [0, 16, 22], "_5": [36, 54], "__": [0, 6], "__call__": [0, 29, 32, 40, 41], "__exit__": 4, "__file__": [60, 71], "__html__": 0, "__init__": [0, 3, 4, 6, 21, 22, 29, 40, 41, 43, 44, 46, 54, 61, 62, 64, 67, 71, 72, 73], "__main__": 56, "__module__": 40, "__name__": [0, 1, 3, 4, 5, 6, 10, 20, 21, 22, 23, 27, 28, 29, 30, 32, 35, 36, 40, 41, 42, 43, 45, 51, 52, 54, 55, 56, 61, 64, 67, 72, 73], "__pycache__": 67, "__repr__": 46, "__slots__": 0, "__tablename__": 46, "__version__": 4, "_anchor": 0, "_app": 0, "_app_ctx_stack": 4, "_appctxglob": 0, "_authent": 0, "_cider": 0, "_client": 71, "_compat": 4, "_data_sql": 71, "_databas": 47, "_extension_name_attr": 4, "_extern": [0, 3], "_formhelp": 53, "_get_current_object": [55, 58], "_get_item": 73, "_handle_api_error": 3, "_hash": 44, "_hello": 22, "_hello_user_id": 22, "_helper": 59, "_method": 0, "_peek_path_info": 29, "_perman": 0, "_request_ctx_stack": 4, "_scheme": [0, 4], "_sentinel": 0, "_stream": 44, "abi": 63, "abil": [0, 4, 6, 21, 24, 35, 59], "abl": [0, 4, 6, 20, 22, 35, 65, 73, 74], "abort": [0, 3, 4, 21, 28, 35, 54, 61], "aborter_class": [0, 4], "about": [1, 4, 5, 6, 8, 20, 21, 22, 24, 28, 30, 32, 33, 35, 36, 38, 46, 51, 53, 55, 56, 59, 61, 62, 63, 64, 66, 68, 69, 71, 72, 74], "abov": [0, 6, 14, 21, 22, 26, 27, 28, 30, 32, 34, 35, 38, 46, 47, 53, 54, 55, 58, 59, 61, 71, 72], "absinth": 4, "absolut": [0, 3, 4, 6, 54], "abstract": [20, 29, 37], "abus": 74, "accept": [0, 4, 35, 53, 54, 58], "accept_charset": 0, "accept_encod": 0, "accept_languag": 0, "accept_mimetyp": 0, "accept_rang": 0, "accept_to": 53, "access": [0, 1, 3, 4, 5, 6, 8, 13, 20, 21, 22, 24, 27, 28, 30, 32, 35, 36, 38, 44, 46, 47, 48, 53, 55, 56, 58, 59, 64, 65, 71], "access_control_allow_credenti": 0, "access_control_allow_head": 0, "access_control_allow_method": 0, "access_control_allow_origin": 0, "access_control_expose_head": 0, "access_control_max_ag": 0, "access_control_request_head": 0, "access_control_request_method": 0, "access_rout": 0, "accident": [0, 3, 4], "accomplish": [2, 40, 41, 54, 59], "accord": [0, 54], "account": [4, 20], "accur": 5, "achiev": [4, 35], "acquir": [9, 16], "across": [0, 1, 3, 27, 54, 60, 72], "act": [0, 73], "action": [0, 61, 69], "activ": [0, 1, 4, 5, 6, 11, 12, 13, 15, 18, 19, 22, 24, 32, 47, 48, 54, 55, 57, 59, 62, 64], "actor": 42, "actors__in": 42, "actual": [0, 3, 4, 6, 11, 12, 13, 17, 18, 20, 21, 30, 31, 35, 40, 43, 52, 54, 55], "ad": [0, 2, 3, 4, 5, 6, 9, 16, 24, 25, 27, 35, 36, 37, 43, 51, 53, 54, 57, 59, 61, 69, 71, 72, 74], "adapt": [0, 2, 4, 10, 53], "add": [0, 2, 4, 5, 6, 8, 9, 16, 20, 21, 22, 23, 24, 28, 30, 32, 34, 36, 38, 40, 42, 43, 46, 47, 52, 53, 54, 55, 60, 61, 62, 64, 67, 69, 73], "add_app_template_filt": [0, 4], "add_app_template_glob": 0, "add_app_template_test": 0, "add_command": [5, 62], "add_default_command": 0, "add_etag": [0, 4], "add_head": 0, "add_language_cod": 51, "add_template_filt": [0, 4], "add_template_glob": 0, "add_template_test": 0, "add_togeth": 32, "add_url_rul": [0, 4, 34, 35, 40, 61, 73], "add_version_opt": 0, "addhandl": 28, "addit": [0, 2, 3, 4, 5, 6, 13, 19, 21, 46, 52, 54, 60], "addition": [0, 3, 4, 21, 47, 58, 59], "addr": 18, "address": [0, 4, 5, 11, 12, 13, 16, 17, 18, 19, 28, 53, 54, 64], "admin": [3, 5, 21, 24, 30, 36, 46], "advanc": [0, 20, 22, 27, 55], "advantag": [0, 4, 20, 29, 53, 58, 65], "advis": [0, 26, 43], "affect": [0, 4, 6, 11, 12, 22, 25, 38, 55, 58], "after": [0, 1, 2, 4, 6, 14, 15, 21, 22, 24, 27, 28, 30, 33, 35, 38, 40, 42, 43, 46, 51, 52, 54, 55, 60, 61, 62, 70, 71, 72, 74], "after_app_request": 0, "after_request": [0, 4, 6, 27, 33, 55], "after_request_func": 0, "after_this_request": [0, 4, 27, 33], "afterrequestcal": 0, "afterward": [0, 72], "ag": [0, 4, 6, 74], "again": [4, 20, 63, 70, 72, 74], "against": [0, 6, 20, 27, 74], "agent": 0, "aggreg": 21, "agnost": 20, "ago": [27, 35], "ah": 35, "ahead": [4, 20], "aid": [0, 4], "aim": 20, "airplai": 56, "ajax": 38, "alert": [36, 54, 74], "alia": [0, 4], "alic": 5, "align": 69, "all": [0, 1, 2, 3, 4, 6, 11, 12, 13, 17, 18, 19, 20, 21, 22, 27, 28, 29, 34, 35, 36, 38, 40, 43, 44, 45, 46, 50, 51, 54, 55, 58, 59, 60, 61, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74], "alloc": 20, "allow": [0, 2, 4, 6, 8, 11, 12, 21, 22, 25, 29, 32, 35, 46, 50, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 71, 72], "allowed_extens": 35, "allowed_fil": 35, "allowed_method": 41, "almost": 35, "alon": 4, "along": [0, 5, 30, 45, 52, 63, 68], "alreadi": [0, 2, 4, 5, 6, 9, 20, 27, 30, 35, 44, 46, 48, 52, 53, 54, 55, 60, 64, 65, 69, 71, 72], "also": [0, 1, 2, 3, 4, 5, 6, 8, 9, 13, 16, 20, 21, 22, 24, 27, 28, 29, 30, 32, 35, 36, 37, 38, 42, 45, 46, 47, 48, 54, 55, 56, 57, 58, 59, 60, 61, 63, 64, 66, 68, 70, 71, 72, 73, 74], "alter": [4, 5, 6, 20], "altern": [0, 6, 33, 36, 42], "although": [0, 4, 20, 27, 38, 63, 74], "altogeth": 59, "alwai": [0, 4, 6, 19, 20, 21, 34, 35, 47, 51, 52, 54, 58, 59, 66, 70, 74], "ambigu": 20, "amount": [0, 32, 35, 40, 48, 52, 59], "an": [0, 1, 2, 3, 4, 5, 6, 8, 10, 14, 15, 18, 20, 21, 22, 23, 24, 27, 28, 29, 30, 31, 32, 33, 34, 37, 38, 40, 41, 42, 43, 45, 46, 47, 48, 50, 51, 52, 54, 55, 56, 57, 58, 59, 61, 62, 63, 64, 65, 68, 70, 71, 72, 73, 74], "anchor": [0, 4], "ancient": [0, 4], "angular": [0, 4], "ani": [0, 2, 3, 4, 5, 6, 8, 9, 11, 12, 13, 16, 18, 20, 21, 22, 26, 27, 28, 29, 32, 33, 38, 40, 53, 54, 55, 57, 60, 62, 63, 64, 65, 66, 67, 70, 71, 72, 73, 74], "annoi": 51, "annot": 4, "ano": 56, "anoth": [0, 3, 4, 5, 6, 8, 11, 12, 20, 21, 22, 25, 27, 29, 32, 38, 41, 50, 51, 52, 54, 55, 56, 61, 62, 63, 64, 65, 66, 71, 72, 73, 74], "answer": [0, 7, 48, 54], "anyon": 22, "anystr": 0, "anyth": [0, 1, 20, 22, 27, 44, 54, 55, 63, 70], "anywai": 59, "anywher": [33, 66, 74], "apach": [6, 11, 12, 13, 14, 15, 18, 19], "api": [2, 3, 4, 22, 23, 27, 38, 44, 45], "api_view": 22, "app": [0, 1, 2, 3, 4, 5, 6, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 27, 28, 29, 30, 32, 33, 34, 35, 36, 38, 40, 41, 42, 43, 44, 45, 46, 47, 48, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 71, 72, 73, 74], "app2": 5, "app_context": [0, 1, 4, 32, 47, 60, 71], "app_context_processor": 0, "app_ctx": 0, "app_ctx_globals_class": [0, 4], "app_errorhandl": 0, "app_import_path": 0, "app_it": 0, "app_template_filt": [0, 4], "app_template_glob": 0, "app_template_test": 0, "app_url_default": 0, "app_url_value_preprocessor": 0, "app_vari": 13, "appcontext": [0, 4, 27, 47, 55], "appcontext_pop": [0, 1, 4, 27], "appcontext_push": [0, 1, 4, 27], "appcontext_tearing_down": [0, 1, 27], "appear": [0, 6, 20, 61, 70], "append": [0, 38, 54, 58], "appengin": 4, "appgroup": [0, 5], "appl": 54, "appli": [0, 2, 4, 6, 14, 17, 20, 22, 27, 38, 52, 54, 59, 72, 73, 74], "applic": [2, 4, 6, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 22, 23, 24, 25, 28, 31, 33, 34, 35, 36, 37, 38, 40, 46, 47, 52, 53, 55, 56, 57, 58, 59, 61, 63, 65, 66, 67, 68, 70, 71, 72, 74], "application_root": [0, 4, 6], "apporblueprintkei": 0, "approach": [4, 6, 22, 40, 46, 47, 49, 65], "appropri": [0, 1, 2, 3, 4, 6, 13, 18, 20, 21, 22, 54], "approv": 22, "ar": [0, 1, 2, 3, 4, 5, 6, 9, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 35, 36, 37, 38, 40, 42, 43, 46, 47, 48, 49, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 67, 68, 69, 70, 71, 72, 73, 74], "arbitrari": [0, 4, 8, 20, 41, 54, 74], "archiv": [4, 32], "aren": [13, 15, 19, 27, 74], "arg": [0, 2, 6, 21, 32, 40, 47, 48, 52, 53, 54, 55, 60, 71], "argument": [0, 3, 4, 5, 6, 11, 12, 13, 15, 19, 22, 30, 32, 36, 38, 42, 47, 53, 54, 56, 58, 59, 60, 61, 71, 72, 73], "aris": 26, "around": [0, 1, 4, 20, 38, 57, 59, 70], "arrai": [0, 4, 74], "articl": [34, 61, 74], "as_attach": [0, 4], "as_text": [0, 60, 71], "as_tupl": [0, 4], "as_view": [0, 4, 22, 73], "ascii": [0, 4], "asctim": 28, "asdict": 0, "asgi": [2, 13, 14, 18, 24], "asgi_app": 10, "asgiref": [2, 10], "ask": [0, 7, 22, 32, 35], "assert": [0, 4, 29, 54, 58, 60, 71], "assertionerror": 0, "assign": [0, 22, 42, 51], "associ": [0, 3, 5, 9, 16, 27, 61, 72], "assum": [0, 9, 16, 21, 22, 29, 35, 47, 52, 54, 63, 65, 67], "assumpt": [0, 4], "async": [0, 4, 10, 11, 12, 24], "async_db_queri": 2, "async_to_sync": 0, "asynchron": [11, 12, 13, 18, 20], "asyncio": [2, 11, 12], "asyncresult": 32, "attach": [0, 4, 6, 54, 74], "attachment_filenam": [0, 4], "attack": [0, 4, 25, 47, 54, 63, 72, 74], "attempt": [0, 1, 4, 6, 55, 56], "attr": 0, "attribut": [0, 1, 4, 6, 22, 30, 38, 42, 53, 54, 58, 59, 60, 61, 70, 74], "attributeerror": 4, "audienc": 0, "audit": 58, "augment": 49, "auth": [0, 60, 61, 67, 69, 70, 71, 72], "authact": 71, "authent": [0, 20, 27, 37, 61, 69, 70, 74], "author": [0, 2, 4, 22, 61, 71], "author_id": [61, 62, 71], "auto": [4, 69], "auto_find_instance_path": 0, "auto_pop": 4, "auto_reload": 0, "autocommit": 46, "autocorrect_location_head": 0, "autodetect": [4, 6], "autoescap": [0, 4, 20, 24, 54, 70], "autoflush": 46, "autogener": 6, "autoincr": 62, "autoload": 46, "automat": [0, 1, 4, 5, 6, 9, 20, 21, 25, 28, 30, 32, 38, 46, 48, 51, 52, 54, 55, 56, 57, 59, 60, 61, 64, 69, 70, 73, 74], "automatically_set_content_length": 0, "avail": [0, 3, 4, 5, 6, 9, 13, 14, 15, 16, 18, 19, 20, 21, 22, 27, 32, 38, 52, 54, 55, 56, 57, 58, 59, 61, 62, 65, 70, 72, 74], "avoid": [0, 3, 4, 5, 6, 22, 25, 33, 34, 54, 55, 61, 65, 73], "aw": [14, 51, 52], "awai": 20, "await": [0, 10, 11, 12, 13, 18, 24, 38], "awar": [0, 4, 21, 22, 54], "awesom": [50, 68], "awkward": 33, "axis_data": 0, "azur": 14, "b": [0, 13, 32, 36, 54, 60, 71, 74], "back": [0, 4, 6, 27, 29, 40, 42, 48, 52, 54, 57, 68, 72], "backend": [0, 4, 21, 29, 31, 32, 43, 66], "backend_app": 29, "background": [24, 36, 37, 55, 69], "backslash": 4, "backspac": 74, "backward": [4, 20], "bad": [0, 4, 6, 20, 21, 38, 43, 54], "badli": 0, "badrequest": [0, 4, 21], "badrequestkeyerror": 4, "bandwidth": [6, 14, 38], "bar": [5, 37], "bare": 4, "base": [2, 3, 4, 6, 11, 12, 14, 20, 21, 22, 24, 29, 32, 33, 37, 38, 46, 47, 51, 52, 54, 55, 61, 67, 69, 72, 74], "base64": 38, "base_url": 0, "baseconvert": 0, "baseexcept": [0, 4], "baseload": 0, "basepost": 22, "baserespons": 0, "bash": [5, 6], "bashrc": 35, "basi": [0, 4, 6], "basic": [0, 3, 9, 13, 14, 15, 16, 18, 19, 21, 24, 27, 32, 35, 36, 37, 42, 46, 50, 54, 57, 65, 66, 70, 74], "bat": 5, "baz": 23, "beanstalk": 14, "beat": 32, "beauti": 51, "becam": 22, "becaus": [0, 2, 3, 4, 5, 6, 11, 12, 13, 18, 19, 20, 21, 27, 35, 46, 47, 48, 51, 52, 54, 55, 57, 58, 59, 60, 61, 62, 63, 64, 66, 70, 72, 73, 74], "becom": [0, 3, 4, 6, 20, 21, 32, 53, 62, 65, 67, 74], "been": [0, 2, 4, 22, 61, 62, 66, 71], "befor": [0, 2, 3, 4, 5, 6, 8, 20, 21, 22, 24, 25, 27, 28, 30, 32, 35, 38, 40, 41, 44, 46, 47, 54, 55, 59, 60, 61, 62, 64, 70, 72], "before_app_first_request": 4, "before_app_request": [0, 4, 72], "before_first_request": 4, "before_render_templ": [0, 4], "before_request": [0, 4, 6, 22, 27, 33, 55, 58, 60], "before_request_func": 0, "before_request_handl": 44, "beforerequestcal": 0, "begin": [0, 1, 4, 6, 22, 37, 55, 63, 71, 72], "beginn": 18, "begun": 6, "behav": [0, 4, 6, 27, 40, 54, 62, 70], "behavior": [0, 4, 5, 6, 20, 21, 24, 27, 60, 71, 73, 74], "behind": [0, 9, 14, 16, 54, 55, 68], "being": [0, 1, 3, 4, 5, 6, 18, 20, 21, 30, 32, 41, 54, 55, 57, 59, 66, 71, 74], "believ": 0, "belong": 0, "below": [0, 9, 14, 21, 22, 28, 29, 43, 51, 54, 60, 61, 63, 69, 74], "benefici": 2, "benefit": [0, 2, 4, 11, 12, 13, 18, 66], "besid": [5, 20, 22, 54, 69, 70], "best": [0, 2, 3, 20, 22, 24], "better": [0, 4, 6, 9, 16, 20, 21, 34, 35, 36, 38, 54, 60], "between": [0, 1, 4, 6, 25, 27, 29, 38, 58, 64, 70], "beyond": [18, 22, 24], "bi": 74, "big": [0, 29, 43, 62, 74], "bigger": [0, 67], "bin": [5, 11, 12, 13, 15, 18, 19, 25], "binari": [0, 4, 18, 26, 38], "binaryio": 0, "bind": [0, 3, 4, 20, 46, 54], "bit": [22, 35, 37, 43, 46, 52, 57, 65, 68], "black": [21, 54], "blink": 54, "blinker": [0, 4, 25, 58], "block": [0, 1, 2, 4, 20, 21, 32, 36, 38, 48, 50, 54, 55, 56, 58, 59, 60, 61, 67, 69, 70, 71, 74], "blog": [21, 22, 24, 60, 65, 66, 67, 69, 70, 72, 74], "blogextens": 22, "blueprint": [1, 4, 6, 22, 24, 27, 30, 32, 37, 55, 62, 65, 69, 70], "blueprint_nam": 3, "blueprintsetupst": 0, "bm": 74, "bodi": [0, 6, 21, 27, 36, 38, 50, 54, 58, 60, 61, 62, 69, 70, 71, 74], "bodyless_method": 41, "boilerpl": 65, "bold": 69, "bookmark": 34, "bool": 0, "boolean": [0, 6], "booleanfield": 53, "boot": 13, "bootstrap": 35, "border": 69, "bose": 74, "both": [0, 4, 6, 21, 25, 51, 59, 61, 63, 70, 71], "bottom": [0, 43, 69], "bound": [0, 2, 6, 22, 30, 55, 59], "box": 68, "bp": [4, 5, 51, 61, 72], "bracket": 0, "branch": 71, "brand": 34, "break": [0, 4, 21, 25, 43, 48, 53, 54], "breakpoint": 8, "breviti": 54, "bridg": 20, "briefli": 4, "bright": 20, "broad": [54, 74], "broader": 0, "broke": 4, "broken": 4, "broker_url": 32, "brows": 0, "browser": [0, 4, 6, 8, 11, 12, 13, 18, 19, 27, 34, 35, 36, 38, 48, 53, 54, 57, 61, 64, 69, 70, 71, 72, 74], "brpart": 71, "bsd": [22, 24], "bt": 74, "bttf": 42, "buffer": [0, 19], "bug": [4, 28, 71], "bugfix": 4, "bui": [9, 16], "build": [0, 4, 20, 21, 24, 27, 43, 50, 59, 60, 66, 67], "build_onli": 35, "buildapi": [43, 66], "builderror": [0, 4], "built": [0, 4, 5, 6, 9, 13, 14, 16, 20, 21, 24, 38, 54, 58, 62, 63, 66], "builtin": [4, 24, 54, 59], "bump": 4, "bunch": 51, "bundl": [20, 25], "busi": 26, "button": [5, 61, 70], "bypass": [11, 12, 13, 18, 19], "byte": [0, 4, 6, 44, 54, 57, 60, 63, 71, 74], "bytesio": [0, 4], "c": [0, 5, 6, 46, 54, 63, 64], "cabc": 0, "cach": [0, 1, 4, 6, 22, 24, 37, 38, 69, 73], "cache_control": 0, "cache_kei": 52, "cache_timeout": [0, 4], "cached_properti": 40, "cae6f6": 69, "calcul": [0, 31, 44, 52], "calculate_content_length": 0, "call": [0, 1, 2, 3, 4, 5, 6, 13, 14, 15, 19, 20, 21, 22, 23, 27, 29, 30, 33, 35, 37, 38, 40, 42, 43, 46, 47, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 65, 66, 70, 71, 72, 73, 74], "call_on_clos": 0, "callabl": [0, 4, 20, 27], "callback": [0, 4, 6, 24, 37, 38, 54, 57, 58], "calvado": 4, "came": [27, 54], "campari": 4, "can": [0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 32, 33, 34, 35, 36, 38, 40, 41, 42, 43, 44, 45, 46, 47, 48, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74], "cancel": 2, "cannot": [0, 2, 3, 4, 21, 30, 38, 54, 55, 58, 60, 74], "canon": [0, 20, 54], "cap": 6, "capabl": [2, 14, 18, 54], "captur": [0, 21, 54, 60, 61, 73], "captured_templ": 58, "care": [0, 4, 22, 28, 32, 44, 46, 48, 55, 72, 74], "carefulli": 21, "carri": [0, 59], "case": [0, 2, 3, 4, 5, 6, 13, 18, 20, 21, 22, 23, 25, 27, 29, 30, 38, 40, 41, 43, 46, 52, 54, 57, 58, 59, 64, 72, 73, 74], "cat": 74, "catch": [0, 4, 8, 21, 27, 45, 54], "catch_al": 45, "categori": [0, 4, 37, 74], "category_filt": [0, 4, 36], "caught": [0, 4], "caus": [0, 4, 8, 11, 12, 13, 18, 19, 20, 21, 26, 35, 36, 54, 59, 64, 70, 74], "cautiou": 59, "caveat": [3, 8, 21], "cc2f2e": 69, "cd": [11, 12, 13, 15, 18, 19, 25, 67], "ceil": 0, "celeri": [4, 21, 24, 37], "celery_app": 32, "celery_init_app": 32, "center": 69, "central": [0, 3, 4, 20, 37], "cert": 4, "certain": [0, 3, 4, 6, 11, 12, 14, 20, 21, 23, 27, 37, 52, 54, 58, 71, 74], "certainli": 20, "certif": [4, 74], "cfg": [0, 4, 6], "cgi": 0, "chain": [0, 17, 27, 33, 38, 55], "challeng": 0, "chang": [0, 2, 3, 5, 6, 8, 20, 21, 22, 24, 25, 27, 28, 30, 32, 38, 44, 54, 55, 56, 59, 60, 61, 62, 63, 64, 66, 69, 70, 71, 72, 73, 74], "changelog": 2, "chapter": [0, 43], "charact": [0, 4, 38, 54, 59, 70, 74], "characterist": 22, "charliz": 42, "charset": [0, 4], "charsetaccept": 0, "chart": 38, "chart_data": 38, "chartlib": 38, "chat": 22, "check": [0, 2, 3, 4, 5, 6, 9, 16, 24, 25, 28, 35, 42, 51, 54, 55, 60, 61, 62, 65, 68, 71, 72, 73, 74], "check_author": 61, "check_password": 28, "check_password_hash": 72, "checklist": 43, "checksum": [24, 37], "checksumcalcstream": 44, "chees": 21, "child": [3, 37, 69], "chip": 4, "choic": 6, "choos": [4, 11, 12, 25, 28, 38, 56, 61, 63], "chosen": [21, 63, 64], "christoph": 42, "chrome": 4, "chunk": [35, 59], "circular": [1, 4, 22], "cl": 5, "class": [2, 4, 6, 20, 21, 24, 27, 28, 29, 32, 36, 40, 41, 42, 44, 46, 49, 50, 53, 54, 58, 60, 61, 64, 70, 71, 74], "class_arg": 0, "class_kwarg": 0, "classmethod": 0, "classvar": 0, "claus": 24, "clean": [4, 22, 60, 62], "cleanup": 0, "clear": [0, 4, 20, 27, 54, 60, 62, 69, 72, 74], "clearer": [4, 22, 61], "clever": [30, 61], "cli": [1, 4, 5, 22, 24, 27, 56, 62], "cli_group": [0, 5], "cli_runn": 4, "click": [0, 4, 5, 24, 25, 60, 62, 66, 68, 70, 71, 74], "clickjack": 74, "client": [4, 21, 24, 27, 35, 38, 41, 48, 54, 55, 58, 70, 71], "clirunn": 0, "clone": 22, "close": [0, 1, 4, 5, 22, 36, 37, 46, 47, 60, 62, 71, 74], "close_connect": 47, "close_db": 62, "close_db_connect": 0, "closer": 71, "closest": 4, "cloud": 14, "cmd": [5, 6], "code": [0, 1, 2, 3, 4, 5, 6, 8, 11, 12, 13, 18, 19, 20, 21, 22, 24, 26, 27, 32, 33, 35, 38, 40, 43, 44, 46, 47, 51, 52, 53, 54, 55, 57, 58, 59, 60, 61, 62, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74], "code_or_except": 0, "codebas": [2, 20], "codenam": 4, "coep": 0, "coerc": 0, "collabor": 22, "collect": [0, 3, 27, 37, 71], "collector": 4, "collid": 22, "color": [50, 69], "column": [22, 46, 50, 62, 69], "com": [0, 28, 29, 38, 74], "combin": [0, 4, 22, 36, 37, 40, 47, 51, 54, 74], "combinedmultidict": 0, "combonam": 22, "come": [0, 2, 17, 20, 21, 25, 29, 51, 54, 57, 59, 62, 66], "comfort": [65, 71], "command": [1, 4, 6, 8, 15, 19, 22, 24, 25, 27, 29, 30, 32, 43, 54, 62, 63, 64, 71, 74], "comment": [9, 16, 68, 74], "commit": [5, 6, 38, 46, 47, 61, 64, 71, 72, 73], "common": [0, 1, 3, 4, 6, 14, 18, 20, 22, 24, 27, 29, 30, 33, 34, 35, 37, 38, 42, 46, 50, 51, 52, 54, 55, 57, 58, 60, 65, 73, 74], "commonli": 0, "commun": [5, 22, 24, 32, 54], "compact": [0, 4, 69], "compactli": 0, "compar": [20, 54, 65, 68, 71, 72, 74], "comparison": 20, "compat": [0, 4, 20, 22, 25], "compil": [13, 15, 18, 19], "complain": [0, 4], "complet": [0, 2, 4, 6, 22, 24, 27, 31, 54, 59, 61], "complete_length": 0, "complex": [0, 15, 18, 20, 22, 24, 32, 38, 52, 54, 60, 73, 74], "complic": [33, 50], "compon": [0, 3, 4, 24, 33], "compress": [0, 4], "compromis": 20, "comput": [0, 54, 63, 65], "con": 46, "concaten": [0, 42], "concept": [6, 14, 20, 22, 24, 27, 32, 51, 59, 68, 74], "conceptu": 4, "concern": [0, 3, 9, 16, 21], "concret": 4, "concurr": [0, 2, 54, 62, 74], "condit": [0, 4, 6, 26, 71], "conf": [9, 16], "config": [0, 1, 3, 4, 6, 9, 22, 23, 27, 28, 30, 32, 35, 42, 54, 59, 60, 62, 63, 64, 67, 71, 74], "config_class": [0, 4], "config_filenam": [21, 30], "config_from_object": 32, "configmodul": 6, "configur": [1, 4, 5, 11, 12, 13, 14, 15, 17, 18, 19, 20, 23, 24, 27, 29, 30, 32, 34, 37, 46, 54, 56, 59, 60, 62, 64, 70, 71, 74], "confirm": [53, 61], "conflict": 54, "conform": 22, "conftest": [60, 67, 71], "confus": [0, 4], "congratul": [61, 64], "conn": 0, "connect": [0, 1, 4, 11, 12, 20, 21, 22, 23, 32, 37, 46, 57, 58, 64, 71], "connect_to_databas": 1, "connect_via": [4, 58], "connected_to": [0, 58], "connection_class": 22, "connectionerror": 21, "connectionrefusederror": 21, "consequenti": 26, "consid": [0, 2, 3, 6, 21, 22, 32, 51, 55, 74], "consider": [11, 12, 24, 59], "consist": [0, 4, 22, 27, 58], "consol": [4, 5, 38, 57], "consolid": 4, "const": [0, 38], "construct": [3, 35, 44, 69], "constructor": [0, 3, 4, 6], "consult": [23, 28, 35, 55], "consum": [0, 21, 44], "contain": [0, 3, 4, 15, 22, 23, 32, 38, 50, 54, 60, 61, 64, 67, 70, 71, 72, 74], "content": [0, 4, 5, 6, 21, 24, 37, 43, 50, 54, 60, 61, 69, 70], "content_encod": 0, "content_languag": 0, "content_length": [0, 41], "content_loc": 0, "content_md5": 0, "content_rang": 0, "content_security_polici": 0, "content_security_policy_report_onli": 0, "content_typ": [0, 21, 60], "contentrang": 0, "contentsecuritypolici": 0, "context": [0, 4, 6, 11, 12, 13, 18, 20, 21, 22, 24, 27, 32, 37, 46, 47, 71, 74], "context_class": 0, "context_processor": [0, 59], "contextlib": [0, 58], "contextmanag": [0, 58], "contextvar": 55, "continu": [0, 2, 4, 8, 20, 38, 54, 56, 60, 61, 62, 63, 64, 65, 66, 67, 69, 70, 71, 72], "contract": 26, "contribut": 24, "contributor": 26, "control": [0, 4, 5, 6, 24, 35, 56, 64, 67, 70, 74], "convei": 0, "conveni": [5, 32, 54, 58, 62, 63, 64], "convent": [4, 24], "convert": [0, 4, 6, 14, 21, 27, 37, 38, 43, 47, 52, 54, 55, 59, 62, 71, 73, 74], "cooki": [0, 4, 6, 25, 27, 33, 36, 63, 72], "cool": 0, "coop": 0, "copi": [0, 4, 5, 6, 24, 50, 52, 63, 69], "copy_current_request_context": [0, 4], "copyright": [26, 50], "core": [18, 20, 24], "coroutin": [0, 2, 11, 12, 20, 55], "correct": [0, 3, 4, 17, 21, 34, 35, 43, 54, 70, 74], "correctli": [0, 4], "correspond": [0, 1, 3, 4, 25, 27, 54, 55, 61], "cost": [0, 20], "could": [0, 3, 4, 6, 8, 13, 15, 18, 20, 21, 22, 29, 30, 32, 36, 47, 51, 54, 57, 59, 61, 63, 70, 73, 74], "count": 71, "counter": [0, 74], "counterapi": 0, "coupl": [6, 30, 35, 53, 59], "cours": [30, 34, 53], "cover": [0, 21, 22, 38, 54, 65, 71], "coverag": [24, 60, 65, 66, 67], "cpu": [2, 13, 15, 18], "cpython": 4, "craft": [0, 21, 74], "crash": [4, 8, 21, 56], "creat": [0, 1, 2, 3, 4, 5, 6, 11, 12, 13, 15, 18, 19, 20, 21, 22, 23, 24, 27, 28, 29, 30, 32, 33, 37, 38, 43, 45, 46, 47, 52, 53, 54, 55, 60, 63, 64, 65, 67, 71, 73, 74], "create_al": 46, "create_app": [0, 1, 4, 5, 11, 12, 13, 15, 18, 19, 21, 22, 29, 30, 32, 60, 61, 62, 63, 64, 71, 72], "create_engin": 46, "create_global_jinja_load": 0, "create_jinja_environ": [0, 4], "create_jinja_load": 4, "create_task": 2, "create_url_adapt": [0, 4], "create_us": 5, "creation": [4, 29, 30, 43], "creator": 29, "credenti": [0, 6, 36, 54], "critic": 21, "cross": [0, 4, 24, 35, 59], "cross_origin_embedder_polici": 0, "cross_origin_opener_polici": 0, "crucial": 54, "cryptograph": [0, 6, 54, 74], "cryptographi": 4, "csp": 0, "csrf": 24, "css": [3, 43, 50, 54, 67, 69, 70, 74], "csv": 48, "ctrl": [5, 54, 64], "ctx": [0, 4, 52, 57], "cumbersom": 54, "cur": 47, "curiou": 20, "currenc": 59, "current": [0, 1, 3, 4, 5, 20, 32, 33, 40, 47, 52, 54, 55, 57, 59, 60, 61, 64, 66, 71, 74], "current_app": [0, 1, 2, 22, 27, 30, 55, 58, 60, 62], "current_timestamp": 62, "current_us": [32, 38], "cursor": 47, "custom": [0, 3, 4, 22, 24, 25, 27, 49, 54, 58, 59, 73, 74], "customcli": 0, "customiz": 4, "cycl": [1, 2], "d": [0, 10, 11, 12, 13, 18, 19, 54, 61, 73], "d2d4784f1b030a9761f5ccaeeaca413f27f2ecb76d6168407af962ddce849f79": 71, "dai": [0, 6], "damag": 26, "danger": [0, 4, 35, 61, 69, 74], "dark": 60, "dash": 22, "data": [2, 4, 5, 19, 20, 21, 24, 25, 26, 27, 35, 37, 38, 44, 46, 48, 53, 55, 61, 62, 64, 67, 68, 70, 71, 72, 73, 74], "databas": [0, 1, 2, 4, 6, 20, 21, 22, 23, 24, 32, 35, 37, 42, 46, 47, 54, 57, 60, 61, 63, 64, 65, 68, 72, 73], "database_uri": 6, "databaseerror": 0, "dataclass": [0, 4], "datarequir": 53, "datastructur": [0, 49], "date": [0, 4], "datetim": [0, 4, 6, 62], "david": 5, "db": [0, 1, 6, 22, 30, 32, 38, 42, 46, 47, 60, 61, 62, 63, 67, 71, 72, 73], "db_fd": 71, "db_path": 71, "db_server": 6, "db_session": [46, 53], "dd": [36, 53], "ddo": 74, "de": 34, "deal": [0, 4, 21, 35, 47, 54], "dealloc": 1, "debug": [0, 4, 24, 28, 48, 55, 56, 58, 64], "debugg": [0, 4, 5, 6, 14, 21, 24, 54, 55, 56, 64], "decid": [0, 2, 20, 22, 54, 65, 73], "decim": [0, 4], "decimalfield": 42, "decis": [0, 24], "declar": [20, 37, 42], "declarative_bas": 46, "decod": [0, 4, 38, 62, 71], "decor": [0, 2, 3, 4, 5, 20, 21, 22, 24, 27, 32, 37, 40, 43, 48, 51, 54, 59, 61, 69, 72], "decorated_funct": 52, "dedic": [6, 9, 14, 16, 34], "def": [0, 1, 2, 3, 5, 6, 20, 21, 22, 27, 28, 29, 30, 32, 33, 34, 35, 36, 38, 40, 41, 43, 44, 45, 46, 47, 48, 51, 52, 53, 54, 55, 58, 59, 60, 61, 62, 64, 67, 71, 72, 73, 74], "default": [0, 3, 4, 5, 6, 8, 13, 18, 20, 21, 22, 24, 27, 29, 32, 35, 36, 38, 45, 52, 54, 59, 60, 61, 62, 63, 64, 71, 72, 73, 74], "default_app": 29, "default_config": 0, "default_handl": 28, "default_mimetyp": 0, "default_set": 6, "default_statu": 0, "default_tag": 0, "defaultjsonprovid": 0, "defeat": 32, "defer": [0, 4, 24, 37, 54, 55], "defin": [0, 2, 3, 4, 5, 21, 22, 24, 28, 35, 37, 40, 42, 46, 50, 52, 53, 57, 60, 61, 64, 65, 70, 72, 73, 74], "definit": [0, 4], "del": 0, "delai": [0, 32], "deleg": 29, "delet": [0, 4, 20, 41, 43, 65, 71, 72, 73, 74], "delete_cooki": 0, "delimit": 70, "demand": 37, "demo": 5, "demonstr": [5, 45, 59], "deni": 54, "denial": 74, "denot": 70, "depend": [0, 3, 4, 6, 9, 11, 12, 13, 15, 16, 19, 20, 21, 22, 24, 28, 29, 38, 43, 54, 55, 57, 59, 63, 66, 67, 74], "deploi": [0, 5, 6, 9, 16, 24, 27, 29, 56, 62, 64, 65, 66, 71, 74], "deploy": [5, 6, 22, 54, 56, 63, 74], "deprec": [4, 20], "deprecationwarn": 4, "deriv": [0, 26], "desc": 61, "describ": [0, 2, 4, 8, 14, 24, 55, 58, 62], "descript": [0, 21, 38, 47, 54, 66, 73], "descriptor": [0, 71], "deseri": [0, 60], "design": [4, 5, 6, 14, 22, 24, 30, 33, 49, 53, 56, 63, 65], "desir": [4, 21, 38], "despit": 71, "destroi": [0, 1, 3, 47], "detail": [0, 7, 20, 24, 28, 30, 54, 56, 58, 60, 62, 68, 73, 74], "detailview": 73, "detect": [0, 4, 5, 25, 27, 30, 60, 63, 74], "detect_typ": 62, "detect_user_languag": 33, "determin": [0, 4, 20, 21, 58], "dev": [4, 5, 27, 63, 64], "develop": [0, 4, 8, 14, 15, 20, 21, 23, 24, 25, 27, 29, 30, 31, 35, 54, 55, 58, 61, 63, 64, 65, 66, 71, 74], "developmentconfig": 6, "di": [4, 47], "dialog": 61, "dict": [0, 4, 6, 21, 22, 27, 32, 38, 46, 47, 52, 54, 59, 60, 62, 71, 72], "dict_storage_class": 0, "dictat": 0, "dictconfig": 28, "dictionari": [0, 4, 6, 21, 35, 47, 51, 52, 54, 59], "did": [0, 4, 43, 46, 54, 55, 64, 74], "didn": [0, 27, 32, 67, 73], "differ": [0, 2, 3, 4, 5, 6, 9, 14, 15, 16, 20, 21, 22, 24, 25, 27, 29, 30, 36, 38, 44, 46, 54, 55, 56, 59, 60, 61, 62, 63, 68, 70, 71, 72, 73, 74], "difficult": [18, 22, 60, 74], "digest": 0, "digest_method": 0, "dira": 5, "dirb": 5, "direct": [0, 1, 9, 16, 20, 22, 26, 48, 69, 72], "direct_passthrough": 0, "directli": [0, 1, 4, 5, 6, 11, 12, 15, 19, 20, 21, 27, 32, 35, 38, 46, 47, 48, 54, 58, 60, 64, 70, 71, 72, 73], "director": 42, "directori": [0, 4, 5, 20, 34, 62, 63, 64, 66, 67, 69, 70, 71], "dirnam": 71, "disabl": [0, 4, 6, 8, 54, 56, 59], "disallow": [0, 6, 35], "disappear": 0, "disclaim": 26, "disconnect": [0, 58], "discord": 22, "discourag": [0, 4, 6], "discov": [0, 28], "discoveri": 24, "discuss": [14, 20, 22, 38], "dispatch": [0, 3, 4, 6, 24, 37, 55, 60], "dispatch_request": [0, 2, 73], "dispatchermiddlewar": 29, "dispatchingapp": 4, "dispatchingjinjaload": 0, "displai": [0, 21, 35, 36, 54, 61, 68, 69, 70, 71], "disposit": [0, 4, 74], "dist": [63, 67], "distinct": [0, 4], "distinguish": [4, 34, 70], "distribut": [22, 25, 26, 27, 63], "div": [36, 38, 50, 61, 69, 70], "dive": [65, 68], "divid": [27, 43], "django": [6, 29, 46], "dl": [36, 53], "do": [0, 2, 3, 4, 5, 6, 8, 11, 12, 13, 14, 18, 19, 20, 21, 22, 27, 28, 29, 30, 31, 32, 34, 35, 36, 38, 40, 41, 43, 44, 47, 48, 51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 65, 66, 67, 68, 71, 72, 73, 74], "do_some_work": 0, "do_teardown_appcontext": 0, "do_teardown_request": 0, "do_the_login": 54, "do_work": 5, "doc": [0, 4, 9, 14, 15, 16, 18, 21, 24, 28, 32, 38, 42, 54, 60, 62, 65, 68, 74], "docker": 74, "doctyp": [35, 36, 50, 54, 70], "document": [0, 4, 5, 6, 7, 8, 9, 13, 15, 16, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 34, 35, 37, 43, 46, 50, 54, 55, 58, 59, 60, 68, 69, 70, 74], "documentroot": 9, "doe": [0, 1, 3, 4, 5, 6, 11, 12, 13, 15, 18, 19, 21, 24, 25, 27, 29, 30, 31, 33, 35, 36, 43, 46, 47, 50, 52, 53, 54, 55, 57, 59, 60, 61, 62, 63, 64, 70, 74], "doesn": [0, 4, 6, 20, 22, 32, 60, 61, 62, 63, 64, 65, 69, 70, 71, 72], "domain": [0, 3, 4, 6, 14, 29, 34, 50], "don": [0, 3, 4, 5, 6, 8, 11, 12, 13, 18, 19, 20, 21, 22, 27, 28, 30, 32, 35, 38, 40, 46, 51, 54, 55, 57, 58, 61, 70, 74], "done": [0, 4, 6, 20, 21, 27, 42, 57, 65, 74], "dot": [0, 3, 4, 5, 6, 13, 19, 40, 52, 71], "dotenv": [0, 4, 24, 25], "doubl": [0, 6, 38, 42, 64, 74], "down": [0, 4, 33, 46, 57, 60, 62], "download": [4, 35, 46], "download_fil": [0, 35], "download_nam": [0, 4], "downsid": [0, 3, 6, 30, 40, 46], "dozen": 0, "drop": [0, 4, 6, 15, 46, 57, 62], "dropdown": 5, "dsn": 21, "dt": [36, 53], "due": [0, 2, 4, 18, 20, 68], "dump": [0, 4, 21], "duplic": [0, 21, 61], "dure": [0, 1, 4, 5, 6, 8, 14, 21, 23, 24, 27, 28, 32, 33, 48, 54, 55, 56, 58, 62, 64, 71, 73], "duti": 64, "dynaconf": 6, "dynam": [4, 29, 38, 54, 70], "e": [0, 3, 4, 5, 6, 10, 21, 22, 43, 46, 62, 66, 71], "each": [0, 1, 2, 4, 6, 13, 14, 15, 17, 19, 20, 22, 23, 24, 25, 27, 28, 29, 32, 36, 42, 43, 46, 47, 48, 52, 54, 55, 58, 60, 61, 62, 67, 70, 71, 72, 73, 74], "eager": [4, 54], "earli": [0, 4, 6, 21, 22, 54], "earlier": [4, 6, 32, 61, 71, 72], "eas": 35, "easi": [3, 13, 15, 19, 20, 22, 24, 27, 29, 37, 38, 51, 53, 54, 65], "easier": [0, 4, 5, 6, 22, 37, 48, 53, 55, 57, 59, 68, 71], "easiest": [6, 31, 50, 54, 57, 71], "easili": [3, 4, 6, 13, 20, 47, 53, 54, 57, 58, 74], "echo": [60, 62], "ecmascript": 74, "eco": 22, "ecosystem": 22, "edg": 0, "edit": [4, 5, 9, 16, 22, 60, 61, 63, 65, 66, 71, 72, 73], "editor": 67, "eee": 69, "effect": [0, 70], "effici": [0, 5, 6, 14, 25, 56, 63, 73], "effort": 46, "eg": [0, 44], "egg": [4, 23, 67], "either": [0, 2, 3, 4, 6, 13, 18, 22, 33, 34, 38, 46, 47, 56, 59, 61, 62, 70, 71, 72, 74], "elast": 14, "element": [50, 53, 54, 74], "elif": [52, 72], "els": [0, 1, 2, 3, 20, 21, 28, 29, 32, 36, 38, 47, 51, 52, 54, 55, 61, 63, 64, 70, 72], "elsewher": [0, 22, 63], "em": 54, "email": [0, 21, 23, 24, 32, 38, 46, 53, 54], "embed": [6, 42, 74], "embeddeddocu": 42, "embeddeddocumentfield": 42, "emit": [4, 21, 58], "empti": [0, 4, 6, 35, 50, 52, 60, 62, 72], "en": 74, "enabl": [0, 2, 3, 4, 5, 6, 8, 11, 12, 20, 25, 32, 40, 48, 54, 55, 56, 59, 74], "enclos": 0, "encod": [0, 4, 38], "encount": [0, 3, 65], "encourag": 46, "enctyp": [0, 35, 54], "end": [0, 1, 4, 5, 6, 9, 16, 20, 22, 27, 33, 36, 37, 43, 44, 46, 47, 54, 55, 59, 60, 61, 62, 67, 69, 70, 72, 74], "endautoescap": 59, "endblock": [21, 36, 50, 61, 70], "endfor": [36, 53, 59, 61, 70], "endif": [36, 53, 54, 61, 70], "endmacro": [0, 53], "endors": 26, "endpoint": [0, 3, 4, 35, 37, 40, 45, 51, 54, 61], "endswith": 29, "endwith": 36, "enforc": [0, 4, 6, 36], "engin": [0, 4, 14, 18, 24, 40, 46, 48, 50, 54, 59, 74], "enhanc": 4, "enorm": 48, "enotdir": 4, "enough": [0, 3, 21, 31, 36, 37, 54, 74], "ensur": [0, 4, 20, 22, 25, 27, 38, 43, 61, 64, 74], "ensure_ascii": 0, "ensure_sync": [0, 2], "enter": [4, 67, 70], "entir": [23, 29, 38, 70, 74], "entiti": [0, 59], "entri": [0, 4, 5, 22, 46], "enum": 0, "enumer": 47, "env": [0, 4, 5, 6, 44, 62], "environ": [0, 4, 8, 14, 24, 27, 28, 29, 41, 44, 48, 54, 55, 63, 66, 67], "environ_bas": 0, "environ_overrid": 0, "environbuild": [0, 4, 60], "equal": [6, 42, 74], "equalto": 53, "equip": 68, "equival": [0, 5, 6, 8, 13, 19, 20, 30, 73], "ergonom": 22, "errno": [5, 54, 56, 64], "error": [0, 1, 2, 4, 6, 13, 15, 19, 24, 27, 29, 32, 35, 36, 38, 53, 61, 70, 71, 72, 73], "error_handl": 4, "error_handler_spec": [0, 4], "errorhandl": [0, 3, 4, 21, 27, 54, 55], "errorhandlercal": 0, "escap": [0, 4, 24, 25, 48, 53, 59, 70, 72, 74], "especi": [0, 20, 51, 54, 58], "essenti": 0, "establish": 62, "estim": 0, "etag": [0, 4], "etc": [0, 2, 3, 4, 6, 9, 14, 16, 21, 27, 30, 54, 57, 74], "evalu": [0, 4, 14, 20, 22, 50], "even": [0, 2, 3, 4, 5, 6, 8, 21, 24, 25, 26, 27, 31, 47, 53, 54, 55, 56, 59, 68, 70, 73, 74], "event": [0, 4, 10, 20, 22, 24, 26, 55, 58], "eventlet": [2, 12, 14, 25], "eventu": 20, "ever": [0, 54], "everi": [0, 1, 3, 4, 5, 6, 20, 22, 27, 30, 35, 43, 47, 51, 71, 73], "everybodi": 57, "everyth": [0, 1, 20, 21, 35, 43, 55, 61, 64, 66, 74], "ex": [0, 3], "exact": [0, 4, 6, 60], "exactli": [0, 22, 35, 46, 52], "examin": 60, "exampl": [0, 1, 2, 3, 4, 5, 6, 15, 20, 22, 23, 28, 29, 30, 32, 33, 34, 36, 37, 38, 43, 44, 45, 46, 47, 49, 50, 52, 53, 54, 55, 56, 58, 59, 60, 63, 64, 65, 67, 68, 69, 71, 72, 73, 74], "exc": 0, "exc_info": 0, "exce": 0, "exceed": [0, 6], "excel": 52, "except": [0, 1, 3, 4, 6, 8, 27, 28, 29, 35, 46, 47, 55, 61, 64, 70, 72, 73], "exclud": [4, 5], "execut": [0, 3, 4, 5, 8, 9, 16, 20, 21, 33, 35, 46, 47, 51, 54, 55, 57, 58, 61, 62, 71, 72, 74], "executescript": [0, 47, 62, 71], "exemplari": 26, "exhaust": [0, 14], "exist": [0, 1, 3, 4, 6, 9, 16, 20, 22, 27, 29, 33, 35, 43, 52, 54, 59, 61, 62, 63, 64, 71, 72, 74], "exit": [0, 4, 55], "exitstack": 4, "expand": [0, 4, 53, 65], "expect": [0, 2, 3, 4, 5, 6, 11, 12, 13, 18, 20, 21, 22, 55, 60, 71, 74], "expens": 52, "experi": [0, 6, 8, 24, 30, 54], "expir": [0, 4, 6, 74], "explain": [4, 24, 35, 54], "explain_template_load": [3, 4, 6], "explan": [60, 66], "explicit": [4, 6, 21, 24, 34, 59], "explicitli": [0, 4, 6, 21, 51, 54, 59, 74], "explor": [5, 27], "export": [0, 4, 5, 6], "expos": [0, 3, 4, 20, 54], "express": [15, 21, 26, 48, 54, 70, 74], "ext": [4, 22, 28], "extend": [0, 3, 4, 21, 24, 36, 50, 60, 61, 70, 73], "extens": [0, 1, 3, 4, 5, 6, 18, 20, 24, 27, 31, 32, 35, 37, 58, 59, 60, 64, 65, 68, 71, 73, 74], "extensionnam": 22, "extern": [0, 2, 4, 6, 17, 22, 24, 74], "extra": [0, 2, 3, 4, 5, 20, 21, 22, 23, 34, 54, 58, 71, 73, 74], "extract": [4, 6, 60], "extrem": 74, "f": [0, 3, 6, 38, 40, 44, 46, 47, 48, 52, 54, 58, 59, 60, 61, 62, 71, 72, 73], "f4q8z": [36, 54], "fabric": 6, "face": [21, 74], "facebook": 74, "facilit": 6, "fact": [3, 20, 38], "facto": 34, "factor": 3, "factori": [0, 1, 4, 5, 11, 12, 13, 15, 18, 19, 20, 21, 22, 24, 29, 37, 47, 60, 61, 62, 63, 72], "fail": [0, 4, 5, 21, 28, 36, 47, 54, 55, 56, 58, 71, 72], "failur": [0, 21], "fake": [17, 20, 55, 57], "fake_init_db": 71, "fall": [0, 4, 6, 22, 29, 40], "fals": [0, 4, 6, 8, 22, 32, 46, 47, 53, 59, 71, 73], "famili": [4, 69], "familiar": [14, 22, 54, 62, 65], "fanci": 21, "far": [0, 20, 27, 40, 61, 66, 68], "fashion": 21, "fast": [9, 16, 18], "faster": [2, 4, 25, 35], "favicon": [24, 37], "favor": 4, "favour": [4, 20], "featur": [0, 2, 4, 6, 7, 9, 13, 15, 16, 18, 19, 20, 25, 35, 37, 38, 52, 61, 65], "feed": 68, "feedback": [4, 36, 54], "feel": 22, "fetch": [24, 32, 37, 39, 47, 61], "fetchal": [47, 61, 72], "fetchon": [61, 71, 72], "few": [0, 20, 27, 46, 53, 68, 72, 74], "field": [0, 5, 6, 28, 42, 53, 70, 74], "figur": [0, 6, 20, 29, 40, 51, 54], "file": [0, 4, 9, 15, 16, 18, 20, 21, 22, 24, 27, 28, 30, 32, 34, 37, 38, 40, 43, 44, 45, 47, 60, 61, 63, 64, 65, 66, 67, 70, 71, 74], "file1": 5, "file2": 5, "file_wrapp": 0, "filenam": [0, 3, 4, 6, 34, 35, 38, 50, 54, 60, 69, 70], "filename_or_fp": 0, "filestorag": 0, "filesystem": [0, 3, 21, 30, 35, 48, 54], "filesystemload": 0, "filewrapp": 0, "fill": [0, 50, 61, 70, 72, 74], "filter": [0, 3, 4, 20, 24, 37, 38, 46, 53, 54, 68, 74], "final": [0, 58, 60, 65, 70], "finalize_request": 4, "find": [0, 3, 4, 5, 6, 21, 22, 24, 32, 34, 37, 40, 43, 53, 54, 60, 63, 64, 65, 66, 69, 71], "find_packag": 4, "findstr": 56, "fine": [21, 43], "finer": 4, "finish": [32, 61, 62], "fip": 4, "fire": [20, 24], "first": [2, 4, 6, 20, 21, 22, 24, 25, 27, 29, 32, 34, 35, 38, 40, 42, 43, 46, 47, 50, 52, 53, 54, 55, 57, 58, 61, 62, 63, 65, 69, 73, 74], "first_registr": 0, "firstnam": 47, "fish": [5, 6], "fishi": 54, "fit": [20, 22, 23, 26], "fix": [0, 4, 17, 28, 61], "fix_head": 0, "fixtur": 24, "flag": [0, 4, 71], "flash": [4, 24, 35, 37, 53, 61, 69, 70, 72], "flask": [0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 13, 14, 15, 16, 19, 21, 23, 27, 29, 30, 31, 33, 34, 35, 36, 38, 40, 41, 42, 43, 45, 48, 51, 52, 53, 55, 56, 57, 59, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74], "flask_": [0, 4, 6], "flask_app": [4, 5, 32], "flask_combonam": 22, "flask_command_opt": 5, "flask_debug": [0, 6], "flask_env": [4, 6], "flask_extension_nam": 22, "flask_foo": [0, 23], "flask_mail_en": 6, "flask_mongoengin": 42, "flask_myapi__credentials__usernam": 6, "flask_nam": 22, "flask_name_low": 22, "flask_opt": 5, "flask_run_port": 5, "flask_secret_kei": 6, "flask_skip_dotenv": [4, 5], "flask_sqlalchemi": 4, "flaskclient": [0, 4], "flaskclirunn": [0, 60], "flaskenv": [0, 4, 5], "flaskgroup": [0, 4, 5], "flaskintegr": 21, "flaskr": [60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72], "flasktask": 32, "flatten": 0, "flaw": 4, "fledg": 35, "flex": 69, "flexibl": [46, 52, 65], "flight": 47, "flip": [4, 6], "flit_cor": [4, 43, 66], "float": [0, 54], "flow": 70, "fluffi": 74, "fly": 48, "fnmatch": 5, "focu": 38, "focus": [4, 69], "folder": [0, 4, 20, 24, 25, 35, 43, 54, 60, 62, 63, 64, 71], "follow": [0, 1, 4, 5, 6, 8, 20, 22, 24, 25, 26, 27, 30, 32, 35, 37, 43, 44, 45, 46, 52, 53, 54, 55, 56, 59, 63, 64, 65, 67, 69, 72, 73, 74], "follow_redirect": [0, 60], "font": 69, "foo": [0, 6, 23], "foo_bar": 23, "foo_spam": 23, "foobar": 4, "footer": [50, 54], "forbidden": [56, 61, 71], "forc": [0, 4, 20, 74], "force_typ": 0, "foreign": 62, "forg": [35, 54], "forgeri": 24, "forget": [4, 54], "form": [0, 4, 6, 20, 24, 26, 28, 32, 35, 36, 37, 38, 44, 52, 54, 61, 68, 69, 70, 71, 72, 73, 74], "form_data_parser_class": 0, "format": [0, 4, 6, 28, 32, 34, 38, 47, 52, 54, 55, 63, 68], "format_pric": 59, "formatt": 28, "formdata": 38, "formdatapars": 0, "formerli": 20, "fortun": [21, 44], "forward": [0, 4, 6, 9, 16, 17, 51, 53, 58], "found": [0, 3, 4, 5, 6, 8, 21, 54, 55, 61, 71], "foundat": 20, "four": [46, 50], "fox": 42, "fp": 0, "framework": [2, 20, 23, 24, 25, 27, 45, 60, 74], "free": [14, 20, 21, 59], "freed": 20, "freez": 0, "frequenc": 21, "fresh": 0, "friendli": 54, "from": [0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 40, 41, 42, 43, 45, 46, 47, 49, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 69, 70, 71, 72, 73, 74], "from_app": 0, "from_envvar": [0, 4, 6], "from_fil": [0, 4, 6], "from_json": [4, 73], "from_map": [0, 4, 27, 32, 64], "from_object": [0, 6], "from_prefixed_env": [0, 4, 6, 27, 32], "from_pyfil": [0, 4, 6, 30, 64], "from_valu": 0, "fromaddr": 28, "fromisoformat": 62, "front": [0, 4, 9, 11, 12, 13, 14, 16, 17, 18, 19, 65], "frontend": [0, 29, 30, 45, 51], "frontend_app": 29, "frozenset": 41, "frustrat": 59, "fspath": 4, "ft": 0, "fulfil": 0, "full": [0, 1, 4, 5, 6, 19, 21, 24, 35, 36, 54, 55, 60, 65], "full_dispatch_request": 0, "full_path": 0, "fulli": [0, 4, 44, 58, 70], "fun": [53, 54, 68], "func": [0, 2], "function": [1, 2, 3, 4, 5, 6, 13, 20, 21, 22, 23, 24, 27, 29, 30, 31, 32, 33, 35, 36, 38, 40, 43, 46, 47, 48, 49, 51, 52, 53, 54, 55, 57, 58, 59, 60, 61, 62, 64, 69, 71, 72, 73], "functool": [52, 72], "fundament": 29, "further": [0, 3, 4, 24, 27, 30, 40, 51, 52, 60, 62, 73], "furthermor": [20, 51], "futur": [0, 4, 6, 42, 66, 67, 71], "g": [0, 1, 3, 4, 10, 20, 21, 22, 27, 33, 46, 47, 51, 52, 54, 55, 57, 58, 59, 60, 61, 62, 70, 71, 72, 73], "gae": 4, "gain": [3, 4, 43], "garbag": 4, "gatewai": 0, "gave": 63, "gcc": 5, "gener": [0, 3, 4, 6, 8, 9, 16, 22, 23, 27, 35, 37, 43, 46, 48, 51, 52, 53, 55, 57, 59, 60, 61, 63, 67, 70, 71, 72, 73, 74], "generate_checksum": 44, "generate_large_csv": 48, "generate_password_hash": 72, "generate_report": [0, 38, 55], "generate_user_arch": 32, "generate_valid": 73, "generator_or_funct": 0, "genshi": 20, "gentl": [37, 43], "geologi": 38, "geology_div": 38, "geology_fact": 38, "geology_url": 38, "germeist": 4, "get": [0, 1, 2, 3, 4, 5, 6, 15, 17, 21, 22, 24, 27, 29, 30, 33, 34, 35, 36, 37, 38, 41, 44, 46, 47, 48, 52, 54, 55, 57, 58, 59, 60, 61, 63, 64, 67, 68, 70, 71, 72, 73, 74], "get_all_us": 54, "get_app_it": 0, "get_appl": 29, "get_command": 0, "get_cookie_domain": 0, "get_cookie_httponli": 0, "get_cookie_nam": [0, 4], "get_cookie_partit": 0, "get_cookie_path": 0, "get_cookie_samesit": 0, "get_cookie_secur": 0, "get_current_context": 4, "get_current_us": 54, "get_data": [0, 2, 4, 60, 71], "get_db": [1, 22, 47, 61, 62, 71, 72], "get_etag": 0, "get_expiration_tim": [0, 4], "get_flashed_messag": [0, 4, 36, 54, 59, 70], "get_json": [0, 4], "get_namespac": [0, 4], "get_one_chees": 21, "get_or_404": [38, 42, 73], "get_post": 61, "get_resourc": 21, "get_respons": [0, 21], "get_send_file_max_ag": [0, 4, 6], "get_template_attribut": [0, 4], "get_us": [21, 28], "get_user_for_prefix": 29, "get_user_for_subdomain": 29, "get_wsgi_head": 0, "get_wsgi_respons": 0, "get_x": 1, "getattr": 47, "getelementbyid": 38, "getlogg": 28, "gettempdir": 35, "gevent": [0, 2, 11, 14, 25], "gif": 35, "git": [4, 67], "github": [21, 22], "gitignor": 67, "give": [0, 4, 5, 20, 21, 34, 36, 53, 54, 59, 61, 63, 65], "given": [0, 3, 4, 5, 6, 21, 22, 32, 38, 51, 54, 71, 73, 74], "global": [1, 4, 21, 22, 24, 38, 54, 55, 59, 64, 73], "glue": 20, "go": [0, 5, 20, 21, 25, 46, 54, 60, 61, 62, 63, 68, 69, 70, 72, 74], "goal": 14, "goe": [3, 40, 44, 52, 60, 70, 74], "good": [0, 1, 6, 9, 16, 20, 26, 31, 35, 36, 38, 43, 47, 52, 55, 58, 65, 74], "googl": [4, 14, 40], "got": [4, 32], "got_first_request": 4, "got_request_except": [0, 27, 55], "grant": 0, "graphql": 60, "grappa": 4, "great": 65, "greatli": 3, "greenlet": [0, 4, 11, 12, 13, 18, 20], "greet": 54, "grep": 56, "group": [0, 4, 5, 15, 25, 43, 60, 72, 73], "groupapi": 73, "grow": [20, 64], "gt": 54, "guarante": [0, 22, 55, 71], "guard": 0, "guess": [0, 4, 34, 74], "guess_language_from_request": 33, "gui": 52, "guid": [0, 22, 32], "guidelin": [4, 24], "gunicorn": [4, 11, 12, 14], "gzip": 0, "h": 74, "h1": [21, 35, 36, 50, 54, 61, 69, 70], "h2": 60, "ha": [0, 1, 2, 3, 4, 5, 6, 13, 18, 20, 21, 22, 27, 28, 32, 35, 40, 42, 43, 46, 47, 48, 51, 52, 54, 55, 59, 60, 61, 62, 64, 69, 72, 74], "habit": 67, "hack": 20, "hacker": [35, 54], "had": [0, 4, 22, 35, 73], "half": [27, 53], "halfwai": 4, "hand": [4, 6, 20, 32, 47, 57, 59], "handi": [21, 30, 47, 54, 57], "handl": [0, 1, 2, 3, 4, 5, 9, 11, 12, 16, 20, 22, 24, 29, 33, 35, 38, 46, 47, 49, 51, 52, 53, 54, 55, 56, 61, 62, 64, 72, 73, 74], "handle_507": 21, "handle_bad_request": 21, "handle_except": [0, 21], "handle_http_except": 0, "handle_url_build_error": [0, 4], "handle_user_except": 0, "handler": [0, 1, 2, 4, 6, 24, 27, 30, 40, 47, 55, 58, 74], "happen": [0, 20, 22, 27, 33, 54, 55, 62, 64, 74], "happili": 35, "hard": [0, 4, 6, 53, 54, 73, 74], "hardcod": [0, 4], "harddriv": 21, "harder": [6, 20], "has_app_context": 0, "has_request_context": [0, 4, 28], "has_static_fold": 0, "hash": [0, 4, 44, 72], "hashlib": [4, 44], "hasn": 61, "hate": [36, 43, 54], "have": [0, 1, 2, 3, 4, 5, 6, 8, 11, 12, 14, 18, 20, 21, 22, 25, 28, 29, 30, 31, 35, 36, 38, 40, 43, 46, 47, 48, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 68, 70, 71, 72, 74], "haven": [2, 70], "he": 35, "head": [0, 3, 4, 41, 46, 50, 53, 54, 59], "header": [0, 4, 6, 9, 15, 16, 17, 21, 24, 27, 29, 38, 41, 54, 60, 61, 69, 70, 71], "headerset": 0, "healthi": 45, "heard": 38, "heartbeat": 45, "height": 69, "hello": [0, 5, 6, 8, 9, 11, 12, 13, 15, 16, 18, 19, 20, 22, 27, 29, 30, 43, 48, 52, 54, 55, 56, 60, 61, 64, 67, 71, 72], "hello_command": 60, "hello_world": [29, 54], "helloextens": 22, "help": [0, 3, 4, 5, 13, 19, 20, 22, 23, 27, 28, 34, 42, 43, 51, 54, 56, 65, 73, 74], "helper": [4, 24, 40, 53, 57, 58, 59], "here": [0, 3, 5, 6, 14, 20, 21, 22, 29, 30, 32, 36, 38, 40, 43, 46, 47, 50, 51, 52, 53, 54, 58, 59, 60, 63, 68, 70, 71, 72, 74], "hexdigest": 44, "hidden": [52, 74], "hide": 4, "hierarchi": [4, 21], "higher": 28, "hint": [4, 24], "histori": [0, 4, 60], "hit": 21, "hmac": 0, "hoc": 4, "hold": [0, 6, 54, 64], "holder": [0, 26], "home": [5, 15, 35, 66, 67, 71], "home_username_": 35, "homepag": 50, "honor": [4, 74], "hook": [0, 4, 24, 30, 44], "host": [0, 4, 6, 9, 13, 16, 17, 19, 21, 24, 29, 54, 63, 74], "host_match": [0, 4, 6], "host_url": 0, "hostnam": [0, 4], "hour": 0, "how": [0, 1, 2, 3, 4, 5, 6, 13, 15, 17, 18, 19, 20, 21, 22, 24, 29, 30, 32, 34, 35, 36, 38, 40, 42, 43, 45, 46, 47, 48, 49, 53, 59, 60, 62, 63, 64, 66, 67, 69, 71, 73, 74], "howev": [0, 1, 2, 3, 4, 6, 8, 11, 12, 13, 14, 15, 18, 19, 20, 21, 26, 27, 30, 33, 34, 38, 40, 44, 54, 57, 59, 60, 61, 62, 65, 67, 71, 73], "hr": [61, 69], "href": [21, 34, 36, 50, 61, 70, 71, 74], "htm": [4, 54, 59], "html": [0, 3, 4, 21, 24, 34, 35, 36, 38, 43, 45, 48, 50, 52, 53, 58, 59, 61, 67, 69, 70, 71, 72, 73, 74], "html5": 4, "htmlcov": [67, 71], "htmlsafe_dump": 4, "http": [0, 2, 4, 5, 6, 9, 11, 13, 14, 16, 17, 18, 19, 21, 24, 27, 35, 37, 38, 50, 53, 55, 56, 60, 61, 63, 64, 69, 70, 73], "http_host": 29, "http_server": 12, "http_x_http_method_overrid": 41, "httpd": [11, 12, 13, 14, 15, 18, 19], "httpexcept": [0, 4, 6, 21], "httpmethodoverridemiddlewar": 41, "httponli": [0, 4, 74], "httpstatu": 0, "hub": 4, "human": 21, "hypercorn": 10, "hypothetical_flask": 20, "i": [0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 21, 22, 23, 24, 25, 26, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 70, 71, 72, 73, 74], "ico": 34, "icon": 34, "id": [0, 4, 5, 8, 21, 22, 32, 38, 46, 47, 50, 54, 56, 60, 61, 62, 70, 71, 72, 73, 74], "idea": [0, 3, 20, 22, 29, 30, 31, 32, 35, 38, 43, 47, 51, 52, 57, 59, 68], "ideal": [0, 3, 6, 54, 74], "ident": 70, "identif": 0, "identifi": [0, 24, 56], "idx": 47, "if_match": 0, "if_modified_sinc": 0, "if_none_match": 0, "if_rang": 0, "if_unmodified_sinc": 0, "ifram": [6, 74], "ifrang": 0, "ignor": [0, 4, 6, 32, 54, 57, 67], "ignore_result": 32, "imag": [0, 34, 54, 68, 69, 74], "image_store_": 0, "image_store_base_url": 0, "image_store_config": 0, "image_store_path": 0, "image_store_typ": 0, "imagin": [30, 35, 40, 43, 52, 54, 74], "imdb": 42, "imdb_id": 42, "img": 0, "immedi": [0, 4, 27, 32, 55, 56, 57], "immutabledict": [0, 4], "immutablelist": 0, "immutablemultidict": 0, "immutableorderedmultidict": 49, "impact": 4, "implement": [0, 2, 3, 4, 5, 6, 13, 20, 21, 22, 25, 29, 30, 35, 37, 43, 47, 52, 54, 55, 58, 61, 74], "impli": [26, 53], "implicit": [4, 20, 74], "implicit_seqence_convers": 0, "implicit_sequence_convers": 0, "implicitli": [0, 4, 6], "implicity_sequence_convers": 0, "import": [0, 1, 3, 4, 5, 6, 10, 11, 12, 13, 15, 17, 18, 19, 20, 21, 22, 23, 27, 28, 29, 30, 32, 33, 34, 35, 36, 38, 40, 41, 42, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 70, 71, 72, 73, 74], "import_nam": [0, 4, 40], "import_str": [6, 40], "importerror": 4, "importlib": 4, "importlib_metadata": 4, "imposs": [32, 38], "improv": [0, 2, 4, 6, 21, 24, 37, 51, 74], "inabl": [4, 59], "inact": 0, "inbound": 0, "incident": 26, "includ": [0, 4, 6, 7, 18, 20, 21, 22, 26, 27, 38, 56, 66, 74], "includesubdomain": 74, "incom": [4, 9, 14, 16, 17, 21, 24, 35, 44, 72], "incompat": 4, "inconsist": 6, "inconveni": 44, "incorrect": [0, 4, 70, 71, 72], "incorrectli": [4, 74], "increas": 74, "increment": 59, "inde": 54, "indent": [0, 4, 70], "independ": [6, 22, 25, 55, 64], "index": [0, 3, 20, 21, 22, 27, 28, 30, 36, 40, 43, 45, 47, 50, 51, 52, 54, 58, 60, 67, 68, 70, 71, 72, 74], "index_templ": 30, "indic": [0, 1, 4, 6, 21, 22, 25, 55, 74], "indirect": 26, "individu": [0, 6, 53, 60, 61, 74], "ineffici": [0, 73], "infer": [0, 3], "infinit": [0, 4, 6], "info": [0, 4, 13, 28, 32, 67], "info_nam": 0, "inform": [0, 1, 4, 5, 6, 8, 15, 18, 20, 21, 22, 24, 29, 30, 32, 37, 38, 42, 46, 51, 52, 53, 55, 57, 58, 59, 60, 61, 71, 72, 74], "infrastructur": 20, "inher": 2, "inherit": [0, 2, 4, 6, 20, 24, 36, 37, 42, 54, 73], "ini_opt": 71, "init": [0, 21, 62, 63, 71], "init_app": [6, 22, 23, 30, 62], "init_db": [0, 1, 46, 47, 62, 71], "init_db_command": 62, "init_every_request": [0, 4, 73], "init_jinja_glob": 4, "initi": [0, 1, 3, 4, 6, 23, 24, 27, 30, 37, 56, 57, 59, 71, 72, 73], "inject": [0, 24, 25, 47, 51, 52, 54, 59, 72, 74], "inject_url_default": 0, "inject_us": 59, "inlin": [0, 4], "inner": [43, 48], "innerhtml": 38, "innermost": [0, 52], "inotifi": 5, "input": [0, 5, 25, 35, 36, 44, 52, 53, 54, 61, 69, 70, 71, 72, 74], "input_stream": 0, "input_termin": 0, "insecur": 0, "insensit": 6, "insert": [0, 46, 47, 53, 59, 61, 71, 72], "insid": [0, 4, 5, 6, 20, 29, 32, 36, 43, 45, 59, 61, 64, 70, 71], "inspect": [0, 6, 38], "instal": [0, 2, 4, 5, 6, 9, 16, 21, 22, 23, 24, 35, 37, 42, 43, 54, 59, 60, 61, 62, 65, 67, 71], "instanc": [0, 1, 3, 4, 5, 20, 21, 22, 23, 24, 27, 29, 30, 32, 33, 42, 43, 44, 47, 51, 52, 54, 55, 57, 60, 62, 63, 64, 67, 71, 73], "instance_path": [0, 4, 6, 64], "instance_rel": 0, "instance_relative_config": [0, 6, 64], "instanti": [0, 3, 6, 20, 29, 42, 52], "instead": [0, 1, 3, 4, 5, 6, 9, 11, 12, 13, 14, 18, 19, 20, 21, 22, 24, 27, 28, 29, 32, 33, 35, 38, 39, 40, 43, 46, 47, 54, 55, 56, 58, 59, 60, 61, 62, 63, 64, 70, 71, 72, 73, 74], "instruct": [3, 4, 5, 6, 14, 23, 56, 63, 67], "insufficientstorag": 21, "int": [0, 6, 32, 38, 54, 61, 73], "integ": [0, 32, 46, 54, 62], "integr": [0, 4, 6, 10, 13, 15, 18, 20, 21, 24, 25, 37, 42, 59], "integrityerror": 72, "intellig": 54, "intend": [0, 3, 4, 14, 56], "intent": 3, "interact": [0, 4, 5, 6, 8, 21, 22, 37, 54, 55, 56, 57, 64, 71], "intercept": [17, 74], "interchang": 21, "interest": [0, 6, 27, 35, 51, 52, 59, 68], "interfac": [1, 4, 8, 14, 19, 20, 24, 25, 27, 29, 30, 36, 54, 55, 56, 62], "interfer": [8, 22, 56], "intermedi": [0, 6], "intern": [1, 4, 6, 21, 22, 24, 27, 29, 40, 49, 54, 55, 71], "internal_server_error": 21, "internalservererror": [0, 4, 21], "internation": 37, "interpret": [0, 4, 6, 29, 62, 74], "interrupt": 26, "intfield": 42, "introduc": [3, 4, 5, 6, 20, 21, 51, 54, 56, 58, 66, 71, 73], "introduct": [0, 37, 43, 54, 59], "invalid": [0, 3, 4, 6, 21, 36, 38, 50, 54, 61, 71], "invalid_api_usag": 21, "invalidapiusag": 21, "invent": 52, "invisibli": 74, "invoc": 0, "invok": [0, 3, 4, 5, 21, 22, 48, 54, 60, 71], "involv": [4, 14, 21, 22], "io": [0, 2, 4], "iobas": 0, "ip": [0, 4, 8, 9, 11, 12, 13, 16, 18, 19, 28, 54], "ipv4": 56, "iri": 0, "is_endpoint_expect": 51, "is_json": [0, 4], "is_multiprocess": 0, "is_multithread": 0, "is_null_sess": 0, "is_packag": 4, "is_prim": 0, "is_run_onc": 0, "is_secur": 0, "is_sequ": 0, "is_stream": 0, "is_weak": 0, "isinst": [0, 21, 52], "isn": [0, 4, 8, 20, 21, 62, 69, 74], "iso": 4, "isol": [0, 29, 60, 66], "issu": [1, 4, 5, 7, 17, 20, 21, 22, 27, 32, 57, 58, 64, 74], "ital": 69, "item": [0, 4, 54, 55, 58, 69, 71, 73], "itemapi": 73, "iter": [0, 4, 20, 42, 47, 48, 54, 59], "iter_all_row": 48, "iter_blueprint": 0, "iter_encod": 0, "iteritem": 0, "its": [0, 3, 5, 9, 11, 12, 13, 15, 16, 18, 19, 20, 21, 22, 25, 26, 27, 28, 54, 56, 58, 59, 61, 63, 66, 68, 72, 73], "itsdanger": [0, 4, 25, 27, 66, 68, 74], "itself": [0, 3, 4, 6, 9, 16, 20, 21, 22, 24, 25, 31, 32, 37, 43, 47, 54, 55, 57, 59, 71, 73], "j": [4, 42], "jack": 21, "javascript": [0, 6, 24, 32, 35, 37, 39, 54, 61, 69, 74], "jinja": [0, 4, 20, 24, 25, 27, 38, 50, 54, 61, 68, 70, 74], "jinja2": [0, 3, 4, 20, 48, 53, 54, 59, 66, 74], "jinja_env": [0, 4, 27, 59], "jinja_environ": 0, "jinja_load": [0, 4], "jinja_opt": [0, 4], "job": [0, 50], "john": [0, 47, 54], "join": [0, 4, 6, 34, 35, 48, 61, 64, 71], "jpeg": 35, "jpg": 35, "jqueri": [35, 38], "json": [4, 6, 24, 27, 37, 39, 44, 73], "json_as_ascii": [4, 6], "json_avail": 4, "json_decod": 4, "json_encod": 4, "json_provider_class": 0, "json_sort_kei": [4, 6], "jsondecod": 4, "jsonencod": 4, "jsonifi": [0, 2, 3, 4, 21, 22, 38, 45, 54, 73, 74], "jsonify_mimetyp": [4, 6], "jsonify_prettyprint_regular": [4, 6], "jsonmixin": 4, "jsonprovid": [0, 4], "jsontag": 0, "just": [0, 3, 4, 5, 6, 20, 21, 29, 35, 36, 40, 43, 46, 47, 54, 57, 63, 64, 66, 69, 72, 74], "jython": 4, "k": [0, 13], "keep": [1, 4, 5, 6, 20, 24, 32, 40, 47, 48, 54, 55, 57, 59, 61, 63, 64, 65, 67, 70, 73, 74], "kei": [0, 4, 6, 22, 32, 35, 47, 50, 52, 59, 60, 62, 72], "key_deriv": 0, "keyboardinterrupt": 4, "keyerror": [0, 54], "keystrok": 40, "keyword": [0, 4, 5, 30, 42, 53, 54, 58, 73], "kick": [0, 4], "kind": [0, 6, 40, 54], "kitten": 74, "kjpksz6n": 71, "know": [0, 3, 17, 20, 21, 27, 32, 35, 38, 54, 55, 58, 60, 61, 62, 64, 72, 73, 74], "knowledg": [0, 35], "known": [0, 21, 27, 64, 73, 74], "kwarg": [0, 2, 4, 32, 40, 52, 53, 72], "label": [53, 61, 69, 70], "lack": [0, 20], "lai": 3, "lambda": [4, 62], "land": 20, "lang_cod": 51, "languag": [0, 20, 25, 33, 51, 62], "languageaccept": 0, "larg": [0, 3, 4, 20, 24, 29, 36, 37, 46, 48, 53, 59, 74], "larger": [3, 6, 29, 35, 43], "last": [0, 4, 22, 61, 69, 72], "last_modifi": 0, "lastnam": 47, "late": [0, 37, 66, 71], "later": [0, 3, 5, 6, 21, 27, 30, 32, 35, 54, 56, 62, 64, 72, 74], "latest": [4, 25], "latin": [0, 4], "latter": 51, "launch": [0, 54], "lax": [0, 6, 74], "layer": [0, 3, 20, 29, 37, 74], "layout": [4, 21, 24, 36, 43, 50, 54, 65, 69], "lazi": [4, 22], "lazili": [4, 24, 37], "lazyview": 40, "lead": [0, 21, 59], "leak": [0, 4, 6], "learn": [22, 32, 61, 62, 64, 65, 68], "least": [0, 6, 31], "leav": [4, 34, 64], "led": [4, 60], "left": 0, "leftov": 4, "legitim": 74, "len": [29, 58, 60], "length": [0, 4, 6, 53, 72], "less": [0, 2, 4, 21, 38, 69, 71], "let": [0, 5, 6, 22, 32, 35, 38, 41, 43, 52, 71, 73], "letter": 6, "level": [0, 1, 2, 3, 4, 5, 6, 9, 16, 21, 22, 28, 29, 55, 64, 74], "levelnam": 28, "leverag": 59, "li": [36, 53, 69, 70], "liabil": 26, "liabl": 26, "lib": 6, "librari": [0, 2, 4, 6, 11, 12, 20, 21, 22, 24, 25, 35, 38, 42, 53, 54, 58, 60, 62, 65, 66, 70, 72], "licens": [22, 24], "life": 1, "lifecycl": [24, 58], "lifetim": [0, 4, 24], "lifo": 0, "lightgrai": 69, "lightweight": [24, 58], "like": [0, 1, 3, 4, 5, 6, 9, 10, 11, 12, 15, 16, 20, 21, 22, 23, 25, 27, 29, 30, 32, 35, 38, 40, 42, 43, 46, 50, 51, 52, 53, 54, 55, 57, 58, 59, 61, 62, 63, 64, 66, 67, 68, 69, 70, 72], "likewis": [0, 54], "limit": [0, 4, 6, 20, 26, 35, 36, 58, 59, 74], "limoncello": 4, "line": [4, 8, 9, 16, 19, 24, 25, 30, 54, 60, 61, 62, 69, 71], "linger": 4, "link": [0, 3, 4, 14, 18, 22, 34, 38, 50, 61, 69, 70, 71, 72, 74], "linux": [0, 5, 9, 16, 25, 56, 63, 71], "list": [0, 4, 6, 9, 14, 16, 22, 26, 36, 47, 53, 54, 58, 59, 61, 63, 66, 69, 71, 72, 73], "list_command": 0, "list_storage_class": 0, "list_templ": 4, "listconvert": 0, "listen": [0, 4, 9, 11, 13, 16, 27, 29, 54, 56, 58], "listfield": 42, "listview": 73, "liter": 5, "littl": [4, 6, 35, 46, 47, 52, 53, 74], "live": [0, 60], "ll": [1, 5, 9, 14, 16, 18, 27, 28, 32, 35, 48, 50, 52, 54, 55, 56, 60, 61, 64, 66, 68, 70, 71, 72, 73, 74], "lloyd": 42, "load": [0, 3, 4, 5, 6, 13, 19, 20, 24, 27, 37, 46, 54, 57, 59, 64, 72, 74], "load_app": 0, "load_default": [0, 4], "load_dotenv": [0, 4, 5], "load_dotenv_default": 0, "load_logged_in_us": [70, 72], "load_us": 0, "loader": [0, 4], "loadmodul": 9, "local": [0, 1, 4, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19, 21, 24, 35, 55, 56, 58, 64, 66, 71], "local_auth": 30, "localhost": [4, 6, 9, 16, 32, 46, 56], "localproxi": [1, 55], "localstack": 4, "locat": [0, 3, 4, 5, 6, 9, 16, 35, 38, 50, 54, 60, 62, 64, 66, 71], "lock": [0, 4, 29], "locked_cached_properti": 4, "log": [0, 4, 6, 8, 13, 15, 19, 20, 24, 32, 36, 37, 38, 52, 61, 65, 71, 72, 74], "log_except": 0, "log_request": 0, "log_respons": 0, "log_security_except": 0, "log_template_rend": 0, "log_the_user_in": 54, "logfil": 13, "logger": [0, 4, 21, 28, 54], "logger_handler_polici": [4, 6], "logger_nam": [4, 6], "logic": [2, 3, 4, 33, 51, 54], "login": [4, 28, 36, 37, 38, 43, 53, 54, 60, 61, 67, 69, 70, 71, 74], "login_get": 54, "login_post": 54, "login_requir": [52, 61, 72, 73], "login_us": 28, "loglevel": 32, "logo": 69, "logout": [54, 60, 70, 71], "long": [0, 2, 6, 32], "longer": [0, 4, 5, 20, 27, 32, 38, 51, 54, 60, 71], "look": [0, 3, 4, 5, 9, 11, 12, 16, 20, 21, 22, 24, 27, 28, 29, 30, 35, 36, 40, 42, 43, 50, 53, 54, 55, 58, 59, 60, 61, 67, 68, 69, 70, 73, 74], "lookup": 0, "loop": [10, 18, 20, 24, 36, 61, 70], "lose": [0, 20, 21], "loss": 26, "lossless": 0, "lost": [0, 1, 22], "lot": [0, 6, 27, 46, 48, 51, 57, 64, 68, 73], "loudli": 4, "love": 57, "low": [2, 55], "lower": [3, 4, 22, 35, 73, 74], "lowercas": [0, 4, 6, 22, 73], "lsof": 56, "lstrip": 29, "lt": 54, "luck": 34, "luckili": 22, "ly": 20, "m": [4, 11, 12, 13, 15, 18, 19, 25, 47, 54, 61, 63, 71], "machin": [8, 27, 63], "maco": [25, 56], "macro": [0, 4, 20, 53, 59], "made": [0, 4, 6, 21, 56, 71, 72], "magic": 36, "mai": [0, 3, 4, 5, 6, 9, 11, 12, 14, 16, 20, 21, 22, 23, 25, 26, 28, 34, 35, 37, 38, 42, 49, 50, 54, 55, 56, 58, 60, 62, 63, 67, 74], "mail": [4, 21, 28], "mail_handl": 28, "mailhost": 28, "main": [0, 5, 20, 29, 46, 56, 57, 61], "mainli": [0, 2, 4, 60], "maintain": [0, 4, 14, 20, 22, 24, 54], "mainten": 22, "major": [8, 20, 54], "make": [0, 1, 2, 3, 4, 5, 6, 7, 9, 14, 15, 20, 21, 22, 24, 27, 30, 33, 35, 36, 37, 42, 43, 46, 47, 48, 51, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 67, 68, 70, 71, 73, 74], "make_abort": [0, 4], "make_app": [4, 5, 29, 30], "make_celeri": 32, "make_condit": 0, "make_config": 0, "make_context": 0, "make_default_options_respons": [0, 4], "make_dict": 47, "make_form_data_pars": 0, "make_null_sess": 0, "make_report": 55, "make_respons": [0, 4, 54], "make_sequ": 0, "make_setup_st": 0, "make_shell_context": 0, "make_test_environ_build": 4, "makechart": 38, "makedir": 64, "mako": 20, "malform": [4, 54], "malici": 0, "man": 74, "manag": [0, 1, 3, 4, 5, 6, 9, 14, 15, 16, 18, 25, 53, 54, 55, 58, 66, 74], "mandatori": 0, "mani": [0, 2, 4, 6, 7, 11, 12, 13, 14, 17, 18, 20, 22, 23, 27, 35, 37, 42, 46, 53, 54, 58, 60, 63, 65, 74], "manifest": 67, "manual": [0, 5, 9, 24, 37, 38, 54, 60, 70, 73], "map": [0, 3, 4, 6, 37, 51, 52, 72, 73], "mapadapt": 0, "mapper": [42, 46], "margin": 69, "mark": [0, 4, 6, 35, 47, 54, 59, 71], "markdown": [54, 59, 68], "markup": [0, 4, 54, 59, 74], "markupsaf": [4, 25, 48, 54, 66], "master": 18, "match": [0, 4, 5, 6, 8, 21, 27, 48, 51, 53, 55, 60, 61, 71, 72], "match_request": 0, "materi": 26, "math": 0, "matter": [61, 66, 67, 72, 73], "max": [0, 4, 6, 53, 69, 74], "max_ag": [0, 4, 74], "max_content_length": [0, 4, 6, 35, 74], "max_cookie_s": [0, 4, 6], "max_form_memory_part": 6, "max_form_memory_s": [0, 4, 6, 74], "max_form_part": [0, 4, 6, 74], "max_forward": 0, "maximum": [0, 4, 6, 35], "md5": 0, "mdn": [38, 54], "me": [0, 35, 42, 54, 60], "me_api": 54, "mean": [0, 1, 2, 3, 4, 5, 11, 12, 13, 14, 18, 19, 22, 24, 32, 36, 40, 54, 55, 57, 59, 61, 65, 66, 70, 73, 74], "meaning": 54, "measur": 71, "mechan": [0, 35], "media": 0, "meet": [0, 20], "megabyt": [0, 35], "member": 0, "memori": [0, 4, 6, 35, 48, 54, 59, 74], "mention": [6, 52, 54, 74], "menu": 5, "merchant": 26, "merg": [4, 5, 6, 59], "mess": 70, "messag": [1, 4, 5, 21, 24, 28, 37, 53, 55, 56, 60, 61, 62, 64, 70, 71, 72], "message_flash": [0, 4], "met": [26, 71], "metadata": [4, 22, 46, 66], "method": [0, 2, 4, 5, 6, 18, 21, 22, 24, 27, 28, 32, 35, 36, 37, 38, 44, 46, 51, 53, 55, 56, 57, 58, 60, 61, 70, 71, 72, 74], "method_not_allow": 21, "methodnotallow": [0, 21], "methodview": [0, 2, 4, 22, 73], "metric": 58, "mic": 0, "michael": 42, "micro": 24, "microframework": 20, "microsoft": [14, 34], "middl": 74, "middleiniti": 47, "middlewar": [0, 4, 10, 17, 20, 24, 29, 30, 35, 41, 48], "might": [0, 3, 4, 6, 9, 21, 22, 23, 27, 29, 35, 36, 38, 40, 46, 48, 50, 51, 53, 54, 57, 61, 62, 65, 66, 67, 68, 69, 74], "million": [14, 74], "mime": 0, "mimeaccept": 0, "mimetyp": [0, 4, 34, 54], "mimetype_param": 0, "min": [53, 69], "mind": [2, 5, 6, 20, 40, 47, 54, 57, 73, 74], "minim": [20, 24, 32], "minimum": [4, 22, 25], "minut": [31, 52, 73, 74], "mirror": 58, "miss": [0, 4, 54, 71], "misspel": 0, "mistak": 21, "mit": 22, "mitig": [0, 74], "mitm": 74, "mixin": [0, 4], "mkdir": [25, 64, 67], "mkstemp": 71, "mod_proxi": 9, "mod_proxy_http": 9, "mod_proxy_uwsgi": 18, "mod_wsgi": 14, "mode": [0, 4, 8, 18, 21, 22, 24, 47, 55, 56, 60, 63, 64, 66, 71], "model": [0, 24, 30, 32, 42, 46, 54, 58, 73, 74], "model_sav": 58, "modern": [2, 4, 9, 15, 16, 38, 54, 74], "modif": [0, 26], "modifi": [0, 3, 4, 6, 24, 27, 30, 33, 35, 54, 55, 61, 63, 71, 72, 74], "modul": [0, 1, 3, 4, 5, 6, 9, 10, 13, 19, 20, 22, 25, 27, 28, 40, 43, 46, 47, 53, 54, 57, 60, 62, 64, 67, 71, 72], "modular": [21, 24, 30, 43], "module_import": 13, "moment": [0, 2, 35], "mongo": 42, "mongodb": [24, 37], "mongodb_set": 42, "mongoengin": [24, 37], "monkeypatch": 71, "monterei": 56, "month": 0, "more": [0, 1, 3, 4, 5, 6, 8, 11, 12, 14, 15, 18, 20, 21, 22, 24, 25, 27, 28, 30, 32, 33, 35, 38, 42, 46, 47, 48, 51, 52, 53, 54, 56, 57, 58, 59, 61, 62, 63, 64, 65, 66, 68, 69, 71, 73, 74], "most": [0, 1, 2, 3, 5, 6, 14, 18, 20, 21, 22, 27, 34, 35, 37, 38, 43, 46, 50, 54, 55, 58, 61, 62, 64, 71, 74], "mostli": [0, 8, 70], "mount": [0, 3, 6, 18, 34], "mous": 74, "mouth": 54, "move": [0, 1, 4, 22, 30, 33, 43, 55, 74], "movi": 42, "mozilla": [69, 74], "mro": [0, 4], "msg": [4, 36], "much": [0, 4, 6, 11, 12, 20, 22, 35, 47, 48, 71, 74], "multi": 32, "multidict": 0, "multipart": [0, 6, 35, 54, 60, 74], "multipl": [0, 2, 3, 4, 5, 6, 13, 18, 19, 20, 22, 27, 29, 30, 43, 46, 53, 54, 55, 62, 67, 73], "multithread": 0, "must": [0, 4, 5, 6, 11, 12, 13, 15, 17, 18, 22, 26, 27, 32, 38, 47, 50, 53, 54, 61, 70, 71], "mutabl": 0, "mutablemap": 0, "my": [5, 20, 24, 36, 50, 73], "my_extens": 5, "my_index": 52, "my_macro": 59, "my_project": 60, "my_sign": [55, 58], "my_wsgi_app": 0, "myapi": 6, "myapi__credentials__usernam": 6, "myapp": [6, 30, 38, 42], "myapplic": [29, 54], "myflask": 49, "myhost": 4, "mylist": 59, "mymiddlewar": 0, "mypi": 4, "myport": 4, "myproject": [4, 25], "myrequest": 49, "myresponseclass": 0, "mysessioninterfac": 0, "mysql": 6, "myvari": 59, "myview": 73, "n": [0, 28, 36, 48, 54], "naiv": 43, "name": [0, 1, 3, 4, 5, 6, 13, 15, 19, 20, 21, 23, 24, 25, 26, 28, 30, 32, 34, 35, 36, 38, 40, 42, 43, 46, 47, 48, 51, 52, 53, 54, 58, 59, 60, 61, 62, 63, 64, 66, 67, 68, 70, 71, 72, 73], "name_flask": 22, "namedtupl": 47, "namespac": [0, 1, 4, 22, 58], "nativ": [2, 4], "natur": [0, 44, 68], "nav": [69, 70], "navig": [11, 12, 13, 18, 19, 54, 72], "nbodi": 71, "nearest": 0, "nearli": 20, "neat": 52, "necessari": [0, 1, 3, 6, 9, 16, 20, 25, 30, 32, 33, 44, 46, 47, 53, 59, 63, 74], "necessarili": [0, 62], "need": [0, 1, 2, 4, 5, 6, 10, 13, 14, 15, 18, 20, 21, 22, 23, 25, 27, 28, 32, 34, 35, 38, 40, 43, 44, 45, 46, 47, 52, 54, 55, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 71, 72, 73, 74], "neg": 0, "neglig": 26, "neither": [26, 74], "nest": [0, 4, 5, 6, 24, 42], "netstat": 56, "network": [4, 14, 21, 54], "never": [0, 20, 21, 35, 40, 47, 54, 58, 72, 74], "new": [0, 1, 4, 5, 6, 21, 22, 23, 29, 35, 38, 43, 52, 53, 54, 55, 58, 59, 61, 62, 63, 65, 66, 68, 71, 72, 73], "newer": [25, 41], "newlin": [0, 4], "next": [0, 4, 5, 6, 14, 29, 35, 36, 40, 43, 52, 54, 64, 68, 71, 72, 73], "nginx": [11, 12, 13, 14, 18, 19, 54], "nice": [21, 30, 52, 54], "nicer": [0, 47, 53], "nlp": 56, "nnn": [54, 64], "no_etag": 0, "noappexcept": 4, "non": [0, 4, 6, 11, 12, 13, 18, 19, 20, 21, 60, 74], "none": [0, 1, 4, 5, 6, 21, 22, 28, 29, 32, 33, 36, 46, 47, 51, 52, 54, 61, 62, 63, 64, 69, 71, 72], "nor": [20, 26], "noreturn": 0, "normal": [0, 3, 4, 54, 57, 71, 72], "nosniff": 74, "not_found": [0, 54], "note": [0, 5, 6, 21, 36, 48, 53, 54, 58], "notfound": [0, 21, 29], "noth": [0, 5, 20, 21, 28, 36, 66, 73], "notic": [26, 40, 52, 53, 54, 62, 71], "notif": [8, 21], "notifi": 58, "now": [0, 4, 5, 15, 17, 20, 21, 25, 27, 32, 34, 35, 43, 47, 53, 54, 58, 59, 60, 61, 62, 64, 66, 67, 68, 69, 70, 72, 73, 74], "nox": 22, "null": [0, 62], "null_session_class": 0, "nullabl": 22, "nullsess": 0, "number": [0, 2, 6, 13, 15, 17, 32, 35, 54], "numer": 20, "nutshel": 0, "o": [0, 4, 6, 15, 34, 35, 64, 71, 74], "obei": 0, "obj": [0, 4], "object": [1, 3, 4, 5, 6, 21, 22, 24, 27, 28, 29, 30, 32, 33, 35, 37, 38, 40, 41, 42, 43, 44, 47, 48, 51, 52, 55, 57, 58, 59, 60, 61, 62, 63, 71, 72, 73], "object_hook": 4, "observ": 66, "obsolet": 39, "obtain": 0, "obviou": 66, "obvious": [3, 20, 54, 59], "occupi": 74, "occur": [0, 4, 8, 15, 21, 54, 55, 58, 72], "oct": 5, "octet": [0, 4], "octob": 22, "od": 0, "odd": 4, "off": [0, 20, 56], "offer": [0, 8, 20, 22], "offici": [22, 42, 46, 54, 59, 65, 66], "often": [0, 6, 9, 16, 28, 33, 47, 54], "ok": [4, 5, 54, 57, 71], "okai": 54, "old": [0, 4, 6, 31, 34, 35, 74], "older": [6, 35, 70, 74], "omit": [54, 61, 62, 72], "on_json_loading_fail": [0, 4], "onc": [0, 3, 4, 5, 6, 11, 12, 22, 29, 51, 59, 60, 62, 65], "onclick": 61, "one": [0, 2, 3, 4, 6, 9, 11, 12, 14, 16, 20, 22, 25, 27, 29, 30, 36, 38, 40, 43, 46, 47, 51, 52, 54, 55, 56, 59, 60, 61, 63, 67, 71, 72, 73, 74], "ones": [0, 4, 21, 34, 43], "onli": [0, 2, 3, 4, 5, 6, 8, 13, 14, 15, 17, 19, 20, 21, 22, 25, 28, 29, 32, 33, 36, 38, 40, 43, 46, 47, 52, 54, 55, 56, 57, 59, 61, 63, 65, 66, 68, 71, 73, 74], "onmouseov": 74, "onto": [0, 4, 5], "onward": [0, 57], "oop": 21, "op": 0, "opaqu": 4, "open": [0, 3, 4, 6, 20, 22, 24, 27, 37, 47, 60, 62, 71], "open_instance_resourc": [0, 4, 6], "open_resourc": [0, 3, 4, 20, 47, 62], "open_sess": 0, "oper": [0, 3, 4, 9, 16, 18, 25, 42, 54, 56, 57, 62, 74], "opposit": 71, "opt": [4, 59], "optim": [0, 18, 40], "option": [3, 4, 6, 13, 15, 18, 19, 21, 24, 36, 38, 40, 41, 43, 54, 55, 56, 58, 59, 60, 61, 63, 66], "order": [0, 4, 5, 6, 20, 27, 29, 47, 49, 54, 58, 61, 73, 74], "order_bi": 38, "ordereddict": 0, "ordinari": 0, "org": 74, "organ": [5, 22, 67, 70, 72], "orig": 0, "origin": [0, 3, 4, 21, 52, 55, 61, 72, 73], "original_except": [0, 4, 21], "orm": 46, "oserror": [5, 54, 56, 64], "other": [0, 1, 3, 4, 5, 6, 9, 11, 12, 14, 15, 16, 18, 20, 21, 22, 23, 24, 25, 26, 27, 29, 32, 33, 38, 40, 43, 48, 54, 55, 56, 57, 58, 60, 61, 62, 63, 64, 65, 66, 67, 69, 70, 71, 73, 74], "other_packag": 28, "otherwis": [0, 1, 4, 6, 8, 11, 12, 13, 18, 19, 21, 22, 26, 29, 35, 38, 43, 46, 52, 53, 54, 56, 61, 62, 63, 71, 72, 74], "our": [3, 21, 22, 35, 54, 60], "out": [0, 3, 4, 5, 6, 9, 16, 20, 25, 26, 27, 29, 34, 35, 40, 42, 51, 54, 59, 61, 63, 65, 68, 70, 71, 72, 74], "outer": 74, "outermost": [27, 52], "outgo": [14, 72], "outgrow": 40, "outlin": [0, 9, 13, 15, 16, 18, 19, 20, 46, 74], "output": [0, 4, 6, 12, 54, 60, 63, 64, 70, 71], "outsid": [0, 1, 4, 6, 9, 16, 22, 27, 28, 37, 47, 54, 55, 64, 71], "outstand": 20, "over": [0, 3, 4, 5, 6, 20, 21, 22, 46, 53, 54, 58, 59, 60, 70, 71, 74], "overhead": [6, 20], "overload": 21, "overrid": [0, 2, 3, 4, 6, 22, 24, 37, 49, 50, 54, 64, 70, 73], "overridden": [0, 3, 4, 6, 22, 64, 70, 71], "oversight": 22, "overview": [5, 24, 25, 36, 54, 63, 65, 68], "overwhelm": [21, 67], "overwrit": 0, "overwritten": 4, "own": [0, 3, 4, 5, 6, 11, 12, 13, 14, 18, 20, 21, 22, 23, 28, 29, 31, 51, 52, 54, 55, 58, 59, 61, 65, 68], "p": [0, 18, 21, 36, 48, 50, 53, 54, 56, 59, 61], "packag": [0, 3, 4, 5, 6, 9, 15, 16, 18, 20, 22, 23, 24, 25, 27, 29, 30, 37, 46, 53, 54, 62, 64, 65, 66, 67, 70, 71], "pad": 69, "page": [0, 3, 4, 6, 8, 9, 13, 14, 15, 16, 18, 19, 24, 25, 29, 32, 37, 38, 50, 52, 53, 54, 55, 58, 59, 60, 61, 62, 64, 68, 69, 70, 71, 72, 73, 74], "page_not_found": [0, 3, 21, 54], "pai": [9, 16], "pain": 0, "pair": [0, 58], "pallet": [4, 5, 7, 22, 26], "parachut": 0, "param": 0, "paramet": [3, 4, 5, 6, 21, 49, 51, 54, 59], "parameter_storage_class": [0, 49], "parametr": 71, "parent": [0, 3, 6, 21, 42, 50, 55, 60], "parenthes": 5, "pars": [0, 4, 5, 6, 38, 44, 74], "parse_arg": 0, "parse_decltyp": 62, "parse_form_data": 0, "parser": [0, 4], "part": [0, 3, 4, 5, 6, 21, 22, 24, 27, 35, 38, 47, 48, 50, 51, 54, 55, 58, 60, 61, 63, 71, 74], "parti": [6, 21, 74], "partial": [4, 59], "particip": 0, "particular": [22, 26, 65, 71], "particularli": [5, 14, 56, 63], "partit": [0, 4, 6], "pass": [0, 1, 4, 5, 6, 8, 17, 20, 21, 22, 23, 27, 30, 33, 36, 37, 38, 40, 41, 46, 47, 48, 52, 53, 54, 55, 56, 59, 60, 61, 64, 71, 72, 73], "pass_script_info": 0, "passdict": 0, "passlist": 0, "passthrough_error": 8, "password": [28, 36, 53, 54, 62, 70, 71, 72], "passwordfield": 53, "past": [0, 20, 24], "patch": [0, 2, 41, 73], "path": [0, 3, 4, 5, 6, 20, 21, 34, 35, 37, 44, 45, 47, 52, 54, 55, 60, 64, 69, 71], "path_info": 29, "path_or_fil": 0, "pathdispatch": 29, "pathlib": [4, 60], "pathlik": [0, 4], "pathnam": 54, "patient": 35, "pattern": [0, 1, 3, 4, 5, 6, 13, 15, 18, 19, 20, 22, 24, 29, 30, 32, 35, 38, 42, 43, 52, 53, 54, 55, 60, 61, 70, 72, 73], "payload": [0, 4, 21, 35], "pbkdf2": 71, "pdf": [4, 35], "peopl": [4, 20, 46, 52, 74], "pep": [4, 27], "per": [0, 4, 6, 11, 12, 22, 29, 51, 68], "percent": 0, "perfect": [4, 6, 22, 29, 57], "perfectli": 21, "perform": [0, 4, 9, 13, 16, 18, 20, 24, 38, 55, 59, 62], "period": [4, 6], "perman": [0, 4, 6, 35, 74], "permanent_session_lifetim": [0, 6, 74], "permiss": [0, 15, 26, 56], "permit": [0, 4, 26], "persist": [20, 27, 54], "person": 54, "perspect": [17, 27], "phase": [22, 27], "php": 35, "pick": [0, 4, 56, 58], "pickl": [0, 4], "pickle_bas": 0, "pictur": [38, 60], "picture_url": 60, "pid": [13, 18], "piec": [4, 44, 48, 59, 60, 74], "pin": [4, 5, 8, 54, 64], "pip": [2, 4, 5, 11, 12, 13, 15, 18, 19, 21, 22, 25, 32, 42, 43, 60, 63, 66, 71], "pitfal": [4, 65], "pixel": 34, "pkg_resourc": 4, "place": [0, 1, 4, 6, 30, 35, 40, 45, 47, 54, 56, 57, 60, 61, 62, 69, 70, 72, 74], "placehold": [70, 72], "plai": [0, 4, 5, 57], "plain": [0, 21, 54, 61, 69], "platform": [13, 17, 18, 24, 63, 71, 74], "pleas": [0, 6, 47, 54, 59], "pleasant": [47, 57], "plu": [0, 74], "pluggabl": [2, 3, 4, 20, 73], "pluggi": 71, "plugin": [24, 35], "png": [35, 38, 60], "point": [0, 1, 3, 4, 5, 6, 9, 16, 18, 22, 27, 32, 33, 38, 44, 47, 48, 54, 55, 56, 57, 62, 65, 71, 74], "pointer": 0, "pointless": 54, "polici": 0, "poll": [32, 35], "pop": [0, 1, 4, 27, 51, 54, 55, 57, 62], "popitem": 0, "popul": [0, 6, 38, 55, 71], "popular": 6, "populate_request": 0, "port": [0, 4, 5, 6, 11, 12, 13, 15, 18, 19, 54, 56, 64], "portabl": 4, "portion": 50, "posit": [0, 54], "possibl": [0, 2, 3, 4, 6, 11, 12, 13, 14, 18, 19, 20, 21, 22, 26, 27, 28, 30, 31, 33, 34, 36, 38, 41, 47, 52, 54, 59, 60, 71, 74], "possibli": 18, "post": [0, 4, 6, 22, 28, 32, 35, 36, 38, 41, 44, 52, 53, 54, 60, 61, 62, 65, 68, 69, 70, 71, 72, 73, 74], "post_id": [0, 54], "post_model": 22, "postapi": 22, "postpon": 4, "postprocess": 0, "potenti": [4, 33, 74], "power": [8, 22, 32, 50, 54, 68], "powershel": [5, 6], "pr": [2, 4, 7], "practic": 24, "pragma": 0, "pre": [0, 4, 9, 16, 69], "preced": [0, 3, 4, 21], "precis": 4, "precompil": 18, "preconfigur": 54, "predat": 2, "preemptiv": 0, "prefer": [0, 4, 5, 6, 11, 12, 20, 22, 30, 38, 46, 56, 72], "preferred_url_schem": [0, 4, 6], "prefix": [0, 3, 4, 6, 9, 16, 21, 22, 29, 36, 40, 51, 52], "preflight": 0, "prefork": 18, "preload": 6, "prepar": 4, "prepend": [0, 72], "preprocess": 44, "preprocess_request": [0, 57, 60], "preprocessor": 0, "present": [0, 3, 4, 5, 6, 20, 21, 54, 55, 56, 59, 74], "preserv": [0, 4, 49, 55], "preserve_context_on_except": 6, "preset": [0, 4], "press": [5, 54, 64], "pretti": [0, 4, 27, 54], "prevent": [0, 4, 6, 74], "preview": 4, "previou": [0, 4, 6, 11, 12, 32, 38, 62, 64], "previous": [0, 4, 22], "price": 14, "primari": [14, 62], "primarili": 54, "primary_kei": [22, 46], "principl": [33, 35], "print": [3, 4, 6, 42, 47, 54, 55, 58, 63], "prior": [4, 26], "prioriti": 3, "privat": [5, 14], "privileg": [11, 12, 13, 15, 18, 19], "proactiv": 28, "probabl": [0, 2, 4, 13, 14, 20, 28, 32, 35, 36, 52, 54, 63], "problem": [0, 3, 4, 6, 20, 21, 25, 35, 40, 43, 54, 55, 59, 74], "process": [0, 2, 4, 11, 12, 13, 15, 18, 19, 20, 22, 27, 29, 30, 32, 44, 53, 55, 56, 74], "process_respons": [0, 57], "processor": [0, 4, 24, 37], "procur": 26, "produc": [4, 38, 45, 54, 60, 70, 73], "product": [0, 4, 5, 9, 11, 12, 16, 20, 21, 24, 25, 26, 27, 28, 29, 35, 54, 56, 65, 71], "productionconfig": 6, "profession": 5, "profil": [21, 38, 48, 54, 74], "profit": 26, "program": [5, 18, 20, 21, 28, 32, 54, 56, 64], "programm": 43, "programmat": 4, "programmingerror": 71, "progress": [32, 37], "project": [1, 2, 3, 4, 5, 6, 20, 21, 22, 24, 25, 28, 40, 43, 45, 54, 61, 62, 63, 64, 65, 68, 71], "promis": 38, "promot": 26, "prompt": 25, "prone": [1, 74], "proof": 0, "propag": [0, 4, 6, 55], "propagate_except": [0, 4, 6], "proper": [0, 4, 20, 21, 57], "properli": [0, 3, 4, 20, 40, 46, 54, 74], "properti": [0, 3, 4, 6, 38, 60], "protect": [0, 8, 25, 54, 74], "proto": [9, 16], "protocol": [0, 20, 41], "provid": [0, 1, 2, 3, 4, 5, 6, 8, 9, 11, 12, 13, 16, 17, 18, 20, 21, 22, 24, 25, 26, 27, 31, 36, 38, 40, 47, 48, 51, 52, 54, 55, 56, 58, 59, 60, 63, 64, 65, 71, 73, 74], "provide_automatic_method": 0, "provide_automatic_opt": [0, 4, 6], "proxi": [0, 1, 3, 4, 9, 11, 12, 13, 14, 15, 16, 18, 19, 21, 24, 27, 41, 54], "proxy_add_x_forwarded_for": 16, "proxy_fix": [17, 54], "proxy_http_modul": 9, "proxy_modul": 9, "proxy_pass": 16, "proxy_set_head": 16, "proxyfix": [17, 27, 54], "proxypass": 9, "ps1": 5, "public": [0, 4, 5, 54, 63], "public_key_pin": 74, "publicli": [14, 22, 54, 63], "publish": [22, 23], "pull": [0, 23, 51], "pull_lang_cod": 51, "punsch": 4, "pure": [13, 19], "purpos": [0, 22, 24, 26, 32], "push": [0, 4, 5, 6, 24, 27, 57, 60], "put": [0, 4, 6, 9, 14, 16, 20, 31, 34, 41, 46, 51, 54, 57, 59, 60], "py": [0, 3, 4, 5, 6, 11, 12, 15, 18, 22, 25, 30, 32, 40, 43, 46, 54, 56, 60, 61, 62, 63, 64, 67, 71, 72], "py3": 63, "pyc": [4, 43, 67], "pycharm": 24, "pyopenssl": 4, "pypi": [2, 4, 11, 12, 13, 18, 22, 23, 25, 32, 46, 53], "pyproject": [4, 5, 43, 66, 67, 71], "pypy3": 4, "pytest": [4, 22, 60, 71], "pytest_cach": 67, "python": [0, 2, 3, 4, 5, 8, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 24, 27, 28, 29, 43, 47, 52, 53, 54, 55, 56, 57, 59, 60, 62, 63, 64, 65, 66, 67, 68, 70, 71], "python3": 25, "python_requir": 22, "pythonanywher": 14, "pythonpath": 5, "pythonx": 6, "pyuwsgi": 18, "pywsgi": 12, "qualiti": 22, "quart": 24, "queri": [0, 2, 4, 21, 22, 32, 37, 38, 46, 54, 60, 61, 62, 72, 73], "query_db": 47, "query_properti": 46, "query_str": [0, 55, 60], "question": [0, 6, 7, 20, 34, 47], "queue": [2, 21, 32], "quick": [20, 24, 40, 43, 59], "quickli": [0, 3, 6, 46, 53, 54], "quickstart": [24, 25, 65, 68], "quit": [0, 5, 20, 27, 35, 54, 64, 68], "quot": [4, 5, 38, 74], "r": [0, 4, 46, 47], "rack": 20, "rais": [0, 3, 4, 6, 8, 21, 27, 35, 38, 54, 55, 61, 64, 71], "rakia": 4, "rakija": 4, "random": [0, 6, 54, 58, 63, 64], "rang": [0, 4], "raquo": 54, "rare": 4, "rate": 42, "rather": [0, 1, 2, 3, 4, 5, 6, 11, 12, 17, 30, 32, 47, 54, 55, 56, 60, 63, 69, 70, 71, 72], "raw": [0, 47, 60], "rb": [0, 60, 71], "re": [0, 4, 5, 6, 13, 14, 18, 19, 20, 21, 22, 27, 34, 35, 38, 52, 53, 54, 57, 60, 61, 62, 64, 65, 66, 67, 68, 70, 73], "reach": 0, "react": 54, "read": [0, 3, 6, 9, 13, 15, 16, 18, 19, 21, 22, 23, 32, 35, 38, 44, 47, 52, 53, 54, 57, 60, 62, 63, 69, 71, 74], "readabl": [0, 21], "reader": 0, "readi": [0, 20, 32, 54], "readlin": [4, 44], "readm": 22, "real": [0, 4, 17, 27, 40, 57, 58, 61, 63, 64], "realis": 21, "realli": [29, 30, 34, 36, 51, 52, 54, 58], "realm": 0, "reason": [0, 3, 20, 22, 33, 35, 43, 57, 58], "receiv": [0, 4, 21, 27, 37, 54, 55, 56, 58, 72, 74], "recent": [4, 6, 20, 42, 46, 61], "recipi": 0, "recogn": [6, 74], "recommend": [0, 3, 4, 5, 6, 10, 21, 24, 25, 32, 43, 46, 49, 53, 54, 56, 57, 58, 59, 74], "reconfigur": 6, "reconstruct": 0, "record": [0, 3, 28, 36, 54, 58, 60, 71], "record_onc": 0, "recreat": 32, "red": 36, "redi": 32, "redirect": [0, 3, 4, 20, 24, 27, 28, 29, 34, 35, 36, 37, 52, 53, 55, 61, 70, 71, 72], "redirect_to": 34, "redistribut": 26, "reduc": [4, 51], "refactor": [4, 61], "refer": [0, 1, 6, 20, 22, 30, 34, 43, 54, 55, 61, 62, 73], "referenc": [0, 69], "referr": 0, "reflect": [0, 6, 20], "refresh": [4, 69], "regard": [0, 29], "regardless": [4, 27, 74], "region": 0, "regist": [0, 1, 4, 6, 22, 24, 27, 32, 33, 35, 46, 53, 57, 61, 64, 65, 67, 71, 73], "register_api": 73, "register_blueprint": [0, 3, 4, 5, 22, 30, 61, 72], "register_convert": 62, "register_error_handl": [0, 4, 21], "registr": [4, 24, 53, 62, 64, 72], "registrar": [9, 16], "registrationform": 53, "registri": 0, "regular": [0, 3, 4, 73, 74], "reimplement": 2, "reintroduc": 4, "reiter": 3, "rel": [0, 3, 4, 6, 20, 34, 50, 54, 60, 62, 64, 67, 69, 70], "relat": [0, 1, 4, 5, 6, 20, 22, 27, 37, 42, 47, 55, 72], "relax": 4, "releas": 4, "relev": [4, 22, 28, 34], "reli": [0, 4, 8, 48, 58], "reliabl": [0, 4, 6, 35], "reload": [0, 4, 6, 8, 14, 25, 38, 54, 64, 70], "remain": [0, 2, 4, 20, 22, 40, 59, 60], "remedi": 74, "rememb": [0, 17, 20, 21, 22, 29, 33, 35, 43, 52, 53, 54, 62, 64, 73], "remember_languag": 33, "remot": [4, 8, 17, 28], "remote_addr": [0, 8, 28], "remote_us": 0, "remov": [0, 4, 5, 6, 9, 16, 46, 51, 54, 70, 71, 72, 74], "removehandl": 28, "renam": [4, 43], "render": [3, 4, 20, 21, 24, 25, 29, 36, 37, 48, 50, 52, 53, 58, 59, 70, 71, 72, 73, 74], "render_field": 53, "render_templ": [0, 3, 4, 21, 30, 36, 38, 52, 53, 54, 59, 61, 70, 72, 73], "render_template_str": [0, 4, 59], "renderchart": 0, "rendit": 20, "repackag": 4, "repeat": 53, "repetit": 51, "replac": [0, 4, 5, 21, 33, 37, 41, 52, 59, 70, 71, 72, 74], "replai": 74, "repli": [0, 54], "report": [0, 4, 7, 21, 38, 71], "repositori": [5, 22, 32, 65], "repres": [0, 8, 22, 38, 42, 54], "represent": 0, "reproduc": 26, "req": 0, "request": [1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 24, 29, 30, 32, 34, 35, 36, 37, 40, 41, 45, 46, 47, 48, 49, 51, 52, 53, 59, 61, 62, 70, 71, 72, 73], "request_class": [0, 49], "request_context": [0, 54], "request_ctx": 0, "request_finish": [0, 27, 55, 58], "request_globals_class": 4, "request_method": 41, "request_or_environ": 0, "request_start": [0, 27, 55, 58], "request_tearing_down": [0, 27, 55, 58], "requestcachecontrol": 0, "requestcontext": [0, 4, 27, 55, 57], "requestedrangenotsatisfi": 0, "requestentitytoolarg": [0, 6, 35], "requestformatt": 28, "requesthead": 9, "requir": [0, 2, 4, 6, 8, 11, 12, 13, 15, 18, 19, 20, 22, 25, 28, 32, 34, 35, 37, 38, 42, 43, 46, 53, 57, 59, 60, 61, 62, 65, 66, 70, 71, 74], "required_method": [0, 4], "rerais": [0, 4], "reset": [0, 60], "resiz": 69, "resolv": [0, 43], "resourc": [0, 1, 4, 20, 21, 22, 24, 38, 51, 54, 57, 60], "resource_not_found": 21, "resp": [0, 54], "respect": [21, 74], "respond": [0, 3, 4, 72], "respons": [2, 4, 6, 14, 21, 24, 27, 28, 32, 33, 35, 38, 48, 55, 57, 60, 62, 64, 71, 72, 74], "response_class": [0, 57], "responsecachecontrol": 0, "responsereturnvalu": 0, "responsestream": 0, "rest": [0, 23, 24, 27, 62, 64, 73], "restart": [5, 54, 64], "restor": [0, 4], "restrict": [0, 4, 6, 74], "restructur": [4, 43], "result": [0, 2, 4, 6, 29, 31, 36, 37, 46, 47, 52, 54, 57, 60, 61, 71, 72], "result_backend": 32, "result_id": 32, "retain": [0, 26], "retri": 0, "retriev": [52, 62, 72], "retry_aft": 0, "return": [0, 1, 2, 3, 4, 5, 6, 20, 22, 24, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 40, 41, 42, 43, 44, 45, 46, 47, 48, 51, 52, 53, 54, 55, 57, 58, 59, 60, 61, 62, 64, 67, 70, 71, 72, 73], "reus": 62, "reusabl": [1, 20, 24, 60], "revalid": 0, "reveal": 6, "revers": [0, 4, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 51, 54, 59], "reverse_filt": 59, "revert": 4, "review": [65, 68, 74], "rewrit": 4, "rewrot": 4, "rfc": [0, 4, 54], "rich": 59, "right": [0, 35, 40, 51, 69, 74], "rightmost": 3, "risk": [0, 4, 8, 54], "role": 0, "room": 38, "room_detail": 38, "room_url": 38, "root": [0, 4, 6, 11, 12, 13, 15, 18, 19, 20, 28, 34, 38, 54], "root_path": [0, 3, 6, 34], "root_url": 0, "rootdir": 71, "rotat": [4, 6], "roughli": 0, "roundtrip": 48, "rout": [2, 3, 4, 6, 21, 24, 27, 28, 29, 30, 32, 34, 35, 36, 38, 40, 43, 44, 45, 47, 48, 51, 52, 53, 55, 60, 61, 64, 67, 71, 72, 73, 74], "routecal": 0, "router": 4, "routing_except": 0, "routingexcept": [0, 4], "row": [47, 48, 62, 72], "row_factori": [47, 62], "rq": 21, "rsplit": [35, 40], "rss": 68, "rstrip": 29, "rt": [0, 4], "rubi": 20, "rule": [0, 3, 4, 27, 40, 52, 74], "run": [0, 1, 2, 3, 4, 6, 8, 9, 14, 16, 20, 21, 22, 24, 25, 27, 28, 29, 30, 31, 32, 35, 38, 42, 43, 48, 54, 55, 56, 57, 59, 61, 62, 66, 67, 70, 72, 74], "run_command": 0, "run_simpl": 0, "runawai": 4, "runner": [4, 5, 24, 71], "runtim": [0, 2, 4, 6], "runtimeerror": [0, 1, 4, 48, 55], "runtimeexcept": 0, "rv": [0, 21, 44, 47, 52, 58], "safe": [0, 4, 38, 43, 53, 54, 59, 64, 70, 73], "safe_join": [0, 4], "safer": [14, 21], "safeti": 0, "sai": [0, 21, 31, 43, 64, 73, 74], "salt": 0, "same": [0, 1, 2, 3, 4, 5, 6, 11, 12, 13, 18, 20, 21, 22, 28, 29, 30, 32, 34, 38, 40, 46, 52, 54, 55, 59, 60, 61, 62, 66, 70, 71, 72, 73], "sameorigin": 74, "samesit": [0, 4, 6, 74], "sampl": [21, 60], "san": [4, 69], "sansio": 4, "satisfi": 0, "save": [0, 5, 27, 34, 35, 42, 54, 58, 59, 60, 61, 64, 72], "save_sess": 0, "scaffold": 4, "scale": 24, "scan": 5, "scene": [55, 68], "schedul": 32, "schema": [0, 37, 62, 67], "scheme": [0, 4, 6, 16, 22], "schnap": 4, "scienc": 20, "scope": [0, 9, 16, 18, 37], "scoped_sess": 46, "screen": [0, 5], "screenshot": 69, "script": [0, 4, 6, 11, 12, 15, 24, 25, 35, 38, 54, 59], "script_info": 4, "script_nam": 6, "script_root": [0, 38], "scriptinfo": [0, 4], "sdist": [18, 22], "sdk": 21, "search": [0, 3, 22, 23, 54, 56, 68], "searchword": 54, "second": [0, 3, 6, 32, 35, 36, 54, 58, 60, 62, 71, 72], "secret": [0, 4, 6, 36, 64], "secret_kei": [0, 6, 27, 36, 54, 63, 64], "secret_key_fallback": [4, 6], "secret_pag": 52, "section": [11, 12, 14, 16, 20, 24, 32, 38, 54, 59, 64, 70], "secur": [0, 4, 5, 6, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19, 24, 25, 35, 54, 56, 59, 63, 72], "secure_filenam": [35, 54], "securecooki": 0, "securecookiesess": 0, "securecookiesessioninterfac": 0, "security_logg": 0, "securityerror": 6, "securityexcept": 0, "see": [0, 1, 2, 3, 4, 5, 6, 7, 11, 12, 13, 18, 20, 21, 22, 27, 28, 29, 30, 32, 35, 37, 39, 43, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 63, 64, 66, 70, 71, 72, 73], "seed": 4, "seek": 0, "seekabl": 0, "seem": [21, 44], "seen": [32, 68], "segment": 29, "select": [5, 35, 46, 47, 61, 71, 72], "select_jinja_autoescap": 0, "self": [0, 4, 6, 21, 22, 24, 28, 29, 32, 40, 41, 44, 46, 58, 69, 71, 74], "semant": 0, "send": [0, 4, 6, 21, 23, 24, 27, 28, 32, 35, 38, 48, 52, 54, 55, 72, 74], "send_fil": [0, 4, 6], "send_file_max_age_default": [0, 4, 6], "send_from_directori": [0, 4, 34, 35], "send_static_fil": [0, 4, 45], "sender": 0, "sendfil": [0, 4, 6], "sens": [0, 2, 6, 22, 46, 51, 59, 61], "sensibl": 24, "sent": [0, 1, 6, 21, 27, 38, 48, 55, 62, 71, 72, 74], "sentri": [8, 21], "sentry_sdk": 21, "separ": [0, 3, 4, 5, 6, 20, 22, 28, 29, 36, 38, 46, 53, 54, 60, 61, 62, 72], "sequenc": 0, "sequenti": 62, "serial": [0, 4, 32, 38, 54, 74], "serializ": [32, 54], "serif": 69, "seriou": 74, "serv": [0, 2, 4, 5, 6, 9, 10, 11, 12, 14, 16, 19, 24, 25, 34, 35, 38, 45, 54, 63, 64, 69], "serve_forev": 12, "server": [0, 2, 4, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 27, 28, 29, 34, 35, 36, 38, 42, 55, 60, 61, 62, 64, 70, 71, 74], "server_nam": [0, 4, 6, 16], "servic": [0, 5, 14, 22, 26, 32, 56, 74], "session": [1, 4, 6, 20, 24, 25, 27, 32, 36, 38, 46, 55, 57, 59, 63, 71, 72, 73, 74], "session_class": 0, "session_cookie_domain": [0, 4, 6], "session_cookie_httponli": [0, 6, 74], "session_cookie_nam": [0, 4, 6], "session_cookie_partit": [0, 4, 6], "session_cookie_path": [0, 6], "session_cookie_samesit": [0, 4, 6, 74], "session_cookie_secur": [0, 6, 74], "session_interfac": [0, 27], "session_refresh_each_request": [0, 4, 6], "session_transact": [0, 4, 60], "sessioninterfac": [0, 4, 27], "sessionmak": 46, "sessionmixin": 0, "set": [0, 1, 3, 4, 6, 9, 17, 20, 21, 22, 27, 28, 29, 30, 32, 33, 35, 38, 40, 41, 43, 51, 52, 54, 60, 61, 62, 63, 64, 66, 67, 70, 71, 73], "set_cooki": [0, 33, 54, 74], "set_data": 0, "set_debug_flag": 0, "set_default": 32, "set_etag": 0, "setattr": 71, "setdefault": [0, 4, 51], "setformatt": 28, "setlevel": 28, "setup": [0, 4, 5, 11, 12, 13, 15, 18, 19, 21, 22, 24, 38, 42, 57, 60, 65, 67], "setuptool": 4, "sever": [3, 54], "sha": 0, "sha1": [0, 4, 44], "sha256": 71, "shall": 26, "shallow": 0, "share": [0, 3, 22, 70], "shared_task": 32, "she": 35, "shell": [0, 4, 6, 24, 25, 47, 54, 55], "shell_command": 0, "shell_context_processor": [0, 5], "shellcontextprocessorcal": 0, "shelltool": 57, "shift_path_info": 29, "ship": [22, 47], "short": 55, "shortcut": [0, 4, 6, 34, 54], "should": [0, 1, 2, 3, 4, 5, 6, 8, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 25, 28, 30, 34, 35, 43, 44, 52, 54, 55, 58, 60, 61, 63, 64, 66, 67, 69, 70, 71, 72, 74], "should_ignore_error": 0, "should_set_cooki": 0, "shouldn": [20, 63, 64], "show": [0, 3, 4, 5, 8, 13, 14, 15, 21, 22, 24, 25, 27, 32, 38, 42, 54, 56, 59, 61, 62, 64, 68, 69, 70, 71, 72, 73, 74], "show_post": [0, 54], "show_subpath": 54, "show_teardown": 55, "show_the_login_form": 54, "show_us": 0, "show_user_profil": 54, "showloginerror": 38, "shown": [0, 4, 6, 11, 12, 13, 15, 18, 19, 21, 32, 38, 54, 60, 61, 70, 72], "shut": [4, 46], "shutdown": [46, 57], "shutdown_sess": 46, "sic": 0, "side": [20, 29, 53, 54], "sign": [0, 6, 25, 54, 72, 74], "signal": [4, 21, 24, 25, 27], "signals_avail": 4, "signatur": [0, 4, 6, 74], "silenc": 0, "silent": [0, 4, 6, 36, 64], "similar": [0, 1, 4, 5, 14, 20, 21, 27, 28, 29, 32, 46, 54, 55, 56, 58, 61, 62, 64, 70, 71], "similarli": [0, 3, 21, 60, 71], "simpl": [0, 1, 3, 5, 6, 13, 20, 21, 29, 32, 35, 37, 38, 40, 44, 46, 47, 50, 52, 54, 60, 64, 67, 71], "simple_blog": 22, "simple_pag": 3, "simpleblog": 22, "simplejson": 4, "simplenamespac": 22, "simpler": [0, 4, 38, 65], "simplest": [28, 32, 38], "simpli": [3, 29, 34, 47, 54], "simplifi": [0, 3, 4, 47, 51, 58], "simul": [0, 9, 16, 55, 71], "sinc": [0, 1, 4, 5, 6, 17, 20, 21, 22, 32, 52, 54, 59, 60, 61, 62, 63, 70, 72, 73], "singl": [0, 4, 6, 14, 19, 20, 22, 24, 37, 38, 40, 47, 51, 67, 68, 73, 74], "site": [0, 6, 21, 24, 35, 50, 52, 56, 59], "situat": [0, 6, 21, 28, 33, 36, 53, 54, 55, 57], "size": [0, 4, 6, 35, 36, 54, 67, 69], "size_hint": 44, "skeleton": 50, "skip": [0, 4, 54, 55], "slash": [0, 4, 29, 52, 54], "slategrai": 69, "slightli": [4, 36], "slow": [31, 38, 62], "small": [0, 4, 6, 15, 18, 21, 24, 35, 43, 62], "smaller": [43, 59], "smtp": 28, "smtphandler": 28, "snake": 74, "snippet": 0, "so": [0, 3, 4, 5, 6, 8, 9, 16, 17, 18, 20, 21, 22, 27, 30, 31, 32, 34, 35, 36, 38, 40, 43, 46, 47, 48, 52, 53, 54, 55, 57, 58, 59, 60, 61, 62, 64, 66, 68, 69, 70, 71, 72, 73, 74], "social": 74, "socket": [0, 56], "softwar": [26, 63], "solid": 69, "solut": [6, 22, 37, 38, 51, 52, 54, 74], "solv": [1, 25, 74], "some": [0, 1, 4, 5, 6, 8, 14, 18, 20, 21, 22, 23, 27, 28, 31, 32, 33, 34, 35, 37, 41, 43, 44, 48, 52, 54, 55, 57, 58, 61, 62, 63, 64, 65, 67, 68, 69, 70, 71, 74], "some_theron_movi": 42, "someon": [35, 74], "someth": [0, 2, 4, 20, 21, 22, 28, 30, 35, 38, 43, 52, 54, 70, 71, 74], "sometim": [0, 3, 21, 29, 33, 36, 44, 48, 54, 59], "somewhat": 40, "somewher": [1, 21, 35, 51, 55], "soon": 28, "sooner": 21, "sorri": 21, "sort": [0, 20, 21, 22], "sort_kei": 0, "sound": [50, 52], "sourc": [0, 3, 6, 21, 22, 26, 71], "spa": 45, "space": [0, 3, 4, 9, 16, 21, 55, 69], "span": [0, 69, 70], "spawn": [0, 2, 18, 54], "spec": [13, 18, 27], "special": [0, 4, 5, 6, 26, 44, 54, 59, 61, 62, 70, 72], "special_api": 44, "special_exception_handl": 0, "specif": [0, 2, 3, 4, 6, 11, 12, 13, 18, 19, 20, 21, 22, 24, 26, 27, 29, 30, 32, 35, 40, 51, 52, 54, 55, 57, 59, 60, 63, 70, 74], "specifi": [0, 3, 4, 5, 13, 15, 18, 19, 22, 28, 34, 35, 54, 58, 61, 74], "speed": [31, 59], "split": [0, 20, 27, 29, 40, 46], "sql": [0, 20, 37, 42, 47, 62, 67, 71, 72], "sqlalchemi": [0, 4, 20, 22, 24, 28, 30, 32, 37, 53, 54], "sqlite": [6, 22, 24, 37, 46, 54, 62, 64], "sqlite3": [46, 47, 62, 71, 72], "sqrt": 0, "src": [5, 74], "ssl": [4, 18], "stabil": 0, "stabl": [4, 5, 14, 56, 63], "stack": [4, 20, 21, 55], "stage": [2, 6, 32, 55], "stale": 0, "stand": 1, "standard": [0, 2, 4, 11, 12, 14, 18, 20, 21, 24, 25, 28, 34, 53, 54, 66, 73], "star": 57, "start": [0, 2, 4, 5, 6, 8, 11, 12, 13, 15, 18, 20, 21, 22, 24, 27, 28, 29, 32, 33, 35, 44, 46, 50, 54, 55, 56, 57, 60, 64, 65, 66, 68, 69, 70, 71, 72, 73], "start_add": 32, "start_respons": [0, 29, 41], "startrespons": 0, "startswith": [3, 21], "startup": 43, "stat": [54, 64], "state": [0, 22, 30, 73, 74], "statement": [0, 3, 4, 21, 22, 46, 47, 48, 54, 57, 60, 70], "static": [0, 4, 20, 24, 27, 34, 38, 43, 45, 50, 65, 67, 70], "static_fold": [0, 3, 4, 45], "static_host": [0, 4], "static_path": 4, "static_url_path": [0, 3, 4, 45], "statu": [0, 21, 27, 35, 45, 54, 61, 71], "status_cod": [0, 21, 58, 60, 71], "stderr": [4, 28], "stdout": [4, 13], "step": [0, 3, 8, 27, 32, 65, 68, 72, 73], "stick": 38, "still": [0, 2, 4, 5, 6, 8, 20, 21, 22, 29, 31, 40, 51, 52, 54, 55, 56, 57, 59, 60, 61, 62, 64, 66, 70, 73, 74], "stmt": 71, "stop": [0, 2, 56, 62], "storag": [4, 21, 49], "store": [0, 4, 6, 20, 22, 24, 27, 30, 32, 35, 44, 52, 54, 57, 60, 62, 70, 72, 73, 74], "stori": 73, "story_list": 73, "str": [0, 3, 4, 6, 21, 32, 71], "straightforward": [0, 18, 30, 35, 52, 64], "strategi": [3, 21, 22], "stream": [4, 6, 19, 20, 24, 28, 37, 44, 54, 74], "stream_templ": [0, 4, 48, 59], "stream_template_str": [0, 4, 48, 59], "stream_with_context": [0, 4, 48, 59], "streamed_respons": [0, 48], "streamhandl": 28, "strftime": 61, "strict": [0, 4, 6, 26], "stricter": 4, "strictli": [0, 74], "string": [0, 4, 5, 6, 20, 22, 40, 46, 47, 48, 51, 52, 53, 54, 59, 60, 61, 64], "stringfield": [42, 53], "stringifi": 38, "strip": 4, "striptag": 54, "strong": [36, 54], "strongli": [4, 6], "structur": [0, 4, 24, 43, 58, 65, 70], "stub": 4, "student": 5, "stuff": 57, "stupid": 74, "style": [3, 43, 50, 54, 67, 69, 70, 73], "stylesheet": [50, 70], "sub": [4, 27], "subclass": [0, 4, 6, 20, 21, 22, 24, 28, 32, 35, 37, 46, 73], "subcommand": 0, "subdomain": [0, 3, 4, 6, 37], "subdomain_match": [0, 4, 6], "subdomaindispatch": 29, "subfold": 45, "subject": 28, "submit": [32, 35, 36, 38, 53, 54, 61, 69, 70, 72, 74], "submodul": 4, "subpath": 54, "subscrib": [0, 4, 24], "subscript": 24, "subsequ": [0, 71, 72], "subset": 0, "substitut": 26, "succe": 72, "success": [0, 4, 21, 32, 62], "successfulli": [0, 28, 32, 36, 71], "suddenli": [40, 54], "sudo": 15, "suffix": 22, "suit": [4, 18], "super": [0, 21, 28, 50], "suppli": [0, 4, 21], "support": [2, 3, 4, 5, 6, 10, 13, 14, 15, 18, 19, 21, 22, 23, 24, 25, 29, 31, 34, 41, 48, 54, 58, 59, 62, 63, 70, 74], "suppos": 4, "suppress": 0, "sure": [0, 3, 4, 6, 9, 13, 15, 16, 18, 19, 21, 24, 27, 35, 43, 46, 47, 51, 54, 55, 58, 61, 70, 71, 74], "surfac": 20, "surpris": 20, "surround": 0, "surviv": 0, "svg": [0, 4, 59], "switch": [4, 6, 11, 12, 62], "sy": [6, 28], "sync": [0, 2, 13, 18], "synchron": [0, 11, 12], "syntax": [0, 4, 13, 19, 20, 38, 56, 59, 70], "syntaxerror": 38, "system": [0, 4, 6, 9, 16, 21, 24, 25, 33, 36, 40, 43, 46, 50, 52, 54, 56, 59, 66, 74], "t": [0, 1, 2, 3, 4, 5, 6, 8, 11, 12, 13, 15, 18, 19, 20, 21, 22, 27, 28, 30, 32, 34, 35, 38, 40, 46, 51, 54, 55, 57, 58, 60, 61, 62, 63, 64, 65, 67, 69, 70, 71, 72, 73, 74], "t_after_request": 0, "t_before_request": 0, "t_error_handl": 0, "t_rout": 0, "t_shell_context_processor": 0, "t_teardown": 0, "t_template_context_processor": 0, "t_template_filt": 0, "t_template_glob": 0, "t_template_test": 0, "t_url_default": 0, "t_url_value_preprocessor": 0, "tab": [4, 34, 70], "tabl": [46, 57, 61, 71], "tag": [4, 23, 34, 35, 38, 50, 52, 59, 63, 68, 70, 74], "tag_class": 0, "tagbyt": 0, "tagdatetim": 0, "tagdict": 0, "taggedjsonseri": [0, 4], "tagmarkup": 0, "tagordereddict": 0, "tagtupl": 0, "taguuid": 0, "take": [0, 3, 4, 5, 20, 21, 27, 28, 29, 31, 32, 38, 53, 54, 56, 60, 61, 62, 65, 69, 71, 72, 73, 74], "taken": [32, 64], "talisman": 74, "talk": 38, "tamper": [54, 72], "target": [0, 74], "task": [11, 12, 20, 24, 37, 54, 65, 68], "task_cl": 32, "task_ignore_result": 32, "task_result": 32, "tci4gzcx": 71, "tcp": 56, "te": 0, "tear": [0, 4, 57, 60], "teardown": [0, 2, 4, 47, 60], "teardown_": 4, "teardown_app_request": 0, "teardown_appcontext": [0, 1, 22, 27, 46, 47, 55, 62], "teardown_appcontext_func": 0, "teardown_db": 1, "teardown_request": [0, 4, 22, 27, 55, 57], "teardown_request_func": 0, "teardown_x": 1, "teardowncal": 0, "technic": 74, "techniqu": [21, 24, 29, 60, 61], "technologi": 20, "tell": [0, 4, 5, 6, 9, 13, 14, 15, 16, 18, 19, 20, 28, 36, 38, 43, 50, 53, 54, 62, 63, 64, 66, 67, 70, 71, 74], "tempfil": [35, 71], "templat": [4, 6, 21, 24, 25, 27, 30, 36, 37, 43, 58, 61, 65, 67, 69, 72, 73, 74], "template_context_processor": 0, "template_filt": [0, 4, 59], "template_fold": [0, 3, 4], "template_glob": [0, 4], "template_nam": [0, 52], "template_name_or_list": 0, "template_rend": [0, 58], "template_test": [0, 4], "templatecontextprocessorcal": 0, "templatenotfound": [3, 70], "templates_auto_reload": [0, 4, 6], "temporari": [0, 35, 54, 71], "temporarili": [0, 4, 8, 58, 59], "tend": [13, 22, 48], "term": [0, 40, 55], "termin": [0, 4, 5, 6, 15, 21, 24, 47, 62, 64, 71], "test": [4, 5, 6, 11, 12, 20, 22, 24, 30, 32, 46, 54, 55, 57, 58, 61, 64, 65, 66, 67], "test_": [60, 71], "test_access_sess": 60, "test_appcontext_sign": 4, "test_auth": [67, 71], "test_auth_token": 60, "test_author_requir": 71, "test_blog": [67, 71], "test_cli_runn": [0, 4, 60, 71], "test_cli_runner_class": 0, "test_client": [0, 4, 55, 58, 60, 71], "test_client_class": [0, 4], "test_config": [64, 71], "test_creat": 71, "test_create_update_valid": 71, "test_db": [67, 71], "test_db_post_model": 60, "test_delet": 71, "test_edit_us": 60, "test_exists_requir": 71, "test_factori": [67, 71], "test_get_close_db": 71, "test_hello": 71, "test_hello_command": 60, "test_index": 71, "test_init_db_command": 71, "test_json_data": 60, "test_login": 71, "test_login_requir": 71, "test_login_validate_input": 71, "test_logout": 71, "test_logout_redirect": 60, "test_modify_sess": 60, "test_regist": 71, "test_register_validate_input": 71, "test_request_context": [0, 4, 54, 55, 57, 60], "test_request_exampl": 60, "test_upd": 71, "test_user_m": 0, "test_validate_user_edit": 60, "testclient": 4, "testcod": 0, "testingconfig": 6, "testpath": 71, "testproject": 3, "testrespons": [0, 60], "text": [0, 4, 6, 21, 36, 38, 46, 48, 50, 54, 59, 60, 62, 69, 70, 71, 74], "textarea": [61, 69], "textfil": 74, "textiobas": 0, "than": [0, 1, 2, 3, 4, 5, 6, 8, 9, 11, 12, 16, 17, 20, 21, 27, 32, 47, 48, 52, 54, 55, 56, 60, 63, 68, 69, 70, 71, 72, 73, 74], "thank": [0, 20, 53], "the_fil": 54, "the_usernam": 47, "thei": [0, 2, 3, 4, 5, 6, 8, 9, 15, 20, 21, 22, 24, 25, 27, 29, 31, 35, 36, 37, 38, 46, 51, 52, 54, 55, 58, 59, 60, 61, 62, 68, 69, 70, 72, 73, 74], "them": [0, 2, 4, 5, 6, 9, 15, 21, 22, 25, 29, 32, 33, 35, 37, 38, 42, 43, 46, 47, 53, 54, 55, 57, 59, 60, 61, 66, 70, 71, 72, 73, 74], "theme": [4, 22, 54, 60], "themselv": [4, 6], "theoret": [0, 74], "theori": 26, "therebi": [0, 4], "therefor": [0, 2, 6, 32, 38], "theron": 42, "thi": [0, 1, 2, 3, 4, 5, 6, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 30, 32, 33, 34, 35, 36, 37, 38, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 69, 70, 71, 72, 73, 74], "thing": [0, 4, 6, 11, 12, 20, 21, 27, 31, 32, 40, 43, 48, 52, 53, 57, 59, 62, 73, 74], "think": 0, "third": [0, 6, 20], "this_is_never_execut": 54, "those": [0, 2, 4, 5, 8, 17, 20, 21, 28, 30, 38, 50, 54, 60, 70, 71, 73], "though": [0, 3, 4, 20, 48, 54, 55, 73], "thread": [0, 2, 4, 19, 24, 29, 46, 54, 55], "threadsaf": 54, "threat": 74, "three": [0, 5, 20, 52, 59, 70, 71], "threshold": 21, "through": [0, 3, 4, 8, 19, 21, 22, 27, 32, 41, 44, 54, 60, 65, 73], "throughout": 68, "throw": 31, "thu": [0, 59], "ti": [2, 20, 32, 62], "tier": 14, "tightli": 15, "time": [0, 2, 3, 4, 5, 6, 14, 20, 21, 22, 30, 31, 33, 52, 54, 55, 57, 58, 61, 62, 64, 71, 73, 74], "timedelta": [0, 4, 6], "timedseri": 74, "timelin": [48, 59], "timeout": [4, 52, 74], "timestamp": [0, 62], "timezon": [0, 4], "tip": 5, "titl": [21, 22, 35, 36, 42, 50, 54, 61, 62, 68, 70, 71], "tl": [9, 16], "tld": 3, "tmp": [6, 46], "to_dict": 21, "to_json": [0, 22, 38, 54, 73], "to_python": 0, "to_url": 0, "toaddr": 28, "todai": 22, "togeth": [32, 46, 55], "toggl": [6, 56], "tojson": [0, 4, 38], "token": [0, 4, 60, 74], "token_hex": [6, 54, 63], "told": [5, 17, 27, 74], "toml": [0, 4, 5, 6, 43, 66, 67, 71], "tomllib": [0, 6], "too": [0, 20, 22, 28, 36, 68, 74], "took": [32, 68, 72], "tool": [4, 6, 8, 20, 22, 24, 56, 63, 66, 71], "toolkit": 24, "top": [0, 3, 4, 5, 6, 20, 42, 43, 54, 55, 64, 67, 69, 74], "topic": [43, 74], "toplevel": 0, "torn": 0, "tort": 26, "total": [41, 71], "total_second": 4, "touch": 6, "tox": 22, "trace": [0, 6, 21], "traceback": [0, 4, 8, 55, 56], "tracebacktyp": 0, "track": [0, 1, 4, 55], "tradeoff": [22, 74], "tradit": [2, 20, 38], "traffic": 74, "trail": [0, 4, 54], "transact": [0, 46], "transfer": 22, "transit": 0, "translat": [27, 54, 74], "transmit": [0, 4, 35, 54, 74], "transpar": 54, "trap": [0, 4], "trap_bad_request_error": [0, 4, 6], "trap_http_except": [0, 6], "trash": 4, "travers": 4, "treat": [0, 4, 6, 9, 16, 20, 27, 54, 55, 60, 64], "tri": [0, 3, 4, 5, 27, 54, 55, 56, 64, 74], "trick": [40, 48, 57, 74], "tricki": [0, 64], "trigger": [0, 2, 3, 4, 5, 21, 54, 57, 74], "trim_namespac": 0, "trivial": 4, "troubl": 20, "true": [0, 3, 4, 6, 8, 22, 30, 32, 35, 36, 42, 46, 47, 53, 56, 58, 60, 61, 64, 71, 73, 74], "truli": [47, 74], "trust": [0, 6, 17, 35, 54], "trusted_host": [0, 4, 6], "truth": 0, "try": [0, 1, 3, 4, 5, 6, 20, 21, 33, 48, 53, 54, 55, 56, 58, 60, 61, 62, 63, 64, 68, 69, 70, 72, 74], "tt0088763": 42, "tune": 13, "tupl": [0, 4, 46, 47, 54, 60, 72], "turbogear": 52, "turn": [4, 8, 21, 72], "tutori": [4, 22, 24, 43, 60, 61, 62, 63, 64, 66, 67, 68, 69, 71, 72], "twice": [4, 54, 70], "two": [0, 3, 5, 11, 12, 20, 32, 38, 40, 43, 50, 54, 59, 61, 72, 73, 74], "txt": [35, 54], "type": [0, 4, 6, 13, 21, 22, 23, 32, 35, 36, 37, 38, 46, 48, 50, 52, 53, 54, 55, 60, 61, 67, 69, 70, 72], "typecheck": 0, "typeddict": 4, "typeerror": [0, 4], "typic": [0, 1, 5, 21, 22, 27, 53, 55, 60, 62, 74], "typo": [0, 4], "u": [0, 27, 32, 38, 46, 53, 57, 61, 74], "ul": [36, 53, 69, 70], "ultim": 2, "unallow": 21, "unauthor": 61, "unavail": [0, 57, 59], "unbind": 0, "unbound": 4, "uncaught": 21, "unchang": [0, 35, 52], "uncheck": 5, "uncom": 9, "uncommon": 27, "undefin": [6, 20], "under": [0, 4, 6, 13, 38, 64, 69], "underli": [0, 54, 55], "underneath": 6, "underscor": [0, 6, 22, 42], "understand": [2, 4, 9, 13, 15, 16, 18, 19, 20, 38, 50, 54, 66], "undertak": 20, "undo": 74, "undocu": 4, "unexpect": [4, 8, 54], "unexpectedli": 71, "unfortun": [6, 22, 52, 74], "unguess": 0, "unhandl": [0, 4, 6, 8, 55], "unicod": 4, "uninstal": 6, "uniqu": [0, 4, 20, 22, 34, 46, 52, 55, 58, 62], "unit": [0, 6, 20, 30, 54, 57, 58, 71], "unittest": [0, 4], "unix": [0, 4, 5], "unknown": [0, 54], "unless": [0, 4, 38, 54, 58, 59, 74], "unlik": [0, 3, 15, 61, 68, 70, 73], "unlimit": [35, 74], "unlink": 71, "unmodifi": 0, "unnecessari": [0, 4, 73], "unpack": 4, "unprint": 4, "unquot": 74, "unregist": [3, 4, 21], "unreleas": 4, "unreli": [0, 4, 20], "unsaf": [38, 74], "unset": [0, 6], "unsign": [4, 6], "unsubscrib": 58, "unsupport": 0, "unsur": 54, "untag": [0, 4], "until": [0, 2, 4, 54, 55, 56, 57, 60, 62, 70], "untrust": [25, 54, 74], "unus": 4, "unwant": [0, 70], "up": [0, 1, 2, 3, 4, 6, 11, 14, 20, 21, 22, 24, 27, 28, 29, 30, 31, 36, 40, 43, 44, 46, 52, 53, 54, 55, 59, 60, 62, 63, 64, 65, 67, 69, 74], "updat": [0, 4, 6, 22, 23, 44, 60, 67, 71, 73, 74], "update_from_json": [38, 73], "update_template_context": 0, "upfront": [40, 57], "upgrad": [4, 74], "upload": [0, 4, 20, 24, 32, 37, 60, 68, 74], "upload_fil": [35, 54], "upload_fold": [0, 35], "uploaded_fil": 54, "upper": [0, 22, 41], "uppercas": [0, 6], "upsid": [2, 46, 47], "upward": [0, 5], "uri": [0, 74], "url": [4, 6, 20, 21, 22, 24, 27, 28, 29, 35, 37, 52, 60, 61, 64, 70, 71, 74], "url_build_error_handl": [0, 4], "url_default": [0, 51], "url_default_funct": 0, "url_for": [0, 3, 4, 6, 21, 28, 34, 35, 36, 38, 50, 51, 52, 53, 54, 59, 61, 69, 70, 72, 73], "url_map": [0, 3, 4, 51, 52], "url_map_class": [0, 4], "url_prefix": [0, 3, 4, 30, 51, 61, 72], "url_root": 0, "url_rul": [0, 40], "url_rule_class": 0, "url_schem": [0, 4], "url_value_preprocessor": [0, 27, 51], "urldefaultcal": 0, "urlencod": 60, "urlvaluepreprocessorcal": 0, "us": [1, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 32, 33, 34, 35, 36, 37, 38, 40, 41, 42, 43, 44, 45, 46, 48, 49, 50, 52, 53, 55, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 70, 71, 72, 73], "usag": [0, 4, 6, 23, 37, 44, 53, 57], "use_cooki": 0, "use_debugg": [0, 8], "use_evalex": 0, "use_reload": [0, 8], "use_x_sendfil": [0, 4, 6], "user": [0, 3, 4, 5, 6, 14, 15, 21, 22, 28, 29, 32, 33, 35, 36, 37, 38, 40, 46, 47, 52, 53, 54, 57, 59, 60, 61, 62, 65, 66, 67, 71, 72, 73, 74], "user123": 6, "user_ag": 0, "user_agent_class": 0, "user_api": 21, "user_cli": 5, "user_detail": [38, 73], "user_id": [0, 21, 22, 32, 38, 47, 60, 71, 72, 74], "user_imag": 54, "user_lang": 33, "user_list": [38, 73], "user_profil": 21, "user_set": 0, "user_upd": 38, "user_url": 38, "userag": 0, "userlist": 73, "usernam": [0, 3, 6, 21, 28, 35, 36, 38, 40, 47, 53, 54, 60, 61, 62, 70, 71, 72, 74], "users_api": 54, "users_list": 73, "usr": 6, "usual": [0, 3, 4, 6, 8, 20, 22, 23, 27, 28, 36, 38, 40, 47, 54, 60], "utc": 4, "utf": [0, 4], "utf8": [62, 71], "util": [0, 3, 4, 6, 29, 35, 40, 42, 54, 60], "utilis": [2, 10], "utility_processor": 59, "uuid": [0, 54], "uwsgi": [12, 14], "v": [0, 62, 71], "valid": [0, 4, 6, 11, 12, 13, 18, 19, 20, 21, 22, 24, 29, 35, 37, 38, 54, 61, 68, 70, 71, 72, 73, 74], "valid_login": 54, "valid_method": 0, "validate_edit_us": 60, "valu": [0, 4, 5, 13, 15, 17, 18, 20, 21, 22, 24, 27, 30, 32, 35, 36, 38, 41, 42, 47, 51, 52, 53, 54, 55, 58, 59, 60, 61, 62, 63, 64, 70, 71, 72, 73, 74], "valueerror": [0, 4], "valuesview": 0, "var": [0, 4, 6, 54, 55, 63], "vari": [0, 4], "variabl": [0, 3, 4, 13, 19, 20, 21, 24, 25, 38, 43, 47, 58, 59, 60, 61, 71, 72], "variable_nam": [0, 54], "variant": [0, 74], "varieti": [5, 20], "variou": [0, 4, 20, 31, 44, 73, 74], "ve": [2, 22, 61, 66, 68, 70, 71], "vector": 74, "venv": [5, 11, 12, 13, 15, 18, 19, 25, 63, 67], "verbos": 71, "veri": [0, 3, 4, 6, 18, 20, 21, 22, 28, 29, 30, 33, 35, 44, 46, 50, 53, 54, 59, 61, 69, 71, 74], "verif": 4, "version": [0, 2, 3, 6, 21, 22, 24, 28, 30, 35, 36, 51, 54, 57, 59, 63, 64, 66, 67, 69], "versu": 46, "vertic": 69, "via": [0, 2, 6, 34, 53], "view": [1, 2, 3, 4, 6, 20, 21, 24, 27, 30, 33, 34, 35, 37, 43, 48, 51, 54, 55, 60, 61, 62, 65, 68, 69, 70, 71], "view_arg": 0, "view_func": [0, 40, 73], "view_funct": 0, "view_rv": 0, "viewpoint": 0, "violat": 41, "virtual": [4, 24, 63, 66, 67], "virtualenv": [6, 11, 12, 13, 15, 18, 19, 24, 63], "visibl": [0, 4, 22, 28, 56], "visit": [54, 61, 64, 72], "visual": 61, "vnd": 34, "vodka": 0, "vote": 42, "vulner": [72, 74], "w": [13, 18], "wa": [0, 3, 4, 6, 20, 21, 27, 32, 35, 44, 46, 47, 51, 54, 55, 56, 59, 60, 61, 62, 71, 72, 74], "wai": [0, 1, 2, 3, 4, 6, 7, 18, 20, 21, 22, 26, 27, 28, 30, 31, 32, 33, 34, 35, 36, 38, 41, 42, 43, 46, 51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 63, 64, 65, 71, 72, 73, 74], "wait": [0, 32, 56], "waitress": [14, 63], "walk": [65, 73], "want": [0, 2, 3, 4, 5, 6, 8, 13, 14, 20, 21, 22, 27, 28, 29, 30, 32, 33, 34, 35, 36, 38, 43, 44, 46, 47, 48, 49, 51, 52, 53, 54, 55, 57, 58, 59, 60, 61, 62, 63, 65, 68, 70, 71], "want_form_data_pars": 0, "warn": [0, 4, 6, 28, 54, 74], "warranti": 26, "wasn": [0, 2], "watchdog": 25, "we": [0, 3, 6, 9, 16, 20, 21, 25, 29, 30, 32, 33, 34, 35, 38, 40, 43, 46, 47, 50, 51, 52, 53, 54, 60, 62, 73, 74], "weak": 0, "weakref": 0, "web": [0, 3, 5, 6, 14, 20, 22, 24, 27, 34, 36, 37, 52, 62, 64, 68, 74], "webob": 20, "webpag": 50, "webserv": [0, 20, 29, 30, 35], "websit": [0, 22, 34, 46, 53, 74], "websocket": 2, "weight": 69, "welcom": 50, "well": [0, 2, 3, 4, 6, 11, 12, 20, 22, 23, 24, 27, 31, 32, 34, 35, 38, 42, 44, 46, 51, 54, 58, 59, 67, 70], "went": [28, 54], "were": [0, 4, 6, 20, 21, 31, 36, 54, 57, 58, 71, 74], "weren": 4, "werkzeug": [0, 1, 4, 6, 8, 17, 20, 21, 24, 25, 27, 29, 35, 40, 49, 52, 54, 55, 60, 61, 63, 66, 68, 72], "what": [0, 3, 4, 6, 9, 13, 15, 16, 17, 18, 19, 21, 22, 24, 25, 27, 31, 32, 33, 35, 40, 43, 54, 56, 57, 58, 59, 60, 61, 63, 65, 68, 72, 73, 74], "whatev": [0, 27, 32], "wheel": [18, 63, 66], "when": [0, 1, 3, 4, 5, 6, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 27, 28, 30, 31, 32, 33, 35, 36, 38, 43, 44, 46, 47, 48, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 61, 62, 63, 64, 65, 71, 72, 73, 74], "when_template_rend": 58, "whenev": [0, 5, 20, 47, 58, 59, 64, 74], "where": [0, 3, 4, 5, 6, 20, 21, 22, 32, 33, 35, 43, 46, 47, 51, 52, 54, 55, 57, 61, 62, 64, 66, 67, 70, 71, 72, 73, 74], "wherea": 2, "wherev": 5, "whether": [0, 2, 4, 6, 14, 26, 32], "which": [0, 1, 2, 3, 4, 5, 6, 8, 11, 12, 13, 14, 15, 18, 19, 20, 21, 27, 28, 29, 30, 32, 35, 36, 38, 40, 47, 50, 51, 53, 54, 55, 57, 58, 60, 62, 63, 64, 68, 70, 71, 72, 73, 74], "while": [0, 1, 3, 4, 5, 6, 20, 21, 22, 23, 32, 35, 43, 46, 48, 52, 54, 55, 56, 64, 65, 67, 71, 74], "whiski": 4, "white": [4, 21, 54, 69], "whl": [63, 66], "who": [35, 72], "whole": [0, 3, 4, 20, 51, 54, 59], "why": [0, 4, 6, 20, 21, 24, 30, 32, 35, 46, 54, 74], "wide": [0, 4, 20, 21], "width": 69, "wiki": [5, 54], "wikipedia": [34, 74], "will_not_be_escap": 59, "window": [0, 4, 5, 6, 9, 13, 15, 16, 18, 19, 25, 38, 56, 63, 70, 74], "winerror": [5, 54, 56, 64], "wish": [2, 36], "with_appcontext": [0, 4, 5], "with_categori": [0, 36], "withgoogl": 74, "within": [0, 1, 2, 3, 4, 5, 25, 27, 30, 32, 54, 59, 70, 71], "without": [0, 2, 3, 4, 6, 9, 11, 12, 14, 15, 16, 20, 21, 22, 26, 32, 35, 38, 40, 48, 54, 59, 60, 61, 70, 71, 72, 73, 74], "won": [0, 1, 5, 20, 22, 28, 32, 38, 54, 62, 63, 69, 71, 72, 74], "wonder": [46, 54], "word": 22, "work": [0, 1, 2, 3, 4, 5, 6, 8, 11, 12, 13, 18, 20, 21, 22, 24, 25, 27, 35, 37, 40, 41, 46, 47, 52, 53, 54, 59, 60, 61, 62, 64, 67, 68, 69, 71, 73, 74], "workaround": 4, "worker": [0, 2, 4, 11, 12, 13, 15, 18, 19, 21, 22, 27, 32, 55], "world": [0, 6, 20, 27, 29, 43, 52, 54, 55, 60, 64, 67, 71, 72], "wors": 20, "would": [0, 2, 3, 4, 5, 6, 8, 11, 12, 13, 18, 19, 20, 21, 22, 29, 30, 31, 32, 33, 35, 38, 40, 43, 47, 51, 52, 54, 57, 58, 59, 60, 61, 71, 72, 73, 74], "wouldn": [21, 22, 32], "wrap": [0, 2, 4, 10, 17, 20, 22, 27, 40, 41, 44, 52, 54, 55, 59, 72], "wrap_fil": 0, "wrapped_view": 72, "wrapper": [0, 2, 4, 48, 59], "write": [0, 1, 2, 5, 6, 11, 12, 15, 20, 22, 25, 27, 28, 29, 34, 40, 51, 53, 54, 55, 60, 61, 62, 64, 67, 69, 70, 71, 72, 73], "written": [0, 15, 22, 26, 61, 70, 71], "wrong": [4, 6, 17, 21, 28], "wrote": [61, 71, 72], "wsgi": [0, 2, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 24, 25, 27, 28, 29, 30, 35, 44, 48, 55, 63, 74], "wsgi_app": [0, 17, 20, 27, 41, 54, 55], "wsgi_errors_stream": 28, "wsgiapplic": 0, "wsgienviron": 0, "wsgiref": 29, "wsgiserv": 12, "wsgitoasgi": [2, 10], "wsl": [13, 18], "wss": 0, "wtf": 53, "wtform": [24, 37], "www": [0, 54, 60], "www_authent": 0, "wwwauthent": 0, "x": [0, 1, 4, 5, 6, 9, 11, 13, 16, 17, 18, 41, 54, 59, 60, 71], "x_for": 17, "x_host": 17, "x_prefix": 17, "x_proto": 17, "xec": [36, 54], "xhtml": [4, 54, 59], "xml": [4, 20, 54, 59], "xmlhttprequest": 38, "xpath": 20, "xss": [24, 35, 59], "y": [6, 61, 74], "y2l": [36, 54], "ye": [20, 35], "year": [42, 55], "year__gt": 42, "yet": [0, 4, 6, 20, 29, 33, 43, 51, 54, 62, 70], "yield": [0, 4, 48, 58, 59, 60, 71], "yml": 4, "yosemit": 74, "you": [0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74], "your": [0, 1, 2, 3, 4, 5, 6, 8, 9, 11, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22, 23, 25, 27, 28, 29, 30, 31, 32, 34, 35, 38, 40, 42, 43, 45, 46, 48, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74], "your_dsn_her": 21, "yourappl": [0, 3, 6, 30, 40, 43, 46, 47], "yourapplication_mod": 6, "yourapplication_set": [0, 6], "yourconfig": 0, "yourpackag": 3, "yourproject": 66, "yourself": [0, 4, 6, 28, 40, 51, 53, 54, 57, 74], "zero": [0, 4], "zip": 4}, "titles": ["API", "The Application Context", "Using async and await", "Modular Applications with Blueprints", "Changes", "Command Line Interface", "Configuration Handling", "Contributing", "Debugging Application Errors", "Apache httpd", "ASGI", "eventlet", "gevent", "Gunicorn", "Deploying to Production", "mod_wsgi", "nginx", "Tell Flask it is Behind a Proxy", "uWSGI", "Waitress", "Design Decisions in Flask", "Handling Application Errors", "Flask Extension Development", "Extensions", "Welcome to Flask", "Installation", "BSD-3-Clause License", "Application Structure and Lifecycle", "Logging", "Application Dispatching", "Application Factories", "Caching", "Background Tasks with Celery", "Deferred Request Callbacks", "Adding a favicon", "Uploading Files", "Message Flashing", "Patterns for Flask", "JavaScript, fetch, and JSON", "AJAX with jQuery", "Lazily Loading Views", "Adding HTTP Method Overrides", "MongoDB with MongoEngine", "Large Applications as Packages", "Request Content Checksums", "Single-Page Applications", "SQLAlchemy in Flask", "Using SQLite 3 with Flask", "Streaming Contents", "Subclassing Flask", "Template Inheritance", "Using URL Processors", "View Decorators", "Form Validation with WTForms", "Quickstart", "The Request Context", "Development Server", "Working with the Shell", "Signals", "Templates", "Testing Flask Applications", "Blog Blueprint", "Define and Access the Database", "Deploy to Production", "Application Setup", "Tutorial", "Make the Project Installable", "Project Layout", "Keep Developing!", "Static Files", "Templates", "Test Coverage", "Blueprints and Views", "Class-based Views", "Security Considerations"], "titleterms": {"": [24, 58], "0": 4, "1": 4, "10": 4, "11": 4, "12": 4, "2": 4, "3": [4, 26, 47], "4": 4, "5": 4, "6": 4, "7": 4, "8": 4, "9": 4, "A": [35, 54, 70], "In": [8, 53, 56, 70], "Not": 20, "On": 55, "One": 20, "The": [1, 3, 8, 20, 22, 53, 54, 55, 59, 61, 64, 70, 72], "With": 36, "about": [0, 54], "abstract": 46, "access": [54, 60, 62], "activ": [25, 60], "ad": [22, 34, 41], "addit": 24, "address": 56, "admin": 28, "after": 57, "ajax": 39, "alreadi": 56, "also": 34, "an": [25, 35, 53, 60], "apach": 9, "api": [0, 21, 24, 54, 73], "applic": [0, 1, 3, 5, 8, 20, 21, 27, 29, 30, 32, 43, 45, 51, 54, 60, 62, 64], "asgi": [10, 20], "async": [2, 13, 18, 20], "authent": [71, 72], "autoescap": 59, "await": [2, 20], "background": [2, 32], "bar": 35, "base": [0, 50, 58, 70, 73], "basic": [6, 28, 30, 48, 73], "befor": 57, "behavior": [22, 54, 59], "behind": 17, "best": 6, "bind": [11, 12, 13, 15, 18, 19], "blog": [61, 71], "blueprint": [0, 3, 5, 21, 43, 51, 61, 72], "bsd": 26, "build": [3, 23, 54, 63], "built": 8, "builtin": 6, "cach": [31, 52], "call": 32, "callback": [33, 55], "categori": 36, "celeri": 32, "central": 40, "chang": 4, "checksum": 44, "child": 50, "circular": 43, "class": [0, 22, 73], "claus": 26, "cli": [0, 60], "client": [0, 60], "code": 56, "combin": 29, "command": [0, 5, 56, 57, 60], "concept": 3, "configur": [0, 6, 9, 16, 22, 28, 42, 63], "connect": [35, 47, 62], "consider": 74, "content": [38, 44, 48, 65, 74], "context": [1, 5, 48, 54, 55, 57, 58, 59, 60], "contribut": 7, "control": 59, "convert": 40, "cooki": [54, 74], "copi": 74, "core": 58, "coverag": 71, "creat": [25, 42, 57, 58, 61, 62, 72], "cross": 74, "csp": 74, "csrf": 74, "custom": [5, 21], "data": [0, 1, 6, 22, 32, 42, 54, 60], "databas": [62, 71], "debug": [5, 6, 8, 21, 54], "debugg": 8, "decis": 20, "declar": 46, "decor": [52, 58, 73], "default": 28, "defer": [33, 56], "defin": [32, 62], "delet": 61, "demand": 47, "depend": [25, 60], "deploi": [14, 54, 63], "describ": 66, "design": 20, "develop": [5, 6, 22, 56, 68], "disabl": 5, "discoveri": [5, 54], "dispatch": [29, 73], "document": [29, 42], "doe": 20, "domain": [9, 16], "dotenv": 5, "dure": 22, "easi": 47, "easier": 35, "email": 28, "endpoint": [52, 72], "engin": 20, "environ": [5, 6, 25], "error": [3, 5, 8, 21, 28, 54, 55, 56], "escap": 54, "event": [1, 2], "eventlet": [11, 13], "exampl": 21, "except": 21, "experi": 57, "explicit": 20, "extens": [2, 22, 23, 28, 30, 46, 53, 54], "extern": [8, 11, 12, 13, 15, 18, 19, 54], "factori": [30, 32, 64, 71], "favicon": 34, "fetch": 38, "file": [3, 5, 6, 35, 54, 62, 69], "filter": [36, 59], "find": 23, "fire": 57, "first": [0, 3, 72], "fixtur": [60, 71], "flash": [0, 36, 54], "flask": [17, 20, 22, 24, 25, 28, 32, 37, 46, 47, 49, 54, 58, 60], "folder": [3, 6], "follow": [38, 60], "forgeri": 74, "form": [53, 60], "frame": 74, "from": [5, 6, 38, 48], "function": 0, "further": [21, 57], "gener": [21, 38, 54], "gentl": 35, "get": [32, 53], "gevent": [12, 13, 18], "global": 0, "good": 54, "greenlet": [2, 25], "guid": 24, "guidelin": 22, "gunicorn": 13, "handl": [6, 21, 27], "handler": [3, 21, 28], "header": 74, "helper": 0, "hint": 73, "hook": 54, "host": 14, "how": [27, 54, 55], "hpkp": 74, "hst": 74, "html": 54, "http": [41, 54, 74], "httpd": 9, "i": [17, 20, 27], "identifi": 60, "ignor": 5, "import": 43, "improv": [30, 35, 57], "incom": 0, "index": 61, "inform": [28, 35, 54], "inherit": 50, "initi": [22, 47, 62], "inject": 28, "insid": 54, "instal": [11, 12, 13, 15, 18, 19, 25, 32, 63, 66], "instanc": 6, "instead": 2, "integr": [5, 32], "interfac": [0, 5, 57], "intern": 0, "internation": 51, "introduct": 35, "issu": 35, "javascript": 38, "jinja": 59, "jqueri": 39, "json": [0, 21, 38, 54, 60, 74], "keep": [0, 68], "kei": [54, 63, 74], "larg": 43, "late": 40, "layer": 46, "layout": [67, 70], "lazili": 40, "librari": 28, "licens": 26, "lifecycl": 27, "lifetim": [1, 55, 73], "line": [0, 5, 56, 57], "load": 40, "local": [20, 54], "log": [21, 28, 54, 70], "login": [52, 72], "logout": 72, "loop": 2, "make": [38, 66], "manual": [1, 46, 55], "map": [40, 42, 46], "mean": 20, "messag": [0, 36, 54], "method": [41, 54, 73], "micro": 20, "middlewar": [27, 54], "mind": 0, "minim": 54, "mod_wsgi": 15, "mode": [5, 6, 54], "model": 22, "modifi": 60, "modular": 3, "mongodb": 42, "mongoengin": 42, "most": 53, "my": 3, "name": [9, 16, 22], "nest": 3, "nginx": 16, "note": [24, 55], "notic": 0, "object": [0, 20, 46, 54], "open": 5, "option": [0, 5, 14, 25, 74], "other": [2, 28, 72], "out": 53, "overrid": 41, "packag": 43, "page": [21, 45], "paramet": 0, "pass": [32, 58], "past": 74, "path": 29, "pattern": 37, "perform": 2, "pin": 74, "platform": 14, "plugin": 5, "polici": 74, "practic": 6, "pro": 35, "processor": [51, 59], "product": [6, 8, 14, 63], "progress": 35, "project": [66, 67], "proxi": [17, 55, 58], "public": 74, "purpos": [1, 55], "push": [1, 55], "pycharm": 5, "python": [6, 25], "quart": 2, "queri": [42, 47], "quickstart": 54, "receiv": 38, "recommend": 22, "redirect": [38, 54, 60], "refer": 24, "regist": [3, 5, 21, 59, 62, 70, 72], "registr": 0, "relat": 46, "reload": [5, 56], "remov": 28, "render": [0, 38, 54], "replac": 38, "request": [0, 22, 27, 28, 33, 38, 44, 54, 55, 57, 58, 60, 74], "requir": [52, 72], "reset": 35, "resourc": [3, 74], "respons": [0, 54], "result": 32, "return": [21, 38], "reusabl": 73, "rout": [0, 20, 54], "rule": 54, "run": [5, 11, 12, 13, 15, 18, 19, 60, 63, 64, 71], "runner": [0, 60], "schema": 47, "script": [5, 74], "secret": [54, 63], "secur": 74, "see": 34, "self": [14, 73], "send": [58, 60], "sender": 58, "serv": 27, "server": [5, 54, 56, 63], "session": [0, 54, 60], "set": [5, 74], "setup": [27, 59, 64, 71], "shell": [5, 57], "signal": [0, 1, 55, 58], "simpl": [36, 43], "singl": 45, "site": 74, "solut": 35, "sql": 46, "sqlalchemi": 46, "sqlite": 47, "standard": 59, "static": [3, 54, 69], "store": 1, "stream": [0, 48, 59], "strict": 74, "structur": 27, "subclass": 49, "subdomain": 29, "subscrib": 58, "subscript": 58, "support": [0, 20], "system": 20, "tabl": 62, "tag": 0, "task": [2, 32], "teardown": 55, "techniqu": 22, "tell": 17, "templat": [0, 3, 20, 38, 48, 50, 52, 53, 54, 59, 70], "termin": 74, "test": [0, 60, 71], "thi": 29, "thread": 20, "tool": 21, "transport": 74, "tutori": 65, "type": 74, "unhandl": 21, "uniqu": 54, "updat": 61, "upload": [35, 54], "url": [0, 3, 38, 40, 51, 54, 72, 73], "us": [0, 2, 23, 30, 47, 51, 54, 56, 74], "usag": 48, "user": [24, 70], "uwsgi": 18, "valid": 53, "valu": 6, "variabl": [5, 6, 54, 73], "version": [4, 25], "view": [0, 22, 38, 40, 52, 53, 72, 73], "virtual": 25, "virtualenv": 5, "visibl": 54, "waitress": 19, "watch": 5, "web": 54, "welcom": 24, "werkzeug": 28, "what": 20, "when": 2, "why": 3, "work": [29, 43, 55, 57], "wsgi": 54, "wtform": 53, "x": 74, "xss": 74}}) diff --git a/_build/server/index.html b/_build/server/index.html new file mode 100644 index 00000000..6937b3aa --- /dev/null +++ b/_build/server/index.html @@ -0,0 +1,190 @@ + + + + + + + + Development Server — Flask Documentation (3.1.x) + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Development Server

+

Flask provides a run command to run the application with a development server. In +debug mode, this server provides an interactive debugger and will reload when code is +changed.

+
+

Warning

+

Do not use the development server when deploying to production. It +is intended for use only during local development. It is not +designed to be particularly efficient, stable, or secure.

+

See Deploying to Production for deployment options.

+
+
+

Command Line

+

The flask run CLI command is the recommended way to run the development server. Use +the --app option to point to your application, and the --debug option to enable +debug mode.

+
$ flask --app hello run --debug
+
+
+

This enables debug mode, including the interactive debugger and reloader, and then +starts the server on http://localhost:5000/. Use flask run --help to see the +available options, and Command Line Interface for detailed instructions about configuring and using +the CLI.

+
+

Address already in use

+

If another program is already using port 5000, you’ll see an OSError +when the server tries to start. It may have one of the following +messages:

+
    +
  • OSError: [Errno 98] Address already in use

  • +
  • OSError: [WinError 10013] An attempt was made to access a socket +in a way forbidden by its access permissions

  • +
+

Either identify and stop the other program, or use +flask run --port 5001 to pick a different port.

+

You can use netstat or lsof to identify what process id is using +a port, then use other operating system tools stop that process. The +following example shows that process id 6847 is using port 5000.

+
+
$ netstat -nlp | grep 5000
+tcp 0 0 127.0.0.1:5000 0.0.0.0:* LISTEN 6847/python
+
+
+
+

macOS Monterey and later automatically starts a service that uses port +5000. You can choose to disable this service instead of using a different port by +searching for “AirPlay Receiver” in System Preferences and toggling it off.

+
+
+

Deferred Errors on Reload

+

When using the flask run command with the reloader, the server will +continue to run even if you introduce syntax errors or other +initialization errors into the code. Accessing the site will show the +interactive debugger for the error, rather than crashing the server.

+

If a syntax error is already present when calling flask run, it will +fail immediately and show the traceback rather than waiting until the +site is accessed. This is intended to make errors more visible initially +while still allowing the server to handle errors on reload.

+
+
+
+

In Code

+

The development server can also be started from Python with the Flask.run() +method. This method takes arguments similar to the CLI options to control the server. +The main difference from the CLI command is that the server will crash if there are +errors when reloading. debug=True can be passed to enable debug mode.

+

Place the call in a main block, otherwise it will interfere when trying to import and +run the application with a production server later.

+
if __name__ == "__main__":
+    app.run(debug=True)
+
+
+
$ python hello.py
+
+
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/shell/index.html b/_build/shell/index.html new file mode 100644 index 00000000..329f80b0 --- /dev/null +++ b/_build/shell/index.html @@ -0,0 +1,192 @@ + + + + + + + + Working with the Shell — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Working with the Shell

+
+Changelog
+

Added in version 0.3.

+
+

One of the reasons everybody loves Python is the interactive shell. It +basically allows you to execute Python commands in real time and +immediately get results back. Flask itself does not come with an +interactive shell, because it does not require any specific setup upfront, +just import your application and start playing around.

+

There are however some handy helpers to make playing around in the shell a +more pleasant experience. The main issue with interactive console +sessions is that you’re not triggering a request like a browser does which +means that g, request and others are not +available. But the code you want to test might depend on them, so what +can you do?

+

This is where some helper functions come in handy. Keep in mind however +that these functions are not only there for interactive shell usage, but +also for unit testing and other situations that require a faked request +context.

+

Generally it’s recommended that you read The Request Context first.

+
+

Command Line Interface

+

Starting with Flask 0.11 the recommended way to work with the shell is the +flask shell command which does a lot of this automatically for you. +For instance the shell is automatically initialized with a loaded +application context.

+

For more information see Command Line Interface.

+
+
+

Creating a Request Context

+

The easiest way to create a proper request context from the shell is by +using the test_request_context method which creates +us a RequestContext:

+
>>> ctx = app.test_request_context()
+
+
+

Normally you would use the with statement to make this request object +active, but in the shell it’s easier to use the +push() and +pop() methods by hand:

+
>>> ctx.push()
+
+
+

From that point onwards you can work with the request object until you +call pop:

+
>>> ctx.pop()
+
+
+
+
+

Firing Before/After Request

+

By just creating a request context, you still don’t have run the code that +is normally run before a request. This might result in your database +being unavailable if you are connecting to the database in a +before-request callback or the current user not being stored on the +g object etc.

+

This however can easily be done yourself. Just call +preprocess_request():

+
>>> ctx = app.test_request_context()
+>>> ctx.push()
+>>> app.preprocess_request()
+
+
+

Keep in mind that the preprocess_request() function +might return a response object, in that case just ignore it.

+

To shutdown a request, you need to trick a bit before the after request +functions (triggered by process_response()) operate on +a response object:

+
>>> app.process_response(app.response_class())
+<Response 0 bytes [200 OK]>
+>>> ctx.pop()
+
+
+

The functions registered as teardown_request() are +automatically called when the context is popped. So this is the perfect +place to automatically tear down resources that were needed by the request +context (such as database connections).

+
+
+

Further Improving the Shell Experience

+

If you like the idea of experimenting in a shell, create yourself a module +with stuff you want to star import into your interactive session. There +you could also define some more helper methods for common things such as +initializing the database, dropping tables etc.

+

Just put them into a module (like shelltools) and import from there:

+
>>> from shelltools import *
+
+
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/signals/index.html b/_build/signals/index.html new file mode 100644 index 00000000..9b2d6814 --- /dev/null +++ b/_build/signals/index.html @@ -0,0 +1,250 @@ + + + + + + + + Signals — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Signals

+

Signals are a lightweight way to notify subscribers of certain events during the +lifecycle of the application and each request. When an event occurs, it emits the +signal, which calls each subscriber.

+

Signals are implemented by the Blinker library. See its documentation for detailed +information. Flask provides some built-in signals. Extensions may provide their own.

+

Many signals mirror Flask’s decorator-based callbacks with similar names. For example, +the request_started signal is similar to the before_request() +decorator. The advantage of signals over handlers is that they can be subscribed to +temporarily, and can’t directly affect the application. This is useful for testing, +metrics, auditing, and more. For example, if you want to know what templates were +rendered at what parts of what requests, there is a signal that will notify you of that +information.

+
+

Core Signals

+

See Signals for a list of all built-in signals. The Application Structure and Lifecycle +page also describes the order that signals and decorators execute.

+
+
+

Subscribing to Signals

+

To subscribe to a signal, you can use the +connect() method of a signal. The first +argument is the function that should be called when the signal is emitted, +the optional second argument specifies a sender. To unsubscribe from a +signal, you can use the disconnect() method.

+

For all core Flask signals, the sender is the application that issued the +signal. When you subscribe to a signal, be sure to also provide a sender +unless you really want to listen for signals from all applications. This is +especially true if you are developing an extension.

+

For example, here is a helper context manager that can be used in a unit test +to determine which templates were rendered and what variables were passed +to the template:

+
from flask import template_rendered
+from contextlib import contextmanager
+
+@contextmanager
+def captured_templates(app):
+    recorded = []
+    def record(sender, template, context, **extra):
+        recorded.append((template, context))
+    template_rendered.connect(record, app)
+    try:
+        yield recorded
+    finally:
+        template_rendered.disconnect(record, app)
+
+
+

This can now easily be paired with a test client:

+
with captured_templates(app) as templates:
+    rv = app.test_client().get('/')
+    assert rv.status_code == 200
+    assert len(templates) == 1
+    template, context = templates[0]
+    assert template.name == 'index.html'
+    assert len(context['items']) == 10
+
+
+

Make sure to subscribe with an extra **extra argument so that your +calls don’t fail if Flask introduces new arguments to the signals.

+

All the template rendering in the code issued by the application app +in the body of the with block will now be recorded in the templates +variable. Whenever a template is rendered, the template object as well as +context are appended to it.

+

Additionally there is a convenient helper method +(connected_to()) that allows you to +temporarily subscribe a function to a signal with a context manager on +its own. Because the return value of the context manager cannot be +specified that way, you have to pass the list in as an argument:

+
from flask import template_rendered
+
+def captured_templates(app, recorded, **extra):
+    def record(sender, template, context):
+        recorded.append((template, context))
+    return template_rendered.connected_to(record, app)
+
+
+

The example above would then look like this:

+
templates = []
+with captured_templates(app, templates, **extra):
+    ...
+    template, context = templates[0]
+
+
+
+
+

Creating Signals

+

If you want to use signals in your own application, you can use the +blinker library directly. The most common use case are named signals in a +custom Namespace. This is what is recommended +most of the time:

+
from blinker import Namespace
+my_signals = Namespace()
+
+
+

Now you can create new signals like this:

+
model_saved = my_signals.signal('model-saved')
+
+
+

The name for the signal here makes it unique and also simplifies +debugging. You can access the name of the signal with the +name attribute.

+
+
+

Sending Signals

+

If you want to emit a signal, you can do so by calling the +send() method. It accepts a sender as first +argument and optionally some keyword arguments that are forwarded to the +signal subscribers:

+
class Model(object):
+    ...
+
+    def save(self):
+        model_saved.send(self)
+
+
+

Try to always pick a good sender. If you have a class that is emitting a +signal, pass self as sender. If you are emitting a signal from a random +function, you can pass current_app._get_current_object() as sender.

+
+

Passing Proxies as Senders

+

Never pass current_app as sender to a signal. Use +current_app._get_current_object() instead. The reason for this is +that current_app is a proxy and not the real application +object.

+
+
+
+

Signals and Flask’s Request Context

+

Signals fully support The Request Context when receiving signals. +Context-local variables are consistently available between +request_started and request_finished, so you can +rely on flask.g and others as needed. Note the limitations described +in Sending Signals and the request_tearing_down signal.

+
+
+

Decorator Based Signal Subscriptions

+

You can also easily subscribe to signals by using the +connect_via() decorator:

+
from flask import template_rendered
+
+@template_rendered.connect_via(app)
+def when_template_rendered(sender, template, context, **extra):
+    print(f'Template {template.name} is rendered with {context}')
+
+
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/templating/index.html b/_build/templating/index.html new file mode 100644 index 00000000..98386855 --- /dev/null +++ b/_build/templating/index.html @@ -0,0 +1,319 @@ + + + + + + + + Templates — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Templates

+

Flask leverages Jinja2 as its template engine. You are obviously free to use +a different template engine, but you still have to install Jinja2 to run +Flask itself. This requirement is necessary to enable rich extensions. +An extension can depend on Jinja2 being present.

+

This section only gives a very quick introduction into how Jinja2 +is integrated into Flask. If you want information on the template +engine’s syntax itself, head over to the official Jinja2 Template +Documentation for +more information.

+
+

Jinja Setup

+

Unless customized, Jinja2 is configured by Flask as follows:

+
    +
  • autoescaping is enabled for all templates ending in .html, +.htm, .xml, .xhtml, as well as .svg when using +render_template().

  • +
  • autoescaping is enabled for all strings when using +render_template_string().

  • +
  • a template has the ability to opt in/out autoescaping with the +{% autoescape %} tag.

  • +
  • Flask inserts a couple of global functions and helpers into the +Jinja2 context, additionally to the values that are present by +default.

  • +
+
+
+

Standard Context

+

The following global variables are available within Jinja2 templates +by default:

+
+
+config
+

The current configuration object (flask.Flask.config)

+
+Changelog
+

Changed in version 0.10: This is now always available, even in imported templates.

+
+
+

Added in version 0.6.

+
+
+ +
+
+request
+

The current request object (flask.request). This variable is +unavailable if the template was rendered without an active request +context.

+
+ +
+
+session
+

The current session object (flask.session). This variable +is unavailable if the template was rendered without an active request +context.

+
+ +
+
+g
+

The request-bound object for global variables (flask.g). This +variable is unavailable if the template was rendered without an active +request context.

+
+ +
+
+url_for()
+

The flask.url_for() function.

+
+ +
+
+get_flashed_messages()
+

The flask.get_flashed_messages() function.

+
+ +
+

The Jinja Context Behavior

+

These variables are added to the context of variables, they are not +global variables. The difference is that by default these will not +show up in the context of imported templates. This is partially caused +by performance considerations, partially to keep things explicit.

+

What does this mean for you? If you have a macro you want to import, +that needs to access the request object you have two possibilities:

+
    +
  1. you explicitly pass the request to the macro as parameter, or +the attribute of the request object you are interested in.

  2. +
  3. you import the macro “with context”.

  4. +
+

Importing with context looks like this:

+
{% from '_helpers.html' import my_macro with context %}
+
+
+
+
+
+

Controlling Autoescaping

+

Autoescaping is the concept of automatically escaping special characters +for you. Special characters in the sense of HTML (or XML, and thus XHTML) +are &, >, <, " as well as '. Because these characters +carry specific meanings in documents on their own you have to replace them +by so called “entities” if you want to use them for text. Not doing so +would not only cause user frustration by the inability to use these +characters in text, but can also lead to security problems. (see +Cross-Site Scripting (XSS))

+

Sometimes however you will need to disable autoescaping in templates. +This can be the case if you want to explicitly inject HTML into pages, for +example if they come from a system that generates secure HTML like a +markdown to HTML converter.

+

There are three ways to accomplish that:

+
    +
  • In the Python code, wrap the HTML string in a Markup +object before passing it to the template. This is in general the +recommended way.

  • +
  • Inside the template, use the |safe filter to explicitly mark a +string as safe HTML ({{ myvariable|safe }})

  • +
  • Temporarily disable the autoescape system altogether.

  • +
+

To disable the autoescape system in templates, you can use the {% +autoescape %} block:

+
{% autoescape false %}
+    <p>autoescaping is disabled here
+    <p>{{ will_not_be_escaped }}
+{% endautoescape %}
+
+
+

Whenever you do this, please be very cautious about the variables you are +using in this block.

+
+
+

Registering Filters

+

If you want to register your own filters in Jinja2 you have two ways to do +that. You can either put them by hand into the +jinja_env of the application or use the +template_filter() decorator.

+

The two following examples work the same and both reverse an object:

+
@app.template_filter('reverse')
+def reverse_filter(s):
+    return s[::-1]
+
+def reverse_filter(s):
+    return s[::-1]
+app.jinja_env.filters['reverse'] = reverse_filter
+
+
+

In case of the decorator the argument is optional if you want to use the +function name as name of the filter. Once registered, you can use the filter +in your templates in the same way as Jinja2’s builtin filters, for example if +you have a Python list in context called mylist:

+
{% for x in mylist | reverse %}
+{% endfor %}
+
+
+
+
+

Context Processors

+

To inject new variables automatically into the context of a template, +context processors exist in Flask. Context processors run before the +template is rendered and have the ability to inject new values into the +template context. A context processor is a function that returns a +dictionary. The keys and values of this dictionary are then merged with +the template context, for all templates in the app:

+
@app.context_processor
+def inject_user():
+    return dict(user=g.user)
+
+
+

The context processor above makes a variable called user available in +the template with the value of g.user. This example is not very +interesting because g is available in templates anyways, but it gives an +idea how this works.

+

Variables are not limited to values; a context processor can also make +functions available to templates (since Python allows passing around +functions):

+
@app.context_processor
+def utility_processor():
+    def format_price(amount, currency="€"):
+        return f"{amount:.2f}{currency}"
+    return dict(format_price=format_price)
+
+
+

The context processor above makes the format_price function available to all +templates:

+
{{ format_price(0.33) }}
+
+
+

You could also build format_price as a template filter (see +Registering Filters), but this demonstrates how to pass functions in a +context processor.

+
+
+

Streaming

+

It can be useful to not render the whole template as one complete +string, instead render it as a stream, yielding smaller incremental +strings. This can be used for streaming HTML in chunks to speed up +initial page load, or to save memory when rendering a very large +template.

+

The Jinja2 template engine supports rendering a template piece +by piece, returning an iterator of strings. Flask provides the +stream_template() and stream_template_string() +functions to make this easier to use.

+
from flask import stream_template
+
+@app.get("/timeline")
+def timeline():
+    return stream_template("timeline.html")
+
+
+

These functions automatically apply the +stream_with_context() wrapper if a request is active, so +that it remains available in the template.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/testing/index.html b/_build/testing/index.html new file mode 100644 index 00000000..4de4f4f7 --- /dev/null +++ b/_build/testing/index.html @@ -0,0 +1,373 @@ + + + + + + + + Testing Flask Applications — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Testing Flask Applications

+

Flask provides utilities for testing an application. This documentation +goes over techniques for working with different parts of the application +in tests.

+

We will use the pytest framework to set up and run our tests.

+
$ pip install pytest
+
+
+

The tutorial goes over how to write tests for +100% coverage of the sample Flaskr blog application. See +the tutorial on tests for a detailed +explanation of specific tests for an application.

+
+

Identifying Tests

+

Tests are typically located in the tests folder. Tests are functions +that start with test_, in Python modules that start with test_. +Tests can also be further grouped in classes that start with Test.

+

It can be difficult to know what to test. Generally, try to test the +code that you write, not the code of libraries that you use, since they +are already tested. Try to extract complex behaviors as separate +functions to test individually.

+
+
+

Fixtures

+

Pytest fixtures allow writing pieces of code that are reusable across +tests. A simple fixture returns a value, but a fixture can also do +setup, yield a value, then do teardown. Fixtures for the application, +test client, and CLI runner are shown below, they can be placed in +tests/conftest.py.

+

If you’re using an +application factory, define an app +fixture to create and configure an app instance. You can add code before +and after the yield to set up and tear down other resources, such as +creating and clearing a database.

+

If you’re not using a factory, you already have an app object you can +import and configure directly. You can still use an app fixture to +set up and tear down resources.

+
import pytest
+from my_project import create_app
+
+@pytest.fixture()
+def app():
+    app = create_app()
+    app.config.update({
+        "TESTING": True,
+    })
+
+    # other setup can go here
+
+    yield app
+
+    # clean up / reset resources here
+
+
+@pytest.fixture()
+def client(app):
+    return app.test_client()
+
+
+@pytest.fixture()
+def runner(app):
+    return app.test_cli_runner()
+
+
+
+
+

Sending Requests with the Test Client

+

The test client makes requests to the application without running a live +server. Flask’s client extends +Werkzeug’s client, see those docs for additional +information.

+

The client has methods that match the common HTTP request methods, +such as client.get() and client.post(). They take many arguments +for building the request; you can find the full documentation in +EnvironBuilder. Typically you’ll use path, +query_string, headers, and data or json.

+

To make a request, call the method the request should use with the path +to the route to test. A TestResponse is returned +to examine the response data. It has all the usual properties of a +response object. You’ll usually look at response.data, which is the +bytes returned by the view. If you want to use text, Werkzeug 2.1 +provides response.text, or use response.get_data(as_text=True).

+
def test_request_example(client):
+    response = client.get("/posts")
+    assert b"<h2>Hello, World!</h2>" in response.data
+
+
+

Pass a dict query_string={"key": "value", ...} to set arguments in +the query string (after the ? in the URL). Pass a dict +headers={} to set request headers.

+

To send a request body in a POST or PUT request, pass a value to +data. If raw bytes are passed, that exact body is used. Usually, +you’ll pass a dict to set form data.

+
+

Form Data

+

To send form data, pass a dict to data. The Content-Type header +will be set to multipart/form-data or +application/x-www-form-urlencoded automatically.

+

If a value is a file object opened for reading bytes ("rb" mode), it +will be treated as an uploaded file. To change the detected filename and +content type, pass a (file, filename, content_type) tuple. File +objects will be closed after making the request, so they do not need to +use the usual with open() as f: pattern.

+

It can be useful to store files in a tests/resources folder, then +use pathlib.Path to get files relative to the current test file.

+
from pathlib import Path
+
+# get the resources folder in the tests folder
+resources = Path(__file__).parent / "resources"
+
+def test_edit_user(client):
+    response = client.post("/user/2/edit", data={
+        "name": "Flask",
+        "theme": "dark",
+        "picture": (resources / "picture.png").open("rb"),
+    })
+    assert response.status_code == 200
+
+
+
+
+

JSON Data

+

To send JSON data, pass an object to json. The Content-Type +header will be set to application/json automatically.

+

Similarly, if the response contains JSON data, the response.json +attribute will contain the deserialized object.

+
def test_json_data(client):
+    response = client.post("/graphql", json={
+        "query": """
+            query User($id: String!) {
+                user(id: $id) {
+                    name
+                    theme
+                    picture_url
+                }
+            }
+        """,
+        variables={"id": 2},
+    })
+    assert response.json["data"]["user"]["name"] == "Flask"
+
+
+
+
+
+

Following Redirects

+

By default, the client does not make additional requests if the response +is a redirect. By passing follow_redirects=True to a request method, +the client will continue to make requests until a non-redirect response +is returned.

+

TestResponse.history is +a tuple of the responses that led up to the final response. Each +response has a request attribute +which records the request that produced that response.

+
def test_logout_redirect(client):
+    response = client.get("/logout", follow_redirects=True)
+    # Check that there was one redirect response.
+    assert len(response.history) == 1
+    # Check that the second request was to the index page.
+    assert response.request.path == "/index"
+
+
+
+
+

Accessing and Modifying the Session

+

To access Flask’s context variables, mainly +session, use the client in a with statement. +The app and request context will remain active after making a request, +until the with block ends.

+
from flask import session
+
+def test_access_session(client):
+    with client:
+        client.post("/auth/login", data={"username": "flask"})
+        # session is still accessible
+        assert session["user_id"] == 1
+
+    # session is no longer accessible
+
+
+

If you want to access or set a value in the session before making a +request, use the client’s +session_transaction() method in a +with statement. It returns a session object, and will save the +session once the block ends.

+
from flask import session
+
+def test_modify_session(client):
+    with client.session_transaction() as session:
+        # set a user id without going through the login route
+        session["user_id"] = 1
+
+    # session is saved now
+
+    response = client.get("/users/me")
+    assert response.json["username"] == "flask"
+
+
+
+
+

Running Commands with the CLI Runner

+

Flask provides test_cli_runner() to create a +FlaskCliRunner, which runs CLI commands in +isolation and captures the output in a Result +object. Flask’s runner extends Click’s runner, +see those docs for additional information.

+

Use the runner’s invoke() method to +call commands in the same way they would be called with the flask +command from the command line.

+
import click
+
+@app.cli.command("hello")
+@click.option("--name", default="World")
+def hello_command(name):
+    click.echo(f"Hello, {name}!")
+
+def test_hello_command(runner):
+    result = runner.invoke(args="hello")
+    assert "World" in result.output
+
+    result = runner.invoke(args=["hello", "--name", "Flask"])
+    assert "Flask" in result.output
+
+
+
+
+

Tests that depend on an Active Context

+

You may have functions that are called from views or commands, that +expect an active application context or +request context because they access request, +session, or current_app. Rather than testing them by making a +request or invoking the command, you can create and activate a context +directly.

+

Use with app.app_context() to push an application context. For +example, database extensions usually require an active app context to +make queries.

+
def test_db_post_model(app):
+    with app.app_context():
+        post = db.session.query(Post).get(1)
+
+
+

Use with app.test_request_context() to push a request context. It +takes the same arguments as the test client’s request methods.

+
def test_validate_user_edit(app):
+    with app.test_request_context(
+        "/user/2/edit", method="POST", data={"name": ""}
+    ):
+        # call a function that accesses `request`
+        messages = validate_edit_user()
+
+    assert messages["name"][0] == "Name cannot be empty."
+
+
+

Creating a test request context doesn’t run any of the Flask dispatching +code, so before_request functions are not called. If you need to +call these, usually it’s better to make a full request instead. However, +it’s possible to call them manually.

+
def test_auth_token(app):
+    with app.test_request_context("/user/2/edit", headers={"X-Auth-Token": "1"}):
+        app.preprocess_request()
+        assert g.user.name == "Flask"
+
+
+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/tutorial/blog/index.html b/_build/tutorial/blog/index.html new file mode 100644 index 00000000..407c9349 --- /dev/null +++ b/_build/tutorial/blog/index.html @@ -0,0 +1,422 @@ + + + + + + + + Blog Blueprint — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Blog Blueprint

+

You’ll use the same techniques you learned about when writing the +authentication blueprint to write the blog blueprint. The blog should +list all posts, allow logged in users to create posts, and allow the +author of a post to edit or delete it.

+

As you implement each view, keep the development server running. As you +save your changes, try going to the URL in your browser and testing them +out.

+
+

The Blueprint

+

Define the blueprint and register it in the application factory.

+
+
flaskr/blog.py
+
from flask import (
+    Blueprint, flash, g, redirect, render_template, request, url_for
+)
+from werkzeug.exceptions import abort
+
+from flaskr.auth import login_required
+from flaskr.db import get_db
+
+bp = Blueprint('blog', __name__)
+
+
+
+

Import and register the blueprint from the factory using +app.register_blueprint(). Place the +new code at the end of the factory function before returning the app.

+
+
flaskr/__init__.py
+
def create_app():
+    app = ...
+    # existing code omitted
+
+    from . import blog
+    app.register_blueprint(blog.bp)
+    app.add_url_rule('/', endpoint='index')
+
+    return app
+
+
+
+

Unlike the auth blueprint, the blog blueprint does not have a +url_prefix. So the index view will be at /, the create +view at /create, and so on. The blog is the main feature of Flaskr, +so it makes sense that the blog index will be the main index.

+

However, the endpoint for the index view defined below will be +blog.index. Some of the authentication views referred to a plain +index endpoint. app.add_url_rule() +associates the endpoint name 'index' with the / url so that +url_for('index') or url_for('blog.index') will both work, +generating the same / URL either way.

+

In another application you might give the blog blueprint a +url_prefix and define a separate index view in the application +factory, similar to the hello view. Then the index and +blog.index endpoints and URLs would be different.

+
+
+

Index

+

The index will show all of the posts, most recent first. A JOIN is +used so that the author information from the user table is +available in the result.

+
+
flaskr/blog.py
+
@bp.route('/')
+def index():
+    db = get_db()
+    posts = db.execute(
+        'SELECT p.id, title, body, created, author_id, username'
+        ' FROM post p JOIN user u ON p.author_id = u.id'
+        ' ORDER BY created DESC'
+    ).fetchall()
+    return render_template('blog/index.html', posts=posts)
+
+
+
+
+
flaskr/templates/blog/index.html
+
{% extends 'base.html' %}
+
+{% block header %}
+  <h1>{% block title %}Posts{% endblock %}</h1>
+  {% if g.user %}
+    <a class="action" href="{{ url_for('blog.create') }}">New</a>
+  {% endif %}
+{% endblock %}
+
+{% block content %}
+  {% for post in posts %}
+    <article class="post">
+      <header>
+        <div>
+          <h1>{{ post['title'] }}</h1>
+          <div class="about">by {{ post['username'] }} on {{ post['created'].strftime('%Y-%m-%d') }}</div>
+        </div>
+        {% if g.user['id'] == post['author_id'] %}
+          <a class="action" href="{{ url_for('blog.update', id=post['id']) }}">Edit</a>
+        {% endif %}
+      </header>
+      <p class="body">{{ post['body'] }}</p>
+    </article>
+    {% if not loop.last %}
+      <hr>
+    {% endif %}
+  {% endfor %}
+{% endblock %}
+
+
+
+

When a user is logged in, the header block adds a link to the +create view. When the user is the author of a post, they’ll see an +“Edit” link to the update view for that post. loop.last is a +special variable available inside Jinja for loops. It’s used to +display a line after each post except the last one, to visually separate +them.

+
+
+

Create

+

The create view works the same as the auth register view. Either +the form is displayed, or the posted data is validated and the post is +added to the database or an error is shown.

+

The login_required decorator you wrote earlier is used on the blog +views. A user must be logged in to visit these views, otherwise they +will be redirected to the login page.

+
+
flaskr/blog.py
+
@bp.route('/create', methods=('GET', 'POST'))
+@login_required
+def create():
+    if request.method == 'POST':
+        title = request.form['title']
+        body = request.form['body']
+        error = None
+
+        if not title:
+            error = 'Title is required.'
+
+        if error is not None:
+            flash(error)
+        else:
+            db = get_db()
+            db.execute(
+                'INSERT INTO post (title, body, author_id)'
+                ' VALUES (?, ?, ?)',
+                (title, body, g.user['id'])
+            )
+            db.commit()
+            return redirect(url_for('blog.index'))
+
+    return render_template('blog/create.html')
+
+
+
+
+
flaskr/templates/blog/create.html
+
{% extends 'base.html' %}
+
+{% block header %}
+  <h1>{% block title %}New Post{% endblock %}</h1>
+{% endblock %}
+
+{% block content %}
+  <form method="post">
+    <label for="title">Title</label>
+    <input name="title" id="title" value="{{ request.form['title'] }}" required>
+    <label for="body">Body</label>
+    <textarea name="body" id="body">{{ request.form['body'] }}</textarea>
+    <input type="submit" value="Save">
+  </form>
+{% endblock %}
+
+
+
+
+
+

Update

+

Both the update and delete views will need to fetch a post +by id and check if the author matches the logged in user. To avoid +duplicating code, you can write a function to get the post and call +it from each view.

+
+
flaskr/blog.py
+
def get_post(id, check_author=True):
+    post = get_db().execute(
+        'SELECT p.id, title, body, created, author_id, username'
+        ' FROM post p JOIN user u ON p.author_id = u.id'
+        ' WHERE p.id = ?',
+        (id,)
+    ).fetchone()
+
+    if post is None:
+        abort(404, f"Post id {id} doesn't exist.")
+
+    if check_author and post['author_id'] != g.user['id']:
+        abort(403)
+
+    return post
+
+
+
+

abort() will raise a special exception that returns an HTTP status +code. It takes an optional message to show with the error, otherwise a +default message is used. 404 means “Not Found”, and 403 means +“Forbidden”. (401 means “Unauthorized”, but you redirect to the +login page instead of returning that status.)

+

The check_author argument is defined so that the function can be +used to get a post without checking the author. This would be useful +if you wrote a view to show an individual post on a page, where the user +doesn’t matter because they’re not modifying the post.

+
+
flaskr/blog.py
+
@bp.route('/<int:id>/update', methods=('GET', 'POST'))
+@login_required
+def update(id):
+    post = get_post(id)
+
+    if request.method == 'POST':
+        title = request.form['title']
+        body = request.form['body']
+        error = None
+
+        if not title:
+            error = 'Title is required.'
+
+        if error is not None:
+            flash(error)
+        else:
+            db = get_db()
+            db.execute(
+                'UPDATE post SET title = ?, body = ?'
+                ' WHERE id = ?',
+                (title, body, id)
+            )
+            db.commit()
+            return redirect(url_for('blog.index'))
+
+    return render_template('blog/update.html', post=post)
+
+
+
+

Unlike the views you’ve written so far, the update function takes +an argument, id. That corresponds to the <int:id> in the route. +A real URL will look like /1/update. Flask will capture the 1, +ensure it’s an int, and pass it as the id argument. If you +don’t specify int: and instead do <id>, it will be a string. +To generate a URL to the update page, url_for() needs to be passed +the id so it knows what to fill in: +url_for('blog.update', id=post['id']). This is also in the +index.html file above.

+

The create and update views look very similar. The main +difference is that the update view uses a post object and an +UPDATE query instead of an INSERT. With some clever refactoring, +you could use one view and template for both actions, but for the +tutorial it’s clearer to keep them separate.

+
+
flaskr/templates/blog/update.html
+
{% extends 'base.html' %}
+
+{% block header %}
+  <h1>{% block title %}Edit "{{ post['title'] }}"{% endblock %}</h1>
+{% endblock %}
+
+{% block content %}
+  <form method="post">
+    <label for="title">Title</label>
+    <input name="title" id="title"
+      value="{{ request.form['title'] or post['title'] }}" required>
+    <label for="body">Body</label>
+    <textarea name="body" id="body">{{ request.form['body'] or post['body'] }}</textarea>
+    <input type="submit" value="Save">
+  </form>
+  <hr>
+  <form action="{{ url_for('blog.delete', id=post['id']) }}" method="post">
+    <input class="danger" type="submit" value="Delete" onclick="return confirm('Are you sure?');">
+  </form>
+{% endblock %}
+
+
+
+

This template has two forms. The first posts the edited data to the +current page (/<id>/update). The other form contains only a button +and specifies an action attribute that posts to the delete view +instead. The button uses some JavaScript to show a confirmation dialog +before submitting.

+

The pattern {{ request.form['title'] or post['title'] }} is used to +choose what data appears in the form. When the form hasn’t been +submitted, the original post data appears, but if invalid form data +was posted you want to display that so the user can fix the error, so +request.form is used instead. request is another variable +that’s automatically available in templates.

+
+
+

Delete

+

The delete view doesn’t have its own template, the delete button is part +of update.html and posts to the /<id>/delete URL. Since there +is no template, it will only handle the POST method and then redirect +to the index view.

+
+
flaskr/blog.py
+
@bp.route('/<int:id>/delete', methods=('POST',))
+@login_required
+def delete(id):
+    get_post(id)
+    db = get_db()
+    db.execute('DELETE FROM post WHERE id = ?', (id,))
+    db.commit()
+    return redirect(url_for('blog.index'))
+
+
+
+

Congratulations, you’ve now finished writing your application! Take some +time to try out everything in the browser. However, there’s still more +to do before the project is complete.

+

Continue to Make the Project Installable.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/tutorial/database/index.html b/_build/tutorial/database/index.html new file mode 100644 index 00000000..2980f6f6 --- /dev/null +++ b/_build/tutorial/database/index.html @@ -0,0 +1,296 @@ + + + + + + + + Define and Access the Database — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Define and Access the Database

+

The application will use a SQLite database to store users and posts. +Python comes with built-in support for SQLite in the sqlite3 +module.

+

SQLite is convenient because it doesn’t require setting up a separate +database server and is built-in to Python. However, if concurrent +requests try to write to the database at the same time, they will slow +down as each write happens sequentially. Small applications won’t notice +this. Once you become big, you may want to switch to a different +database.

+

The tutorial doesn’t go into detail about SQL. If you are not familiar +with it, the SQLite docs describe the language.

+
+

Connect to the Database

+

The first thing to do when working with a SQLite database (and most +other Python database libraries) is to create a connection to it. Any +queries and operations are performed using the connection, which is +closed after the work is finished.

+

In web applications this connection is typically tied to the request. It +is created at some point when handling a request, and closed before the +response is sent.

+
+
flaskr/db.py
+
import sqlite3
+from datetime import datetime
+
+import click
+from flask import current_app, g
+
+
+def get_db():
+    if 'db' not in g:
+        g.db = sqlite3.connect(
+            current_app.config['DATABASE'],
+            detect_types=sqlite3.PARSE_DECLTYPES
+        )
+        g.db.row_factory = sqlite3.Row
+
+    return g.db
+
+
+def close_db(e=None):
+    db = g.pop('db', None)
+
+    if db is not None:
+        db.close()
+
+
+
+

g is a special object that is unique for each request. It is +used to store data that might be accessed by multiple functions during +the request. The connection is stored and reused instead of creating a +new connection if get_db is called a second time in the same +request.

+

current_app is another special object that points to the Flask +application handling the request. Since you used an application factory, +there is no application object when writing the rest of your code. +get_db will be called when the application has been created and is +handling a request, so current_app can be used.

+

sqlite3.connect() establishes a connection to the file pointed at +by the DATABASE configuration key. This file doesn’t have to exist +yet, and won’t until you initialize the database later.

+

sqlite3.Row tells the connection to return rows that behave +like dicts. This allows accessing the columns by name.

+

close_db checks if a connection was created by checking if g.db +was set. If the connection exists, it is closed. Further down you will +tell your application about the close_db function in the application +factory so that it is called after each request.

+
+
+

Create the Tables

+

In SQLite, data is stored in tables and columns. These need to be +created before you can store and retrieve data. Flaskr will store users +in the user table, and posts in the post table. Create a file +with the SQL commands needed to create empty tables:

+
+
flaskr/schema.sql
+
DROP TABLE IF EXISTS user;
+DROP TABLE IF EXISTS post;
+
+CREATE TABLE user (
+  id INTEGER PRIMARY KEY AUTOINCREMENT,
+  username TEXT UNIQUE NOT NULL,
+  password TEXT NOT NULL
+);
+
+CREATE TABLE post (
+  id INTEGER PRIMARY KEY AUTOINCREMENT,
+  author_id INTEGER NOT NULL,
+  created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
+  title TEXT NOT NULL,
+  body TEXT NOT NULL,
+  FOREIGN KEY (author_id) REFERENCES user (id)
+);
+
+
+
+

Add the Python functions that will run these SQL commands to the +db.py file:

+
+
flaskr/db.py
+
def init_db():
+    db = get_db()
+
+    with current_app.open_resource('schema.sql') as f:
+        db.executescript(f.read().decode('utf8'))
+
+
+@click.command('init-db')
+def init_db_command():
+    """Clear the existing data and create new tables."""
+    init_db()
+    click.echo('Initialized the database.')
+
+
+sqlite3.register_converter(
+    "timestamp", lambda v: datetime.fromisoformat(v.decode())
+)
+
+
+
+

open_resource() opens a file relative to +the flaskr package, which is useful since you won’t necessarily know +where that location is when deploying the application later. get_db +returns a database connection, which is used to execute the commands +read from the file.

+

click.command() defines a command line command called init-db +that calls the init_db function and shows a success message to the +user. You can read Command Line Interface to learn more about writing commands.

+

The call to sqlite3.register_converter() tells Python how to +interpret timestamp values in the database. We convert the value to a +datetime.datetime.

+
+
+

Register with the Application

+

The close_db and init_db_command functions need to be registered +with the application instance; otherwise, they won’t be used by the +application. However, since you’re using a factory function, that +instance isn’t available when writing the functions. Instead, write a +function that takes an application and does the registration.

+
+
flaskr/db.py
+
def init_app(app):
+    app.teardown_appcontext(close_db)
+    app.cli.add_command(init_db_command)
+
+
+
+

app.teardown_appcontext() tells +Flask to call that function when cleaning up after returning the +response.

+

app.cli.add_command() adds a new +command that can be called with the flask command.

+

Import and call this function from the factory. Place the new code at +the end of the factory function before returning the app.

+
+
flaskr/__init__.py
+
def create_app():
+    app = ...
+    # existing code omitted
+
+    from . import db
+    db.init_app(app)
+
+    return app
+
+
+
+
+
+

Initialize the Database File

+

Now that init-db has been registered with the app, it can be called +using the flask command, similar to the run command from the +previous page.

+
+

Note

+

If you’re still running the server from the previous page, you can +either stop the server, or run this command in a new terminal. If +you use a new terminal, remember to change to your project directory +and activate the env as described in Installation.

+
+

Run the init-db command:

+
$ flask --app flaskr init-db
+Initialized the database.
+
+
+

There will now be a flaskr.sqlite file in the instance folder in +your project.

+

Continue to Blueprints and Views.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/tutorial/deploy/index.html b/_build/tutorial/deploy/index.html new file mode 100644 index 00000000..64d2d27e --- /dev/null +++ b/_build/tutorial/deploy/index.html @@ -0,0 +1,191 @@ + + + + + + + + Deploy to Production — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Deploy to Production

+

This part of the tutorial assumes you have a server that you want to +deploy your application to. It gives an overview of how to create the +distribution file and install it, but won’t go into specifics about +what server or software to use. You can set up a new environment on your +development computer to try out the instructions below, but probably +shouldn’t use it for hosting a real public application. See +Deploying to Production for a list of many different ways to host your +application.

+
+

Build and Install

+

When you want to deploy your application elsewhere, you build a wheel +(.whl) file. Install and use the build tool to do this.

+
$ pip install build
+$ python -m build --wheel
+
+
+

You can find the file in dist/flaskr-1.0.0-py3-none-any.whl. The +file name is in the format of {project name}-{version}-{python tag} +-{abi tag}-{platform tag}.

+

Copy this file to another machine, +set up a new virtualenv, then install the +file with pip.

+
$ pip install flaskr-1.0.0-py3-none-any.whl
+
+
+

Pip will install your project along with its dependencies.

+

Since this is a different machine, you need to run init-db again to +create the database in the instance folder.

+
+
$ flask --app flaskr init-db
+
+
+
+

When Flask detects that it’s installed (not in editable mode), it uses +a different directory for the instance folder. You can find it at +.venv/var/flaskr-instance instead.

+
+
+

Configure the Secret Key

+

In the beginning of the tutorial that you gave a default value for +SECRET_KEY. This should be changed to some random bytes in +production. Otherwise, attackers could use the public 'dev' key to +modify the session cookie, or anything else that uses the secret key.

+

You can use the following command to output a random secret key:

+
$ python -c 'import secrets; print(secrets.token_hex())'
+
+'192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'
+
+
+

Create the config.py file in the instance folder, which the factory +will read from if it exists. Copy the generated value into it.

+
+
.venv/var/flaskr-instance/config.py
+
SECRET_KEY = '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'
+
+
+
+

You can also set any other necessary configuration here, although +SECRET_KEY is the only one needed for Flaskr.

+
+
+

Run with a Production Server

+

When running publicly rather than in development, you should not use the +built-in development server (flask run). The development server is +provided by Werkzeug for convenience, but is not designed to be +particularly efficient, stable, or secure.

+

Instead, use a production WSGI server. For example, to use Waitress, +first install it in the virtual environment:

+
$ pip install waitress
+
+
+

You need to tell Waitress about your application, but it doesn’t use +--app like flask run does. You need to tell it to import and +call the application factory to get an application object.

+
$ waitress-serve --call 'flaskr:create_app'
+
+Serving on http://0.0.0.0:8080
+
+
+

See Deploying to Production for a list of many different ways to host +your application. Waitress is just an example, chosen for the tutorial +because it supports both Windows and Linux. There are many more WSGI +servers and deployment options that you may choose for your project.

+

Continue to Keep Developing!.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/tutorial/factory/index.html b/_build/tutorial/factory/index.html new file mode 100644 index 00000000..6a1b5c3c --- /dev/null +++ b/_build/tutorial/factory/index.html @@ -0,0 +1,249 @@ + + + + + + + + Application Setup — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Application Setup

+

A Flask application is an instance of the Flask class. +Everything about the application, such as configuration and URLs, will +be registered with this class.

+

The most straightforward way to create a Flask application is to create +a global Flask instance directly at the top of your code, like +how the “Hello, World!” example did on the previous page. While this is +simple and useful in some cases, it can cause some tricky issues as the +project grows.

+

Instead of creating a Flask instance globally, you will create +it inside a function. This function is known as the application +factory. Any configuration, registration, and other setup the +application needs will happen inside the function, then the application +will be returned.

+
+

The Application Factory

+

It’s time to start coding! Create the flaskr directory and add the +__init__.py file. The __init__.py serves double duty: it will +contain the application factory, and it tells Python that the flaskr +directory should be treated as a package.

+
$ mkdir flaskr
+
+
+
+
flaskr/__init__.py
+
import os
+
+from flask import Flask
+
+
+def create_app(test_config=None):
+    # create and configure the app
+    app = Flask(__name__, instance_relative_config=True)
+    app.config.from_mapping(
+        SECRET_KEY='dev',
+        DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
+    )
+
+    if test_config is None:
+        # load the instance config, if it exists, when not testing
+        app.config.from_pyfile('config.py', silent=True)
+    else:
+        # load the test config if passed in
+        app.config.from_mapping(test_config)
+
+    # ensure the instance folder exists
+    try:
+        os.makedirs(app.instance_path)
+    except OSError:
+        pass
+
+    # a simple page that says hello
+    @app.route('/hello')
+    def hello():
+        return 'Hello, World!'
+
+    return app
+
+
+
+

create_app is the application factory function. You’ll add to it +later in the tutorial, but it already does a lot.

+
    +
  1. app = Flask(__name__, instance_relative_config=True) creates the +Flask instance.

    +
      +
    • __name__ is the name of the current Python module. The app +needs to know where it’s located to set up some paths, and +__name__ is a convenient way to tell it that.

    • +
    • instance_relative_config=True tells the app that +configuration files are relative to the +instance folder. The instance folder +is located outside the flaskr package and can hold local +data that shouldn’t be committed to version control, such as +configuration secrets and the database file.

    • +
    +
  2. +
  3. app.config.from_mapping() sets +some default configuration that the app will use:

    +
      +
    • SECRET_KEY is used by Flask and extensions to keep data +safe. It’s set to 'dev' to provide a convenient value +during development, but it should be overridden with a random +value when deploying.

    • +
    • DATABASE is the path where the SQLite database file will be +saved. It’s under +app.instance_path, which is the +path that Flask has chosen for the instance folder. You’ll learn +more about the database in the next section.

    • +
    +
  4. +
  5. app.config.from_pyfile() overrides +the default configuration with values taken from the config.py +file in the instance folder if it exists. For example, when +deploying, this can be used to set a real SECRET_KEY.

    +
      +
    • test_config can also be passed to the factory, and will be +used instead of the instance configuration. This is so the tests +you’ll write later in the tutorial can be configured +independently of any development values you have configured.

    • +
    +
  6. +
  7. os.makedirs() ensures that +app.instance_path exists. Flask +doesn’t create the instance folder automatically, but it needs to be +created because your project will create the SQLite database file +there.

  8. +
  9. @app.route() creates a simple route so you can +see the application working before getting into the rest of the +tutorial. It creates a connection between the URL /hello and a +function that returns a response, the string 'Hello, World!' in +this case.

  10. +
+
+
+

Run The Application

+

Now you can run your application using the flask command. From the +terminal, tell Flask where to find your application, then run it in +debug mode. Remember, you should still be in the top-level +flask-tutorial directory, not the flaskr package.

+

Debug mode shows an interactive debugger whenever a page raises an +exception, and restarts the server whenever you make changes to the +code. You can leave it running and just reload the browser page as you +follow the tutorial.

+
$ flask --app flaskr run --debug
+
+
+

You’ll see output similar to this:

+
* Serving Flask app "flaskr"
+* Debug mode: on
+* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
+* Restarting with stat
+* Debugger is active!
+* Debugger PIN: nnn-nnn-nnn
+
+
+

Visit http://127.0.0.1:5000/hello in a browser and you should see the +“Hello, World!” message. Congratulations, you’re now running your Flask +web application!

+

If another program is already using port 5000, you’ll see +OSError: [Errno 98] or OSError: [WinError 10013] when the +server tries to start. See Address already in use for how to +handle that.

+

Continue to Define and Access the Database.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/tutorial/index.html b/_build/tutorial/index.html new file mode 100644 index 00000000..dd7793b8 --- /dev/null +++ b/_build/tutorial/index.html @@ -0,0 +1,134 @@ + + + + + + + + Tutorial — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Tutorial

+ +

This tutorial will walk you through creating a basic blog application +called Flaskr. Users will be able to register, log in, create posts, +and edit or delete their own posts. You will be able to package and +install the application on other computers.

+screenshot of index page +

It’s assumed that you’re already familiar with Python. The official +tutorial in the Python docs is a great way to learn or review first.

+

While it’s designed to give a good starting point, the tutorial doesn’t +cover all of Flask’s features. Check out the Quickstart for an +overview of what Flask can do, then dive into the docs to find out more. +The tutorial only uses what’s provided by Flask and Python. In another +project, you might decide to use Extensions or other libraries +to make some tasks simpler.

+screenshot of login page +

Flask is flexible. It doesn’t require you to use any particular project +or code layout. However, when first starting, it’s helpful to use a more +structured approach. This means that the tutorial will require a bit of +boilerplate up front, but it’s done to avoid many common pitfalls that +new developers encounter, and it creates a project that’s easy to expand +on. Once you become more comfortable with Flask, you can step out of +this structure and take full advantage of Flask’s flexibility.

+screenshot of edit page +

The tutorial project is available as an example in the Flask +repository, if you want to compare your project +with the final product as you follow the tutorial.

+

Continue to Project Layout.

+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/tutorial/install/index.html b/_build/tutorial/install/index.html new file mode 100644 index 00000000..5208a58a --- /dev/null +++ b/_build/tutorial/install/index.html @@ -0,0 +1,178 @@ + + + + + + + + Make the Project Installable — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Make the Project Installable

+

Making your project installable means that you can build a wheel file and install that +in another environment, just like you installed Flask in your project’s environment. +This makes deploying your project the same as installing any other library, so you’re +using all the standard Python tools to manage everything.

+

Installing also comes with other benefits that might not be obvious from +the tutorial or as a new Python user, including:

+
    +
  • Currently, Python and Flask understand how to use the flaskr +package only because you’re running from your project’s directory. +Installing means you can import it no matter where you run from.

  • +
  • You can manage your project’s dependencies just like other packages +do, so pip install yourproject.whl installs them.

  • +
  • Test tools can isolate your test environment from your development +environment.

  • +
+
+

Note

+

This is being introduced late in the tutorial, but in your future +projects you should always start with this.

+
+
+

Describe the Project

+

The pyproject.toml file describes your project and how to build it.

+
+
pyproject.toml
+
[project]
+name = "flaskr"
+version = "1.0.0"
+description = "The basic blog app built in the Flask tutorial."
+dependencies = [
+    "flask",
+]
+
+[build-system]
+requires = ["flit_core<4"]
+build-backend = "flit_core.buildapi"
+
+
+
+

See the official Packaging tutorial for more +explanation of the files and options used.

+
+
+

Install the Project

+

Use pip to install your project in the virtual environment.

+
$ pip install -e .
+
+
+

This tells pip to find pyproject.toml in the current directory and install the +project in editable or development mode. Editable mode means that as you make +changes to your local code, you’ll only need to re-install if you change the metadata +about the project, such as its dependencies.

+

You can observe that the project is now installed with pip list.

+
$ pip list
+
+Package        Version   Location
+-------------- --------- ----------------------------------
+click          6.7
+Flask          1.0
+flaskr         1.0.0     /home/user/Projects/flask-tutorial
+itsdangerous   0.24
+Jinja2         2.10
+MarkupSafe     1.0
+pip            9.0.3
+Werkzeug       0.14.1
+
+
+

Nothing changes from how you’ve been running your project so far. +--app is still set to flaskr and flask run still runs +the application, but you can call it from anywhere, not just the +flask-tutorial directory.

+

Continue to Test Coverage.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/tutorial/layout/index.html b/_build/tutorial/layout/index.html new file mode 100644 index 00000000..9114519c --- /dev/null +++ b/_build/tutorial/layout/index.html @@ -0,0 +1,193 @@ + + + + + + + + Project Layout — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Project Layout

+

Create a project directory and enter it:

+
$ mkdir flask-tutorial
+$ cd flask-tutorial
+
+
+

Then follow the installation instructions to set +up a Python virtual environment and install Flask for your project.

+

The tutorial will assume you’re working from the flask-tutorial +directory from now on. The file names at the top of each code block are +relative to this directory.

+
+

A Flask application can be as simple as a single file.

+
+
hello.py
+
from flask import Flask
+
+app = Flask(__name__)
+
+
+@app.route('/')
+def hello():
+    return 'Hello, World!'
+
+
+
+

However, as a project gets bigger, it becomes overwhelming to keep all +the code in one file. Python projects use packages to organize code +into multiple modules that can be imported where needed, and the +tutorial will do this as well.

+

The project directory will contain:

+
    +
  • flaskr/, a Python package containing your application code and +files.

  • +
  • tests/, a directory containing test modules.

  • +
  • .venv/, a Python virtual environment where Flask and other +dependencies are installed.

  • +
  • Installation files telling Python how to install your project.

  • +
  • Version control config, such as git. You should make a habit of +using some type of version control for all your projects, no matter +the size.

  • +
  • Any other project files you might add in the future.

  • +
+

By the end, your project layout will look like this:

+
/home/user/Projects/flask-tutorial
+├── flaskr/
+│   ├── __init__.py
+│   ├── db.py
+│   ├── schema.sql
+│   ├── auth.py
+│   ├── blog.py
+│   ├── templates/
+│   │   ├── base.html
+│   │   ├── auth/
+│   │   │   ├── login.html
+│   │   │   └── register.html
+│   │   └── blog/
+│   │       ├── create.html
+│   │       ├── index.html
+│   │       └── update.html
+│   └── static/
+│       └── style.css
+├── tests/
+│   ├── conftest.py
+│   ├── data.sql
+│   ├── test_factory.py
+│   ├── test_db.py
+│   ├── test_auth.py
+│   └── test_blog.py
+├── .venv/
+├── pyproject.toml
+└── MANIFEST.in
+
+
+

If you’re using version control, the following files that are generated +while running your project should be ignored. There may be other files +based on the editor you use. In general, ignore files that you didn’t +write. For example, with git:

+
+
.gitignore
+
.venv/
+
+*.pyc
+__pycache__/
+
+instance/
+
+.pytest_cache/
+.coverage
+htmlcov/
+
+dist/
+build/
+*.egg-info/
+
+
+
+

Continue to Application Setup.

+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/tutorial/next/index.html b/_build/tutorial/next/index.html new file mode 100644 index 00000000..3c5afade --- /dev/null +++ b/_build/tutorial/next/index.html @@ -0,0 +1,124 @@ + + + + + + + + Keep Developing! — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Keep Developing!

+

You’ve learned about quite a few Flask and Python concepts throughout +the tutorial. Go back and review the tutorial and compare your code with +the steps you took to get there. Compare your project to the +example project, which might look a bit +different due to the step-by-step nature of the tutorial.

+

There’s a lot more to Flask than what you’ve seen so far. Even so, +you’re now equipped to start developing your own web applications. Check +out the Quickstart for an overview of what Flask can do, then +dive into the docs to keep learning. Flask uses Jinja, Click, +Werkzeug, and ItsDangerous behind the scenes, and they all have +their own documentation too. You’ll also be interested in +Extensions which make tasks like working with the database or +validating form data easier and more powerful.

+

If you want to keep developing your Flaskr project, here are some ideas +for what to try next:

+
    +
  • A detail view to show a single post. Click a post’s title to go to +its page.

  • +
  • Like / unlike a post.

  • +
  • Comments.

  • +
  • Tags. Clicking a tag shows all the posts with that tag.

  • +
  • A search box that filters the index page by name.

  • +
  • Paged display. Only show 5 posts per page.

  • +
  • Upload an image to go along with a post.

  • +
  • Format posts using Markdown.

  • +
  • An RSS feed of new posts.

  • +
+

Have fun and make awesome applications!

+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/tutorial/static/index.html b/_build/tutorial/static/index.html new file mode 100644 index 00000000..2f7202a0 --- /dev/null +++ b/_build/tutorial/static/index.html @@ -0,0 +1,152 @@ + + + + + + + + Static Files — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Static Files

+

The authentication views and templates work, but they look very plain +right now. Some CSS can be added to add style to the HTML layout you +constructed. The style won’t change, so it’s a static file rather than +a template.

+

Flask automatically adds a static view that takes a path relative +to the flaskr/static directory and serves it. The base.html +template already has a link to the style.css file:

+
{{ url_for('static', filename='style.css') }}
+
+
+

Besides CSS, other types of static files might be files with JavaScript +functions, or a logo image. They are all placed under the +flaskr/static directory and referenced with +url_for('static', filename='...').

+

This tutorial isn’t focused on how to write CSS, so you can just copy +the following into the flaskr/static/style.css file:

+
+
flaskr/static/style.css
+
html { font-family: sans-serif; background: #eee; padding: 1rem; }
+body { max-width: 960px; margin: 0 auto; background: white; }
+h1 { font-family: serif; color: #377ba8; margin: 1rem 0; }
+a { color: #377ba8; }
+hr { border: none; border-top: 1px solid lightgray; }
+nav { background: lightgray; display: flex; align-items: center; padding: 0 0.5rem; }
+nav h1 { flex: auto; margin: 0; }
+nav h1 a { text-decoration: none; padding: 0.25rem 0.5rem; }
+nav ul  { display: flex; list-style: none; margin: 0; padding: 0; }
+nav ul li a, nav ul li span, header .action { display: block; padding: 0.5rem; }
+.content { padding: 0 1rem 1rem; }
+.content > header { border-bottom: 1px solid lightgray; display: flex; align-items: flex-end; }
+.content > header h1 { flex: auto; margin: 1rem 0 0.25rem 0; }
+.flash { margin: 1em 0; padding: 1em; background: #cae6f6; border: 1px solid #377ba8; }
+.post > header { display: flex; align-items: flex-end; font-size: 0.85em; }
+.post > header > div:first-of-type { flex: auto; }
+.post > header h1 { font-size: 1.5em; margin-bottom: 0; }
+.post .about { color: slategray; font-style: italic; }
+.post .body { white-space: pre-line; }
+.content:last-child { margin-bottom: 0; }
+.content form { margin: 1em 0; display: flex; flex-direction: column; }
+.content label { font-weight: bold; margin-bottom: 0.5em; }
+.content input, .content textarea { margin-bottom: 1em; }
+.content textarea { min-height: 12em; resize: vertical; }
+input.danger { color: #cc2f2e; }
+input[type=submit] { align-self: start; min-width: 10em; }
+
+
+
+

You can find a less compact version of style.css in the +example code.

+

Go to http://127.0.0.1:5000/auth/login and the page should look like the +screenshot below.

+screenshot of login page +

You can read more about CSS from Mozilla’s documentation. If +you change a static file, refresh the browser page. If the change +doesn’t show up, try clearing your browser’s cache.

+

Continue to Blog Blueprint.

+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/tutorial/templates/index.html b/_build/tutorial/templates/index.html new file mode 100644 index 00000000..6210503f --- /dev/null +++ b/_build/tutorial/templates/index.html @@ -0,0 +1,268 @@ + + + + + + + + Templates — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Templates

+

You’ve written the authentication views for your application, but if +you’re running the server and try to go to any of the URLs, you’ll see a +TemplateNotFound error. That’s because the views are calling +render_template(), but you haven’t written the templates yet. +The template files will be stored in the templates directory inside +the flaskr package.

+

Templates are files that contain static data as well as placeholders +for dynamic data. A template is rendered with specific data to produce a +final document. Flask uses the Jinja template library to render +templates.

+

In your application, you will use templates to render HTML which +will display in the user’s browser. In Flask, Jinja is configured to +autoescape any data that is rendered in HTML templates. This means +that it’s safe to render user input; any characters they’ve entered that +could mess with the HTML, such as < and > will be escaped with +safe values that look the same in the browser but don’t cause unwanted +effects.

+

Jinja looks and behaves mostly like Python. Special delimiters are used +to distinguish Jinja syntax from the static data in the template. +Anything between {{ and }} is an expression that will be output +to the final document. {% and %} denotes a control flow +statement like if and for. Unlike Python, blocks are denoted +by start and end tags rather than indentation since static text within +a block could change indentation.

+
+

The Base Layout

+

Each page in the application will have the same basic layout around a +different body. Instead of writing the entire HTML structure in each +template, each template will extend a base template and override +specific sections.

+
+
flaskr/templates/base.html
+
<!doctype html>
+<title>{% block title %}{% endblock %} - Flaskr</title>
+<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
+<nav>
+  <h1>Flaskr</h1>
+  <ul>
+    {% if g.user %}
+      <li><span>{{ g.user['username'] }}</span>
+      <li><a href="{{ url_for('auth.logout') }}">Log Out</a>
+    {% else %}
+      <li><a href="{{ url_for('auth.register') }}">Register</a>
+      <li><a href="{{ url_for('auth.login') }}">Log In</a>
+    {% endif %}
+  </ul>
+</nav>
+<section class="content">
+  <header>
+    {% block header %}{% endblock %}
+  </header>
+  {% for message in get_flashed_messages() %}
+    <div class="flash">{{ message }}</div>
+  {% endfor %}
+  {% block content %}{% endblock %}
+</section>
+
+
+
+

g is automatically available in templates. Based on if +g.user is set (from load_logged_in_user), either the username +and a log out link are displayed, or links to register and log in +are displayed. url_for() is also automatically available, and is +used to generate URLs to views instead of writing them out manually.

+

After the page title, and before the content, the template loops over +each message returned by get_flashed_messages(). You used +flash() in the views to show error messages, and this is the code +that will display them.

+

There are three blocks defined here that will be overridden in the other +templates:

+
    +
  1. {% block title %} will change the title displayed in the +browser’s tab and window title.

  2. +
  3. {% block header %} is similar to title but will change the +title displayed on the page.

  4. +
  5. {% block content %} is where the content of each page goes, such +as the login form or a blog post.

  6. +
+

The base template is directly in the templates directory. To keep +the others organized, the templates for a blueprint will be placed in a +directory with the same name as the blueprint.

+
+
+

Register

+
+
flaskr/templates/auth/register.html
+
{% extends 'base.html' %}
+
+{% block header %}
+  <h1>{% block title %}Register{% endblock %}</h1>
+{% endblock %}
+
+{% block content %}
+  <form method="post">
+    <label for="username">Username</label>
+    <input name="username" id="username" required>
+    <label for="password">Password</label>
+    <input type="password" name="password" id="password" required>
+    <input type="submit" value="Register">
+  </form>
+{% endblock %}
+
+
+
+

{% extends 'base.html' %} tells Jinja that this template should +replace the blocks from the base template. All the rendered content must +appear inside {% block %} tags that override blocks from the base +template.

+

A useful pattern used here is to place {% block title %} inside +{% block header %}. This will set the title block and then output +the value of it into the header block, so that both the window and page +share the same title without writing it twice.

+

The input tags are using the required attribute here. This tells +the browser not to submit the form until those fields are filled in. If +the user is using an older browser that doesn’t support that attribute, +or if they are using something besides a browser to make requests, you +still want to validate the data in the Flask view. It’s important to +always fully validate the data on the server, even if the client does +some validation as well.

+
+
+

Log In

+

This is identical to the register template except for the title and +submit button.

+
+
flaskr/templates/auth/login.html
+
{% extends 'base.html' %}
+
+{% block header %}
+  <h1>{% block title %}Log In{% endblock %}</h1>
+{% endblock %}
+
+{% block content %}
+  <form method="post">
+    <label for="username">Username</label>
+    <input name="username" id="username" required>
+    <label for="password">Password</label>
+    <input type="password" name="password" id="password" required>
+    <input type="submit" value="Log In">
+  </form>
+{% endblock %}
+
+
+
+
+
+

Register A User

+

Now that the authentication templates are written, you can register a +user. Make sure the server is still running (flask run if it’s not), +then go to http://127.0.0.1:5000/auth/register.

+

Try clicking the “Register” button without filling out the form and see +that the browser shows an error message. Try removing the required +attributes from the register.html template and click “Register” +again. Instead of the browser showing an error, the page will reload and +the error from flash() in the view will be shown.

+

Fill out a username and password and you’ll be redirected to the login +page. Try entering an incorrect username, or the correct username and +incorrect password. If you log in you’ll get an error because there’s +no index view to redirect to yet.

+

Continue to Static Files.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/tutorial/tests/index.html b/_build/tutorial/tests/index.html new file mode 100644 index 00000000..01a98e09 --- /dev/null +++ b/_build/tutorial/tests/index.html @@ -0,0 +1,622 @@ + + + + + + + + Test Coverage — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Test Coverage

+

Writing unit tests for your application lets you check that the code +you wrote works the way you expect. Flask provides a test client that +simulates requests to the application and returns the response data.

+

You should test as much of your code as possible. Code in functions only +runs when the function is called, and code in branches, such as if +blocks, only runs when the condition is met. You want to make sure that +each function is tested with data that covers each branch.

+

The closer you get to 100% coverage, the more comfortable you can be +that making a change won’t unexpectedly change other behavior. However, +100% coverage doesn’t guarantee that your application doesn’t have bugs. +In particular, it doesn’t test how the user interacts with the +application in the browser. Despite this, test coverage is an important +tool to use during development.

+
+

Note

+

This is being introduced late in the tutorial, but in your future +projects you should test as you develop.

+
+

You’ll use pytest and coverage to test and measure your code. +Install them both:

+
$ pip install pytest coverage
+
+
+
+

Setup and Fixtures

+

The test code is located in the tests directory. This directory is +next to the flaskr package, not inside it. The +tests/conftest.py file contains setup functions called fixtures +that each test will use. Tests are in Python modules that start with +test_, and each test function in those modules also starts with +test_.

+

Each test will create a new temporary database file and populate some +data that will be used in the tests. Write a SQL file to insert that +data.

+
+
tests/data.sql
+
INSERT INTO user (username, password)
+VALUES
+  ('test', 'pbkdf2:sha256:50000$TCI4GzcX$0de171a4f4dac32e3364c7ddc7c14f3e2fa61f2d17574483f7ffbb431b4acb2f'),
+  ('other', 'pbkdf2:sha256:50000$kJPKsz6N$d2d4784f1b030a9761f5ccaeeaca413f27f2ecb76d6168407af962ddce849f79');
+
+INSERT INTO post (title, body, author_id, created)
+VALUES
+  ('test title', 'test' || x'0a' || 'body', 1, '2018-01-01 00:00:00');
+
+
+
+

The app fixture will call the factory and pass test_config to +configure the application and database for testing instead of using your +local development configuration.

+
+
tests/conftest.py
+
import os
+import tempfile
+
+import pytest
+from flaskr import create_app
+from flaskr.db import get_db, init_db
+
+with open(os.path.join(os.path.dirname(__file__), 'data.sql'), 'rb') as f:
+    _data_sql = f.read().decode('utf8')
+
+
+@pytest.fixture
+def app():
+    db_fd, db_path = tempfile.mkstemp()
+
+    app = create_app({
+        'TESTING': True,
+        'DATABASE': db_path,
+    })
+
+    with app.app_context():
+        init_db()
+        get_db().executescript(_data_sql)
+
+    yield app
+
+    os.close(db_fd)
+    os.unlink(db_path)
+
+
+@pytest.fixture
+def client(app):
+    return app.test_client()
+
+
+@pytest.fixture
+def runner(app):
+    return app.test_cli_runner()
+
+
+
+

tempfile.mkstemp() creates and opens a temporary file, returning +the file descriptor and the path to it. The DATABASE path is +overridden so it points to this temporary path instead of the instance +folder. After setting the path, the database tables are created and the +test data is inserted. After the test is over, the temporary file is +closed and removed.

+

TESTING tells Flask that the app is in test mode. Flask changes +some internal behavior so it’s easier to test, and other extensions can +also use the flag to make testing them easier.

+

The client fixture calls +app.test_client() with the application +object created by the app fixture. Tests will use the client to make +requests to the application without running the server.

+

The runner fixture is similar to client. +app.test_cli_runner() creates a runner +that can call the Click commands registered with the application.

+

Pytest uses fixtures by matching their function names with the names +of arguments in the test functions. For example, the test_hello +function you’ll write next takes a client argument. Pytest matches +that with the client fixture function, calls it, and passes the +returned value to the test function.

+
+
+

Factory

+

There’s not much to test about the factory itself. Most of the code will +be executed for each test already, so if something fails the other tests +will notice.

+

The only behavior that can change is passing test config. If config is +not passed, there should be some default configuration, otherwise the +configuration should be overridden.

+
+
tests/test_factory.py
+
from flaskr import create_app
+
+
+def test_config():
+    assert not create_app().testing
+    assert create_app({'TESTING': True}).testing
+
+
+def test_hello(client):
+    response = client.get('/hello')
+    assert response.data == b'Hello, World!'
+
+
+
+

You added the hello route as an example when writing the factory at +the beginning of the tutorial. It returns “Hello, World!”, so the test +checks that the response data matches.

+
+
+

Database

+

Within an application context, get_db should return the same +connection each time it’s called. After the context, the connection +should be closed.

+
+
tests/test_db.py
+
import sqlite3
+
+import pytest
+from flaskr.db import get_db
+
+
+def test_get_close_db(app):
+    with app.app_context():
+        db = get_db()
+        assert db is get_db()
+
+    with pytest.raises(sqlite3.ProgrammingError) as e:
+        db.execute('SELECT 1')
+
+    assert 'closed' in str(e.value)
+
+
+
+

The init-db command should call the init_db function and output +a message.

+
+
tests/test_db.py
+
def test_init_db_command(runner, monkeypatch):
+    class Recorder(object):
+        called = False
+
+    def fake_init_db():
+        Recorder.called = True
+
+    monkeypatch.setattr('flaskr.db.init_db', fake_init_db)
+    result = runner.invoke(args=['init-db'])
+    assert 'Initialized' in result.output
+    assert Recorder.called
+
+
+
+

This test uses Pytest’s monkeypatch fixture to replace the +init_db function with one that records that it’s been called. The +runner fixture you wrote above is used to call the init-db +command by name.

+
+
+

Authentication

+

For most of the views, a user needs to be logged in. The easiest way to +do this in tests is to make a POST request to the login view +with the client. Rather than writing that out every time, you can write +a class with methods to do that, and use a fixture to pass it the client +for each test.

+
+
tests/conftest.py
+
class AuthActions(object):
+    def __init__(self, client):
+        self._client = client
+
+    def login(self, username='test', password='test'):
+        return self._client.post(
+            '/auth/login',
+            data={'username': username, 'password': password}
+        )
+
+    def logout(self):
+        return self._client.get('/auth/logout')
+
+
+@pytest.fixture
+def auth(client):
+    return AuthActions(client)
+
+
+
+

With the auth fixture, you can call auth.login() in a test to +log in as the test user, which was inserted as part of the test +data in the app fixture.

+

The register view should render successfully on GET. On POST +with valid form data, it should redirect to the login URL and the user’s +data should be in the database. Invalid data should display error +messages.

+
+
tests/test_auth.py
+
import pytest
+from flask import g, session
+from flaskr.db import get_db
+
+
+def test_register(client, app):
+    assert client.get('/auth/register').status_code == 200
+    response = client.post(
+        '/auth/register', data={'username': 'a', 'password': 'a'}
+    )
+    assert response.headers["Location"] == "/auth/login"
+
+    with app.app_context():
+        assert get_db().execute(
+            "SELECT * FROM user WHERE username = 'a'",
+        ).fetchone() is not None
+
+
+@pytest.mark.parametrize(('username', 'password', 'message'), (
+    ('', '', b'Username is required.'),
+    ('a', '', b'Password is required.'),
+    ('test', 'test', b'already registered'),
+))
+def test_register_validate_input(client, username, password, message):
+    response = client.post(
+        '/auth/register',
+        data={'username': username, 'password': password}
+    )
+    assert message in response.data
+
+
+
+

client.get() makes a GET request +and returns the Response object returned by Flask. Similarly, +client.post() makes a POST +request, converting the data dict into form data.

+

To test that the page renders successfully, a simple request is made and +checked for a 200 OK status_code. If +rendering failed, Flask would return a 500 Internal Server Error +code.

+

headers will have a Location header with the login +URL when the register view redirects to the login view.

+

data contains the body of the response as bytes. If +you expect a certain value to render on the page, check that it’s in +data. Bytes must be compared to bytes. If you want to compare text, +use get_data(as_text=True) +instead.

+

pytest.mark.parametrize tells Pytest to run the same test function +with different arguments. You use it here to test different invalid +input and error messages without writing the same code three times.

+

The tests for the login view are very similar to those for +register. Rather than testing the data in the database, +session should have user_id set after logging in.

+
+
tests/test_auth.py
+
def test_login(client, auth):
+    assert client.get('/auth/login').status_code == 200
+    response = auth.login()
+    assert response.headers["Location"] == "/"
+
+    with client:
+        client.get('/')
+        assert session['user_id'] == 1
+        assert g.user['username'] == 'test'
+
+
+@pytest.mark.parametrize(('username', 'password', 'message'), (
+    ('a', 'test', b'Incorrect username.'),
+    ('test', 'a', b'Incorrect password.'),
+))
+def test_login_validate_input(auth, username, password, message):
+    response = auth.login(username, password)
+    assert message in response.data
+
+
+
+

Using client in a with block allows accessing context variables +such as session after the response is returned. Normally, +accessing session outside of a request would raise an error.

+

Testing logout is the opposite of login. session should +not contain user_id after logging out.

+
+
tests/test_auth.py
+
def test_logout(client, auth):
+    auth.login()
+
+    with client:
+        auth.logout()
+        assert 'user_id' not in session
+
+
+
+
+
+

Blog

+

All the blog views use the auth fixture you wrote earlier. Call +auth.login() and subsequent requests from the client will be logged +in as the test user.

+

The index view should display information about the post that was +added with the test data. When logged in as the author, there should be +a link to edit the post.

+

You can also test some more authentication behavior while testing the +index view. When not logged in, each page shows links to log in or +register. When logged in, there’s a link to log out.

+
+
tests/test_blog.py
+
import pytest
+from flaskr.db import get_db
+
+
+def test_index(client, auth):
+    response = client.get('/')
+    assert b"Log In" in response.data
+    assert b"Register" in response.data
+
+    auth.login()
+    response = client.get('/')
+    assert b'Log Out' in response.data
+    assert b'test title' in response.data
+    assert b'by test on 2018-01-01' in response.data
+    assert b'test\nbody' in response.data
+    assert b'href="/1/update"' in response.data
+
+
+
+

A user must be logged in to access the create, update, and +delete views. The logged in user must be the author of the post to +access update and delete, otherwise a 403 Forbidden status +is returned. If a post with the given id doesn’t exist, +update and delete should return 404 Not Found.

+
+
tests/test_blog.py
+
@pytest.mark.parametrize('path', (
+    '/create',
+    '/1/update',
+    '/1/delete',
+))
+def test_login_required(client, path):
+    response = client.post(path)
+    assert response.headers["Location"] == "/auth/login"
+
+
+def test_author_required(app, client, auth):
+    # change the post author to another user
+    with app.app_context():
+        db = get_db()
+        db.execute('UPDATE post SET author_id = 2 WHERE id = 1')
+        db.commit()
+
+    auth.login()
+    # current user can't modify other user's post
+    assert client.post('/1/update').status_code == 403
+    assert client.post('/1/delete').status_code == 403
+    # current user doesn't see edit link
+    assert b'href="/1/update"' not in client.get('/').data
+
+
+@pytest.mark.parametrize('path', (
+    '/2/update',
+    '/2/delete',
+))
+def test_exists_required(client, auth, path):
+    auth.login()
+    assert client.post(path).status_code == 404
+
+
+
+

The create and update views should render and return a +200 OK status for a GET request. When valid data is sent in a +POST request, create should insert the new post data into the +database, and update should modify the existing data. Both pages +should show an error message on invalid data.

+
+
tests/test_blog.py
+
def test_create(client, auth, app):
+    auth.login()
+    assert client.get('/create').status_code == 200
+    client.post('/create', data={'title': 'created', 'body': ''})
+
+    with app.app_context():
+        db = get_db()
+        count = db.execute('SELECT COUNT(id) FROM post').fetchone()[0]
+        assert count == 2
+
+
+def test_update(client, auth, app):
+    auth.login()
+    assert client.get('/1/update').status_code == 200
+    client.post('/1/update', data={'title': 'updated', 'body': ''})
+
+    with app.app_context():
+        db = get_db()
+        post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()
+        assert post['title'] == 'updated'
+
+
+@pytest.mark.parametrize('path', (
+    '/create',
+    '/1/update',
+))
+def test_create_update_validate(client, auth, path):
+    auth.login()
+    response = client.post(path, data={'title': '', 'body': ''})
+    assert b'Title is required.' in response.data
+
+
+
+

The delete view should redirect to the index URL and the post should +no longer exist in the database.

+
+
tests/test_blog.py
+
def test_delete(client, auth, app):
+    auth.login()
+    response = client.post('/1/delete')
+    assert response.headers["Location"] == "/"
+
+    with app.app_context():
+        db = get_db()
+        post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()
+        assert post is None
+
+
+
+
+
+

Running the Tests

+

Some extra configuration, which is not required but makes running tests with coverage +less verbose, can be added to the project’s pyproject.toml file.

+
+
pyproject.toml
+
[tool.pytest.ini_options]
+testpaths = ["tests"]
+
+[tool.coverage.run]
+branch = true
+source = ["flaskr"]
+
+
+
+

To run the tests, use the pytest command. It will find and run all +the test functions you’ve written.

+
$ pytest
+
+========================= test session starts ==========================
+platform linux -- Python 3.6.4, pytest-3.5.0, py-1.5.3, pluggy-0.6.0
+rootdir: /home/user/Projects/flask-tutorial
+collected 23 items
+
+tests/test_auth.py ........                                      [ 34%]
+tests/test_blog.py ............                                  [ 86%]
+tests/test_db.py ..                                              [ 95%]
+tests/test_factory.py ..                                         [100%]
+
+====================== 24 passed in 0.64 seconds =======================
+
+
+

If any tests fail, pytest will show the error that was raised. You can +run pytest -v to get a list of each test function rather than dots.

+

To measure the code coverage of your tests, use the coverage command +to run pytest instead of running it directly.

+
$ coverage run -m pytest
+
+
+

You can either view a simple coverage report in the terminal:

+
$ coverage report
+
+Name                 Stmts   Miss Branch BrPart  Cover
+------------------------------------------------------
+flaskr/__init__.py      21      0      2      0   100%
+flaskr/auth.py          54      0     22      0   100%
+flaskr/blog.py          54      0     16      0   100%
+flaskr/db.py            24      0      4      0   100%
+------------------------------------------------------
+TOTAL                  153      0     44      0   100%
+
+
+

An HTML report allows you to see which lines were covered in each file:

+
$ coverage html
+
+
+

This generates files in the htmlcov directory. Open +htmlcov/index.html in your browser to see the report.

+

Continue to Deploy to Production.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/tutorial/views/index.html b/_build/tutorial/views/index.html new file mode 100644 index 00000000..4ad6c8c6 --- /dev/null +++ b/_build/tutorial/views/index.html @@ -0,0 +1,383 @@ + + + + + + + + Blueprints and Views — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Blueprints and Views

+

A view function is the code you write to respond to requests to your +application. Flask uses patterns to match the incoming request URL to +the view that should handle it. The view returns data that Flask turns +into an outgoing response. Flask can also go the other direction and +generate a URL to a view based on its name and arguments.

+
+

Create a Blueprint

+

A Blueprint is a way to organize a group of related views and +other code. Rather than registering views and other code directly with +an application, they are registered with a blueprint. Then the blueprint +is registered with the application when it is available in the factory +function.

+

Flaskr will have two blueprints, one for authentication functions and +one for the blog posts functions. The code for each blueprint will go +in a separate module. Since the blog needs to know about authentication, +you’ll write the authentication one first.

+
+
flaskr/auth.py
+
import functools
+
+from flask import (
+    Blueprint, flash, g, redirect, render_template, request, session, url_for
+)
+from werkzeug.security import check_password_hash, generate_password_hash
+
+from flaskr.db import get_db
+
+bp = Blueprint('auth', __name__, url_prefix='/auth')
+
+
+
+

This creates a Blueprint named 'auth'. Like the application +object, the blueprint needs to know where it’s defined, so __name__ +is passed as the second argument. The url_prefix will be prepended +to all the URLs associated with the blueprint.

+

Import and register the blueprint from the factory using +app.register_blueprint(). Place the +new code at the end of the factory function before returning the app.

+
+
flaskr/__init__.py
+
def create_app():
+    app = ...
+    # existing code omitted
+
+    from . import auth
+    app.register_blueprint(auth.bp)
+
+    return app
+
+
+
+

The authentication blueprint will have views to register new users and +to log in and log out.

+
+
+

The First View: Register

+

When the user visits the /auth/register URL, the register view +will return HTML with a form for them to fill out. When they submit +the form, it will validate their input and either show the form again +with an error message or create the new user and go to the login page.

+

For now you will just write the view code. On the next page, you’ll +write templates to generate the HTML form.

+
+
flaskr/auth.py
+
@bp.route('/register', methods=('GET', 'POST'))
+def register():
+    if request.method == 'POST':
+        username = request.form['username']
+        password = request.form['password']
+        db = get_db()
+        error = None
+
+        if not username:
+            error = 'Username is required.'
+        elif not password:
+            error = 'Password is required.'
+
+        if error is None:
+            try:
+                db.execute(
+                    "INSERT INTO user (username, password) VALUES (?, ?)",
+                    (username, generate_password_hash(password)),
+                )
+                db.commit()
+            except db.IntegrityError:
+                error = f"User {username} is already registered."
+            else:
+                return redirect(url_for("auth.login"))
+
+        flash(error)
+
+    return render_template('auth/register.html')
+
+
+
+

Here’s what the register view function is doing:

+
    +
  1. @bp.route associates the URL /register +with the register view function. When Flask receives a request +to /auth/register, it will call the register view and use +the return value as the response.

  2. +
  3. If the user submitted the form, +request.method will be 'POST'. In this +case, start validating the input.

  4. +
  5. request.form is a special type of +dict mapping submitted form keys and values. The user will +input their username and password.

  6. +
  7. Validate that username and password are not empty.

  8. +
  9. If validation succeeds, insert the new user data into the database.

    +
      +
    • db.execute takes a SQL +query with ? placeholders for any user input, and a tuple of +values to replace the placeholders with. The database library +will take care of escaping the values so you are not vulnerable +to a SQL injection attack.

    • +
    • For security, passwords should never be stored in the database +directly. Instead, +generate_password_hash() is used to +securely hash the password, and that hash is stored. Since this +query modifies data, +db.commit() needs to be +called afterwards to save the changes.

    • +
    • An sqlite3.IntegrityError will occur if the username +already exists, which should be shown to the user as another +validation error.

    • +
    +
  10. +
  11. After storing the user, they are redirected to the login page. +url_for() generates the URL for the login view based on its +name. This is preferable to writing the URL directly as it allows +you to change the URL later without changing all code that links to +it. redirect() generates a redirect response to the generated +URL.

  12. +
  13. If validation fails, the error is shown to the user. flash() +stores messages that can be retrieved when rendering the template.

  14. +
  15. When the user initially navigates to auth/register, or +there was a validation error, an HTML page with the registration +form should be shown. render_template() will render a template +containing the HTML, which you’ll write in the next step of the +tutorial.

  16. +
+
+
+

Login

+

This view follows the same pattern as the register view above.

+
+
flaskr/auth.py
+
@bp.route('/login', methods=('GET', 'POST'))
+def login():
+    if request.method == 'POST':
+        username = request.form['username']
+        password = request.form['password']
+        db = get_db()
+        error = None
+        user = db.execute(
+            'SELECT * FROM user WHERE username = ?', (username,)
+        ).fetchone()
+
+        if user is None:
+            error = 'Incorrect username.'
+        elif not check_password_hash(user['password'], password):
+            error = 'Incorrect password.'
+
+        if error is None:
+            session.clear()
+            session['user_id'] = user['id']
+            return redirect(url_for('index'))
+
+        flash(error)
+
+    return render_template('auth/login.html')
+
+
+
+

There are a few differences from the register view:

+
    +
  1. The user is queried first and stored in a variable for later use.

    +

    fetchone() returns one row from the query. +If the query returned no results, it returns None. Later, +fetchall() will be used, which returns a list +of all results.

    +
  2. +
  3. check_password_hash() hashes the submitted +password in the same way as the stored hash and securely compares +them. If they match, the password is valid.

  4. +
  5. session is a dict that stores data across requests. +When validation succeeds, the user’s id is stored in a new +session. The data is stored in a cookie that is sent to the +browser, and the browser then sends it back with subsequent requests. +Flask securely signs the data so that it can’t be tampered with.

  6. +
+

Now that the user’s id is stored in the session, it will be +available on subsequent requests. At the beginning of each request, if +a user is logged in their information should be loaded and made +available to other views.

+
+
flaskr/auth.py
+
@bp.before_app_request
+def load_logged_in_user():
+    user_id = session.get('user_id')
+
+    if user_id is None:
+        g.user = None
+    else:
+        g.user = get_db().execute(
+            'SELECT * FROM user WHERE id = ?', (user_id,)
+        ).fetchone()
+
+
+
+

bp.before_app_request() registers +a function that runs before the view function, no matter what URL is +requested. load_logged_in_user checks if a user id is stored in the +session and gets that user’s data from the database, storing it +on g.user, which lasts for the length of the request. If +there is no user id, or if the id doesn’t exist, g.user will be +None.

+
+
+

Logout

+

To log out, you need to remove the user id from the session. +Then load_logged_in_user won’t load a user on subsequent requests.

+
+
flaskr/auth.py
+
@bp.route('/logout')
+def logout():
+    session.clear()
+    return redirect(url_for('index'))
+
+
+
+
+
+

Require Authentication in Other Views

+

Creating, editing, and deleting blog posts will require a user to be +logged in. A decorator can be used to check this for each view it’s +applied to.

+
+
flaskr/auth.py
+
def login_required(view):
+    @functools.wraps(view)
+    def wrapped_view(**kwargs):
+        if g.user is None:
+            return redirect(url_for('auth.login'))
+
+        return view(**kwargs)
+
+    return wrapped_view
+
+
+
+

This decorator returns a new view function that wraps the original view +it’s applied to. The new function checks if a user is loaded and +redirects to the login page otherwise. If a user is loaded the original +view is called and continues normally. You’ll use this decorator when +writing the blog views.

+
+
+

Endpoints and URLs

+

The url_for() function generates the URL to a view based on a name +and arguments. The name associated with a view is also called the +endpoint, and by default it’s the same as the name of the view +function.

+

For example, the hello() view that was added to the app +factory earlier in the tutorial has the name 'hello' and can be +linked to with url_for('hello'). If it took an argument, which +you’ll see later, it would be linked to using +url_for('hello', who='World').

+

When using a blueprint, the name of the blueprint is prepended to the +name of the function, so the endpoint for the login function you +wrote above is 'auth.login' because you added it to the 'auth' +blueprint.

+

Continue to Templates.

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/views/index.html b/_build/views/index.html new file mode 100644 index 00000000..3d743f1e --- /dev/null +++ b/_build/views/index.html @@ -0,0 +1,416 @@ + + + + + + + + Class-based Views — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Class-based Views

+

This page introduces using the View and MethodView +classes to write class-based views.

+

A class-based view is a class that acts as a view function. Because it +is a class, different instances of the class can be created with +different arguments, to change the behavior of the view. This is also +known as generic, reusable, or pluggable views.

+

An example of where this is useful is defining a class that creates an +API based on the database model it is initialized with.

+

For more complex API behavior and customization, look into the various +API extensions for Flask.

+
+

Basic Reusable View

+

Let’s walk through an example converting a view function to a view +class. We start with a view function that queries a list of users then +renders a template to show the list.

+
@app.route("/users/")
+def user_list():
+    users = User.query.all()
+    return render_template("users.html", users=users)
+
+
+

This works for the user model, but let’s say you also had more models +that needed list pages. You’d need to write another view function for +each model, even though the only thing that would change is the model +and template name.

+

Instead, you can write a View subclass that will query a model +and render a template. As the first step, we’ll convert the view to a +class without any customization.

+
from flask.views import View
+
+class UserList(View):
+    def dispatch_request(self):
+        users = User.query.all()
+        return render_template("users.html", objects=users)
+
+app.add_url_rule("/users/", view_func=UserList.as_view("user_list"))
+
+
+

The View.dispatch_request() method is the equivalent of the view +function. Calling View.as_view() method will create a view +function that can be registered on the app with its +add_url_rule() method. The first argument to +as_view is the name to use to refer to the view with +url_for().

+
+

Note

+

You can’t decorate the class with @app.route() the way you’d +do with a basic view function.

+
+

Next, we need to be able to register the same view class for different +models and templates, to make it more useful than the original function. +The class will take two arguments, the model and template, and store +them on self. Then dispatch_request can reference these instead +of hard-coded values.

+
class ListView(View):
+    def __init__(self, model, template):
+        self.model = model
+        self.template = template
+
+    def dispatch_request(self):
+        items = self.model.query.all()
+        return render_template(self.template, items=items)
+
+
+

Remember, we create the view function with View.as_view() instead of +creating the class directly. Any extra arguments passed to as_view +are then passed when creating the class. Now we can register the same +view to handle multiple models.

+
app.add_url_rule(
+    "/users/",
+    view_func=ListView.as_view("user_list", User, "users.html"),
+)
+app.add_url_rule(
+    "/stories/",
+    view_func=ListView.as_view("story_list", Story, "stories.html"),
+)
+
+
+
+
+

URL Variables

+

Any variables captured by the URL are passed as keyword arguments to the +dispatch_request method, as they would be for a regular view +function.

+
class DetailView(View):
+    def __init__(self, model):
+        self.model = model
+        self.template = f"{model.__name__.lower()}/detail.html"
+
+    def dispatch_request(self, id)
+        item = self.model.query.get_or_404(id)
+        return render_template(self.template, item=item)
+
+app.add_url_rule(
+    "/users/<int:id>",
+    view_func=DetailView.as_view("user_detail", User)
+)
+
+
+
+
+

View Lifetime and self

+

By default, a new instance of the view class is created every time a +request is handled. This means that it is safe to write other data to +self during the request, since the next request will not see it, +unlike other forms of global state.

+

However, if your view class needs to do a lot of complex initialization, +doing it for every request is unnecessary and can be inefficient. To +avoid this, set View.init_every_request to False, which will +only create one instance of the class and use it for every request. In +this case, writing to self is not safe. If you need to store data +during the request, use g instead.

+

In the ListView example, nothing writes to self during the +request, so it is more efficient to create a single instance.

+
class ListView(View):
+    init_every_request = False
+
+    def __init__(self, model, template):
+        self.model = model
+        self.template = template
+
+    def dispatch_request(self):
+        items = self.model.query.all()
+        return render_template(self.template, items=items)
+
+
+

Different instances will still be created each for each as_view +call, but not for each request to those views.

+
+
+

View Decorators

+

The view class itself is not the view function. View decorators need to +be applied to the view function returned by as_view, not the class +itself. Set View.decorators to a list of decorators to apply.

+
class UserList(View):
+    decorators = [cache(minutes=2), login_required]
+
+app.add_url_rule('/users/', view_func=UserList.as_view())
+
+
+

If you didn’t set decorators, you could apply them manually instead. +This is equivalent to:

+
view = UserList.as_view("users_list")
+view = cache(minutes=2)(view)
+view = login_required(view)
+app.add_url_rule('/users/', view_func=view)
+
+
+

Keep in mind that order matters. If you’re used to @decorator style, +this is equivalent to:

+
@app.route("/users/")
+@login_required
+@cache(minutes=2)
+def user_list():
+    ...
+
+
+
+
+

Method Hints

+

A common pattern is to register a view with methods=["GET", "POST"], +then check request.method == "POST" to decide what to do. Setting +View.methods is equivalent to passing the list of methods to +add_url_rule or route.

+
class MyView(View):
+    methods = ["GET", "POST"]
+
+    def dispatch_request(self):
+        if request.method == "POST":
+            ...
+        ...
+
+app.add_url_rule('/my-view', view_func=MyView.as_view('my-view'))
+
+
+

This is equivalent to the following, except further subclasses can +inherit or change the methods.

+
app.add_url_rule(
+    "/my-view",
+    view_func=MyView.as_view("my-view"),
+    methods=["GET", "POST"],
+)
+
+
+
+
+

Method Dispatching and APIs

+

For APIs it can be helpful to use a different function for each HTTP +method. MethodView extends the basic View to dispatch +to different methods of the class based on the request method. Each HTTP +method maps to a method of the class with the same (lowercase) name.

+

MethodView automatically sets View.methods based on the +methods defined by the class. It even knows how to handle subclasses +that override or define other methods.

+

We can make a generic ItemAPI class that provides get (detail), +patch (edit), and delete methods for a given model. A GroupAPI can +provide get (list) and post (create) methods.

+
from flask.views import MethodView
+
+class ItemAPI(MethodView):
+    init_every_request = False
+
+    def __init__(self, model):
+        self.model = model
+        self.validator = generate_validator(model)
+
+    def _get_item(self, id):
+        return self.model.query.get_or_404(id)
+
+    def get(self, id):
+        item = self._get_item(id)
+        return jsonify(item.to_json())
+
+    def patch(self, id):
+        item = self._get_item(id)
+        errors = self.validator.validate(item, request.json)
+
+        if errors:
+            return jsonify(errors), 400
+
+        item.update_from_json(request.json)
+        db.session.commit()
+        return jsonify(item.to_json())
+
+    def delete(self, id):
+        item = self._get_item(id)
+        db.session.delete(item)
+        db.session.commit()
+        return "", 204
+
+class GroupAPI(MethodView):
+    init_every_request = False
+
+    def __init__(self, model):
+        self.model = model
+        self.validator = generate_validator(model, create=True)
+
+    def get(self):
+        items = self.model.query.all()
+        return jsonify([item.to_json() for item in items])
+
+    def post(self):
+        errors = self.validator.validate(request.json)
+
+        if errors:
+            return jsonify(errors), 400
+
+        db.session.add(self.model.from_json(request.json))
+        db.session.commit()
+        return jsonify(item.to_json())
+
+def register_api(app, model, name):
+    item = ItemAPI.as_view(f"{name}-item", model)
+    group = GroupAPI.as_view(f"{name}-group", model)
+    app.add_url_rule(f"/{name}/<int:id>", view_func=item)
+    app.add_url_rule(f"/{name}/", view_func=group)
+
+register_api(app, User, "users")
+register_api(app, Story, "stories")
+
+
+

This produces the following views, a standard REST API!

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

URL

Method

Description

/users/

GET

List all users

/users/

POST

Create a new user

/users/<id>

GET

Show a single user

/users/<id>

PATCH

Update a user

/users/<id>

DELETE

Delete a user

/stories/

GET

List all stories

/stories/

POST

Create a new story

/stories/<id>

GET

Show a single story

/stories/<id>

PATCH

Update a story

/stories/<id>

DELETE

Delete a story

+
+
+ + +
+
+
+
+ + +
+
+ + + diff --git a/_build/web-security/index.html b/_build/web-security/index.html new file mode 100644 index 00000000..30f5ab22 --- /dev/null +++ b/_build/web-security/index.html @@ -0,0 +1,381 @@ + + + + + + + + Security Considerations — Flask Documentation (3.1.x) + + + + + + + + + + + + + + +
+
+
+
+ +
+

Security Considerations

+

Web applications face many types of potential security problems, and it can be +hard to get everything right, or even to know what “right” is in general. Flask +tries to solve a few of these things by default, but there are other parts you +may have to take care of yourself. Many of these solutions are tradeoffs, and +will depend on each application’s specific needs and threat model. Many hosting +platforms may take care of certain types of problems without the need for the +Flask application to handle them.

+
+

Resource Use

+

A common category of attacks is “Denial of Service” (DoS or DDoS). This is a +very broad category, and different variants target different layers in a +deployed application. In general, something is done to increase how much +processing time or memory is used to handle each request, to the point where +there are not enough resources to handle legitimate requests.

+

Flask provides a few configuration options to handle resource use. They can +also be set on individual requests to customize only that request. The +documentation for each goes into more detail.

+ +

Regardless of these settings, you should also review what settings are available +from your operating system, container deployment (Docker etc), WSGI server, HTTP +server, and hosting platform. They typically have ways to set process resource +limits, timeouts, and other checks regardless of how Flask is configured.

+
+
+

Cross-Site Scripting (XSS)

+

Cross site scripting is the concept of injecting arbitrary HTML (and with +it JavaScript) into the context of a website. To remedy this, developers +have to properly escape text so that it cannot include arbitrary HTML +tags. For more information on that have a look at the Wikipedia article +on Cross-Site Scripting.

+

Flask configures Jinja2 to automatically escape all values unless +explicitly told otherwise. This should rule out all XSS problems caused +in templates, but there are still other places where you have to be +careful:

+
    +
  • generating HTML without the help of Jinja2

  • +
  • calling Markup on data submitted by users

  • +
  • sending out HTML from uploaded files, never do that, use the +Content-Disposition: attachment header to prevent that problem.

  • +
  • sending out textfiles from uploaded files. Some browsers are using +content-type guessing based on the first few bytes so users could +trick a browser to execute HTML.

  • +
+

Another thing that is very important are unquoted attributes. While +Jinja2 can protect you from XSS issues by escaping HTML, there is one +thing it cannot protect you from: XSS by attribute injection. To counter +this possible attack vector, be sure to always quote your attributes with +either double or single quotes when using Jinja expressions in them:

+
<input value="{{ value }}">
+
+
+

Why is this necessary? Because if you would not be doing that, an +attacker could easily inject custom JavaScript handlers. For example an +attacker could inject this piece of HTML+JavaScript:

+
onmouseover=alert(document.cookie)
+
+
+

When the user would then move with the mouse over the input, the cookie +would be presented to the user in an alert window. But instead of showing +the cookie to the user, a good attacker might also execute any other +JavaScript code. In combination with CSS injections the attacker might +even make the element fill out the entire page so that the user would +just have to have the mouse anywhere on the page to trigger the attack.

+

There is one class of XSS issues that Jinja’s escaping does not protect +against. The a tag’s href attribute can contain a javascript: URI, +which the browser will execute when clicked if not secured properly.

+
<a href="{{ value }}">click here</a>
+<a href="javascript:alert('unsafe');">click here</a>
+
+
+

To prevent this, you’ll need to set the Content Security Policy (CSP) response header.

+
+
+

Cross-Site Request Forgery (CSRF)

+

Another big problem is CSRF. This is a very complex topic and I won’t +outline it here in detail just mention what it is and how to theoretically +prevent it.

+

If your authentication information is stored in cookies, you have implicit +state management. The state of “being logged in” is controlled by a +cookie, and that cookie is sent with each request to a page. +Unfortunately that includes requests triggered by 3rd party sites. If you +don’t keep that in mind, some people might be able to trick your +application’s users with social engineering to do stupid things without +them knowing.

+

Say you have a specific URL that, when you sent POST requests to will +delete a user’s profile (say http://example.com/user/delete). If an +attacker now creates a page that sends a post request to that page with +some JavaScript they just have to trick some users to load that page and +their profiles will end up being deleted.

+

Imagine you were to run Facebook with millions of concurrent users and +someone would send out links to images of little kittens. When users +would go to that page, their profiles would get deleted while they are +looking at images of fluffy cats.

+

How can you prevent that? Basically for each request that modifies +content on the server you would have to either use a one-time token and +store that in the cookie and also transmit it with the form data. +After receiving the data on the server again, you would then have to +compare the two tokens and ensure they are equal.

+

Why does Flask not do that for you? The ideal place for this to happen is +the form validation framework, which does not exist in Flask.

+
+
+

JSON Security

+

In Flask 0.10 and lower, jsonify() did not serialize top-level +arrays to JSON. This was because of a security vulnerability in ECMAScript 4.

+

ECMAScript 5 closed this vulnerability, so only extremely old browsers are +still vulnerable. All of these browsers have other more serious +vulnerabilities, so +this behavior was changed and jsonify() now supports serializing +arrays.

+
+
+

Security Headers

+

Browsers recognize various response headers in order to control security. We +recommend reviewing each of the headers below for use in your application. +The Flask-Talisman extension can be used to manage HTTPS and the security +headers for you.

+
+

HTTP Strict Transport Security (HSTS)

+

Tells the browser to convert all HTTP requests to HTTPS, preventing +man-in-the-middle (MITM) attacks.

+
response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
+
+
+ +
+
+

Content Security Policy (CSP)

+

Tell the browser where it can load various types of resource from. This header +should be used whenever possible, but requires some work to define the correct +policy for your site. A very strict policy would be:

+
response.headers['Content-Security-Policy'] = "default-src 'self'"
+
+
+ +
+
+

X-Content-Type-Options

+

Forces the browser to honor the response content type instead of trying to +detect it, which can be abused to generate a cross-site scripting (XSS) +attack.

+
response.headers['X-Content-Type-Options'] = 'nosniff'
+
+
+ +
+
+

X-Frame-Options

+

Prevents external sites from embedding your site in an iframe. This +prevents a class of attacks where clicks in the outer frame can be translated +invisibly to clicks on your page’s elements. This is also known as +“clickjacking”.

+
response.headers['X-Frame-Options'] = 'SAMEORIGIN'
+
+
+ +
+ +
+

HTTP Public Key Pinning (HPKP)

+

This tells the browser to authenticate with the server using only the specific +certificate key to prevent MITM attacks.

+
+

Warning

+

Be careful when enabling this, as it is very difficult to undo if you set up +or upgrade your key incorrectly.

+
+ +
+
+
+

Copy/Paste to Terminal

+

Hidden characters such as the backspace character (\b, ^H) can +cause text to render differently in HTML than how it is interpreted if +pasted into a terminal.

+

For example, import y\bose\bm\bi\bt\be\b renders as +import yosemite in HTML, but the backspaces are applied when pasted +into a terminal, and it becomes import os.

+

If you expect users to copy and paste untrusted code from your site, +such as from comments posted by users on a technical blog, consider +applying extra filtering, such as replacing all \b characters.

+
body = body.replace("\b", "")
+
+
+

Most modern terminals will warn about and remove hidden characters when +pasting, so this isn’t strictly necessary. It’s also possible to craft +dangerous commands in other ways that aren’t possible to filter. +Depending on your site’s use case, it may be good to show a warning +about copying code in general.

+
+
+ + +
+
+
+
+ + +
+
+ + +