quickstart.rst
This file
Path
docs/quickstart.rst
842 lines · 30.2 KiB
Last changed by
Merge pull request #2296 from tullyrankin/debugger-documentation-1625David Lordbefore adoption88b0213
History of this fileTake it
The walk stopped after 200 commits: lines older than a228a3b point at it.
Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 1–28why, one step back1.. _quickstart:23Quickstart4==========56Eager to get started? This page gives a good introduction to Flask. It7assumes you already have Flask installed. If you do not, head over to the8:ref:`installation` section.91011A Minimal Application12---------------------1314A minimal Flask application looks something like this::1516 from flask import Flask17 app = Flask(__name__)1819 @app.route('/')20 def hello_world():21 return 'Hello, World!'2223So what did that code do?24251. First we imported the :class:`~flask.Flask` class. An instance of this26 class will be our WSGI application.272. Next we create an instance of this class. The first argument is the name of28 the application's module or package. If you are using a single module (asclean up code formatting in some docsDavid Lordbefore adoption1928f28
line 29why, one step back29 in this example), you should use ``__name__`` because depending on if it'sMerge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 30–44why, one step back30 started as application or imported as module the name will be different31 (``'__main__'`` versus the actual import name). This is needed so that32 Flask knows where to look for templates, static files, and so on. For more33 information have a look at the :class:`~flask.Flask` documentation.343. We then use the :meth:`~flask.Flask.route` decorator to tell Flask what URL35 should trigger our function.364. The function is given a name which is also used to generate URLs for that37 particular function, and returns the message we want to display in the38 user's browser.3940Just save it as :file:`hello.py` or something similar. Make sure to not call41your application :file:`flask.py` because this would conflict with Flask42itself.4344To run the application you can either use the :command:`flask` command orclean up code formatting in some docsDavid Lordbefore adoption1928f28
line 45why, one step back45python's ``-m`` switch with Flask. Before you can do that you needMerge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 46why, one step back46to tell your terminal the application to work with by exporting theclean up code formatting in some docsDavid Lordbefore adoption1928f28
line 47why, one step back47``FLASK_APP`` environment variable::Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 48–52why, one step back4849 $ export FLASK_APP=hello.py50 $ flask run51 * Running on http://127.0.0.1:5000/52clean up code formatting in some docsDavid Lordbefore adoption1928f28
line 53why, one step back53If you are on Windows you need to use ``set`` instead of ``export``.Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 54why, one step back54clean up code formatting in some docsDavid Lordbefore adoption1928f28
line 55why, one step back55Alternatively you can use :command:`python -m flask`::Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 56–88why, one step back5657 $ export FLASK_APP=hello.py58 $ python -m flask run59 * Running on http://127.0.0.1:5000/6061This launches a very simple builtin server, which is good enough for testing62but probably not what you want to use in production. For deployment options see63:ref:`deployment`.6465Now head over to `http://127.0.0.1:5000/ <http://127.0.0.1:5000/>`_, and you66should see your hello world greeting.6768.. _public-server:6970.. admonition:: Externally Visible Server7172 If you run the server you will notice that the server is only accessible73 from your own computer, not from any other in the network. This is the74 default because in debugging mode a user of the application can execute75 arbitrary Python code on your computer.7677 If you have the debugger disabled or trust the users on your network,78 you can make the server publicly available simply by adding79 ``--host=0.0.0.0`` to the command line::8081 flask run --host=0.0.0.08283 This tells your operating system to listen on all public IPs.848586What to do if the Server does not Start87---------------------------------------88clean up code formatting in some docsDavid Lordbefore adoption1928f28
line 89why, one step back89In case the :command:`python -m flask` fails or :command:`flask` does not exist,Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 90–97why, one step back90there are multiple reasons this might be the case. First of all you need91to look at the error message.9293Old Version of Flask94````````````````````9596Versions of Flask older than 0.11 use to have different ways to start the97application. In short, the :command:`flask` command did not exist, andclean up code formatting in some docsDavid Lordbefore adoption1928f28
line 98why, one step back98neither did :command:`python -m flask`. In that case you have two options:Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 99–104why, one step back99either upgrade to newer Flask versions or have a look at the :ref:`server`100docs to see the alternative method for running a server.101102Invalid Import Name103```````````````````104Migrate various docs links to https (#2180)Jeff Widmanbefore adoptionbb0e755
lines 105–107why, one step back105The ``FLASK_APP`` environment variable is the name of the module to import at106:command:`flask run`. In case that module is incorrectly named you will get an107import error upon start (or if debug is enabled when you navigate to theRemove `-a/--app` from Quickstart documentation (#2046)Michael Recachinasbefore adoption49ecc88
line 108why, one step back108application). It will tell you what it tried to import and why it failed.Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 109–125why, one step back109110The most common reason is a typo or because you did not actually create an111``app`` object.112113.. _debug-mode:114115Debug Mode116----------117118(Want to just log errors and stack traces? See :ref:`application-errors`)119120The :command:`flask` script is nice to start a local development server, but121you would have to restart it manually after each change to your code.122That is not very nice and Flask can do better. If you enable debug123support the server will reload itself on code changes, and it will also124provide you with a helpful debugger if things go wrong.125clean up code formatting in some docsDavid Lordbefore adoption1928f28
line 126why, one step back126To enable debug mode you can export the ``FLASK_DEBUG`` environment variableMerge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 127–131why, one step back127before running the server::128129 $ export FLASK_DEBUG=1130 $ flask run131clean up code formatting in some docsDavid Lordbefore adoption1928f28
line 132why, one step back132(On Windows you need to use ``set`` instead of ``export``).Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 133–155why, one step back133134This does the following things:1351361. it activates the debugger1372. it activates the automatic reloader1383. it enables the debug mode on the Flask application.139140There are more parameters that are explained in the :ref:`server` docs.141142.. admonition:: Attention143144 Even though the interactive debugger does not work in forking environments145 (which makes it nearly impossible to use on production servers), it still146 allows the execution of arbitrary code. This makes it a major security risk147 and therefore it **must never be used on production machines**.148149Screenshot of the debugger in action:150151.. image:: _static/debugger.png152 :align: center153 :class: screenshot154 :alt: screenshot of debugger in action155Merge pull request #2296 from tullyrankin/debugger-documentation-1625David Lordbefore adoption88b0213
lines 156–160why, one step back156More information on using the debugger can be found in the `Werkzeug 157documentation`_.158159.. _Werkzeug documentation: http://werkzeug.pocoo.org/docs/debug/#using-the-debugger160Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 161–166why, one step back161Have another debugger in mind? See :ref:`working-with-debuggers`.162163164Routing165-------166Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
lines 167–169why, one step back167Modern web applications use meaningful URLs to help users. Users are more168likely to like a page and come back if the page uses a meaningful URL they can169remember and use to directly visit a page.Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 170why, one step back170Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
line 171why, one step back171Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 172–180why, one step back172173 @app.route('/')174 def index():175 return 'Index Page'176177 @app.route('/hello')178 def hello():179 return 'Hello, World'180Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
lines 181–182why, one step back181You can do more! You can make parts of the URL dynamic and attach multiple182rules to a function.Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 183–186why, one step back183184Variable Rules185``````````````186Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
lines 187–190why, one step back187You can add variable sections to a URL by marking sections with188``<variable_name>``. Your function then receives the ``<variable_name>``189as a keyword argument. Optionally, you can use a converter to specify the type190of the argument like ``<converter:variable_name>``. ::Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 191–201why, one step back191192 @app.route('/user/<username>')193 def show_user_profile(username):194 # show the user profile for that user195 return 'User %s' % username196197 @app.route('/post/<int:post_id>')198 def show_post(post_id):199 # show the post with the given id, the id is an integer200 return 'Post %d' % post_id201Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
lines 202–205why, one step back202 @app.route('/path/<path:subpath>')203 def show_subpath(subpath):204 # show the subpath after /path/205 return 'Subpath %s' % subpathMerge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 206why, one step back206Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
line 207why, one step back207Converter types:Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 208why, one step back208Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
lines 209–215why, one step back209========== ==========================================210``string`` (default) accepts any text without a slash211``int`` accepts positive integers212``float`` accepts positive floating point values213``path`` like ``string`` but also accepts slashes214``uuid`` accepts UUID strings215========== ==========================================Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 216why, one step back216Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
lines 217–218why, one step back217Unique URLs / Redirection Behavior218``````````````````````````````````Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 219why, one step back219Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
line 220why, one step back220Take these two rules::Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 221why, one step back221Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
lines 222–224why, one step back222 @app.route('/projects/')223 def projects():224 return 'The project page'Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 225why, one step back225Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
lines 226–228why, one step back226 @app.route('/about')227 def about():228 return 'The about page'Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 229why, one step back229Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
lines 230–234why, one step back230Though they look similar, they differ in their use of the trailing slash in231the URL. In the first case, the canonical URL for the ``projects`` endpoint232uses a trailing slash. It's similar to a folder in a file system; if you233access the URL without a trailing slash, Flask redirects you to the234canonical URL with the trailing slash.Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 235why, one step back235Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
lines 236–238why, one step back236In the second case, however, the URL definition lacks a trailing slash,237like the pathname of a file on UNIX-like systems. Accessing the URL with a238trailing slash produces a 404 “Not Found” error.Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 239why, one step back239Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
lines 240–243why, one step back240This behavior allows relative URLs to continue working even if the trailing241slash is omitted, consistent with how Apache and other servers work. Also,242the URLs will stay unique, which helps search engines avoid indexing the243same page twice.Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 244–249why, one step back244245.. _url-building:246247URL Building248````````````249Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
lines 250–253why, one step back250To build a URL to a specific function, use the :func:`~flask.url_for` function.251It accepts the name of the function as its first argument and any number of252keyword arguments, each corresponding to a variable part of the URL rule.253Unknown variable parts are appended to the URL as query parameters.Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 254–257why, one step back254255Why would you want to build URLs using the URL reversing function256:func:`~flask.url_for` instead of hard-coding them into your templates?257Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
lines 258–265why, one step back2581. Reversing is often more descriptive than hard-coding the URLs.2592. You can change your URLs in one go instead of needing to remember to260 manually change hard-coded URLs.2613. URL building handles escaping of special characters and Unicode data262 transparently.2634. If your application is placed outside the URL root, for example, in264 ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly265 handles that for you.Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 266why, one step back266Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
lines 267–270why, one step back267For example, here we use the :meth:`~flask.Flask.test_request_context` method268to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`269tells Flask to behave as though it's handling a request even while we use a270Python shell. See :ref:`context-locals`. ::Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 271why, one step back271Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
line 272why, one step back272 from flask import Flask, url_forMerge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 273why, one step back273Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
line 274why, one step back274 app = Flask(__name__)Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 275why, one step back275Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
lines 276–278why, one step back276 @app.route('/')277 def index():278 return 'index'Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 279why, one step back279Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
line 280why, one step back280 @app.route('/login')Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 281why, one step back281 def login():Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
line 282why, one step back282 return 'login'Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 283why, one step back283Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
lines 284–286why, one step back284 @app.route('/user/<username>')285 def profile(username):286 return '{}'s profile'.format(username)Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 287why, one step back287Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
lines 288–292why, one step back288 with app.test_request_context():289 print(url_for('index'))290 print(url_for('login'))291 print(url_for('login', next='/'))292 print(url_for('profile', username='John Doe'))Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 293why, one step back293Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
lines 294–297why, one step back294 /295 /login296 /login?next=/297 /user/John%20DoeMerge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 298why, one step back298Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
lines 299–300why, one step back299HTTP Methods300````````````Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 301why, one step back301Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
lines 302–306why, one step back302Web applications use different HTTP methods when accessing URLs. You should303familiarize yourself with the HTTP methods as you work with Flask. By default,304a route only answers to ``GET`` requests. You can use the ``methods`` argument305of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.306::Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 307why, one step back307Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
lines 308–313why, one step back308 @app.route('/login', methods=['GET', 'POST'])309 def login():310 if request.method == 'POST':311 do_the_login()312 else:313 show_the_login_form()Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 314why, one step back314Merge pull request #2277 from jlara310/masterDavid Lordbefore adoptionc01ddc5
lines 315–317why, one step back315If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method316and handles ``HEAD`` requests according to the the `HTTP RFC`_. Likewise,317``OPTIONS`` is automatically implemented for you.Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 318why, one step back318Migrate various docs links to https (#2180)Jeff Widmanbefore adoptionbb0e755
line 319why, one step back319.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txtMerge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 320–397why, one step back320321Static Files322------------323324Dynamic web applications also need static files. That's usually where325the CSS and JavaScript files are coming from. Ideally your web server is326configured to serve them for you, but during development Flask can do that327as well. Just create a folder called :file:`static` in your package or next to328your module and it will be available at ``/static`` on the application.329330To generate URLs for static files, use the special ``'static'`` endpoint name::331332 url_for('static', filename='style.css')333334The file has to be stored on the filesystem as :file:`static/style.css`.335336Rendering Templates337-------------------338339Generating HTML from within Python is not fun, and actually pretty340cumbersome because you have to do the HTML escaping on your own to keep341the application secure. Because of that Flask configures the `Jinja2342<http://jinja.pocoo.org/>`_ template engine for you automatically.343344To render a template you can use the :func:`~flask.render_template`345method. All you have to do is provide the name of the template and the346variables you want to pass to the template engine as keyword arguments.347Here's a simple example of how to render a template::348349 from flask import render_template350351 @app.route('/hello/')352 @app.route('/hello/<name>')353 def hello(name=None):354 return render_template('hello.html', name=name)355356Flask will look for templates in the :file:`templates` folder. So if your357application is a module, this folder is next to that module, if it's a358package it's actually inside your package:359360**Case 1**: a module::361362 /application.py363 /templates364 /hello.html365366**Case 2**: a package::367368 /application369 /__init__.py370 /templates371 /hello.html372373For templates you can use the full power of Jinja2 templates. Head over374to the official `Jinja2 Template Documentation375<http://jinja.pocoo.org/docs/templates>`_ for more information.376377Here is an example template:378379.. sourcecode:: html+jinja380381 <!doctype html>382 <title>Hello from Flask</title>383 {% if name %}384 <h1>Hello {{ name }}!</h1>385 {% else %}386 <h1>Hello, World!</h1>387 {% endif %}388389Inside templates you also have access to the :class:`~flask.request`,390:class:`~flask.session` and :class:`~flask.g` [#]_ objects391as well as the :func:`~flask.get_flashed_messages` function.392393Templates are especially useful if inheritance is used. If you want to394know how that works, head over to the :ref:`template-inheritance` pattern395documentation. Basically template inheritance makes it possible to keep396certain elements on each page (like header, navigation and footer).397clean up code formatting in some docsDavid Lordbefore adoption1928f28
line 398why, one step back398Automatic escaping is enabled, so if ``name`` contains HTML it will be escapedMerge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 399–404why, one step back399automatically. If you can trust a variable and you know that it will be400safe HTML (for example because it came from a module that converts wiki401markup to HTML) you can mark it as safe by using the402:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the403template. Head over to the Jinja 2 documentation for more examples.404clean up code formatting in some docsDavid Lordbefore adoption1928f28
line 405why, one step back405Here is a basic introduction to how the :class:`~jinja2.Markup` class works::Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 406why, one step back406clean up code formatting in some docsDavid Lordbefore adoption1928f28
lines 407–413why, one step back407 >>> from flask import Markup408 >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'409 Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')410 >>> Markup.escape('<blink>hacker</blink>')411 Markup(u'<blink>hacker</blink>')412 >>> Markup('<em>Marked up</em> » HTML').striptags()413 u'Marked up \xbb HTML'Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 414–489why, one step back414415.. versionchanged:: 0.5416417 Autoescaping is no longer enabled for all templates. The following418 extensions for templates trigger autoescaping: ``.html``, ``.htm``,419 ``.xml``, ``.xhtml``. Templates loaded from a string will have420 autoescaping disabled.421422.. [#] Unsure what that :class:`~flask.g` object is? It's something in which423 you can store information for your own needs, check the documentation of424 that object (:class:`~flask.g`) and the :ref:`sqlite3` for more425 information.426427428Accessing Request Data429----------------------430431For web applications it's crucial to react to the data a client sends to432the server. In Flask this information is provided by the global433:class:`~flask.request` object. If you have some experience with Python434you might be wondering how that object can be global and how Flask435manages to still be threadsafe. The answer is context locals:436437438.. _context-locals:439440Context Locals441``````````````442443.. admonition:: Insider Information444445 If you want to understand how that works and how you can implement446 tests with context locals, read this section, otherwise just skip it.447448Certain objects in Flask are global objects, but not of the usual kind.449These objects are actually proxies to objects that are local to a specific450context. What a mouthful. But that is actually quite easy to understand.451452Imagine the context being the handling thread. A request comes in and the453web server decides to spawn a new thread (or something else, the454underlying object is capable of dealing with concurrency systems other455than threads). When Flask starts its internal request handling it456figures out that the current thread is the active context and binds the457current application and the WSGI environments to that context (thread).458It does that in an intelligent way so that one application can invoke another459application without breaking.460461So what does this mean to you? Basically you can completely ignore that462this is the case unless you are doing something like unit testing. You463will notice that code which depends on a request object will suddenly break464because there is no request object. The solution is creating a request465object yourself and binding it to the context. The easiest solution for466unit testing is to use the :meth:`~flask.Flask.test_request_context`467context manager. In combination with the ``with`` statement it will bind a468test request so that you can interact with it. Here is an example::469470 from flask import request471472 with app.test_request_context('/hello', method='POST'):473 # now you can do something with the request until the474 # end of the with block, such as basic assertions:475 assert request.path == '/hello'476 assert request.method == 'POST'477478The other possibility is passing a whole WSGI environment to the479:meth:`~flask.Flask.request_context` method::480481 from flask import request482483 with app.request_context(environ):484 assert request.method == 'POST'485486The Request Object487``````````````````488489The request object is documented in the API section and we will not coverFix Request Reference (#2151)Dennis Chenbefore adoption9900a72
line 490why, one step back490it here in detail (see :class:`~flask.Request`). Here is a broad overview ofMerge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 491why, one step back491some of the most common operations. First of all you have to import it fromclean up code formatting in some docsDavid Lordbefore adoption1928f28
line 492why, one step back492the ``flask`` module::Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 493–496why, one step back493494 from flask import request495496The current request method is available by using theFix Request Reference (#2151)Dennis Chenbefore adoption9900a72
line 497why, one step back497:attr:`~flask.Request.method` attribute. To access form data (dataMerge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 498why, one step back498transmitted in a ``POST`` or ``PUT`` request) you can use theFix Request Reference (#2151)Dennis Chenbefore adoption9900a72
line 499why, one step back499:attr:`~flask.Request.form` attribute. Here is a full example of the twoMerge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 500–514why, one step back500attributes mentioned above::501502 @app.route('/login', methods=['POST', 'GET'])503 def login():504 error = None505 if request.method == 'POST':506 if valid_login(request.form['username'],507 request.form['password']):508 return log_the_user_in(request.form['username'])509 else:510 error = 'Invalid username/password'511 # the code below is executed if the request method512 # was GET or the credentials were invalid513 return render_template('login.html', error=error)514clean up code formatting in some docsDavid Lordbefore adoption1928f28
line 515why, one step back515What happens if the key does not exist in the ``form`` attribute? In thatMerge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 516–521why, one step back516case a special :exc:`KeyError` is raised. You can catch it like a517standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request518error page is shown instead. So for many situations you don't have to519deal with that problem.520521To access parameters submitted in the URL (``?key=value``) you can use theFix Request Reference (#2151)Dennis Chenbefore adoption9900a72
line 522why, one step back522:attr:`~flask.Request.args` attribute::Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 523–530why, one step back523524 searchword = request.args.get('key', '')525526We recommend accessing URL parameters with `get` or by catching the527:exc:`KeyError` because users might change the URL and presenting them a 400528bad request page in that case is not user friendly.529530For a full list of methods and attributes of the request object, head overFix Request Reference (#2151)Dennis Chenbefore adoption9900a72
line 531why, one step back531to the :class:`~flask.Request` documentation.Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 532–676why, one step back532533534File Uploads535````````````536537You can handle uploaded files with Flask easily. Just make sure not to538forget to set the ``enctype="multipart/form-data"`` attribute on your HTML539form, otherwise the browser will not transmit your files at all.540541Uploaded files are stored in memory or at a temporary location on the542filesystem. You can access those files by looking at the543:attr:`~flask.request.files` attribute on the request object. Each544uploaded file is stored in that dictionary. It behaves just like a545standard Python :class:`file` object, but it also has a546:meth:`~werkzeug.datastructures.FileStorage.save` method that allows you to store that547file on the filesystem of the server. Here is a simple example showing how548that works::549550 from flask import request551552 @app.route('/upload', methods=['GET', 'POST'])553 def upload_file():554 if request.method == 'POST':555 f = request.files['the_file']556 f.save('/var/www/uploads/uploaded_file.txt')557 ...558559If you want to know how the file was named on the client before it was560uploaded to your application, you can access the561:attr:`~werkzeug.datastructures.FileStorage.filename` attribute. However please keep in562mind that this value can be forged so never ever trust that value. If you563want to use the filename of the client to store the file on the server,564pass it through the :func:`~werkzeug.utils.secure_filename` function that565Werkzeug provides for you::566567 from flask import request568 from werkzeug.utils import secure_filename569570 @app.route('/upload', methods=['GET', 'POST'])571 def upload_file():572 if request.method == 'POST':573 f = request.files['the_file']574 f.save('/var/www/uploads/' + secure_filename(f.filename))575 ...576577For some better examples, checkout the :ref:`uploading-files` pattern.578579Cookies580```````581582To access cookies you can use the :attr:`~flask.Request.cookies`583attribute. To set cookies you can use the584:attr:`~flask.Response.set_cookie` method of response objects. The585:attr:`~flask.Request.cookies` attribute of request objects is a586dictionary with all the cookies the client transmits. If you want to use587sessions, do not use the cookies directly but instead use the588:ref:`sessions` in Flask that add some security on top of cookies for you.589590Reading cookies::591592 from flask import request593594 @app.route('/')595 def index():596 username = request.cookies.get('username')597 # use cookies.get(key) instead of cookies[key] to not get a598 # KeyError if the cookie is missing.599600Storing cookies::601602 from flask import make_response603604 @app.route('/')605 def index():606 resp = make_response(render_template(...))607 resp.set_cookie('username', 'the username')608 return resp609610Note that cookies are set on response objects. Since you normally611just return strings from the view functions Flask will convert them into612response objects for you. If you explicitly want to do that you can use613the :meth:`~flask.make_response` function and then modify it.614615Sometimes you might want to set a cookie at a point where the response616object does not exist yet. This is possible by utilizing the617:ref:`deferred-callbacks` pattern.618619For this also see :ref:`about-responses`.620621Redirects and Errors622--------------------623624To redirect a user to another endpoint, use the :func:`~flask.redirect`625function; to abort a request early with an error code, use the626:func:`~flask.abort` function::627628 from flask import abort, redirect, url_for629630 @app.route('/')631 def index():632 return redirect(url_for('login'))633634 @app.route('/login')635 def login():636 abort(401)637 this_is_never_executed()638639This is a rather pointless example because a user will be redirected from640the index to a page they cannot access (401 means access denied) but it641shows how that works.642643By default a black and white error page is shown for each error code. If644you want to customize the error page, you can use the645:meth:`~flask.Flask.errorhandler` decorator::646647 from flask import render_template648649 @app.errorhandler(404)650 def page_not_found(error):651 return render_template('page_not_found.html'), 404652653Note the ``404`` after the :func:`~flask.render_template` call. This654tells Flask that the status code of that page should be 404 which means655not found. By default 200 is assumed which translates to: all went well.656657See :ref:`error-handlers` for more details.658659.. _about-responses:660661About Responses662---------------663664The return value from a view function is automatically converted into a665response object for you. If the return value is a string it's converted666into a response object with the string as response body, a ``200 OK``667status code and a :mimetype:`text/html` mimetype. The logic that Flask applies to668converting return values into response objects is as follows:6696701. If a response object of the correct type is returned it's directly671 returned from the view.6722. If it's a string, a response object is created with that data and the673 default parameters.6743. If a tuple is returned the items in the tuple can provide extra675 information. Such tuples have to be in the form ``(response, status,676 headers)`` or ``(response, headers)`` where at least one item hasclean up code formatting in some docsDavid Lordbefore adoption1928f28
lines 677–678why, one step back677 to be in the tuple. The ``status`` value will override the status code678 and ``headers`` can be a list or dictionary of additional header values.Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 679–684why, one step back6794. If none of that works, Flask will assume the return value is a680 valid WSGI application and convert that into a response object.681682If you want to get hold of the resulting response object inside the view683you can use the :func:`~flask.make_response` function.684clean up code formatting in some docsDavid Lordbefore adoption1928f28
line 685why, one step back685Imagine you have a view like this::Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 686–692why, one step back686687 @app.errorhandler(404)688 def not_found(error):689 return render_template('error.html'), 404690691You just need to wrap the return expression with692:func:`~flask.make_response` and get the response object to modify it, thenclean up code formatting in some docsDavid Lordbefore adoption1928f28
line 693why, one step back693return it::Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 694–731why, one step back694695 @app.errorhandler(404)696 def not_found(error):697 resp = make_response(render_template('error.html'), 404)698 resp.headers['X-Something'] = 'A value'699 return resp700701.. _sessions:702703Sessions704--------705706In addition to the request object there is also a second object called707:class:`~flask.session` which allows you to store information specific to a708user from one request to the next. This is implemented on top of cookies709for you and signs the cookies cryptographically. What this means is that710the user could look at the contents of your cookie but not modify it,711unless they know the secret key used for signing.712713In order to use sessions you have to set a secret key. Here is how714sessions work::715716 from flask import Flask, session, redirect, url_for, escape, request717718 app = Flask(__name__)719720 @app.route('/')721 def index():722 if 'username' in session:723 return 'Logged in as %s' % escape(session['username'])724 return 'You are not logged in'725726 @app.route('/login', methods=['GET', 'POST'])727 def login():728 if request.method == 'POST':729 session['username'] = request.form['username']730 return redirect(url_for('index'))731 return '''remove unnecessary form action attributesDavid Lordbefore adoptioncd1a9b7
line 732why, one step back732 <form method="post">Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 733–754why, one step back733 <p><input type=text name=username>734 <p><input type=submit value=Login>735 </form>736 '''737738 @app.route('/logout')739 def logout():740 # remove the username from the session if it's there741 session.pop('username', None)742 return redirect(url_for('index'))743744 # set the secret key. keep this really secret:745 app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'746747The :func:`~flask.escape` mentioned here does escaping for you if you are748not using the template engine (as in this example).749750.. admonition:: How to generate good secret keys751752 The problem with random is that it's hard to judge what is truly random. And753 a secret key should be as random as possible. Your operating system754 has ways to generate pretty random stuff based on a cryptographicclean up code formatting in some docsDavid Lordbefore adoption1928f28
line 755why, one step back755 random generator which can be used to get such a key::Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 756why, one step back756clean up code formatting in some docsDavid Lordbefore adoption1928f28
lines 757–759why, one step back757 >>> import os758 >>> os.urandom(24)759 '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
line 760why, one step back760clean up code formatting in some docsDavid Lordbefore adoption1928f28
line 761why, one step back761 Just take that thing and copy/paste it into your code and you're done.Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 762–768why, one step back762763A note on cookie-based sessions: Flask will take the values you put into the764session object and serialize them into a cookie. If you are finding some765values do not persist across requests, cookies are indeed enabled, and you are766not getting a clear error message, check the size of the cookie in your page767responses compared to the size supported by web browsers.768sessions documentation (client side vs server side) #434 (#1888)dawran6before adoption3d856e0
lines 769–771why, one step back769Besides the default client-side based sessions, if you want to handle770sessions on the server-side instead, there are several771Flask extensions that support this.Merge pull request #1862 from antsar/masterJeff Widmanbefore adoptiona228a3b
lines 772–842why, one step back772773Message Flashing774----------------775776Good applications and user interfaces are all about feedback. If the user777does not get enough feedback they will probably end up hating the778application. Flask provides a really simple way to give feedback to a779user with the flashing system. The flashing system basically makes it780possible to record a message at the end of a request and access it on the next781(and only the next) request. This is usually combined with a layout782template to expose the message.783784To flash a message use the :func:`~flask.flash` method, to get hold of the785messages you can use :func:`~flask.get_flashed_messages` which is also786available in the templates. Check out the :ref:`message-flashing-pattern`787for a full example.788789Logging790-------791792.. versionadded:: 0.3793794Sometimes you might be in a situation where you deal with data that795should be correct, but actually is not. For example you may have some client-side796code that sends an HTTP request to the server but it's obviously797malformed. This might be caused by a user tampering with the data, or the798client code failing. Most of the time it's okay to reply with ``400 Bad799Request`` in that situation, but sometimes that won't do and the code has800to continue working.801802You may still want to log that something fishy happened. This is where803loggers come in handy. As of Flask 0.3 a logger is preconfigured for you804to use.805806Here are some example log calls::807808 app.logger.debug('A value for debugging')809 app.logger.warning('A warning occurred (%d apples)', 42)810 app.logger.error('An error occurred')811812The attached :attr:`~flask.Flask.logger` is a standard logging813:class:`~logging.Logger`, so head over to the official `logging814documentation <https://docs.python.org/library/logging.html>`_ for more815information.816817Read more on :ref:`application-errors`.818819Hooking in WSGI Middlewares820---------------------------821822If you want to add a WSGI middleware to your application you can wrap the823internal WSGI application. For example if you want to use one of the824middlewares from the Werkzeug package to work around bugs in lighttpd, you825can do it like this::826827 from werkzeug.contrib.fixers import LighttpdCGIRootFix828 app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)829830Using Flask Extensions831----------------------832833Extensions are packages that help you accomplish common tasks. For834example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple835and easy to use with Flask.836837For more on Flask extensions, have a look at :ref:`extensions`.838839Deploying to a Web Server840-------------------------841842Ready to deploy your new Flask app? Go to :ref:`deployment`.