quickstart.rst
This file
Path
docs/quickstart.rst
890 lines · 32.8 KiB
Last changed by
clean up code formatting in some docsDavid Lordbefore adoption1928f28
History of this fileTake it
The walk stopped after 200 commits: lines older than 86e8267 point at it.
Merge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
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 #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 30–39why, 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.39quickstart: Remove reference to `python hello.py`Markus Unterwaditzerbefore adoptionf91aea2
lines 40–42why, one step back40Just save it as :file:`hello.py` or something similar. Make sure to not call41your application :file:`flask.py` because this would conflict with Flask42itself.Merge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 43–44why, one step back4344To 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 needUpdate docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
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 #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
line 48why, one step back48Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
lines 49–50why, one step back49 $ export FLASK_APP=hello.py50 $ flask runMerge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 51–52why, one step back51 * 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 #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
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`::Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
lines 56–58why, one step back5657 $ export FLASK_APP=hello.py58 $ python -m flask runMerge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 59–80why, one step back59 * 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::80Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
line 81why, one step back81 flask run --host=0.0.0.0Merge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 82–88why, one step back8283 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 #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 90–95why, 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````````````````````95Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
line 96why, one step back96Versions of Flask older than 0.11 use to have different ways to start theMerge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
line 97why, one step back97application. 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 #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
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```````````````````104clean up code formatting in some docsDavid Lordbefore adoption1928f28
line 105why, one step back105The ``-a`` argument to :command:`flask` is the name of the module toUpdate docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
lines 106–108why, one step back106import. In case that module is incorrectly named you will get an import107error upon start (or if debug is enabled when you navigate to the108application). It will tell you what it tried to import and why it failed.Merge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 109–117why, one step back109110The most common reason is a typo or because you did not actually create an111``app`` object.112113.. _debug-mode:114115Debug Mode116----------117Fix #1195Markus Unterwaditzerbefore adoption66b4ea9
lines 118–119why, one step back118(Want to just log errors and stack traces? See :ref:`application-errors`)119Merge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 120–125why, one step back120The :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 variableUpdate docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
line 127why, one step back127before running the server::Merge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
line 128why, one step back128Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
lines 129–131why, one step back129 $ 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 #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 133–204why, 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 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():177 return 'Hello, World'178179But 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:201202=========== ===============================================203`string` accepts any text without a slash (the default)204`int` accepts integersclean up code formatting in some docsDavid Lordbefore adoption1928f28
line 205why, one step back205`float` like ``int`` but for floating point valuesMerge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
line 206why, one step back206`path` like the default but also accepts slashesAdd two missing converters for flask in the docslord63before adoptione0a8fd3
lines 207–208why, one step back207`any` matches one of the items provided208`uuid` accepts UUID stringsMerge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 209–228why, one step back209=========== ===============================================210211.. admonition:: Unique URLs / Redirection Behavior212213 Flask's URL rules are based on Werkzeug's routing module. The idea214 behind that module is to ensure beautiful and unique URLs based on215 precedents laid down by Apache and earlier HTTP servers.216217 Take these two rules::218219 @app.route('/projects/')220 def projects():221 return 'The project page'222223 @app.route('/about')224 def about():225 return 'The about page'226227 Though they look rather similar, they differ in their use of the trailing228 slash in the URL *definition*. In the first case, the canonical URL for theclean up code formatting in some docsDavid Lordbefore adoption1928f28
line 229why, one step back229 ``projects`` endpoint has a trailing slash. In that sense, it is similar toMerge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 230–252why, one step back230 a folder on a filesystem. Accessing it without a trailing slash will cause231 Flask to redirect to the canonical URL with the trailing slash.232233 In the second case, however, the URL is defined without a trailing slash,234 rather like the pathname of a file on UNIX-like systems. Accessing the URL235 with a trailing slash will produce a 404 "Not Found" error.236237 This behavior allows relative URLs to continue working even if the trailing238 slash is omitted, consistent with how Apache and other servers work. Also,239 the URLs will stay unique, which helps search engines avoid indexing the240 same page twice.241242243.. _url-building:244245URL Building246````````````247248If it can match URLs, can Flask also generate them? Of course it can. To249build a URL to a specific function you can use the :func:`~flask.url_for`250function. It accepts the name of the function as first argument and a number251of keyword arguments, each corresponding to the variable part of the URL rule.252Unknown variable parts are appended to the URL as query parameters. Here areclean up code formatting in some docsDavid Lordbefore adoption1928f28
line 253why, one step back253some examples::Merge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
line 254why, one step back254clean up code formatting in some docsDavid Lordbefore adoption1928f28
lines 255–275why, one step back255 >>> from flask import Flask, url_for256 >>> app = Flask(__name__)257 >>> @app.route('/')258 ... def index(): pass259 ...260 >>> @app.route('/login')261 ... def login(): pass262 ...263 >>> @app.route('/user/<username>')264 ... def profile(username): pass265 ...266 >>> with app.test_request_context():267 ... print url_for('index')268 ... print url_for('login')269 ... print url_for('login', next='/')270 ... print url_for('profile', username='John Doe')271 ...272 /273 /login274 /login?next=/275 /user/John%20DoeMerge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 276–290why, one step back276277(This also uses the :meth:`~flask.Flask.test_request_context` method, explained278below. It tells Flask to behave as though it is handling a request, even279though we are interacting with it through a Python shell. Have a look at the280explanation below. :ref:`context-locals`).281282Why would you want to build URLs using the URL reversing function283:func:`~flask.url_for` instead of hard-coding them into your templates?284There are three good reasons for this:2852861. Reversing is often more descriptive than hard-coding the URLs. More287 importantly, it allows you to change URLs in one go, without having to288 remember to change URLs all over the place.2892. URL building will handle escaping of special characters and Unicode290 data transparently for you, so you don't have to deal with them.clean up code formatting in some docsDavid Lordbefore adoption1928f28
lines 291–292why, one step back2913. If your application is placed outside the URL root - say, in292 ``/myapplication`` instead of ``/`` - :func:`~flask.url_for` will handleMerge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 293–300why, one step back293 that properly for you.294295296HTTP Methods297````````````298299HTTP (the protocol web applications are speaking) knows different methods for300accessing URLs. By default, a route only answers to ``GET`` requests, but thatclean up code formatting in some docsDavid Lordbefore adoption1928f28
line 301why, one step back301can be changed by providing the ``methods`` argument to theMerge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 302–323why, one step back302:meth:`~flask.Flask.route` decorator. Here are some examples::303304 from flask import request305306 @app.route('/login', methods=['GET', 'POST'])307 def login():308 if request.method == 'POST':309 do_the_login()310 else:311 show_the_login_form()312313If ``GET`` is present, ``HEAD`` will be added automatically for you. You314don't have to deal with that. It will also make sure that ``HEAD`` requests315are handled as the `HTTP RFC`_ (the document describing the HTTP316protocol) demands, so you can completely ignore that part of the HTTP317specification. Likewise, as of Flask 0.6, ``OPTIONS`` is implemented for you318automatically as well.319320You have no idea what an HTTP method is? Worry not, here is a quick321introduction to HTTP methods and why they matter:322323The HTTP method (also often called "the verb") tells the server what theminor revision of documentation.bagrattebefore adoption9a80fe6
line 324why, one step back324client wants to *do* with the requested page. The following methods areMerge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 325–448why, one step back325very common:326327``GET``328 The browser tells the server to just *get* the information stored on329 that page and send it. This is probably the most common method.330331``HEAD``332 The browser tells the server to get the information, but it is only333 interested in the *headers*, not the content of the page. An334 application is supposed to handle that as if a ``GET`` request was335 received but to not deliver the actual content. In Flask you don't336 have to deal with that at all, the underlying Werkzeug library handles337 that for you.338339``POST``340 The browser tells the server that it wants to *post* some new341 information to that URL and that the server must ensure the data is342 stored and only stored once. This is how HTML forms usually343 transmit data to the server.344345``PUT``346 Similar to ``POST`` but the server might trigger the store procedure347 multiple times by overwriting the old values more than once. Now you348 might be asking why this is useful, but there are some good reasons349 to do it this way. Consider that the connection is lost during350 transmission: in this situation a system between the browser and the351 server might receive the request safely a second time without breaking352 things. With ``POST`` that would not be possible because it must only353 be triggered once.354355``DELETE``356 Remove the information at the given location.357358``OPTIONS``359 Provides a quick way for a client to figure out which methods are360 supported by this URL. Starting with Flask 0.6, this is implemented361 for you automatically.362363Now the interesting part is that in HTML4 and XHTML1, the only methods a364form can submit to the server are ``GET`` and ``POST``. But with JavaScript365and future HTML standards you can use the other methods as well. Furthermore366HTTP has become quite popular lately and browsers are no longer the only367clients that are using HTTP. For instance, many revision control systems368use it.369370.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt371372Static Files373------------374375Dynamic web applications also need static files. That's usually where376the CSS and JavaScript files are coming from. Ideally your web server is377configured to serve them for you, but during development Flask can do that378as well. Just create a folder called :file:`static` in your package or next to379your module and it will be available at ``/static`` on the application.380381To generate URLs for static files, use the special ``'static'`` endpoint name::382383 url_for('static', filename='style.css')384385The file has to be stored on the filesystem as :file:`static/style.css`.386387Rendering Templates388-------------------389390Generating HTML from within Python is not fun, and actually pretty391cumbersome because you have to do the HTML escaping on your own to keep392the application secure. Because of that Flask configures the `Jinja2393<http://jinja.pocoo.org/>`_ template engine for you automatically.394395To render a template you can use the :func:`~flask.render_template`396method. All you have to do is provide the name of the template and the397variables you want to pass to the template engine as keyword arguments.398Here's a simple example of how to render a template::399400 from flask import render_template401402 @app.route('/hello/')403 @app.route('/hello/<name>')404 def hello(name=None):405 return render_template('hello.html', name=name)406407Flask will look for templates in the :file:`templates` folder. So if your408application is a module, this folder is next to that module, if it's a409package it's actually inside your package:410411**Case 1**: a module::412413 /application.py414 /templates415 /hello.html416417**Case 2**: a package::418419 /application420 /__init__.py421 /templates422 /hello.html423424For templates you can use the full power of Jinja2 templates. Head over425to the official `Jinja2 Template Documentation426<http://jinja.pocoo.org/docs/templates>`_ for more information.427428Here is an example template:429430.. sourcecode:: html+jinja431432 <!doctype html>433 <title>Hello from Flask</title>434 {% if name %}435 <h1>Hello {{ name }}!</h1>436 {% else %}437 <h1>Hello, World!</h1>438 {% endif %}439440Inside templates you also have access to the :class:`~flask.request`,441:class:`~flask.session` and :class:`~flask.g` [#]_ objects442as well as the :func:`~flask.get_flashed_messages` function.443444Templates are especially useful if inheritance is used. If you want to445know how that works, head over to the :ref:`template-inheritance` pattern446documentation. Basically template inheritance makes it possible to keep447certain elements on each page (like header, navigation and footer).448clean up code formatting in some docsDavid Lordbefore adoption1928f28
line 449why, one step back449Automatic escaping is enabled, so if ``name`` contains HTML it will be escapedMerge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 450–455why, one step back450automatically. If you can trust a variable and you know that it will be451safe HTML (for example because it came from a module that converts wiki452markup to HTML) you can mark it as safe by using the453:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the454template. Head over to the Jinja 2 documentation for more examples.455clean up code formatting in some docsDavid Lordbefore adoption1928f28
line 456why, one step back456Here is a basic introduction to how the :class:`~jinja2.Markup` class works::Merge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
line 457why, one step back457clean up code formatting in some docsDavid Lordbefore adoption1928f28
lines 458–464why, one step back458 >>> from flask import Markup459 >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'460 Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')461 >>> Markup.escape('<blink>hacker</blink>')462 Markup(u'<blink>hacker</blink>')463 >>> Markup('<em>Marked up</em> » HTML').striptags()464 u'Marked up \xbb HTML'Merge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 465–542why, one step back465466.. versionchanged:: 0.5467468 Autoescaping is no longer enabled for all templates. The following469 extensions for templates trigger autoescaping: ``.html``, ``.htm``,470 ``.xml``, ``.xhtml``. Templates loaded from a string will have471 autoescaping disabled.472473.. [#] Unsure what that :class:`~flask.g` object is? It's something in which474 you can store information for your own needs, check the documentation of475 that object (:class:`~flask.g`) and the :ref:`sqlite3` for more476 information.477478479Accessing Request Data480----------------------481482For web applications it's crucial to react to the data a client sends to483the server. In Flask this information is provided by the global484:class:`~flask.request` object. If you have some experience with Python485you might be wondering how that object can be global and how Flask486manages to still be threadsafe. The answer is context locals:487488489.. _context-locals:490491Context Locals492``````````````493494.. admonition:: Insider Information495496 If you want to understand how that works and how you can implement497 tests with context locals, read this section, otherwise just skip it.498499Certain objects in Flask are global objects, but not of the usual kind.500These objects are actually proxies to objects that are local to a specific501context. What a mouthful. But that is actually quite easy to understand.502503Imagine the context being the handling thread. A request comes in and the504web server decides to spawn a new thread (or something else, the505underlying object is capable of dealing with concurrency systems other506than threads). When Flask starts its internal request handling it507figures out that the current thread is the active context and binds the508current application and the WSGI environments to that context (thread).509It does that in an intelligent way so that one application can invoke another510application without breaking.511512So what does this mean to you? Basically you can completely ignore that513this is the case unless you are doing something like unit testing. You514will notice that code which depends on a request object will suddenly break515because there is no request object. The solution is creating a request516object yourself and binding it to the context. The easiest solution for517unit testing is to use the :meth:`~flask.Flask.test_request_context`518context manager. In combination with the ``with`` statement it will bind a519test request so that you can interact with it. Here is an example::520521 from flask import request522523 with app.test_request_context('/hello', method='POST'):524 # now you can do something with the request until the525 # end of the with block, such as basic assertions:526 assert request.path == '/hello'527 assert request.method == 'POST'528529The other possibility is passing a whole WSGI environment to the530:meth:`~flask.Flask.request_context` method::531532 from flask import request533534 with app.request_context(environ):535 assert request.method == 'POST'536537The Request Object538``````````````````539540The request object is documented in the API section and we will not cover541it here in detail (see :class:`~flask.request`). Here is a broad overview of542some of the most common operations. First of all you have to import it fromclean up code formatting in some docsDavid Lordbefore adoption1928f28
line 543why, one step back543the ``flask`` module::Merge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 544–565why, one step back544545 from flask import request546547The current request method is available by using the548:attr:`~flask.request.method` attribute. To access form data (data549transmitted in a ``POST`` or ``PUT`` request) you can use the550:attr:`~flask.request.form` attribute. Here is a full example of the two551attributes mentioned above::552553 @app.route('/login', methods=['POST', 'GET'])554 def login():555 error = None556 if request.method == 'POST':557 if valid_login(request.form['username'],558 request.form['password']):559 return log_the_user_in(request.form['username'])560 else:561 error = 'Invalid username/password'562 # the code below is executed if the request method563 # was GET or the credentials were invalid564 return render_template('login.html', error=error)565clean up code formatting in some docsDavid Lordbefore adoption1928f28
line 566why, one step back566What happens if the key does not exist in the ``form`` attribute? In thatMerge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 567–618why, one step back567case a special :exc:`KeyError` is raised. You can catch it like a568standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request569error page is shown instead. So for many situations you don't have to570deal with that problem.571572To access parameters submitted in the URL (``?key=value``) you can use the573:attr:`~flask.request.args` attribute::574575 searchword = request.args.get('key', '')576577We recommend accessing URL parameters with `get` or by catching the578:exc:`KeyError` because users might change the URL and presenting them a 400579bad request page in that case is not user friendly.580581For a full list of methods and attributes of the request object, head over582to the :class:`~flask.request` documentation.583584585File Uploads586````````````587588You can handle uploaded files with Flask easily. Just make sure not to589forget to set the ``enctype="multipart/form-data"`` attribute on your HTML590form, otherwise the browser will not transmit your files at all.591592Uploaded files are stored in memory or at a temporary location on the593filesystem. You can access those files by looking at the594:attr:`~flask.request.files` attribute on the request object. Each595uploaded file is stored in that dictionary. It behaves just like a596standard Python :class:`file` object, but it also has a597:meth:`~werkzeug.datastructures.FileStorage.save` method that allows you to store that598file on the filesystem of the server. Here is a simple example showing how599that works::600601 from flask import request602603 @app.route('/upload', methods=['GET', 'POST'])604 def upload_file():605 if request.method == 'POST':606 f = request.files['the_file']607 f.save('/var/www/uploads/uploaded_file.txt')608 ...609610If you want to know how the file was named on the client before it was611uploaded to your application, you can access the612:attr:`~werkzeug.datastructures.FileStorage.filename` attribute. However please keep in613mind that this value can be forged so never ever trust that value. If you614want to use the filename of the client to store the file on the server,615pass it through the :func:`~werkzeug.utils.secure_filename` function that616Werkzeug provides for you::617618 from flask import requestMerge pull request #1461 from justinwp/patch-1Markus Unterwaditzerbefore adoption1e15e17
line 619why, one step back619 from werkzeug.utils import secure_filenameMerge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 620–707why, one step back620621 @app.route('/upload', methods=['GET', 'POST'])622 def upload_file():623 if request.method == 'POST':624 f = request.files['the_file']625 f.save('/var/www/uploads/' + secure_filename(f.filename))626 ...627628For some better examples, checkout the :ref:`uploading-files` pattern.629630Cookies631```````632633To access cookies you can use the :attr:`~flask.Request.cookies`634attribute. To set cookies you can use the635:attr:`~flask.Response.set_cookie` method of response objects. The636:attr:`~flask.Request.cookies` attribute of request objects is a637dictionary with all the cookies the client transmits. If you want to use638sessions, do not use the cookies directly but instead use the639:ref:`sessions` in Flask that add some security on top of cookies for you.640641Reading cookies::642643 from flask import request644645 @app.route('/')646 def index():647 username = request.cookies.get('username')648 # use cookies.get(key) instead of cookies[key] to not get a649 # KeyError if the cookie is missing.650651Storing cookies::652653 from flask import make_response654655 @app.route('/')656 def index():657 resp = make_response(render_template(...))658 resp.set_cookie('username', 'the username')659 return resp660661Note that cookies are set on response objects. Since you normally662just return strings from the view functions Flask will convert them into663response objects for you. If you explicitly want to do that you can use664the :meth:`~flask.make_response` function and then modify it.665666Sometimes you might want to set a cookie at a point where the response667object does not exist yet. This is possible by utilizing the668:ref:`deferred-callbacks` pattern.669670For this also see :ref:`about-responses`.671672Redirects and Errors673--------------------674675To redirect a user to another endpoint, use the :func:`~flask.redirect`676function; to abort a request early with an error code, use the677:func:`~flask.abort` function::678679 from flask import abort, redirect, url_for680681 @app.route('/')682 def index():683 return redirect(url_for('login'))684685 @app.route('/login')686 def login():687 abort(401)688 this_is_never_executed()689690This is a rather pointless example because a user will be redirected from691the index to a page they cannot access (401 means access denied) but it692shows how that works.693694By default a black and white error page is shown for each error code. If695you want to customize the error page, you can use the696:meth:`~flask.Flask.errorhandler` decorator::697698 from flask import render_template699700 @app.errorhandler(404)701 def page_not_found(error):702 return render_template('page_not_found.html'), 404703704Note the ``404`` after the :func:`~flask.render_template` call. This705tells Flask that the status code of that page should be 404 which means706not found. By default 200 is assumed which translates to: all went well.707Merge pull request #1429 from flying-sheep/errorhandler-rework-docsMarkus Unterwaditzerbefore adoption06f2be3
lines 708–709why, one step back708See :ref:`error-handlers` for more details.709Merge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 710–727why, one step back710.. _about-responses:711712About Responses713---------------714715The return value from a view function is automatically converted into a716response object for you. If the return value is a string it's converted717into a response object with the string as response body, a ``200 OK``718status code and a :mimetype:`text/html` mimetype. The logic that Flask applies to719converting return values into response objects is as follows:7207211. If a response object of the correct type is returned it's directly722 returned from the view.7232. If it's a string, a response object is created with that data and the724 default parameters.7253. If a tuple is returned the items in the tuple can provide extra726 information. Such tuples have to be in the form ``(response, status,727 headers)`` or ``(response, headers)`` where at least one item hasclean up code formatting in some docsDavid Lordbefore adoption1928f28
lines 728–729why, one step back728 to be in the tuple. The ``status`` value will override the status code729 and ``headers`` can be a list or dictionary of additional header values.Merge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 730–735why, one step back7304. If none of that works, Flask will assume the return value is a731 valid WSGI application and convert that into a response object.732733If you want to get hold of the resulting response object inside the view734you can use the :func:`~flask.make_response` function.735clean up code formatting in some docsDavid Lordbefore adoption1928f28
line 736why, one step back736Imagine you have a view like this::Merge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 737–743why, one step back737738 @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, thenclean up code formatting in some docsDavid Lordbefore adoption1928f28
line 744why, one step back744return it::Merge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 745–782why, one step back745746 @app.errorhandler(404)747 def not_found(error):748 resp = make_response(render_template('error.html'), 404)749 resp.headers['X-Something'] = 'A value'750 return resp751752.. _sessions:753754Sessions755--------756757In addition to the request object there is also a second object called758:class:`~flask.session` which allows you to store information specific to a759user from one request to the next. This is implemented on top of cookies760for you and signs the cookies cryptographically. What this means is that761the user could look at the contents of your cookie but not modify it,762unless they know the secret key used for signing.763764In order to use sessions you have to set a secret key. Here is how765sessions work::766767 from flask import Flask, session, redirect, url_for, escape, request768769 app = Flask(__name__)770771 @app.route('/')772 def index():773 if 'username' in session:774 return 'Logged in as %s' % escape(session['username'])775 return 'You are not logged in'776777 @app.route('/login', methods=['GET', 'POST'])778 def login():779 if request.method == 'POST':780 session['username'] = request.form['username']781 return redirect(url_for('index'))782 return '''remove unnecessary form action attributesDavid Lordbefore adoptioncd1a9b7
line 783why, one step back783 <form method="post">Merge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 784–805why, one step back784 <p><input type=text name=username>785 <p><input type=submit value=Login>786 </form>787 '''788789 @app.route('/logout')790 def logout():791 # remove the username from the session if it's there792 session.pop('username', None)793 return redirect(url_for('index'))794795 # set the secret key. keep this really secret:796 app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'797798The :func:`~flask.escape` mentioned here does escaping for you if you are799not using the template engine (as in this example).800801.. admonition:: How to generate good secret keys802803 The problem with random is that it's hard to judge what is truly random. And804 a secret key should be as random as possible. Your operating system805 has ways to generate pretty random stuff based on a cryptographicclean up code formatting in some docsDavid Lordbefore adoption1928f28
line 806why, one step back806 random generator which can be used to get such a key::Merge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
line 807why, one step back807clean up code formatting in some docsDavid Lordbefore adoption1928f28
lines 808–810why, one step back808 >>> import os809 >>> os.urandom(24)810 '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'Merge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
line 811why, one step back811clean up code formatting in some docsDavid Lordbefore adoption1928f28
line 812why, one step back812 Just take that thing and copy/paste it into your code and you're done.Merge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 813–890why, one step back813814A note on cookie-based sessions: Flask will take the values you put into the815session object and serialize them into a cookie. If you are finding some816values do not persist across requests, cookies are indeed enabled, and you are817not getting a clear error message, check the size of the cookie in your page818responses compared to the size supported by web browsers.819820821Message Flashing822----------------823824Good applications and user interfaces are all about feedback. If the user825does not get enough feedback they will probably end up hating the826application. Flask provides a really simple way to give feedback to a827user with the flashing system. The flashing system basically makes it828possible to record a message at the end of a request and access it on the next829(and only the next) request. This is usually combined with a layout830template to expose the message.831832To flash a message use the :func:`~flask.flash` method, to get hold of the833messages you can use :func:`~flask.get_flashed_messages` which is also834available in the templates. Check out the :ref:`message-flashing-pattern`835for a full example.836837Logging838-------839840.. versionadded:: 0.3841842Sometimes you might be in a situation where you deal with data that843should be correct, but actually is not. For example you may have some client-side844code that sends an HTTP request to the server but it's obviously845malformed. This might be caused by a user tampering with the data, or the846client code failing. Most of the time it's okay to reply with ``400 Bad847Request`` in that situation, but sometimes that won't do and the code has848to continue working.849850You may still want to log that something fishy happened. This is where851loggers come in handy. As of Flask 0.3 a logger is preconfigured for you852to use.853854Here are some example log calls::855856 app.logger.debug('A value for debugging')857 app.logger.warning('A warning occurred (%d apples)', 42)858 app.logger.error('An error occurred')859860The attached :attr:`~flask.Flask.logger` is a standard logging861:class:`~logging.Logger`, so head over to the official `logging862documentation <https://docs.python.org/library/logging.html>`_ for more863information.864865Read more on :ref:`application-errors`.866867Hooking in WSGI Middlewares868---------------------------869870If you want to add a WSGI middleware to your application you can wrap the871internal WSGI application. For example if you want to use one of the872middlewares from the Werkzeug package to work around bugs in lighttpd, you873can do it like this::874875 from werkzeug.contrib.fixers import LighttpdCGIRootFix876 app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)877878Using Flask Extensions879----------------------880881Extensions are packages that help you accomplish common tasks. For882example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple883and easy to use with Flask.884885For more on Flask extensions, have a look at :ref:`extensions`.886887Deploying to a Web Server888-------------------------889890Ready to deploy your new Flask app? Go to :ref:`deployment`.