quickstart.rst
This file
Path
docs/quickstart.rst
932 lines · 31.5 KiB
Last changed by
Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc
History of this fileTake it
The walk stopped after 200 commits: lines older than 4f3dbb3 point at it.
Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 1–3why, one step back1Quickstart2==========3Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 4–5why, one step back4Eager to get started? This page gives a good introduction to Flask.5Follow :doc:`installation` to set up a project and install Flask first.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 6–10why, one step back678A Minimal Application9---------------------10Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 11why, one step back11A minimal Flask application looks something like this:Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 12why, one step back12Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 13–14why, one step back13.. code-block:: python14Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 15why, one step back15 from flask import FlaskMerge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 16why, one step back16Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 17–18why, one step back17 app = Flask(__name__)18Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 19why, one step back19 @app.route("/")Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 20why, one step back20 def hello_world():Merge pull request #3529 from pgkrit/masterDavid Lordbefore adoption3d61fc4
line 21why, one step back21 return "<p>Hello, World!</p>"Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 22–24why, one step back2223So what did that code do?24Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 25–36why, one step back251. First we imported the :class:`~flask.Flask` class. An instance of26 this class will be our WSGI application.272. Next we create an instance of this class. The first argument is the28 name of the application's module or package. ``__name__`` is a29 convenient shortcut for this that is appropriate for most cases.30 This is needed so that Flask knows where to look for resources such31 as templates and static files.323. We then use the :meth:`~flask.Flask.route` decorator to tell Flask33 what URL should trigger our function.344. The function returns the message we want to display in the user's35 browser. The default content type is HTML, so HTML in the string36 will be rendered by the browser.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 37why, one step back37Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 38why, one step back38Save it as :file:`hello.py` or something similar. Make sure to not callMerge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 39–41why, one step back39your application :file:`flask.py` because this would conflict with Flask40itself.41Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 42–43why, one step back42To run the application, use the :command:`flask` command or43:command:`python -m flask`. Before you can do that you needMerge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 44why, one step back44to tell your terminal the application to work with by exporting theMerge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 45why, one step back45``FLASK_APP`` environment variable:Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 46why, one step back46Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc
line 47why, one step back47.. tabs::Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 48why, one step back48Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc
line 49why, one step back49 .. group-tab:: BashMerge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 50why, one step back50Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc
line 51why, one step back51 .. code-block:: textMerge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 52why, one step back52Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc
lines 53–55why, one step back53 $ export FLASK_APP=hello.py54 $ flask run55 * Running on http://127.0.0.1:5000/Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 56why, one step back56Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc
line 57why, one step back57 .. group-tab:: CMDMerge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 58why, one step back58Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc
line 59why, one step back59 .. code-block:: textMerge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 60why, one step back60Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc
lines 61–72why, one step back61 > set FLASK_APP=hello.py62 > flask run63 * Running on http://127.0.0.1:5000/6465 .. group-tab:: Powershell6667 .. code-block:: text6869 > $env:FLASK_APP = "hello.py"70 > flask run71 * Running on http://127.0.0.1:5000/72remove unused ref directivesDavid Lordbefore adoption171aabc
lines 73–75why, one step back73This launches a very simple builtin server, which is good enough for74testing but probably not what you want to use in production. For75deployment options see :doc:`deploying/index`.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 76why, one step back76Merge branch '1.0.x'David Lordbefore adoption1351d0a
lines 77–78why, one step back77Now head over to http://127.0.0.1:5000/, and you should see your hello78world greeting.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 79–100why, one step back7980.. _public-server:8182.. admonition:: Externally Visible Server8384 If you run the server you will notice that the server is only accessible85 from your own computer, not from any other in the network. This is the86 default because in debugging mode a user of the application can execute87 arbitrary Python code on your computer.8889 If you have the debugger disabled or trust the users on your network,90 you can make the server publicly available simply by adding91 ``--host=0.0.0.0`` to the command line::9293 $ flask run --host=0.0.0.09495 This tells your operating system to listen on all public IPs.969798What to do if the Server does not Start99---------------------------------------100Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
lines 101–103why, one step back101In case the :command:`python -m flask` fails or :command:`flask`102does not exist, there are multiple reasons this might be the case.103First of all you need to look at the error message.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 104–110why, one step back104105Old Version of Flask106````````````````````107108Versions of Flask older than 0.11 use to have different ways to start the109application. In short, the :command:`flask` command did not exist, and110neither did :command:`python -m flask`. In that case you have two options:Merge pull request #3434 from pallets/eager-loadDavid Lordbefore adoptionbfa9ace
lines 111–112why, one step back111either upgrade to newer Flask versions or have a look at :doc:`/server`112to see the alternative method for running a server.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 113–128why, one step back113114Invalid Import Name115```````````````````116117The ``FLASK_APP`` environment variable is the name of the module to import at118:command:`flask run`. In case that module is incorrectly named you will get an119import error upon start (or if debug is enabled when you navigate to the120application). It will tell you what it tried to import and why it failed.121122The most common reason is a typo or because you did not actually create an123``app`` object.124125126Debug Mode127----------128Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 129–132why, one step back129The ``flask run`` command can do more than just start the development130server. By enabling debug mode, the server will automatically reload if131code changes, and will show an interactive debugger in the browser if an132error occurs during a request.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 133why, one step back133Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 134–137why, one step back134.. image:: _static/debugger.png135 :align: center136 :class: screenshot137 :alt: The interactive debugger in action.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 138why, one step back138Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
line 139why, one step back139.. warning::Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 140why, one step back140Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 141–144why, one step back141 The debugger allows executing arbitrary Python code from the142 browser. It is protected by a pin, but still represents a major143 security risk. Do not run the development server or debugger in a144 production environment.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 145why, one step back145Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 146–147why, one step back146To enable all development features, set the ``FLASK_ENV`` environment147variable to ``development`` before calling ``flask run``.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 148why, one step back148Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc
line 149why, one step back149.. tabs::Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 150why, one step back150Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc
lines 151–170why, one step back151 .. group-tab:: Bash152153 .. code-block:: text154155 $ export FLASK_ENV=development156 $ flask run157158 .. group-tab:: CMD159160 .. code-block:: text161162 > set FLASK_ENV=development163 > flask run164165 .. group-tab:: Powershell166167 .. code-block:: text168169 > $env:FLASK_ENV = "development"170 > flask runMerge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 171why, one step back171Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
line 172why, one step back172See also:Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 173why, one step back173Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 174–179why, one step back174- :doc:`/server` and :doc:`/cli` for information about running in175 development mode.176- :doc:`/debugging` for information about using the built-in debugger177 and other debuggers.178- :doc:`/logging` and :doc:`/errorhandling` to log errors and display179 nice error pages.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 180–181why, one step back180181Merge pull request #3529 from pgkrit/masterDavid Lordbefore adoption3d61fc4
lines 182–209why, one step back182HTML Escaping183-------------184185When returning HTML (the default response type in Flask), any186user-provided values rendered in the output must be escaped to protect187from injection attacks. HTML templates rendered with Jinja, introduced188later, will do this automatically.189190:func:`~markupsafe.escape`, shown here, can be used manually. It is191omitted in most examples for brevity, but you should always be aware of192how you're using untrusted data.193194.. code-block:: python195196 from markupsafe import escape197198 @app.route("/<name>")199 def hello(name):200 return f"Hello, {escape(name)}!"201202If a user managed to submit the name ``<script>alert("bad")</script>``,203escaping causes it to be rendered as text, rather than running the204script in the user's browser.205206``<name>`` in the route captures a value from the URL and passes it to207the view function. These variable rules are explained below.208209Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 210–237why, one step back210Routing211-------212213Modern web applications use meaningful URLs to help users. Users are more214likely to like a page and come back if the page uses a meaningful URL they can215remember and use to directly visit a page.216217Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::218219 @app.route('/')220 def index():221 return 'Index Page'222223 @app.route('/hello')224 def hello():225 return 'Hello, World'226227You can do more! You can make parts of the URL dynamic and attach multiple228rules to a function.229230Variable Rules231``````````````232233You can add variable sections to a URL by marking sections with234``<variable_name>``. Your function then receives the ``<variable_name>``235as a keyword argument. Optionally, you can use a converter to specify the type236of the argument like ``<converter:variable_name>``. ::237Merge remote-tracking branch 'origin/1.1.x'David Lordbefore adoption07556da
lines 238–239why, one step back238 from markupsafe import escape239Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 240–242why, one step back240 @app.route('/user/<username>')241 def show_user_profile(username):242 # show the user profile for that userMerge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 243why, one step back243 return f'User {username}'Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 244–247why, one step back244245 @app.route('/post/<int:post_id>')246 def show_post(post_id):247 # show the post with the given id, the id is an integerMerge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 248why, one step back248 return f'Post {post_id}'Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 249–252why, one step back249250 @app.route('/path/<path:subpath>')251 def show_subpath(subpath):252 # show the subpath after /path/Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 253why, one step back253 return f'Subpath {subpath}'Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 254–263why, one step back254255Converter types:256257========== ==========================================258``string`` (default) accepts any text without a slash259``int`` accepts positive integers260``float`` accepts positive floating point values261``path`` like ``string`` but also accepts slashes262``uuid`` accepts UUID strings263========== ==========================================Merge pull request #3529 from pgkrit/masterDavid Lordbefore adoption3d61fc4
line 264why, one step back264Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 265–280why, one step back265266Unique URLs / Redirection Behavior267``````````````````````````````````268269The following two rules differ in their use of a trailing slash. ::270271 @app.route('/projects/')272 def projects():273 return 'The project page'274275 @app.route('/about')276 def about():277 return 'The about page'278279The canonical URL for the ``projects`` endpoint has a trailing slash.280It's similar to a folder in a file system. If you access the URL withoutMerge pull request #3674 from DeepOde/masterGrey Libefore adoption3fe5eec
lines 281–282why, one step back281a trailing slash (``/projects``), Flask redirects you to the canonical URL282with the trailing slash (``/projects/``).Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 283–285why, one step back283284The canonical URL for the ``about`` endpoint does not have a trailing285slash. It's similar to the pathname of a file. Accessing the URL with aMerge pull request #3674 from DeepOde/masterGrey Libefore adoption3fe5eec
lines 286–288why, one step back286trailing slash (``/about/``) produces a 404 "Not Found" error. This helps287keep URLs unique for these resources, which helps search engines avoid288indexing the same page twice.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 289–305why, one step back289290291.. _url-building:292293URL Building294````````````295296To build a URL to a specific function, use the :func:`~flask.url_for` function.297It accepts the name of the function as its first argument and any number of298keyword arguments, each corresponding to a variable part of the URL rule.299Unknown variable parts are appended to the URL as query parameters.300301Why would you want to build URLs using the URL reversing function302:func:`~flask.url_for` instead of hard-coding them into your templates?3033041. Reversing is often more descriptive than hard-coding the URLs.3052. You can change your URLs in one go instead of needing to remember toMerge pull request #3101 from tbm/docs-formattingDavid Lordbefore adoptionc795adf
line 306why, one step back306 manually change hard-coded URLs.Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
line 307why, one step back3073. URL building handles escaping of special characters transparently.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 308–310why, one step back3084. The generated paths are always absolute, avoiding unexpected behavior309 of relative paths in browsers.3105. If your application is placed outside the URL root, for example, inMerge pull request #3101 from tbm/docs-formattingDavid Lordbefore adoptionc795adf
lines 311–312why, one step back311 ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly312 handles that for you.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 313–320why, one step back313314For example, here we use the :meth:`~flask.Flask.test_request_context` method315to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`316tells Flask to behave as though it's handling a request even while we use a317Python shell. See :ref:`context-locals`.318319.. code-block:: python320Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 321why, one step back321 from flask import url_forMerge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 322–332why, one step back322323 @app.route('/')324 def index():325 return 'index'326327 @app.route('/login')328 def login():329 return 'login'330331 @app.route('/user/<username>')332 def profile(username):Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 333why, one step back333 return f'{username}\'s profile'Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 334–393why, one step back334335 with app.test_request_context():336 print(url_for('index'))337 print(url_for('login'))338 print(url_for('login', next='/'))339 print(url_for('profile', username='John Doe'))340341.. code-block:: text342343 /344 /login345 /login?next=/346 /user/John%20Doe347348349HTTP Methods350````````````351352Web applications use different HTTP methods when accessing URLs. You should353familiarize yourself with the HTTP methods as you work with Flask. By default,354a route only answers to ``GET`` requests. You can use the ``methods`` argument355of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.356::357358 from flask import request359360 @app.route('/login', methods=['GET', 'POST'])361 def login():362 if request.method == 'POST':363 return do_the_login()364 else:365 return show_the_login_form()366367If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method368and handles ``HEAD`` requests according to the `HTTP RFC`_. Likewise,369``OPTIONS`` is automatically implemented for you.370371.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt372373Static Files374------------375376Dynamic web applications also need static files. That's usually where377the CSS and JavaScript files are coming from. Ideally your web server is378configured to serve them for you, but during development Flask can do that379as well. Just create a folder called :file:`static` in your package or next to380your module and it will be available at ``/static`` on the application.381382To generate URLs for static files, use the special ``'static'`` endpoint name::383384 url_for('static', filename='style.css')385386The file has to be stored on the filesystem as :file:`static/style.css`.387388Rendering Templates389-------------------390391Generating HTML from within Python is not fun, and actually pretty392cumbersome because you have to do the HTML escaping on your own to keep393the application secure. Because of that Flask configures the `Jinja2Merge pull request #3427 from greyli/update-old-linksDavid Lordbefore adoption25a5d30
line 394why, one step back394<https://palletsprojects.com/p/jinja/>`_ template engine for you automatically.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 395–426why, one step back395396To render a template you can use the :func:`~flask.render_template`397method. All you have to do is provide the name of the template and the398variables you want to pass to the template engine as keyword arguments.399Here's a simple example of how to render a template::400401 from flask import render_template402403 @app.route('/hello/')404 @app.route('/hello/<name>')405 def hello(name=None):406 return render_template('hello.html', name=name)407408Flask will look for templates in the :file:`templates` folder. So if your409application is a module, this folder is next to that module, if it's a410package it's actually inside your package:411412**Case 1**: a module::413414 /application.py415 /templates416 /hello.html417418**Case 2**: a package::419420 /application421 /__init__.py422 /templates423 /hello.html424425For templates you can use the full power of Jinja2 templates. Head over426to the official `Jinja2 Template DocumentationMerge pull request #3427 from greyli/update-old-linksDavid Lordbefore adoption25a5d30
line 427why, one step back427<https://jinja.palletsprojects.com/templates/>`_ for more information.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 428–445why, one step back428429Here is an example template:430431.. sourcecode:: html+jinja432433 <!doctype html>434 <title>Hello from Flask</title>435 {% if name %}436 <h1>Hello {{ name }}!</h1>437 {% else %}438 <h1>Hello, World!</h1>439 {% endif %}440441Inside templates you also have access to the :class:`~flask.request`,442:class:`~flask.session` and :class:`~flask.g` [#]_ objects443as well as the :func:`~flask.get_flashed_messages` function.444445Templates are especially useful if inheritance is used. If you want toremove unused ref directivesDavid Lordbefore adoption171aabc
lines 446–448why, one step back446know how that works, see :doc:`patterns/templateinheritance`. Basically447template inheritance makes it possible to keep certain elements on each448page (like header, navigation and footer).Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 449–453why, one step back449450Automatic escaping is enabled, so if ``name`` contains HTML it will be escaped451automatically. If you can trust a variable and you know that it will be452safe HTML (for example because it came from a module that converts wiki453markup to HTML) you can mark it as safe by using theMerge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 454why, one step back454:class:`~markupsafe.Markup` class or by using the ``|safe`` filter in theMerge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 455–456why, one step back455template. Head over to the Jinja 2 documentation for more examples.456Merge remote-tracking branch 'origin/1.1.x'David Lordbefore adoption07556da
line 457why, one step back457Here is a basic introduction to how the :class:`~markupsafe.Markup` class works::Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 458why, one step back458Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 459why, one step back459 >>> from markupsafe import MarkupMerge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 460why, one step back460 >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
line 461why, one step back461 Markup('<strong>Hello <blink>hacker</blink>!</strong>')Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 462why, one step back462 >>> Markup.escape('<blink>hacker</blink>')Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
line 463why, one step back463 Markup('<blink>hacker</blink>')Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 464why, one step back464 >>> Markup('<em>Marked up</em> » HTML').striptags()Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
line 465why, one step back465 'Marked up \xbb HTML'Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 466–474why, one step back466467.. versionchanged:: 0.5468469 Autoescaping is no longer enabled for all templates. The following470 extensions for templates trigger autoescaping: ``.html``, ``.htm``,471 ``.xml``, ``.xhtml``. Templates loaded from a string will have472 autoescaping disabled.473474.. [#] Unsure what that :class:`~flask.g` object is? It's something in whichremove unused ref directivesDavid Lordbefore adoption171aabc
lines 475–476why, one step back475 you can store information for your own needs. See the documentation476 for :class:`flask.g` and :doc:`patterns/sqlite3`.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 477–594why, one step back477478479Accessing Request Data480----------------------481482For web applications it's crucial to react to the data a client sends to483the server. In Flask this information is provided by the global484:class:`~flask.request` object. If you have some experience with Python485you might be wondering how that object can be global and how Flask486manages to still be threadsafe. The answer is context locals:487488489.. _context-locals:490491Context Locals492``````````````493494.. admonition:: Insider Information495496 If you want to understand how that works and how you can implement497 tests with context locals, read this section, otherwise just skip it.498499Certain objects in Flask are global objects, but not of the usual kind.500These objects are actually proxies to objects that are local to a specific501context. What a mouthful. But that is actually quite easy to understand.502503Imagine the context being the handling thread. A request comes in and the504web server decides to spawn a new thread (or something else, the505underlying object is capable of dealing with concurrency systems other506than threads). When Flask starts its internal request handling it507figures out that the current thread is the active context and binds the508current application and the WSGI environments to that context (thread).509It does that in an intelligent way so that one application can invoke another510application without breaking.511512So what does this mean to you? Basically you can completely ignore that513this is the case unless you are doing something like unit testing. You514will notice that code which depends on a request object will suddenly break515because there is no request object. The solution is creating a request516object yourself and binding it to the context. The easiest solution for517unit testing is to use the :meth:`~flask.Flask.test_request_context`518context manager. In combination with the ``with`` statement it will bind a519test request so that you can interact with it. Here is an example::520521 from flask import request522523 with app.test_request_context('/hello', method='POST'):524 # now you can do something with the request until the525 # end of the with block, such as basic assertions:526 assert request.path == '/hello'527 assert request.method == 'POST'528529The other possibility is passing a whole WSGI environment to the530:meth:`~flask.Flask.request_context` method::531532 with app.request_context(environ):533 assert request.method == 'POST'534535The Request Object536``````````````````537538The request object is documented in the API section and we will not cover539it here in detail (see :class:`~flask.Request`). Here is a broad overview of540some of the most common operations. First of all you have to import it from541the ``flask`` module::542543 from flask import request544545The current request method is available by using the546:attr:`~flask.Request.method` attribute. To access form data (data547transmitted in a ``POST`` or ``PUT`` request) you can use the548:attr:`~flask.Request.form` attribute. Here is a full example of the two549attributes mentioned above::550551 @app.route('/login', methods=['POST', 'GET'])552 def login():553 error = None554 if request.method == 'POST':555 if valid_login(request.form['username'],556 request.form['password']):557 return log_the_user_in(request.form['username'])558 else:559 error = 'Invalid username/password'560 # the code below is executed if the request method561 # was GET or the credentials were invalid562 return render_template('login.html', error=error)563564What happens if the key does not exist in the ``form`` attribute? In that565case a special :exc:`KeyError` is raised. You can catch it like a566standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request567error page is shown instead. So for many situations you don't have to568deal with that problem.569570To access parameters submitted in the URL (``?key=value``) you can use the571:attr:`~flask.Request.args` attribute::572573 searchword = request.args.get('key', '')574575We recommend accessing URL parameters with `get` or by catching the576:exc:`KeyError` because users might change the URL and presenting them a 400577bad request page in that case is not user friendly.578579For a full list of methods and attributes of the request object, head over580to the :class:`~flask.Request` documentation.581582583File Uploads584````````````585586You can handle uploaded files with Flask easily. Just make sure not to587forget to set the ``enctype="multipart/form-data"`` attribute on your HTML588form, otherwise the browser will not transmit your files at all.589590Uploaded files are stored in memory or at a temporary location on the591filesystem. You can access those files by looking at the592:attr:`~flask.request.files` attribute on the request object. Each593uploaded file is stored in that dictionary. It behaves just like a594standard Python :class:`file` object, but it also has aMerge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
lines 595–597why, one step back595:meth:`~werkzeug.datastructures.FileStorage.save` method that596allows you to store that file on the filesystem of the server.597Here is a simple example showing how that works::Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 598–609why, one step back598599 from flask import request600601 @app.route('/upload', methods=['GET', 'POST'])602 def upload_file():603 if request.method == 'POST':604 f = request.files['the_file']605 f.save('/var/www/uploads/uploaded_file.txt')606 ...607608If you want to know how the file was named on the client before it was609uploaded to your application, you can access theMerge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
lines 610–614why, one step back610:attr:`~werkzeug.datastructures.FileStorage.filename` attribute.611However please keep in mind that this value can be forged612so never ever trust that value. If you want to use the filename613of the client to store the file on the server, pass it through the614:func:`~werkzeug.utils.secure_filename` function thatMerge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 615–621why, one step back615Werkzeug provides for you::616617 from werkzeug.utils import secure_filename618619 @app.route('/upload', methods=['GET', 'POST'])620 def upload_file():621 if request.method == 'POST':Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
lines 622–623why, one step back622 file = request.files['the_file']623 file.save(f"/var/www/uploads/{secure_filename(f.filename)}")Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 624–625why, one step back624 ...625remove unused ref directivesDavid Lordbefore adoption171aabc
line 626why, one step back626For some better examples, see :doc:`patterns/fileuploads`.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 627–665why, one step back627628Cookies629```````630631To access cookies you can use the :attr:`~flask.Request.cookies`632attribute. To set cookies you can use the633:attr:`~flask.Response.set_cookie` method of response objects. The634:attr:`~flask.Request.cookies` attribute of request objects is a635dictionary with all the cookies the client transmits. If you want to use636sessions, do not use the cookies directly but instead use the637:ref:`sessions` in Flask that add some security on top of cookies for you.638639Reading cookies::640641 from flask import request642643 @app.route('/')644 def index():645 username = request.cookies.get('username')646 # use cookies.get(key) instead of cookies[key] to not get a647 # KeyError if the cookie is missing.648649Storing cookies::650651 from flask import make_response652653 @app.route('/')654 def index():655 resp = make_response(render_template(...))656 resp.set_cookie('username', 'the username')657 return resp658659Note that cookies are set on response objects. Since you normally660just return strings from the view functions Flask will convert them into661response objects for you. If you explicitly want to do that you can use662the :meth:`~flask.make_response` function and then modify it.663664Sometimes you might want to set a cookie at a point where the response665object does not exist yet. This is possible by utilizing theremove unused ref directivesDavid Lordbefore adoption171aabc
line 666why, one step back666:doc:`patterns/deferredcallbacks` pattern.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 667–705why, one step back667668For this also see :ref:`about-responses`.669670Redirects and Errors671--------------------672673To redirect a user to another endpoint, use the :func:`~flask.redirect`674function; to abort a request early with an error code, use the675:func:`~flask.abort` function::676677 from flask import abort, redirect, url_for678679 @app.route('/')680 def index():681 return redirect(url_for('login'))682683 @app.route('/login')684 def login():685 abort(401)686 this_is_never_executed()687688This is a rather pointless example because a user will be redirected from689the index to a page they cannot access (401 means access denied) but it690shows how that works.691692By default a black and white error page is shown for each error code. If693you want to customize the error page, you can use the694:meth:`~flask.Flask.errorhandler` decorator::695696 from flask import render_template697698 @app.errorhandler(404)699 def page_not_found(error):700 return render_template('page_not_found.html'), 404701702Note the ``404`` after the :func:`~flask.render_template` call. This703tells Flask that the status code of that page should be 404 which means704not found. By default 200 is assumed which translates to: all went well.705remove unused ref directivesDavid Lordbefore adoption171aabc
line 706why, one step back706See :doc:`errorhandling` for more details.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 707–712why, one step back707708.. _about-responses:709710About Responses711---------------712Merge pull request #3111 from pgjones/masterDavid Lordbefore adoption855d59b
lines 713–719why, one step back713The return value from a view function is automatically converted into714a response object for you. If the return value is a string it's715converted into a response object with the string as response body, a716``200 OK`` status code and a :mimetype:`text/html` mimetype. If the717return value is a dict, :func:`jsonify` is called to produce a response.718The logic that Flask applies to converting return values into response719objects is as follows:Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 720–722why, one step back7207211. If a response object of the correct type is returned it's directly722 returned from the view.Merge pull request #3111 from pgjones/masterDavid Lordbefore adoption855d59b
lines 723–732why, one step back7232. If it's a string, a response object is created with that data and724 the default parameters.7253. If it's a dict, a response object is created using ``jsonify``.7264. If a tuple is returned the items in the tuple can provide extra727 information. Such tuples have to be in the form728 ``(response, status)``, ``(response, headers)``, or729 ``(response, status, headers)``. The ``status`` value will override730 the status code and ``headers`` can be a list or dictionary of731 additional header values.7325. If none of that works, Flask will assume the return value is aMerge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 733–739why, one step back733 valid WSGI application and convert that into a response object.734735If you want to get hold of the resulting response object inside the view736you can use the :func:`~flask.make_response` function.737738Imagine you have a view like this::739Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 740–741why, one step back740 from flask import render_template741Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 742–749why, one step back742 @app.errorhandler(404)743 def not_found(error):744 return render_template('error.html'), 404745746You just need to wrap the return expression with747:func:`~flask.make_response` and get the response object to modify it, then748return it::749Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 750–751why, one step back750 from flask import make_response751Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 752–756why, one step back752 @app.errorhandler(404)753 def not_found(error):754 resp = make_response(render_template('error.html'), 404)755 resp.headers['X-Something'] = 'A value'756 return respMerge pull request #3111 from pgjones/masterDavid Lordbefore adoption855d59b
lines 757–784why, one step back757758759APIs with JSON760``````````````761762A common response format when writing an API is JSON. It's easy to get763started writing such an API with Flask. If you return a ``dict`` from a764view, it will be converted to a JSON response.765766.. code-block:: python767768 @app.route("/me")769 def me_api():770 user = get_current_user()771 return {772 "username": user.username,773 "theme": user.theme,774 "image": url_for("user_image", filename=user.image),775 }776777Depending on your API design, you may want to create JSON responses for778types other than ``dict``. In that case, use the779:func:`~flask.json.jsonify` function, which will serialize any supported780JSON data type. Or look into Flask community extensions that support781more complex applications.782783.. code-block:: python784Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 785–786why, one step back785 from flask import jsonify786Merge pull request #3111 from pgjones/masterDavid Lordbefore adoption855d59b
lines 787–791why, one step back787 @app.route("/users")788 def users_api():789 users = get_all_users()790 return jsonify([user.to_json() for user in users])791Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 792–807why, one step back792793.. _sessions:794795Sessions796--------797798In addition to the request object there is also a second object called799:class:`~flask.session` which allows you to store information specific to a800user from one request to the next. This is implemented on top of cookies801for you and signs the cookies cryptographically. What this means is that802the user could look at the contents of your cookie but not modify it,803unless they know the secret key used for signing.804805In order to use sessions you have to set a secret key. Here is how806sessions work::807Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 808why, one step back808 from flask import sessionMerge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 809–815why, one step back809810 # Set the secret key to some random bytes. Keep this really secret!811 app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'812813 @app.route('/')814 def index():815 if 'username' in session:Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 816why, one step back816 return f'Logged in as {session["username"]}'Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 817–869why, one step back817 return 'You are not logged in'818819 @app.route('/login', methods=['GET', 'POST'])820 def login():821 if request.method == 'POST':822 session['username'] = request.form['username']823 return redirect(url_for('index'))824 return '''825 <form method="post">826 <p><input type=text name=username>827 <p><input type=submit value=Login>828 </form>829 '''830831 @app.route('/logout')832 def logout():833 # remove the username from the session if it's there834 session.pop('username', None)835 return redirect(url_for('index'))836837.. admonition:: How to generate good secret keys838839 A secret key should be as random as possible. Your operating system has840 ways to generate pretty random data based on a cryptographic random841 generator. Use the following command to quickly generate a value for842 :attr:`Flask.secret_key` (or :data:`SECRET_KEY`)::843844 $ python -c 'import os; print(os.urandom(16))'845 b'_5#y2L"F4Q8z\n\xec]/'846847A note on cookie-based sessions: Flask will take the values you put into the848session object and serialize them into a cookie. If you are finding some849values do not persist across requests, cookies are indeed enabled, and you are850not getting a clear error message, check the size of the cookie in your page851responses compared to the size supported by web browsers.852853Besides the default client-side based sessions, if you want to handle854sessions on the server-side instead, there are several855Flask extensions that support this.856857Message Flashing858----------------859860Good applications and user interfaces are all about feedback. If the user861does not get enough feedback they will probably end up hating the862application. Flask provides a really simple way to give feedback to a863user with the flashing system. The flashing system basically makes it864possible to record a message at the end of a request and access it on the next865(and only the next) request. This is usually combined with a layout866template to expose the message.867868To flash a message use the :func:`~flask.flash` method, to get hold of the869messages you can use :func:`~flask.get_flashed_messages` which is alsoremove unused ref directivesDavid Lordbefore adoption171aabc
lines 870–871why, one step back870available in the templates. See :doc:`patterns/flashing` for a full871example.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 872–878why, one step back872873Logging874-------875876.. versionadded:: 0.3877878Sometimes you might be in a situation where you deal with data thatMerge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
lines 879–884why, one step back879should be correct, but actually is not. For example you may have880some client-side code that sends an HTTP request to the server881but it's obviously malformed. This might be caused by a user tampering882with the data, or the client code failing. Most of the time it's okay883to reply with ``400 Bad Request`` in that situation, but sometimes884that won't do and the code has to continue working.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 885–896why, one step back885886You may still want to log that something fishy happened. This is where887loggers come in handy. As of Flask 0.3 a logger is preconfigured for you888to use.889890Here are some example log calls::891892 app.logger.debug('A value for debugging')893 app.logger.warning('A warning occurred (%d apples)', 42)894 app.logger.error('An error occurred')895896The attached :attr:`~flask.Flask.logger` is a standard loggingMerge branch '1.0.x'David Lordbefore adoption1351d0a
lines 897–898why, one step back897:class:`~logging.Logger`, so head over to the official :mod:`logging`898docs for more information.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 899why, one step back899remove unused ref directivesDavid Lordbefore adoption171aabc
line 900why, one step back900See :doc:`errorhandling`.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 901why, one step back901remove unused ref directivesDavid Lordbefore adoption171aabc
line 902why, one step back902Merge branch '1.1.x'David Lordbefore adoption40eadfc
lines 903–904why, one step back903Hooking in WSGI Middleware904--------------------------Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 905why, one step back905Merge branch '1.1.x'David Lordbefore adoption40eadfc
lines 906–909why, one step back906To add WSGI middleware to your Flask application, wrap the application's907``wsgi_app`` attribute. For example, to apply Werkzeug's908:class:`~werkzeug.middlware.proxy_fix.ProxyFix` middleware for running909behind Nginx:Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 910why, one step back910Merge branch '1.1.x'David Lordbefore adoption40eadfc
lines 911–918why, one step back911.. code-block:: python912913 from werkzeug.middleware.proxy_fix import ProxyFix914 app.wsgi_app = ProxyFix(app.wsgi_app)915916Wrapping ``app.wsgi_app`` instead of ``app`` means that ``app`` still917points at your Flask application, not at the middleware, so you can918continue to use and configure ``app`` directly.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 919–926why, one step back919920Using Flask Extensions921----------------------922923Extensions are packages that help you accomplish common tasks. For924example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple925and easy to use with Flask.926remove unused ref directivesDavid Lordbefore adoption171aabc
line 927why, one step back927For more on Flask extensions, see :doc:`extensions`.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 928–931why, one step back928929Deploying to a Web Server930-------------------------931remove unused ref directivesDavid Lordbefore adoption171aabc
line 932why, one step back932Ready to deploy your new Flask app? See :doc:`deploying/index`.