quickstart.rst
This file
Path
docs/quickstart.rst
823 lines · 29.8 KiB
Last changed by
Fixed various stylistic issues in documentationFNDbefore adoption7ccca13
History of this fileTake it
The walk stopped after 200 commits: lines older than e2fed6c point at it.
Fixed another typoArmin Ronacherbefore adoptione2fed6c
lines 1–5why, one step back1.. _quickstart:23Quickstart4==========5Fixed various stylistic issues in documentationFNDbefore adoption7ccca13
line 6why, one step back6Eager to get started? This page gives a good introduction on how to getFixed another typoArmin Ronacherbefore adoptione2fed6c
lines 7–20why, one step back7started with Flask. This assumes you already have Flask installed. If8you do not, head over to the :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 #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086
line 21why, one step back21 return 'Hello World!'Fixed another typoArmin Ronacherbefore adoptione2fed6c
lines 22–41why, one step back2223 if __name__ == '__main__':24 app.run()2526Just save it as `hello.py` or something similar and run it with your27Python interpreter. Make sure to not call your application `flask.py`28because this would conflict with Flask itself.2930::3132 $ python hello.py33 * Running on http://127.0.0.1:5000/3435Head over to `http://127.0.0.1:5000/ <http://127.0.0.1:5000/>`_, you should36see your hello world greeting.3738So what did that code do?39401. First we imported the :class:`~flask.Flask` class. An instance of this41 class will be our WSGI application. The first argument is the name ofFixed various stylistic issues in documentationFNDbefore adoption7ccca13
lines 42–43why, one step back42 the application's module. If you are using a single module (as in this example)43 you should use `__name__` because depending on whether it's started asFixed another typoArmin Ronacherbefore adoptione2fed6c
lines 44–45why, one step back44 application or imported as module the name will be different45 (``'__main__'`` versus the actual import name). For more informationFixed various stylistic issues in documentationFNDbefore adoption7ccca13
line 46why, one step back46 on this technique, have a look at the :class:`~flask.Flask` documentation.Fixed another typoArmin Ronacherbefore adoptione2fed6c
lines 47–50why, one step back472. Next we create an instance of it. We pass it the name of the module /48 package. This is needed so that Flask knows where it should look for49 templates, static files and so on.503. Then we use the :meth:`~flask.Flask.route` decorator to tell FlaskFixed various stylistic issues in documentationFNDbefore adoption7ccca13
line 51why, one step back51 which URL should trigger our function.Fixed another typoArmin Ronacherbefore adoptione2fed6c
lines 52–65why, one step back524. The function then has a name which is also used to generate URLs to53 that particular function, and returns the message we want to display in54 the user's browser.555. Finally we use the :meth:`~flask.Flask.run` function to run the56 local server with our application. The ``if __name__ == '__main__':``57 makes sure the server only runs if the script is executed directly from58 the Python interpreter and not used as imported module.5960To stop the server, hit control-C.6162.. _public-server:6364.. admonition:: Externally Visible Server65Fixed various stylistic issues in documentationFNDbefore adoption7ccca13
line 66why, one step back66 If you run the server you will notice that the server is only accessibleFixed another typoArmin Ronacherbefore adoptione2fed6c
lines 67–68why, one step back67 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 executeFixed various stylistic issues in documentationFNDbefore adoption7ccca13
line 69why, one step back69 arbitrary Python code on your computer.Fixed another typoArmin Ronacherbefore adoptione2fed6c
line 70why, one step back70Fixed various stylistic issues in documentationFNDbefore adoption7ccca13
lines 71–73why, one step back71 If you have `debug` disabled or trust the users on your network, you can72 make the server publicly available simply by changing the call of the73 :meth:`~flask.Flask.run` method to look like this::Fixed another typoArmin Ronacherbefore adoptione2fed6c
lines 74–84why, one step back7475 app.run(host='0.0.0.0')7677 This tells your operating system to listen on a public IP.787980Debug Mode81----------8283The :meth:`~flask.Flask.run` method is nice to start a local84development server, but you would have to restart it manually after eachFixed various stylistic issues in documentationFNDbefore adoption7ccca13
lines 85–87why, one step back85change to your code. That is not very nice and Flask can do better. If86you enable debug support the server will reload itself on code changes,87and it will also provide you with a helpful debugger if things go wrong.Fixed another typoArmin Ronacherbefore adoptione2fed6c
lines 88–94why, one step back8889There are two ways to enable debugging. Either set that flag on the90application object::9192 app.debug = True93 app.run()94Fixed various stylistic issues in documentationFNDbefore adoption7ccca13
line 95why, one step back95Or pass it to `run`::Fixed another typoArmin Ronacherbefore adoptione2fed6c
lines 96–124why, one step back9697 app.run(debug=True)9899Both will have exactly the same effect.100101.. admonition:: Attention102103 Even though the interactive debugger does not work in forking environments104 (which makes it nearly impossible to use on production servers), it still105 allows the execution of arbitrary code. That makes it a major security106 risk and therefore it **must never be used on production machines**.107108Screenshot of the debugger in action:109110.. image:: _static/debugger.png111 :align: center112 :class: screenshot113 :alt: screenshot of debugger in action114115.. admonition:: Working With Other Debuggers116117 Debuggers interfere with each other. If you are using another debugger118 (e.g. PyDev or IntelliJ), you may need to set ``app.debug = False``.119120121Routing122-------123124Modern web applications have beautiful URLs. This helps people rememberFixed various stylistic issues in documentationFNDbefore adoption7ccca13
line 125why, one step back125the URLs, which is especially handy for applications that are used fromFixed another typoArmin Ronacherbefore adoptione2fed6c
lines 126–172why, one step back126mobile devices with slower network connections. If the user can directly127go to the desired page without having to hit the index page it is more128likely they will like the page and come back next time.129130As you have seen above, the :meth:`~flask.Flask.route` decorator is used131to bind a function to a URL. Here are some basic examples::132133 @app.route('/')134 def index():135 return 'Index Page'136137 @app.route('/hello')138 def hello():139 return 'Hello World'140141But there is more to it! You can make certain parts of the URL dynamic142and attach multiple rules to a function.143144Variable Rules145``````````````146147To add variable parts to a URL you can mark these special sections as148``<variable_name>``. Such a part is then passed as keyword argument to149your function. Optionally a converter can be specified by specifying a150rule with ``<converter:variable_name>``. Here are some nice examples::151152 @app.route('/user/<username>')153 def show_user_profile(username):154 # show the user profile for that user155 pass156157 @app.route('/post/<int:post_id>')158 def show_post(post_id):159 # show the post with the given id, the id is an integer160 pass161162The following converters exist:163164=========== ===========================================165`int` accepts integers166`float` like `int` but for floating point values167`path` like the default but also accepts slashes168=========== ===========================================169170.. admonition:: Unique URLs / Redirection Behaviour171172 Flask's URL rules are based on Werkzeug's routing module. The ideaFixed various stylistic issues in documentationFNDbefore adoption7ccca13
lines 173–174why, one step back173 behind that module is to ensure nice-looking and also unique URLs based174 on behaviour coined by Apache and earlier servers.Fixed another typoArmin Ronacherbefore adoptione2fed6c
lines 175–191why, one step back175176 Take these two rules::177178 @app.route('/projects/')179 def projects():180 pass181182 @app.route('/about')183 def about():184 pass185186 They look rather similar, the difference is the trailing slash in the187 URL *definition*. In the first case, the canonical URL for the188 `projects` endpoint has a trailing slash. It's similar to a folder in189 that sense. Accessing it without a trailing slash will cause Flask to190 redirect to the canonical URL with the trailing slash.191Fixed various stylistic issues in documentationFNDbefore adoption7ccca13
line 192why, one step back192 However, in the second case the URL is defined without a slash so itFixed another typoArmin Ronacherbefore adoptione2fed6c
line 193why, one step back193 behaves similar to a file and accessing the URL with a trailing slashFixed various stylistic issues in documentationFNDbefore adoption7ccca13
line 194why, one step back194 will result in a 404 error.Fixed another typoArmin Ronacherbefore adoptione2fed6c
lines 195–198why, one step back195196 Why is this? This allows relative URLs to continue working if users197 access the page when they forget a trailing slash. This behaviour is198 also consistent with how Apache and other servers work. Also, the URLsFixed various stylistic issues in documentationFNDbefore adoption7ccca13
line 199why, one step back199 will stay unique which ensures search engines do not index the same pageFixed another typoArmin Ronacherbefore adoptione2fed6c
lines 200–239why, one step back200 twice.201202203.. _url-building:204205URL Building206````````````207208If it can match URLs, can it also generate them? Of course it can. To209build a URL to a specific function you can use the :func:`~flask.url_for`210function. It accepts the name of the function as first argument and a211number of keyword arguments, each corresponding to the variable part of212the URL rule. Unknown variable parts are appended to the URL as query213parameter. Here are some examples:214215>>> from flask import Flask, url_for216>>> app = Flask(__name__)217>>> @app.route('/')218... def index(): pass219...220>>> @app.route('/login')221... def login(): pass222...223>>> @app.route('/user/<username>')224... def profile(username): pass225...226>>> with app.test_request_context():227... print url_for('index')228... print url_for('login')229... print url_for('login', next='/')230... print url_for('profile', username='John Doe')231...232/233/login234/login?next=/235/user/John%20Doe236237(This also uses the :meth:`~flask.Flask.test_request_context` method238explained below. It basically tells Flask to think we are handling a239request even though we are not, we are in an interactive Python shell.Fixed various stylistic issues in documentationFNDbefore adoption7ccca13
line 240why, one step back240Have a look at the explanation below: :ref:`context-locals`.)Fixed another typoArmin Ronacherbefore adoptione2fed6c
lines 241–271why, one step back241242Why would you want to build URLs instead of hardcoding them in your243templates? There are three good reasons for this:2442451. reversing is often more descriptive than hardcoding the URLs. Also and246 more importantly you can change URLs in one go without having to change247 the URLs all over the place.2482. URL building will handle escaping of special characters and Unicode249 data transparently for you, you don't have to deal with that.2503. If your application is placed outside the URL root (so say in251 ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will252 handle that properly for you.253254255HTTP Methods256````````````257258HTTP (the protocol web applications are speaking) knows different methods259to access URLs. By default a route only answers to `GET` requests, but260that can be changed by providing the `methods` argument to the261:meth:`~flask.Flask.route` decorator. Here are some examples::262263 @app.route('/login', methods=['GET', 'POST'])264 def login():265 if request.method == 'POST':266 do_the_login()267 else:268 show_the_login_form()269270If `GET` is present, `HEAD` will be added automatically for you. You271don't have to deal with that. It will also make sure that `HEAD` requestsFixed various stylistic issues in documentationFNDbefore adoption7ccca13
line 272why, one step back272are handled as the `HTTP RFC`_ (the document describing the HTTPFixed another typoArmin Ronacherbefore adoptione2fed6c
line 273why, one step back273protocol) demands, so you can completely ignore that part of the HTTPFixed various stylistic issues in documentationFNDbefore adoption7ccca13
lines 274–275why, one step back274specification. Likewise, as of Flask 0.6, `OPTIONS` is implemented for you275automatically as well.Fixed another typoArmin Ronacherbefore adoptione2fed6c
lines 276–298why, one step back276277You have no idea what an HTTP method is? Worry not, here is a quick278introduction to HTTP methods and why they matter:279280The HTTP method (also often called "the verb") tells the server what the281clients wants to *do* with the requested page. The following methods are282very common:283284`GET`285 The browser tells the server to just *get* the information stored on286 that page and send it. This is probably the most common method.287288`HEAD`289 The browser tells the server to get the information, but it is only290 interested in the *headers*, not the content of the page. An291 application is supposed to handle that as if a `GET` request was292 received but to not deliver the actual content. In Flask you don't293 have to deal with that at all, the underlying Werkzeug library handles294 that for you.295296`POST`297 The browser tells the server that it wants to *post* some new298 information to that URL and that the server must ensure the data isFixed various stylistic issues in documentationFNDbefore adoption7ccca13
lines 299–300why, one step back299 stored and only stored once. This is how HTML forms usually300 transmit data to the server.Fixed another typoArmin Ronacherbefore adoptione2fed6c
lines 301–304why, one step back301302`PUT`303 Similar to `POST` but the server might trigger the store procedure304 multiple times by overwriting the old values more than once. Now youFixed various stylistic issues in documentationFNDbefore adoption7ccca13
lines 305–306why, one step back305 might be asking why this is useful, but there are some good reasons306 to do it this way. Consider that the connection is lost duringFixed another typoArmin Ronacherbefore adoptione2fed6c
lines 307–331why, one step back307 transmission: in this situation a system between the browser and the308 server might receive the request safely a second time without breaking309 things. With `POST` that would not be possible because it must only310 be triggered once.311312`DELETE`313 Remove the information at the given location.314315`OPTIONS`316 Provides a quick way for a client to figure out which methods are317 supported by this URL. Starting with Flask 0.6, this is implemented318 for you automatically.319320Now the interesting part is that in HTML4 and XHTML1, the only methods a321form can submit to the server are `GET` and `POST`. But with JavaScript322and future HTML standards you can use the other methods as well. Furthermore323HTTP has become quite popular lately and browsers are no longer the only324clients that are using HTTP. For instance, many revision control system325use it.326327.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt328329Static Files330------------331Fixed various stylistic issues in documentationFNDbefore adoption7ccca13
line 332why, one step back332Dynamic web applications also need static files. That's usually whereFixed another typoArmin Ronacherbefore adoptione2fed6c
lines 333–337why, one step back333the CSS and JavaScript files are coming from. Ideally your web server is334configured to serve them for you, but during development Flask can do that335as well. Just create a folder called `static` in your package or next to336your module and it will be available at `/static` on the application.337Fixed various stylistic issues in documentationFNDbefore adoption7ccca13
line 338why, one step back338To generate URLs that part of the URL, use the special ``'static'`` URLFixed another typoArmin Ronacherbefore adoptione2fed6c
lines 339–353why, one step back339name::340341 url_for('static', filename='style.css')342343The file has to be stored on the filesystem as ``static/style.css``.344345Rendering Templates346-------------------347348Generating HTML from within Python is not fun, and actually pretty349cumbersome because you have to do the HTML escaping on your own to keep350the application secure. Because of that Flask configures the `Jinja2351<http://jinja.pocoo.org/2/>`_ template engine for you automatically.352353To render a template you can use the :func:`~flask.render_template`Fixed various stylistic issues in documentationFNDbefore adoption7ccca13
line 354why, one step back354method. All you have to do is provide the name of the template and theFixed another typoArmin Ronacherbefore adoptione2fed6c
lines 355–365why, one step back355variables you want to pass to the template engine as keyword arguments.356Here's a simple example of how to render a template::357358 from flask import render_template359360 @app.route('/hello/')361 @app.route('/hello/<name>')362 def hello(name=None):363 return render_template('hello.html', name=name)364365Flask will look for templates in the `templates` folder. So if yourFixed various stylistic issues in documentationFNDbefore adoption7ccca13
line 366why, one step back366application is a module, this folder is next to that module, if it's aFixed another typoArmin Ronacherbefore adoptione2fed6c
lines 367–406why, one step back367package it's actually inside your package:368369**Case 1**: a module::370371 /application.py372 /templates373 /hello.html374375**Case 2**: a package::376377 /application378 /__init__.py379 /templates380 /hello.html381382For templates you can use the full power of Jinja2 templates. Head over383to the the official `Jinja2 Template Documentation384<http://jinja.pocoo.org/2/documentation/templates>`_ for more information.385386Here is an example template:387388.. sourcecode:: html+jinja389390 <!doctype html>391 <title>Hello from Flask</title>392 {% if name %}393 <h1>Hello {{ name }}!</h1>394 {% else %}395 <h1>Hello World!</h1>396 {% endif %}397398Inside templates you also have access to the :class:`~flask.request`,399:class:`~flask.session` and :class:`~flask.g` [#]_ objects400as well as the :func:`~flask.get_flashed_messages` function.401402Templates are especially useful if inheritance is used. If you want to403know how that works, head over to the :ref:`template-inheritance` pattern404documentation. Basically template inheritance makes it possible to keep405certain elements on each page (like header, navigation and footer).406Fixed various stylistic issues in documentationFNDbefore adoption7ccca13
line 407why, one step back407Automatic escaping is enabled, so if `name` contains HTML it will be escapedFixed another typoArmin Ronacherbefore adoptione2fed6c
line 408why, one step back408automatically. If you can trust a variable and you know that it will beFixed various stylistic issues in documentationFNDbefore adoption7ccca13
line 409why, one step back409safe HTML (for example because it came from a module that converts wikiFixed another typoArmin Ronacherbefore adoptione2fed6c
lines 410–443why, one step back410markup to HTML) you can mark it as safe by using the411:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the412template. Head over to the Jinja 2 documentation for more examples.413414Here is a basic introduction to how the :class:`~jinja2.Markup` class works:415416>>> from flask import Markup417>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'418Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')419>>> Markup.escape('<blink>hacker</blink>')420Markup(u'<blink>hacker</blink>')421>>> Markup('<em>Marked up</em> » HTML').striptags()422u'Marked up \xbb HTML'423424.. versionchanged:: 0.5425426 Autoescaping is no longer enabled for all templates. The following427 extensions for templates trigger autoescaping: ``.html``, ``.htm``,428 ``.xml``, ``.xhtml``. Templates loaded from a string will have429 autoescaping disabled.430431.. [#] Unsure what that :class:`~flask.g` object is? It's something in which432 you can store information for your own needs, check the documentation of433 that object (:class:`~flask.g`) and the :ref:`sqlite3` for more434 information.435436437Accessing Request Data438----------------------439440For web applications it's crucial to react to the data a client sent to441the server. In Flask this information is provided by the global442:class:`~flask.request` object. If you have some experience with Python443you might be wondering how that object can be global and how FlaskFixed various stylistic issues in documentationFNDbefore adoption7ccca13
line 444why, one step back444manages to still be threadsafe. The answer is context locals:Fixed another typoArmin Ronacherbefore adoptione2fed6c
lines 445–461why, one step back445446447.. _context-locals:448449Context Locals450``````````````451452.. admonition:: Insider Information453454 If you want to understand how that works and how you can implement455 tests with context locals, read this section, otherwise just skip it.456457Certain objects in Flask are global objects, but not of the usual kind.458These objects are actually proxies to objects that are local to a specific459context. What a mouthful. But that is actually quite easy to understand.460461Imagine the context being the handling thread. A request comes in and theFixed various stylistic issues in documentationFNDbefore adoption7ccca13
lines 462–464why, one step back462web server decides to spawn a new thread (or something else, the463underlying object is capable of dealing with concurrency systems other464than threads). When Flask starts its internal request handling itFixed another typoArmin Ronacherbefore adoptione2fed6c
lines 465–466why, one step back465figures out that the current thread is the active context and binds the466current application and the WSGI environments to that context (thread).Fixed various stylistic issues in documentationFNDbefore adoption7ccca13
line 467why, one step back467It does that in an intelligent way so that one application can invoke anotherFixed another typoArmin Ronacherbefore adoptione2fed6c
lines 468–470why, one step back468application without breaking.469470So what does this mean to you? Basically you can completely ignore thatFixed various stylistic issues in documentationFNDbefore adoption7ccca13
lines 471–472why, one step back471this is the case unless you are doing something like unit testing. You472will notice that code which depends on a request object will suddenly breakFixed another typoArmin Ronacherbefore adoptione2fed6c
lines 473–474why, one step back473because there is no request object. The solution is creating a request474object yourself and binding it to the context. The easiest solution forFixed various stylistic issues in documentationFNDbefore adoption7ccca13
line 475why, one step back475unit testing is to use the :meth:`~flask.Flask.test_request_context`Fixed another typoArmin Ronacherbefore adoptione2fed6c
lines 476–589why, one step back476context manager. In combination with the `with` statement it will bind a477test request so that you can interact with it. Here is an example::478479 from flask import request480481 with app.test_request_context('/hello', method='POST'):482 # now you can do something with the request until the483 # end of the with block, such as basic assertions:484 assert request.path == '/hello'485 assert request.method == 'POST'486487The other possibility is passing a whole WSGI environment to the488:meth:`~flask.Flask.request_context` method::489490 from flask import request491492 with app.request_context(environ):493 assert request.method == 'POST'494495The Request Object496``````````````````497498The request object is documented in the API section and we will not cover499it here in detail (see :class:`~flask.request`). Here is a broad overview of500some of the most common operations. First of all you have to import it from501the `flask` module::502503 from flask import request504505The current request method is available by using the506:attr:`~flask.request.method` attribute. To access form data (data507transmitted in a `POST` or `PUT` request) you can use the508:attr:`~flask.request.form` attribute. Here is a full example of the two509attributes mentioned above::510511 @app.route('/login', methods=['POST', 'GET'])512 def login():513 error = None514 if request.method == 'POST':515 if valid_login(request.form['username'],516 request.form['password']):517 return log_the_user_in(request.form['username'])518 else:519 error = 'Invalid username/password'520 # this is executed if the request method was GET or the521 # credentials were invalid522523What happens if the key does not exist in the `form` attribute? In that524case a special :exc:`KeyError` is raised. You can catch it like a525standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request526error page is shown instead. So for many situations you don't have to527deal with that problem.528529To access parameters submitted in the URL (``?key=value``) you can use the530:attr:`~flask.request.args` attribute::531532 searchword = request.args.get('q', '')533534We recommend accessing URL parameters with `get` or by catching the535`KeyError` because users might change the URL and presenting them a 400536bad request page in that case is not user friendly.537538For a full list of methods and attributes of the request object, head over539to the :class:`~flask.request` documentation.540541542File Uploads543````````````544545You can handle uploaded files with Flask easily. Just make sure not to546forget to set the ``enctype="multipart/form-data"`` attribute on your HTML547form, otherwise the browser will not transmit your files at all.548549Uploaded files are stored in memory or at a temporary location on the550filesystem. You can access those files by looking at the551:attr:`~flask.request.files` attribute on the request object. Each552uploaded file is stored in that dictionary. It behaves just like a553standard Python :class:`file` object, but it also has a554:meth:`~werkzeug.datastructures.FileStorage.save` method that allows you to store that555file on the filesystem of the server. Here is a simple example showing how556that works::557558 from flask import request559560 @app.route('/upload', methods=['GET', 'POST'])561 def upload_file():562 if request.method == 'POST':563 f = request.files['the_file']564 f.save('/var/www/uploads/uploaded_file.txt')565 ...566567If you want to know how the file was named on the client before it was568uploaded to your application, you can access the569:attr:`~werkzeug.datastructures.FileStorage.filename` attribute. However please keep in570mind that this value can be forged so never ever trust that value. If you571want to use the filename of the client to store the file on the server,572pass it through the :func:`~werkzeug.utils.secure_filename` function that573Werkzeug provides for you::574575 from flask import request576 from werkzeug import secure_filename577578 @app.route('/upload', methods=['GET', 'POST'])579 def upload_file():580 if request.method == 'POST':581 f = request.files['the_file']582 f.save('/var/www/uploads/' + secure_filename(f.filename))583 ...584585For some better examples, checkout the :ref:`uploading-files` pattern.586587Cookies588```````589Improved cookie documentationArmin Ronacherbefore adoption13005d7
lines 590–617why, one step back590To access cookies you can use the :attr:`~flask.Request.cookies`591attribute. To set cookies you can use the592:attr:`~flask.Response.set_cookie` method of response objects. The593:attr:`~flask.Request.cookies` attribute of request objects is a594dictionary with all the cookies the client transmits. If you want to use595sessions, do not use the cookies directly but instead use the596:ref:`sessions` in Flask that add some security on top of cookies for you.597598Reading cookies::599600 from flask import request601602 @app.route('/')603 def index():604 username = request.cookies.get('username')605 # use cookies.get(key) instead of cookies[key] to not get a606 # KeyError if the cookie is missing.607608Storing cookies::609610 from flask import make_response611612 @app.route('/')613 def index():614 resp = make_response(render_template(...))615 resp.set_cookie('username', 'the username')616 return resp617Simple documentation corrections, mostly typos.Craig Dennisbefore adoption75050d4
line 618why, one step back618Note that cookies are set on response objects. Since you normallyImproved cookie documentationArmin Ronacherbefore adoption13005d7
lines 619–621why, one step back619just return strings from the view functions Flask will convert them into620response objects for you. If you explicitly want to do that you can use621the :meth:`~flask.make_response` function and then modify it.Fixed another typoArmin Ronacherbefore adoptione2fed6c
line 622why, one step back622Updated the documentation to show how to set cookies for not yet existing responsesArmin Ronacherbefore adoptionb40af3c
lines 623–626why, one step back623Sometimes you might want to set a cookie at a point where the response624object does not exist yet. This is possible by utilizing the625:ref:`deferred-callbacks` pattern.626Extended quickstart docs for the headersArmin Ronacherbefore adoption5b16532
line 627why, one step back627For this also see :ref:`about-responses`.Fixed another typoArmin Ronacherbefore adoptione2fed6c
lines 628–663why, one step back628629Redirects and Errors630--------------------631632To redirect a user to somewhere else you can use the633:func:`~flask.redirect` function. To abort a request early with an error634code use the :func:`~flask.abort` function. Here an example how this works::635636 from flask import abort, redirect, url_for637638 @app.route('/')639 def index():640 return redirect(url_for('login'))641642 @app.route('/login')643 def login():644 abort(401)645 this_is_never_executed()646647This is a rather pointless example because a user will be redirected from648the index to a page they cannot access (401 means access denied) but it649shows how that works.650651By default a black and white error page is shown for each error code. If652you want to customize the error page, you can use the653:meth:`~flask.Flask.errorhandler` decorator::654655 from flask import render_template656657 @app.errorhandler(404)658 def page_not_found(error):659 return render_template('page_not_found.html'), 404660661Note the ``404`` after the :func:`~flask.render_template` call. This662tells Flask that the status code of that page should be 404 which means663not found. By default 200 is assumed which translates to: all went well.Extended quickstart docs for the headersArmin Ronacherbefore adoption5b16532
lines 664–681why, one step back664665.. _about-responses:666667About Responses668---------------669670The return value from a view function is automatically converted into a671response object for you. If the return value is a string it's converted672into a response object with the string as response body, an ``200 OK``673error code and a ``text/html`` mimetype. The logic that Flask applies to674converting return values into response objects is as follows:6756761. If a response object of the correct type is returned it's directly677 returned from the view.6782. If it's a string, a response object is created with that data and the679 default parameters.6803. If a tuple is returned the response object is created by passing the681 tuple as arguments to the response object's constructor.Fixed various stylistic issues in documentationFNDbefore adoption7ccca13
lines 682–683why, one step back6824. If none of that works, Flask will assume the return value is a683 valid WSGI application and convert that into a response object.Extended quickstart docs for the headersArmin Ronacherbefore adoption5b16532
lines 684–706why, one step back684685If you want to get hold of the resulting response object inside the view686you can use the :func:`~flask.make_response` function.687688Imagine you have a view like this:689690.. sourcecode:: python691692 @app.errorhandler(404)693 def not_found(error):694 return render_template('error.html'), 404695696You just need to wrap the return expression with697:func:`~flask.make_response` and get the result object to modify it, then698return it:699700.. sourcecode:: python701702 @app.errorhandler(404)703 def not_found(error):704 resp = make_response(render_template('error.html'), 404)705 resp.headers['X-Something'] = 'A value'706 return respFixed another typoArmin Ronacherbefore adoptione2fed6c
lines 707–712why, one step back707708.. _sessions:709710Sessions711--------712Fixed various stylistic issues in documentationFNDbefore adoption7ccca13
lines 713–714why, one step back713In addition to the request object there is also a second object called714:class:`~flask.session` which allows you to store information specific to aFixed another typoArmin Ronacherbefore adoptione2fed6c
lines 715–753why, one step back715user from one request to the next. This is implemented on top of cookies716for you and signs the cookies cryptographically. What this means is that717the user could look at the contents of your cookie but not modify it,718unless they know the secret key used for signing.719720In order to use sessions you have to set a secret key. Here is how721sessions work::722723 from flask import Flask, session, redirect, url_for, escape, request724725 app = Flask(__name__)726727 @app.route('/')728 def index():729 if 'username' in session:730 return 'Logged in as %s' % escape(session['username'])731 return 'You are not logged in'732733 @app.route('/login', methods=['GET', 'POST'])734 def login():735 if request.method == 'POST':736 session['username'] = request.form['username']737 return redirect(url_for('index'))738 return '''739 <form action="" method="post">740 <p><input type=text name=username>741 <p><input type=submit value=Login>742 </form>743 '''744745 @app.route('/logout')746 def logout():747 # remove the username from the session if its there748 session.pop('username', None)749 return redirect(url_for('index'))750751 # set the secret key. keep this really secret:752 app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'753Fixed various stylistic issues in documentationFNDbefore adoption7ccca13
lines 754–755why, one step back754The :func:`~flask.escape` mentioned here does escaping for you if you are755not using the template engine (as in this example).Fixed another typoArmin Ronacherbefore adoptione2fed6c
lines 756–758why, one step back756757.. admonition:: How to generate good secret keys758Fixed various stylistic issues in documentationFNDbefore adoption7ccca13
line 759why, one step back759 The problem with random is that it's hard to judge what is truly random. AndFixed another typoArmin Ronacherbefore adoptione2fed6c
lines 760–776why, one step back760 a secret key should be as random as possible. Your operating system761 has ways to generate pretty random stuff based on a cryptographic762 random generator which can be used to get such a key:763764 >>> import os765 >>> os.urandom(24)766 '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'767768 Just take that thing and copy/paste it into your code and you're done.769770Message Flashing771----------------772773Good applications and user interfaces are all about feedback. If the user774does not get enough feedback they will probably end up hating the775application. Flask provides a really simple way to give feedback to a776user with the flashing system. The flashing system basically makes itFixed various stylistic issues in documentationFNDbefore adoption7ccca13
lines 777–779why, one step back777possible to record a message at the end of a request and access it on the next778(and only the next) request. This is usually combined with a layout779template to expose the message.Fixed another typoArmin Ronacherbefore adoptione2fed6c
lines 780–791why, one step back780781To flash a message use the :func:`~flask.flash` method, to get hold of the782messages you can use :func:`~flask.get_flashed_messages` which is also783available in the templates. Check out the :ref:`message-flashing-pattern`784for a full example.785786Logging787-------788789.. versionadded:: 0.3790791Sometimes you might be in a situation where you deal with data thatFixed various stylistic issues in documentationFNDbefore adoption7ccca13
lines 792–795why, one step back792should be correct, but actually is not. For example you may have some client-side793code that sends an HTTP request to the server but it's obviously794malformed. This might be caused by a user tampering with the data, or the795client code failing. Most of the time it's okay to reply with ``400 BadFixed another typoArmin Ronacherbefore adoptione2fed6c
lines 796–823why, one step back796Request`` in that situation, but sometimes that won't do and the code has797to continue working.798799You may still want to log that something fishy happened. This is where800loggers come in handy. As of Flask 0.3 a logger is preconfigured for you801to use.802803Here are some example log calls::804805 app.logger.debug('A value for debugging')806 app.logger.warning('A warning occurred (%d apples)', 42)807 app.logger.error('An error occurred')808809The attached :attr:`~flask.Flask.logger` is a standard logging810:class:`~logging.Logger`, so head over to the official `logging811documentation <http://docs.python.org/library/logging.html>`_ for more812information.813814Hooking in WSGI Middlewares815---------------------------816817If you want to add a WSGI middleware to your application you can wrap the818internal WSGI application. For example if you want to use one of the819middlewares from the Werkzeug package to work around bugs in lighttpd, you820can do it like this::821822 from werkzeug.contrib.fixers import LighttpdCGIRootFix823 app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)