quickstart.rst
This file
Path
docs/quickstart.rst
892 lines · 32.7 KiB
Last changed by
Fix #1195Markus Unterwaditzerbefore adoption66b4ea9
History of this fileTake it
The walk stopped after 200 commits: lines older than 5693b9d point at it.
Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 1–20why, 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():Merge pull request #1318 from cerivera/masterMarkus Unterwaditzerbefore adoptione3ba459
line 21why, one step back21 return 'Hello, World!'Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 22–25why, one step back2223So what did that code do?24251. First we imported the :class:`~flask.Flask` class. An instance of thisMerge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01
line 26why, one step back26 class will be our WSGI application.Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 27–39why, one step back272. 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 (as29 in this example), you should use `__name__` because depending on if it's30 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.39Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894
lines 40–42why, one step back40Just save it as :file:`hello.py` (or something similar) and run it with your Python41interpreter. Make sure to not call your application :file:`flask.py` because this42would conflict with Flask itself.Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
line 43why, one step back43Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894
lines 44–61why, one step back44To run the application you can either use the :command:`flask` command or45python's :option:`-m` switch with Flask::4647 $ flask -a hello run48 * Running on http://127.0.0.1:5000/4950or alternatively::5152 $ python -m flask -a hello run53 * Running on http://127.0.0.1:5000/5455This launches a very simple builtin server, which is good enough for testing56but probably not what you want to use in production. For deployment options see57:ref:`deployment`.5859Now head over to `http://127.0.0.1:5000/ <http://127.0.0.1:5000/>`_, and you60should see your hello world greeting.61Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 62–78why, one step back62.. _public-server:6364.. admonition:: Externally Visible Server6566 If you run the server you will notice that the server is only accessible67 from your own computer, not from any other in the network. This is the68 default because in debugging mode a user of the application can execute69 arbitrary Python code on your computer.7071 If you have the debugger disabled or trust the users on your network,72 you can make the server publicly available simply by adding73 ``--host=0.0.0.0`` to the command line::7475 flask -a hello run --host=0.0.0.07677 This tells your operating system to listen on all public IPs.78Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894
line 79why, one step back79Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 80–82why, one step back80What to do if the Server does not Start81---------------------------------------82Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 83why, one step back83In case the ``python -m flask`` fails or :command:`flask` does not exist,Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 84–90why, one step back84there are multiple reasons this might be the case. First of all you need85to look at the error message.8687Old Version of Flask88````````````````````8990Versions of Flask older than 1.0 use to have different ways to start theMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 91why, one step back91application. In short, the :command:`flask` command did not exist, andMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 92–99why, one step back92neither did ``python -m flask``. In that case you have two options:93either upgrade to newer Flask versions or have a look at the :ref:`server`94docs to see the alternative method for running a server.9596Python older 2.797````````````````9899In case you have a version of Python older than 2.7 ``python -m flask``Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 100why, one step back100does not work. You can either use :command:`flask` or ``python -mMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 101–107why, one step back101flask.cli`` as an alternative. This is because Python before 2.7 does no102permit packages to act as executable modules. For more information see103:ref:`cli`.104105Invalid Import Name106```````````````````107Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 108why, one step back108The :option:`-a` argument to :command:`flask` is the name of the module to import. InMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 109–120why, one step back109case that module is incorrectly named you will get an import error upon110start (or if debug is enabled when you navigate to the application). It111will tell you what it tried to import and why it failed.112113The most common reason is a typo or because you did not actually create an114``app`` object.115116.. _debug-mode:117118Debug Mode119----------120Fix #1195Markus Unterwaditzerbefore adoption66b4ea9
lines 121–122why, one step back121(Want to just log errors and stack traces? See :ref:`application-errors`)122Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 123why, one step back123The :command:`flask` script is nice to start a local development server, butMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 124–129why, one step back124you would have to restart it manually after each change to your code.125That is not very nice and Flask can do better. If you enable debug126support the server will reload itself on code changes, and it will also127provide you with a helpful debugger if things go wrong.128129There are different ways to enable the debug mode. The most obvious oneMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 130why, one step back130is the :option:`--debug` parameter to the :command:`flask` command::Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 131–176why, one step back131132 flask --debug -a hello run133134This 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 action155156Have another debugger in mind? See :ref:`working-with-debuggers`.157158159Routing160-------161162Modern web applications have beautiful URLs. This helps people remember163the URLs, which is especially handy for applications that are used from164mobile devices with slower network connections. If the user can directly165go to the desired page without having to hit the index page it is more166likely they will like the page and come back next time.167168As you have seen above, the :meth:`~flask.Flask.route` decorator is used to169bind a function to a URL. Here are some basic examples::170171 @app.route('/')172 def index():173 return 'Index Page'174175 @app.route('/hello')176 def hello():Merge pull request #1318 from cerivera/masterMarkus Unterwaditzerbefore adoptione3ba459
line 177why, one step back177 return 'Hello, World'Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 178–201why, one step back178179But there is more to it! You can make certain parts of the URL dynamic and180attach multiple rules to a function.181182Variable Rules183``````````````184185To add variable parts to a URL you can mark these special sections as186``<variable_name>``. Such a part is then passed as a keyword argument to your187function. Optionally a converter can be used by specifying a rule with188``<converter:variable_name>``. Here are some nice examples::189190 @app.route('/user/<username>')191 def show_user_profile(username):192 # show the user profile for that user193 return 'User %s' % username194195 @app.route('/post/<int:post_id>')196 def show_post(post_id):197 # show the post with the given id, the id is an integer198 return 'Post %d' % post_id199200The following converters exist:201Merge pull request #1183 from k-funk/patch-1Markus Unterwaditzerbefore adoption2401e21
lines 202–203why, one step back202=========== ===============================================203`string` accepts any text without a slash (the default)Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 204–206why, one step back204`int` accepts integers205`float` like `int` but for floating point values206`path` like the default but also accepts slashesMerge pull request #1183 from k-funk/patch-1Markus Unterwaditzerbefore adoption2401e21
line 207why, one step back207=========== ===============================================Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 208–227why, one step back208209.. admonition:: Unique URLs / Redirection Behavior210211 Flask's URL rules are based on Werkzeug's routing module. The idea212 behind that module is to ensure beautiful and unique URLs based on213 precedents laid down by Apache and earlier HTTP servers.214215 Take these two rules::216217 @app.route('/projects/')218 def projects():219 return 'The project page'220221 @app.route('/about')222 def about():223 return 'The about page'224225 Though they look rather similar, they differ in their use of the trailing226 slash in the URL *definition*. In the first case, the canonical URL for the227 `projects` endpoint has a trailing slash. In that sense, it is similar toMerge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd
line 228why, one step back228 a folder on a filesystem. Accessing it without a trailing slash will causeMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 229–297why, one step back229 Flask to redirect to the canonical URL with the trailing slash.230231 In the second case, however, the URL is defined without a trailing slash,232 rather like the pathname of a file on UNIX-like systems. Accessing the URL233 with a trailing slash will produce a 404 "Not Found" error.234235 This behavior allows relative URLs to continue working even if the trailing236 slash is omitted, consistent with how Apache and other servers work. Also,237 the URLs will stay unique, which helps search engines avoid indexing the238 same page twice.239240241.. _url-building:242243URL Building244````````````245246If it can match URLs, can Flask also generate them? Of course it can. To247build a URL to a specific function you can use the :func:`~flask.url_for`248function. It accepts the name of the function as first argument and a number249of keyword arguments, each corresponding to the variable part of the URL rule.250Unknown variable parts are appended to the URL as query parameters. Here are251some examples:252253>>> from flask import Flask, url_for254>>> app = Flask(__name__)255>>> @app.route('/')256... def index(): pass257...258>>> @app.route('/login')259... def login(): pass260...261>>> @app.route('/user/<username>')262... def profile(username): pass263...264>>> with app.test_request_context():265... print url_for('index')266... print url_for('login')267... print url_for('login', next='/')268... print url_for('profile', username='John Doe')269...270/271/login272/login?next=/273/user/John%20Doe274275(This also uses the :meth:`~flask.Flask.test_request_context` method, explained276below. It tells Flask to behave as though it is handling a request, even277though we are interacting with it through a Python shell. Have a look at the278explanation below. :ref:`context-locals`).279280Why would you want to build URLs using the URL reversing function281:func:`~flask.url_for` instead of hard-coding them into your templates?282There are three good reasons for this:2832841. Reversing is often more descriptive than hard-coding the URLs. More285 importantly, it allows you to change URLs in one go, without having to286 remember to change URLs all over the place.2872. URL building will handle escaping of special characters and Unicode288 data transparently for you, so you don't have to deal with them.2893. If your application is placed outside the URL root (say, in290 ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will handle291 that properly for you.292293294HTTP Methods295````````````296297HTTP (the protocol web applications are speaking) knows different methods forMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 298why, one step back298accessing URLs. By default, a route only answers to ``GET`` requests, but thatMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 299–310why, one step back299can be changed by providing the `methods` argument to the300:meth:`~flask.Flask.route` decorator. Here are some examples::301302 from flask import request303304 @app.route('/login', methods=['GET', 'POST'])305 def login():306 if request.method == 'POST':307 do_the_login()308 else:309 show_the_login_form()310Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
lines 311–312why, one step back311If ``GET`` is present, ``HEAD`` will be added automatically for you. You312don't have to deal with that. It will also make sure that ``HEAD`` requestsMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 313–314why, one step back313are handled as the `HTTP RFC`_ (the document describing the HTTP314protocol) demands, so you can completely ignore that part of the HTTPMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 315why, one step back315specification. Likewise, as of Flask 0.6, ``OPTIONS`` is implemented for youMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 316–324why, one step back316automatically as well.317318You have no idea what an HTTP method is? Worry not, here is a quick319introduction to HTTP methods and why they matter:320321The HTTP method (also often called "the verb") tells the server what the322clients wants to *do* with the requested page. The following methods are323very common:324Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 325why, one step back325``GET``Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 326–328why, one step back326 The browser tells the server to just *get* the information stored on327 that page and send it. This is probably the most common method.328Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 329why, one step back329``HEAD``Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 330–331why, one step back330 The browser tells the server to get the information, but it is only331 interested in the *headers*, not the content of the page. AnMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 332why, one step back332 application is supposed to handle that as if a ``GET`` request wasMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 333–336why, one step back333 received but to not deliver the actual content. In Flask you don't334 have to deal with that at all, the underlying Werkzeug library handles335 that for you.336Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 337why, one step back337``POST``Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 338–342why, one step back338 The browser tells the server that it wants to *post* some new339 information to that URL and that the server must ensure the data is340 stored and only stored once. This is how HTML forms usually341 transmit data to the server.342Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
lines 343–344why, one step back343``PUT``344 Similar to ``POST`` but the server might trigger the store procedureMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 345–349why, one step back345 multiple times by overwriting the old values more than once. Now you346 might be asking why this is useful, but there are some good reasons347 to do it this way. Consider that the connection is lost during348 transmission: in this situation a system between the browser and the349 server might receive the request safely a second time without breakingMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 350why, one step back350 things. With ``POST`` that would not be possible because it must onlyMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 351–352why, one step back351 be triggered once.352Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 353why, one step back353``DELETE``Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 354–355why, one step back354 Remove the information at the given location.355Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 356why, one step back356``OPTIONS``Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 357–361why, one step back357 Provides a quick way for a client to figure out which methods are358 supported by this URL. Starting with Flask 0.6, this is implemented359 for you automatically.360361Now the interesting part is that in HTML4 and XHTML1, the only methods aMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 362why, one step back362form can submit to the server are ``GET`` and ``POST``. But with JavaScriptMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 363–375why, one step back363and future HTML standards you can use the other methods as well. Furthermore364HTTP has become quite popular lately and browsers are no longer the only365clients that are using HTTP. For instance, many revision control systems366use it.367368.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt369370Static Files371------------372373Dynamic web applications also need static files. That's usually where374the CSS and JavaScript files are coming from. Ideally your web server is375configured to serve them for you, but during development Flask can do thatMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
lines 376–377why, one step back376as well. Just create a folder called :file:`static` in your package or next to377your module and it will be available at ``/static`` on the application.Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 378–382why, one step back378379To generate URLs for static files, use the special ``'static'`` endpoint name::380381 url_for('static', filename='style.css')382Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 383why, one step back383The file has to be stored on the filesystem as :file:`static/style.css`.Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 384–404why, one step back384385Rendering Templates386-------------------387388Generating HTML from within Python is not fun, and actually pretty389cumbersome because you have to do the HTML escaping on your own to keep390the application secure. Because of that Flask configures the `Jinja2391<http://jinja.pocoo.org/>`_ template engine for you automatically.392393To render a template you can use the :func:`~flask.render_template`394method. All you have to do is provide the name of the template and the395variables you want to pass to the template engine as keyword arguments.396Here's a simple example of how to render a template::397398 from flask import render_template399400 @app.route('/hello/')401 @app.route('/hello/<name>')402 def hello(name=None):403 return render_template('hello.html', name=name)404Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 405why, one step back405Flask will look for templates in the :file:`templates` folder. So if yourMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 406–434why, one step back406application is a module, this folder is next to that module, if it's a407package it's actually inside your package:408409**Case 1**: a module::410411 /application.py412 /templates413 /hello.html414415**Case 2**: a package::416417 /application418 /__init__.py419 /templates420 /hello.html421422For templates you can use the full power of Jinja2 templates. Head over423to the official `Jinja2 Template Documentation424<http://jinja.pocoo.org/docs/templates>`_ for more information.425426Here is an example template:427428.. sourcecode:: html+jinja429430 <!doctype html>431 <title>Hello from Flask</title>432 {% if name %}433 <h1>Hello {{ name }}!</h1>434 {% else %}Merge pull request #1318 from cerivera/masterMarkus Unterwaditzerbefore adoptione3ba459
line 435why, one step back435 <h1>Hello, World!</h1>Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 436–479why, one step back436 {% endif %}437438Inside templates you also have access to the :class:`~flask.request`,439:class:`~flask.session` and :class:`~flask.g` [#]_ objects440as well as the :func:`~flask.get_flashed_messages` function.441442Templates are especially useful if inheritance is used. If you want to443know how that works, head over to the :ref:`template-inheritance` pattern444documentation. Basically template inheritance makes it possible to keep445certain elements on each page (like header, navigation and footer).446447Automatic escaping is enabled, so if `name` contains HTML it will be escaped448automatically. If you can trust a variable and you know that it will be449safe HTML (for example because it came from a module that converts wiki450markup to HTML) you can mark it as safe by using the451:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the452template. Head over to the Jinja 2 documentation for more examples.453454Here is a basic introduction to how the :class:`~jinja2.Markup` class works:455456>>> from flask import Markup457>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'458Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')459>>> Markup.escape('<blink>hacker</blink>')460Markup(u'<blink>hacker</blink>')461>>> Markup('<em>Marked up</em> » HTML').striptags()462u'Marked up \xbb HTML'463464.. versionchanged:: 0.5465466 Autoescaping is no longer enabled for all templates. The following467 extensions for templates trigger autoescaping: ``.html``, ``.htm``,468 ``.xml``, ``.xhtml``. Templates loaded from a string will have469 autoescaping disabled.470471.. [#] Unsure what that :class:`~flask.g` object is? It's something in which472 you can store information for your own needs, check the documentation of473 that object (:class:`~flask.g`) and the :ref:`sqlite3` for more474 information.475476477Accessing Request Data478----------------------479Merge pull request #1299 from sateeshkumarb/patch-1Markus Unterwaditzerbefore adoption4fde65e
line 480why, one step back480For web applications it's crucial to react to the data a client sends toMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 481–515why, one step back481the server. In Flask this information is provided by the global482:class:`~flask.request` object. If you have some experience with Python483you might be wondering how that object can be global and how Flask484manages to still be threadsafe. The answer is context locals:485486487.. _context-locals:488489Context Locals490``````````````491492.. admonition:: Insider Information493494 If you want to understand how that works and how you can implement495 tests with context locals, read this section, otherwise just skip it.496497Certain objects in Flask are global objects, but not of the usual kind.498These objects are actually proxies to objects that are local to a specific499context. What a mouthful. But that is actually quite easy to understand.500501Imagine the context being the handling thread. A request comes in and the502web server decides to spawn a new thread (or something else, the503underlying object is capable of dealing with concurrency systems other504than threads). When Flask starts its internal request handling it505figures out that the current thread is the active context and binds the506current application and the WSGI environments to that context (thread).507It does that in an intelligent way so that one application can invoke another508application without breaking.509510So what does this mean to you? Basically you can completely ignore that511this is the case unless you are doing something like unit testing. You512will notice that code which depends on a request object will suddenly break513because there is no request object. The solution is creating a request514object yourself and binding it to the context. The easiest solution for515unit testing is to use the :meth:`~flask.Flask.test_request_context`Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 516why, one step back516context manager. In combination with the ``with`` statement it will bind aMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 517–546why, one step back517test request so that you can interact with it. Here is an example::518519 from flask import request520521 with app.test_request_context('/hello', method='POST'):522 # now you can do something with the request until the523 # end of the with block, such as basic assertions:524 assert request.path == '/hello'525 assert request.method == 'POST'526527The other possibility is passing a whole WSGI environment to the528:meth:`~flask.Flask.request_context` method::529530 from flask import request531532 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 (dataMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 547why, one step back547transmitted in a ``POST`` or ``PUT`` request) you can use theMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 548–575why, one step back548: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 theMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 576why, one step back576:exc:`KeyError` because users might change the URL and presenting them a 400Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 577–616why, one step back577bad 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 a595:meth:`~werkzeug.datastructures.FileStorage.save` method that allows you to store that596file on the filesystem of the server. Here is a simple example showing how597that works::598599 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 the610:attr:`~werkzeug.datastructures.FileStorage.filename` attribute. However please keep in611mind that this value can be forged so never ever trust that value. If you612want to use the filename of the client to store the file on the server,613pass it through the :func:`~werkzeug.utils.secure_filename` function that614Werkzeug provides for you::615616 from flask import requestMerge pull request #1461 from justinwp/patch-1Markus Unterwaditzerbefore adoption1e15e17
line 617why, one step back617 from werkzeug.utils import secure_filenameMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 618–705why, one step back618619 @app.route('/upload', methods=['GET', 'POST'])620 def upload_file():621 if request.method == 'POST':622 f = request.files['the_file']623 f.save('/var/www/uploads/' + secure_filename(f.filename))624 ...625626For some better examples, checkout the :ref:`uploading-files` pattern.627628Cookies629```````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 the666:ref:`deferred-callbacks` pattern.667668For 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.705Merge pull request #1429 from flying-sheep/errorhandler-rework-docsMarkus Unterwaditzerbefore adoption06f2be3
lines 706–707why, one step back706See :ref:`error-handlers` for more details.707Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 708–715why, one step back708.. _about-responses:709710About Responses711---------------712713The return value from a view function is automatically converted into a714response object for you. If the return value is a string it's converted715into a response object with the string as response body, a ``200 OK``Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 716why, one step back716status code and a :mimetype:`text/html` mimetype. The logic that Flask applies toMerge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 717–866why, one step back717converting return values into response objects is as follows:7187191. If a response object of the correct type is returned it's directly720 returned from the view.7212. If it's a string, a response object is created with that data and the722 default parameters.7233. If a tuple is returned the items in the tuple can provide extra724 information. Such tuples have to be in the form ``(response, status,725 headers)`` or ``(response, headers)`` where at least one item has726 to be in the tuple. The `status` value will override the status code727 and `headers` can be a list or dictionary of additional header values.7284. If none of that works, Flask will assume the return value is a729 valid WSGI application and convert that into a response object.730731If you want to get hold of the resulting response object inside the view732you can use the :func:`~flask.make_response` function.733734Imagine you have a view like this:735736.. sourcecode:: python737738 @app.errorhandler(404)739 def not_found(error):740 return render_template('error.html'), 404741742You just need to wrap the return expression with743:func:`~flask.make_response` and get the response object to modify it, then744return it:745746.. sourcecode:: python747748 @app.errorhandler(404)749 def not_found(error):750 resp = make_response(render_template('error.html'), 404)751 resp.headers['X-Something'] = 'A value'752 return resp753754.. _sessions:755756Sessions757--------758759In addition to the request object there is also a second object called760:class:`~flask.session` which allows you to store information specific to a761user from one request to the next. This is implemented on top of cookies762for you and signs the cookies cryptographically. What this means is that763the user could look at the contents of your cookie but not modify it,764unless they know the secret key used for signing.765766In order to use sessions you have to set a secret key. Here is how767sessions work::768769 from flask import Flask, session, redirect, url_for, escape, request770771 app = Flask(__name__)772773 @app.route('/')774 def index():775 if 'username' in session:776 return 'Logged in as %s' % escape(session['username'])777 return 'You are not logged in'778779 @app.route('/login', methods=['GET', 'POST'])780 def login():781 if request.method == 'POST':782 session['username'] = request.form['username']783 return redirect(url_for('index'))784 return '''785 <form action="" method="post">786 <p><input type=text name=username>787 <p><input type=submit value=Login>788 </form>789 '''790791 @app.route('/logout')792 def logout():793 # remove the username from the session if it's there794 session.pop('username', None)795 return redirect(url_for('index'))796797 # set the secret key. keep this really secret:798 app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'799800The :func:`~flask.escape` mentioned here does escaping for you if you are801not using the template engine (as in this example).802803.. admonition:: How to generate good secret keys804805 The problem with random is that it's hard to judge what is truly random. And806 a secret key should be as random as possible. Your operating system807 has ways to generate pretty random stuff based on a cryptographic808 random generator which can be used to get such a key:809810 >>> import os811 >>> os.urandom(24)812 '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'813814 Just take that thing and copy/paste it into your code and you're done.815816A note on cookie-based sessions: Flask will take the values you put into the817session object and serialize them into a cookie. If you are finding some818values do not persist across requests, cookies are indeed enabled, and you are819not getting a clear error message, check the size of the cookie in your page820responses compared to the size supported by web browsers.821822823Message Flashing824----------------825826Good applications and user interfaces are all about feedback. If the user827does not get enough feedback they will probably end up hating the828application. Flask provides a really simple way to give feedback to a829user with the flashing system. The flashing system basically makes it830possible to record a message at the end of a request and access it on the next831(and only the next) request. This is usually combined with a layout832template to expose the message.833834To flash a message use the :func:`~flask.flash` method, to get hold of the835messages you can use :func:`~flask.get_flashed_messages` which is also836available in the templates. Check out the :ref:`message-flashing-pattern`837for a full example.838839Logging840-------841842.. versionadded:: 0.3843844Sometimes you might be in a situation where you deal with data that845should be correct, but actually is not. For example you may have some client-side846code that sends an HTTP request to the server but it's obviously847malformed. This might be caused by a user tampering with the data, or the848client code failing. Most of the time it's okay to reply with ``400 Bad849Request`` in that situation, but sometimes that won't do and the code has850to continue working.851852You may still want to log that something fishy happened. This is where853loggers come in handy. As of Flask 0.3 a logger is preconfigured for you854to use.855856Here are some example log calls::857858 app.logger.debug('A value for debugging')859 app.logger.warning('A warning occurred (%d apples)', 42)860 app.logger.error('An error occurred')861862The attached :attr:`~flask.Flask.logger` is a standard logging863:class:`~logging.Logger`, so head over to the official `logging864documentation <https://docs.python.org/library/logging.html>`_ for more865information.866Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894
lines 867–868why, one step back867Read more on :ref:`application-errors`.868Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 869–879why, one step back869Hooking in WSGI Middlewares870---------------------------871872If you want to add a WSGI middleware to your application you can wrap the873internal WSGI application. For example if you want to use one of the874middlewares from the Werkzeug package to work around bugs in lighttpd, you875can do it like this::876877 from werkzeug.contrib.fixers import LighttpdCGIRootFix878 app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)879Merge pull request #1376 from KWinston/masterMarkus Unterwaditzerbefore adoptionec5811d
lines 880–888why, one step back880Using Flask Extensions881----------------------882883Extensions are packages that help you accomplish common tasks. For884example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple885and easy to use with Flask.886887For more on Flask extensions, have a look at :ref:`extensions`.888Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d
lines 889–891why, one step back889Deploying to a Web Server890-------------------------891Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894
line 892why, one step back892Ready to deploy your new Flask app? Go to :ref:`deployment`.