quickstart.rst
This file
Path
docs/quickstart.rst
879 lines · 32.3 KiB
Last changed by
Merge pull request #1318 from cerivera/masterMarkus Unterwaditzerbefore adoptione3ba459
History of this fileTake it
The walk stopped after 200 commits: lines older than ff59db1 point at it.
Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
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 pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
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 pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
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 pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
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 pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 62–70why, 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.70Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
lines 71–73why, one step back71 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::Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
line 74why, one step back74Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
line 75why, one step back75 flask -a hello run --host=0.0.0.0Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 76–78why, one step back7677 This tells your operating system to listen on all public IPs.78Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894
line 79why, one step back79Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
lines 80–81why, one step back80What to do if the Server does not Start81---------------------------------------Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
line 82why, one step back82Merge 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,Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
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, andUpdated docs for click supportArmin Ronacherbefore adoptione9d1fc4
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 -mUpdated docs for click supportArmin Ronacherbefore adoptione9d1fc4
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. InUpdated docs for click supportArmin Ronacherbefore adoptione9d1fc4
lines 109–115why, 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.115Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 116–120why, one step back116.. _debug-mode:117118Debug Mode119----------120Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 121why, one step back121The :command:`flask` script is nice to start a local development server, butUpdated docs for click supportArmin Ronacherbefore adoptione9d1fc4
lines 122–125why, one step back122you would have to restart it manually after each change to your code.123That is not very nice and Flask can do better. If you enable debug124support the server will reload itself on code changes, and it will also125provide you with a helpful debugger if things go wrong.Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
line 126why, one step back126Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
line 127why, one step back127There are different ways to enable the debug mode. The most obvious oneMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 128why, one step back128is the :option:`--debug` parameter to the :command:`flask` command::Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
line 129why, one step back129Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
line 130why, one step back130 flask --debug -a hello runMerge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
line 131why, one step back131Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
line 132why, one step back132This does the following things:Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
line 133why, one step back133Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
lines 134–136why, one step back1341. it activates the debugger1352. it activates the automatic reloader1363. it enables the debug mode on the Flask application.Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
line 137why, one step back137Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
line 138why, one step back138There are more parameters that are explained in the :ref:`server` docs.Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 139–174why, one step back139140.. admonition:: Attention141142 Even though the interactive debugger does not work in forking environments143 (which makes it nearly impossible to use on production servers), it still144 allows the execution of arbitrary code. This makes it a major security risk145 and therefore it **must never be used on production machines**.146147Screenshot of the debugger in action:148149.. image:: _static/debugger.png150 :align: center151 :class: screenshot152 :alt: screenshot of debugger in action153154Have another debugger in mind? See :ref:`working-with-debuggers`.155156157Routing158-------159160Modern web applications have beautiful URLs. This helps people remember161the URLs, which is especially handy for applications that are used from162mobile devices with slower network connections. If the user can directly163go to the desired page without having to hit the index page it is more164likely they will like the page and come back next time.165166As you have seen above, the :meth:`~flask.Flask.route` decorator is used to167bind a function to a URL. Here are some basic examples::168169 @app.route('/')170 def index():171 return 'Index Page'172173 @app.route('/hello')174 def hello():Merge pull request #1318 from cerivera/masterMarkus Unterwaditzerbefore adoptione3ba459
line 175why, one step back175 return 'Hello, World'Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 176–199why, one step back176177But there is more to it! You can make certain parts of the URL dynamic and178attach multiple rules to a function.179180Variable Rules181``````````````182183To add variable parts to a URL you can mark these special sections as184``<variable_name>``. Such a part is then passed as a keyword argument to your185function. Optionally a converter can be used by specifying a rule with186``<converter:variable_name>``. Here are some nice examples::187188 @app.route('/user/<username>')189 def show_user_profile(username):190 # show the user profile for that user191 return 'User %s' % username192193 @app.route('/post/<int:post_id>')194 def show_post(post_id):195 # show the post with the given id, the id is an integer196 return 'Post %d' % post_id197198The following converters exist:199Merge pull request #1183 from k-funk/patch-1Markus Unterwaditzerbefore adoption2401e21
lines 200–201why, one step back200=========== ===============================================201`string` accepts any text without a slash (the default)Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 202–204why, one step back202`int` accepts integers203`float` like `int` but for floating point values204`path` like the default but also accepts slashesMerge pull request #1183 from k-funk/patch-1Markus Unterwaditzerbefore adoption2401e21
line 205why, one step back205=========== ===============================================Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 206–225why, one step back206207.. admonition:: Unique URLs / Redirection Behavior208209 Flask's URL rules are based on Werkzeug's routing module. The idea210 behind that module is to ensure beautiful and unique URLs based on211 precedents laid down by Apache and earlier HTTP servers.212213 Take these two rules::214215 @app.route('/projects/')216 def projects():217 return 'The project page'218219 @app.route('/about')220 def about():221 return 'The about page'222223 Though they look rather similar, they differ in their use of the trailing224 slash in the URL *definition*. In the first case, the canonical URL for the225 `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 226why, one step back226 a folder on a filesystem. Accessing it without a trailing slash will causeMerge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 227–277why, one step back227 Flask to redirect to the canonical URL with the trailing slash.228229 In the second case, however, the URL is defined without a trailing slash,230 rather like the pathname of a file on UNIX-like systems. Accessing the URL231 with a trailing slash will produce a 404 "Not Found" error.232233 This behavior allows relative URLs to continue working even if the trailing234 slash is omitted, consistent with how Apache and other servers work. Also,235 the URLs will stay unique, which helps search engines avoid indexing the236 same page twice.237238239.. _url-building:240241URL Building242````````````243244If it can match URLs, can Flask also generate them? Of course it can. To245build a URL to a specific function you can use the :func:`~flask.url_for`246function. It accepts the name of the function as first argument and a number247of keyword arguments, each corresponding to the variable part of the URL rule.248Unknown variable parts are appended to the URL as query parameters. Here are249some examples:250251>>> from flask import Flask, url_for252>>> app = Flask(__name__)253>>> @app.route('/')254... def index(): pass255...256>>> @app.route('/login')257... def login(): pass258...259>>> @app.route('/user/<username>')260... def profile(username): pass261...262>>> with app.test_request_context():263... print url_for('index')264... print url_for('login')265... print url_for('login', next='/')266... print url_for('profile', username='John Doe')267...268/269/login270/login?next=/271/user/John%20Doe272273(This also uses the :meth:`~flask.Flask.test_request_context` method, explained274below. It tells Flask to behave as though it is handling a request, even275though we are interacting with it through a Python shell. Have a look at the276explanation below. :ref:`context-locals`).277Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
lines 278–280why, one step back278Why would you want to build URLs using the URL reversing function279:func:`~flask.url_for` instead of hard-coding them into your templates?280There are three good reasons for this:Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 281–295why, one step back2812821. Reversing is often more descriptive than hard-coding the URLs. More283 importantly, it allows you to change URLs in one go, without having to284 remember to change URLs all over the place.2852. URL building will handle escaping of special characters and Unicode286 data transparently for you, so you don't have to deal with them.2873. If your application is placed outside the URL root (say, in288 ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will handle289 that properly for you.290291292HTTP Methods293````````````294295HTTP (the protocol web applications are speaking) knows different methods forMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 296why, one step back296accessing URLs. By default, a route only answers to ``GET`` requests, but thatMerge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 297–299why, one step back297can be changed by providing the `methods` argument to the298:meth:`~flask.Flask.route` decorator. Here are some examples::299Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption36e86be
lines 300–301why, one step back300 from flask import request301Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 302–308why, one step back302 @app.route('/login', methods=['GET', 'POST'])303 def login():304 if request.method == 'POST':305 do_the_login()306 else:307 show_the_login_form()308Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
lines 309–310why, one step back309If ``GET`` is present, ``HEAD`` will be added automatically for you. You310don't have to deal with that. It will also make sure that ``HEAD`` requestsMerge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 311–312why, one step back311are handled as the `HTTP RFC`_ (the document describing the HTTP312protocol) demands, so you can completely ignore that part of the HTTPMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 313why, one step back313specification. Likewise, as of Flask 0.6, ``OPTIONS`` is implemented for youMerge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 314–322why, one step back314automatically as well.315316You have no idea what an HTTP method is? Worry not, here is a quick317introduction to HTTP methods and why they matter:318319The HTTP method (also often called "the verb") tells the server what the320clients wants to *do* with the requested page. The following methods are321very common:322Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 323why, one step back323``GET``Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 324–326why, one step back324 The browser tells the server to just *get* the information stored on325 that page and send it. This is probably the most common method.326Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 327why, one step back327``HEAD``Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 328–329why, one step back328 The browser tells the server to get the information, but it is only329 interested in the *headers*, not the content of the page. AnMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 330why, one step back330 application is supposed to handle that as if a ``GET`` request wasMerge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 331–334why, one step back331 received but to not deliver the actual content. In Flask you don't332 have to deal with that at all, the underlying Werkzeug library handles333 that for you.334Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 335why, one step back335``POST``Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 336–340why, one step back336 The browser tells the server that it wants to *post* some new337 information to that URL and that the server must ensure the data is338 stored and only stored once. This is how HTML forms usually339 transmit data to the server.340Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
lines 341–342why, one step back341``PUT``342 Similar to ``POST`` but the server might trigger the store procedureMerge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 343–347why, one step back343 multiple times by overwriting the old values more than once. Now you344 might be asking why this is useful, but there are some good reasons345 to do it this way. Consider that the connection is lost during346 transmission: in this situation a system between the browser and the347 server might receive the request safely a second time without breakingMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 348why, one step back348 things. With ``POST`` that would not be possible because it must onlyMerge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 349–350why, one step back349 be triggered once.350Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 351why, one step back351``DELETE``Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 352–353why, one step back352 Remove the information at the given location.353Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 354why, one step back354``OPTIONS``Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 355–359why, one step back355 Provides a quick way for a client to figure out which methods are356 supported by this URL. Starting with Flask 0.6, this is implemented357 for you automatically.358359Now 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 360why, one step back360form can submit to the server are ``GET`` and ``POST``. But with JavaScriptMerge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 361–373why, one step back361and future HTML standards you can use the other methods as well. Furthermore362HTTP has become quite popular lately and browsers are no longer the only363clients that are using HTTP. For instance, many revision control systems364use it.365366.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt367368Static Files369------------370371Dynamic web applications also need static files. That's usually where372the CSS and JavaScript files are coming from. Ideally your web server is373configured to serve them for you, but during development Flask can do thatMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
lines 374–375why, one step back374as well. Just create a folder called :file:`static` in your package or next to375your module and it will be available at ``/static`` on the application.Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 376–380why, one step back376377To generate URLs for static files, use the special ``'static'`` endpoint name::378379 url_for('static', filename='style.css')380Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 381why, one step back381The file has to be stored on the filesystem as :file:`static/style.css`.Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 382–388why, one step back382383Rendering Templates384-------------------385386Generating HTML from within Python is not fun, and actually pretty387cumbersome because you have to do the HTML escaping on your own to keep388the application secure. Because of that Flask configures the `Jinja2Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption67e4d3e
line 389why, one step back389<http://jinja.pocoo.org/>`_ template engine for you automatically.Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 390–402why, one step back390391To render a template you can use the :func:`~flask.render_template`392method. All you have to do is provide the name of the template and the393variables you want to pass to the template engine as keyword arguments.394Here's a simple example of how to render a template::395396 from flask import render_template397398 @app.route('/hello/')399 @app.route('/hello/<name>')400 def hello(name=None):401 return render_template('hello.html', name=name)402Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 403why, one step back403Flask will look for templates in the :file:`templates` folder. So if yourMerge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 404–421why, one step back404application is a module, this folder is next to that module, if it's a405package it's actually inside your package:406407**Case 1**: a module::408409 /application.py410 /templates411 /hello.html412413**Case 2**: a package::414415 /application416 /__init__.py417 /templates418 /hello.html419420For templates you can use the full power of Jinja2 templates. Head over421to the official `Jinja2 Template DocumentationMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption67e4d3e
line 422why, one step back422<http://jinja.pocoo.org/docs/templates>`_ for more information.Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 423–432why, one step back423424Here is an example template:425426.. sourcecode:: html+jinja427428 <!doctype html>429 <title>Hello from Flask</title>430 {% if name %}431 <h1>Hello {{ name }}!</h1>432 {% else %}Merge pull request #1318 from cerivera/masterMarkus Unterwaditzerbefore adoptione3ba459
line 433why, one step back433 <h1>Hello, World!</h1>Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 434–477why, one step back434 {% endif %}435436Inside templates you also have access to the :class:`~flask.request`,437:class:`~flask.session` and :class:`~flask.g` [#]_ objects438as well as the :func:`~flask.get_flashed_messages` function.439440Templates are especially useful if inheritance is used. If you want to441know how that works, head over to the :ref:`template-inheritance` pattern442documentation. Basically template inheritance makes it possible to keep443certain elements on each page (like header, navigation and footer).444445Automatic escaping is enabled, so if `name` contains HTML it will be escaped446automatically. If you can trust a variable and you know that it will be447safe HTML (for example because it came from a module that converts wiki448markup to HTML) you can mark it as safe by using the449:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the450template. Head over to the Jinja 2 documentation for more examples.451452Here is a basic introduction to how the :class:`~jinja2.Markup` class works:453454>>> from flask import Markup455>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'456Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')457>>> Markup.escape('<blink>hacker</blink>')458Markup(u'<blink>hacker</blink>')459>>> Markup('<em>Marked up</em> » HTML').striptags()460u'Marked up \xbb HTML'461462.. versionchanged:: 0.5463464 Autoescaping is no longer enabled for all templates. The following465 extensions for templates trigger autoescaping: ``.html``, ``.htm``,466 ``.xml``, ``.xhtml``. Templates loaded from a string will have467 autoescaping disabled.468469.. [#] Unsure what that :class:`~flask.g` object is? It's something in which470 you can store information for your own needs, check the documentation of471 that object (:class:`~flask.g`) and the :ref:`sqlite3` for more472 information.473474475Accessing Request Data476----------------------477Merge pull request #1299 from sateeshkumarb/patch-1Markus Unterwaditzerbefore adoption4fde65e
line 478why, one step back478For web applications it's crucial to react to the data a client sends toMerge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 479–513why, one step back479the server. In Flask this information is provided by the global480:class:`~flask.request` object. If you have some experience with Python481you might be wondering how that object can be global and how Flask482manages to still be threadsafe. The answer is context locals:483484485.. _context-locals:486487Context Locals488``````````````489490.. admonition:: Insider Information491492 If you want to understand how that works and how you can implement493 tests with context locals, read this section, otherwise just skip it.494495Certain objects in Flask are global objects, but not of the usual kind.496These objects are actually proxies to objects that are local to a specific497context. What a mouthful. But that is actually quite easy to understand.498499Imagine the context being the handling thread. A request comes in and the500web server decides to spawn a new thread (or something else, the501underlying object is capable of dealing with concurrency systems other502than threads). When Flask starts its internal request handling it503figures out that the current thread is the active context and binds the504current application and the WSGI environments to that context (thread).505It does that in an intelligent way so that one application can invoke another506application without breaking.507508So what does this mean to you? Basically you can completely ignore that509this is the case unless you are doing something like unit testing. You510will notice that code which depends on a request object will suddenly break511because there is no request object. The solution is creating a request512object yourself and binding it to the context. The easiest solution for513unit testing is to use the :meth:`~flask.Flask.test_request_context`Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 514why, one step back514context manager. In combination with the ``with`` statement it will bind aMerge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 515–544why, one step back515test request so that you can interact with it. Here is an example::516517 from flask import request518519 with app.test_request_context('/hello', method='POST'):520 # now you can do something with the request until the521 # end of the with block, such as basic assertions:522 assert request.path == '/hello'523 assert request.method == 'POST'524525The other possibility is passing a whole WSGI environment to the526:meth:`~flask.Flask.request_context` method::527528 from flask import request529530 with app.request_context(environ):531 assert request.method == 'POST'532533The Request Object534``````````````````535536The request object is documented in the API section and we will not cover537it here in detail (see :class:`~flask.request`). Here is a broad overview of538some of the most common operations. First of all you have to import it from539the `flask` module::540541 from flask import request542543The current request method is available by using the544:attr:`~flask.request.method` attribute. To access form data (dataMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 545why, one step back545transmitted in a ``POST`` or ``PUT`` request) you can use theMerge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 546–573why, one step back546:attr:`~flask.request.form` attribute. Here is a full example of the two547attributes mentioned above::548549 @app.route('/login', methods=['POST', 'GET'])550 def login():551 error = None552 if request.method == 'POST':553 if valid_login(request.form['username'],554 request.form['password']):555 return log_the_user_in(request.form['username'])556 else:557 error = 'Invalid username/password'558 # the code below is executed if the request method559 # was GET or the credentials were invalid560 return render_template('login.html', error=error)561562What happens if the key does not exist in the `form` attribute? In that563case a special :exc:`KeyError` is raised. You can catch it like a564standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request565error page is shown instead. So for many situations you don't have to566deal with that problem.567568To access parameters submitted in the URL (``?key=value``) you can use the569:attr:`~flask.request.args` attribute::570571 searchword = request.args.get('key', '')572573We recommend accessing URL parameters with `get` or by catching theMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 574why, one step back574:exc:`KeyError` because users might change the URL and presenting them a 400Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 575–711why, one step back575bad request page in that case is not user friendly.576577For a full list of methods and attributes of the request object, head over578to the :class:`~flask.request` documentation.579580581File Uploads582````````````583584You can handle uploaded files with Flask easily. Just make sure not to585forget to set the ``enctype="multipart/form-data"`` attribute on your HTML586form, otherwise the browser will not transmit your files at all.587588Uploaded files are stored in memory or at a temporary location on the589filesystem. You can access those files by looking at the590:attr:`~flask.request.files` attribute on the request object. Each591uploaded file is stored in that dictionary. It behaves just like a592standard Python :class:`file` object, but it also has a593:meth:`~werkzeug.datastructures.FileStorage.save` method that allows you to store that594file on the filesystem of the server. Here is a simple example showing how595that works::596597 from flask import request598599 @app.route('/upload', methods=['GET', 'POST'])600 def upload_file():601 if request.method == 'POST':602 f = request.files['the_file']603 f.save('/var/www/uploads/uploaded_file.txt')604 ...605606If you want to know how the file was named on the client before it was607uploaded to your application, you can access the608:attr:`~werkzeug.datastructures.FileStorage.filename` attribute. However please keep in609mind that this value can be forged so never ever trust that value. If you610want to use the filename of the client to store the file on the server,611pass it through the :func:`~werkzeug.utils.secure_filename` function that612Werkzeug provides for you::613614 from flask import request615 from werkzeug import secure_filename616617 @app.route('/upload', methods=['GET', 'POST'])618 def upload_file():619 if request.method == 'POST':620 f = request.files['the_file']621 f.save('/var/www/uploads/' + secure_filename(f.filename))622 ...623624For some better examples, checkout the :ref:`uploading-files` pattern.625626Cookies627```````628629To access cookies you can use the :attr:`~flask.Request.cookies`630attribute. To set cookies you can use the631:attr:`~flask.Response.set_cookie` method of response objects. The632:attr:`~flask.Request.cookies` attribute of request objects is a633dictionary with all the cookies the client transmits. If you want to use634sessions, do not use the cookies directly but instead use the635:ref:`sessions` in Flask that add some security on top of cookies for you.636637Reading cookies::638639 from flask import request640641 @app.route('/')642 def index():643 username = request.cookies.get('username')644 # use cookies.get(key) instead of cookies[key] to not get a645 # KeyError if the cookie is missing.646647Storing cookies::648649 from flask import make_response650651 @app.route('/')652 def index():653 resp = make_response(render_template(...))654 resp.set_cookie('username', 'the username')655 return resp656657Note that cookies are set on response objects. Since you normally658just return strings from the view functions Flask will convert them into659response objects for you. If you explicitly want to do that you can use660the :meth:`~flask.make_response` function and then modify it.661662Sometimes you might want to set a cookie at a point where the response663object does not exist yet. This is possible by utilizing the664:ref:`deferred-callbacks` pattern.665666For this also see :ref:`about-responses`.667668Redirects and Errors669--------------------670671To redirect a user to another endpoint, use the :func:`~flask.redirect`672function; to abort a request early with an error code, use the673:func:`~flask.abort` function::674675 from flask import abort, redirect, url_for676677 @app.route('/')678 def index():679 return redirect(url_for('login'))680681 @app.route('/login')682 def login():683 abort(401)684 this_is_never_executed()685686This is a rather pointless example because a user will be redirected from687the index to a page they cannot access (401 means access denied) but it688shows how that works.689690By default a black and white error page is shown for each error code. If691you want to customize the error page, you can use the692:meth:`~flask.Flask.errorhandler` decorator::693694 from flask import render_template695696 @app.errorhandler(404)697 def page_not_found(error):698 return render_template('page_not_found.html'), 404699700Note the ``404`` after the :func:`~flask.render_template` call. This701tells Flask that the status code of that page should be 404 which means702not found. By default 200 is assumed which translates to: all went well.703704.. _about-responses:705706About Responses707---------------708709The return value from a view function is automatically converted into a710response object for you. If the return value is a string it's converted711into 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 712why, one step back712status code and a :mimetype:`text/html` mimetype. The logic that Flask applies toMerge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 713–720why, one step back713converting return values into response objects is as follows:7147151. If a response object of the correct type is returned it's directly716 returned from the view.7172. If it's a string, a response object is created with that data and the718 default parameters.7193. If a tuple is returned the items in the tuple can provide extra720 information. Such tuples have to be in the form ``(response, status,Merge pull request #938 from ahlen/response-with-headers-without-statusArmin Ronacherbefore adoptionc9bf907
lines 721–723why, one step back721 headers)`` or ``(response, headers)`` where at least one item has722 to be in the tuple. The `status` value will override the status code723 and `headers` can be a list or dictionary of additional header values.Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 724–859why, one step back7244. If none of that works, Flask will assume the return value is a725 valid WSGI application and convert that into a response object.726727If you want to get hold of the resulting response object inside the view728you can use the :func:`~flask.make_response` function.729730Imagine you have a view like this:731732.. sourcecode:: python733734 @app.errorhandler(404)735 def not_found(error):736 return render_template('error.html'), 404737738You just need to wrap the return expression with739:func:`~flask.make_response` and get the response object to modify it, then740return it:741742.. sourcecode:: python743744 @app.errorhandler(404)745 def not_found(error):746 resp = make_response(render_template('error.html'), 404)747 resp.headers['X-Something'] = 'A value'748 return resp749750.. _sessions:751752Sessions753--------754755In addition to the request object there is also a second object called756:class:`~flask.session` which allows you to store information specific to a757user from one request to the next. This is implemented on top of cookies758for you and signs the cookies cryptographically. What this means is that759the user could look at the contents of your cookie but not modify it,760unless they know the secret key used for signing.761762In order to use sessions you have to set a secret key. Here is how763sessions work::764765 from flask import Flask, session, redirect, url_for, escape, request766767 app = Flask(__name__)768769 @app.route('/')770 def index():771 if 'username' in session:772 return 'Logged in as %s' % escape(session['username'])773 return 'You are not logged in'774775 @app.route('/login', methods=['GET', 'POST'])776 def login():777 if request.method == 'POST':778 session['username'] = request.form['username']779 return redirect(url_for('index'))780 return '''781 <form action="" method="post">782 <p><input type=text name=username>783 <p><input type=submit value=Login>784 </form>785 '''786787 @app.route('/logout')788 def logout():789 # remove the username from the session if it's there790 session.pop('username', None)791 return redirect(url_for('index'))792793 # set the secret key. keep this really secret:794 app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'795796The :func:`~flask.escape` mentioned here does escaping for you if you are797not using the template engine (as in this example).798799.. admonition:: How to generate good secret keys800801 The problem with random is that it's hard to judge what is truly random. And802 a secret key should be as random as possible. Your operating system803 has ways to generate pretty random stuff based on a cryptographic804 random generator which can be used to get such a key:805806 >>> import os807 >>> os.urandom(24)808 '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'809810 Just take that thing and copy/paste it into your code and you're done.811812A note on cookie-based sessions: Flask will take the values you put into the813session object and serialize them into a cookie. If you are finding some814values do not persist across requests, cookies are indeed enabled, and you are815not getting a clear error message, check the size of the cookie in your page816responses compared to the size supported by web browsers.817818819Message Flashing820----------------821822Good applications and user interfaces are all about feedback. If the user823does not get enough feedback they will probably end up hating the824application. Flask provides a really simple way to give feedback to a825user with the flashing system. The flashing system basically makes it826possible to record a message at the end of a request and access it on the next827(and only the next) request. This is usually combined with a layout828template to expose the message.829830To flash a message use the :func:`~flask.flash` method, to get hold of the831messages you can use :func:`~flask.get_flashed_messages` which is also832available in the templates. Check out the :ref:`message-flashing-pattern`833for a full example.834835Logging836-------837838.. versionadded:: 0.3839840Sometimes you might be in a situation where you deal with data that841should be correct, but actually is not. For example you may have some client-side842code that sends an HTTP request to the server but it's obviously843malformed. This might be caused by a user tampering with the data, or the844client code failing. Most of the time it's okay to reply with ``400 Bad845Request`` in that situation, but sometimes that won't do and the code has846to continue working.847848You may still want to log that something fishy happened. This is where849loggers come in handy. As of Flask 0.3 a logger is preconfigured for you850to use.851852Here are some example log calls::853854 app.logger.debug('A value for debugging')855 app.logger.warning('A warning occurred (%d apples)', 42)856 app.logger.error('An error occurred')857858The attached :attr:`~flask.Flask.logger` is a standard logging859:class:`~logging.Logger`, so head over to the official `loggingMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption67e4d3e
line 860why, one step back860documentation <https://docs.python.org/library/logging.html>`_ for moreMerge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 861–862why, one step back861information.862Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894
lines 863–864why, one step back863Read more on :ref:`application-errors`.864Merge pull request #858 from svieira/patch-2Daniel Neuhäuserbefore adoptionff59db1
lines 865–878why, one step back865Hooking in WSGI Middlewares866---------------------------867868If you want to add a WSGI middleware to your application you can wrap the869internal WSGI application. For example if you want to use one of the870middlewares from the Werkzeug package to work around bugs in lighttpd, you871can do it like this::872873 from werkzeug.contrib.fixers import LighttpdCGIRootFix874 app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)875876Deploying to a Web Server877-------------------------878Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894
line 879why, one step back879Ready to deploy your new Flask app? Go to :ref:`deployment`.