quickstart.rst
This file
Path
docs/quickstart.rst
894 lines · 32.7 KiB
Last changed by
quickstart: Remove reference to `python hello.py`Markus Unterwaditzerbefore adoptionf91aea2
History of this fileTake it
The walk stopped after 200 commits: lines older than 41b5d77 point at it.
Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77
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 #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77
lines 22–39why, one step back2223So 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 (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.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 #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77
lines 43–44why, one step back4344To run the application you can either use the :command:`flask` command orUpdate docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
lines 45–47why, one step back45python's :option:`-m` switch with Flask. Before you can do that you need46to tell your terminal the application to work with by exporting the47`FLASK_APP` environment variable::Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77
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 #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77
lines 51–52why, one step back51 * Running on http://127.0.0.1:5000/52Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
line 53why, one step back53If you are on Windows you need to use `set` instead of `export`.Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77
line 54why, one step back54Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
lines 55–58why, one step back55Alternatively you can use `python -m flask`::5657 $ export FLASK_APP=hello.py58 $ python -m flask runMerge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77
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 #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77
lines 82–95why, one step back8283 This tells your operating system to listen on all public IPs.848586What to do if the Server does not Start87---------------------------------------8889In case the ``python -m flask`` fails or :command:`flask` does not exist,90there 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 #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77
lines 97–104why, one step back97application. In short, the :command:`flask` command did not exist, and98neither did ``python -m flask``. In that case you have two options:99either 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```````````````````104Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
lines 105–108why, one step back105The :option:`-a` argument to :command:`flask` is the name of the module to106import. 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 #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77
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 #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77
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.125Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
lines 126–127why, one step back126To enable debug mode you can export the `FLASK_DEBUG` environment variable127before running the server::Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77
line 128why, one step back128Update docs to the new CLI patternsArmin Ronacherbefore adoptiona7d829c
lines 129–132why, one step back129 $ export FLASK_DEBUG=1130 $ flask run131132(On Windows you need to use `set` instead of `export`).Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77
lines 133–176why, 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():Merge pull request #1318 from cerivera/masterMarkus Unterwaditzerbefore adoptione3ba459
line 177why, one step back177 return 'Hello, World'Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77
lines 178–206why, 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:201202=========== ===============================================203`string` accepts any text without a slash (the default)204`int` accepts integers205`float` like `int` but for floating point values206`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 #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77
lines 209–323why, 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 the229 `projects` endpoint has a trailing slash. In that sense, it is similar to230 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 are253some examples:254255>>> 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%20Doe276277(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.2913. If your application is placed outside the URL root (say, in292 ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will handle293 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 that301can be changed by providing the `methods` argument to the302: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 #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77
lines 325–436why, 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 %}Merge pull request #1318 from cerivera/masterMarkus Unterwaditzerbefore adoptione3ba459
line 437why, one step back437 <h1>Hello, World!</h1>Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77
lines 438–481why, one step back438 {% 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).448449Automatic escaping is enabled, so if `name` contains HTML it will be escaped450automatically. 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.455456Here is a basic introduction to how the :class:`~jinja2.Markup` class works:457458>>> from flask import Markup459>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'460Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')461>>> Markup.escape('<blink>hacker</blink>')462Markup(u'<blink>hacker</blink>')463>>> Markup('<em>Marked up</em> » HTML').striptags()464u'Marked up \xbb HTML'465466.. 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----------------------481Merge pull request #1299 from sateeshkumarb/patch-1Markus Unterwaditzerbefore adoption4fde65e
line 482why, one step back482For web applications it's crucial to react to the data a client sends toMerge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77
lines 483–618why, one step back483the 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 from543the `flask` module::544545 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)565566What happens if the key does not exist in the `form` attribute? In that567case 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 #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77
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 #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77
lines 710–881why, 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 has728 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.7304. 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.735736Imagine you have a view like this:737738.. sourcecode:: python739740 @app.errorhandler(404)741 def not_found(error):742 return render_template('error.html'), 404743744You just need to wrap the return expression with745:func:`~flask.make_response` and get the response object to modify it, then746return it:747748.. sourcecode:: python749750 @app.errorhandler(404)751 def not_found(error):752 resp = make_response(render_template('error.html'), 404)753 resp.headers['X-Something'] = 'A value'754 return resp755756.. _sessions:757758Sessions759--------760761In addition to the request object there is also a second object called762:class:`~flask.session` which allows you to store information specific to a763user from one request to the next. This is implemented on top of cookies764for you and signs the cookies cryptographically. What this means is that765the user could look at the contents of your cookie but not modify it,766unless they know the secret key used for signing.767768In order to use sessions you have to set a secret key. Here is how769sessions work::770771 from flask import Flask, session, redirect, url_for, escape, request772773 app = Flask(__name__)774775 @app.route('/')776 def index():777 if 'username' in session:778 return 'Logged in as %s' % escape(session['username'])779 return 'You are not logged in'780781 @app.route('/login', methods=['GET', 'POST'])782 def login():783 if request.method == 'POST':784 session['username'] = request.form['username']785 return redirect(url_for('index'))786 return '''787 <form action="" method="post">788 <p><input type=text name=username>789 <p><input type=submit value=Login>790 </form>791 '''792793 @app.route('/logout')794 def logout():795 # remove the username from the session if it's there796 session.pop('username', None)797 return redirect(url_for('index'))798799 # set the secret key. keep this really secret:800 app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'801802The :func:`~flask.escape` mentioned here does escaping for you if you are803not using the template engine (as in this example).804805.. admonition:: How to generate good secret keys806807 The problem with random is that it's hard to judge what is truly random. And808 a secret key should be as random as possible. Your operating system809 has ways to generate pretty random stuff based on a cryptographic810 random generator which can be used to get such a key:811812 >>> import os813 >>> os.urandom(24)814 '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'815816 Just take that thing and copy/paste it into your code and you're done.817818A note on cookie-based sessions: Flask will take the values you put into the819session object and serialize them into a cookie. If you are finding some820values do not persist across requests, cookies are indeed enabled, and you are821not getting a clear error message, check the size of the cookie in your page822responses compared to the size supported by web browsers.823824825Message Flashing826----------------827828Good applications and user interfaces are all about feedback. If the user829does not get enough feedback they will probably end up hating the830application. Flask provides a really simple way to give feedback to a831user with the flashing system. The flashing system basically makes it832possible to record a message at the end of a request and access it on the next833(and only the next) request. This is usually combined with a layout834template to expose the message.835836To flash a message use the :func:`~flask.flash` method, to get hold of the837messages you can use :func:`~flask.get_flashed_messages` which is also838available in the templates. Check out the :ref:`message-flashing-pattern`839for a full example.840841Logging842-------843844.. versionadded:: 0.3845846Sometimes you might be in a situation where you deal with data that847should be correct, but actually is not. For example you may have some client-side848code that sends an HTTP request to the server but it's obviously849malformed. This might be caused by a user tampering with the data, or the850client code failing. Most of the time it's okay to reply with ``400 Bad851Request`` in that situation, but sometimes that won't do and the code has852to continue working.853854You may still want to log that something fishy happened. This is where855loggers come in handy. As of Flask 0.3 a logger is preconfigured for you856to use.857858Here are some example log calls::859860 app.logger.debug('A value for debugging')861 app.logger.warning('A warning occurred (%d apples)', 42)862 app.logger.error('An error occurred')863864The attached :attr:`~flask.Flask.logger` is a standard logging865:class:`~logging.Logger`, so head over to the official `logging866documentation <https://docs.python.org/library/logging.html>`_ for more867information.868869Read more on :ref:`application-errors`.870871Hooking in WSGI Middlewares872---------------------------873874If you want to add a WSGI middleware to your application you can wrap the875internal WSGI application. For example if you want to use one of the876middlewares from the Werkzeug package to work around bugs in lighttpd, you877can do it like this::878879 from werkzeug.contrib.fixers import LighttpdCGIRootFix880 app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)881Merge pull request #1376 from KWinston/masterMarkus Unterwaditzerbefore adoptionec5811d
lines 882–890why, one step back882Using Flask Extensions883----------------------884885Extensions are packages that help you accomplish common tasks. For886example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple887and easy to use with Flask.888889For more on Flask extensions, have a look at :ref:`extensions`.890Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77
lines 891–894why, one step back891Deploying to a Web Server892-------------------------893894Ready to deploy your new Flask app? Go to :ref:`deployment`.