Skip to content
Myr

quickstart.rst

This file

Path

docs/quickstart.rst

852 lines · 31.2 KiB

Last changed by

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption30d9efb

History of this file

Take it

The walk stopped after 200 commits: lines older than 0b33693 point at it.

Allow loading template from iterableDmitry Shevchenkobefore adoption0b33693

lines 1–40why, one step back
1.. _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!'2223 if __name__ == '__main__':24 app.run()2526Just save it as `hello.py` (or something similar) and run it with your Python27interpreter. Make sure to not call your application `flask.py` because this28would conflict with Flask itself.2930::3132 $ python hello.py33 * Running on http://127.0.0.1:5000/3435Now head over to `http://127.0.0.1:5000/ <http://127.0.0.1:5000/>`_, and you36should see your hello world greeting.3738So what did that code do?39401. First we imported the :class:`~flask.Flask` class. An instance of this

Merge pull request #683 from alexcouper/masterKenneth Reitzbefore adoptionaa83d91

lines 41–48why, one step back
41 class will be our WSGI application.
422. Next we create an instance of this class. The first argument is the name of43 the application's module or package. If you are using a single module (as44 in this example), you should use `__name__` because depending on if it's45 started as application or imported as module the name will be different46 (``'__main__'`` versus the actual import name). This is needed so that47 Flask knows where to look for templates, static files, and so on. For more48 information have a look at the :class:`~flask.Flask` documentation.

Allow loading template from iterableDmitry Shevchenkobefore adoption0b33693

lines 49–56why, one step back
493. We then use the :meth:`~flask.Flask.route` decorator to tell Flask what URL
50 should trigger our function.514. The function is given a name which is also used to generate URLs for that52 particular function, and returns the message we want to display in the53 user's browser.545. Finally we use the :meth:`~flask.Flask.run` function to run the local server55 with our application. The ``if __name__ == '__main__':`` makes sure the56 server only runs if the script is executed directly from the Python

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption30d9efb

line 57why, one step back
57 interpreter and not used as an imported module.

Allow loading template from iterableDmitry Shevchenkobefore adoption0b33693

lines 58–145why, one step back
58
59To stop the server, hit control-C.6061.. _public-server:6263.. admonition:: Externally Visible Server6465 If you run the server you will notice that the server is only accessible66 from your own computer, not from any other in the network. This is the67 default because in debugging mode a user of the application can execute68 arbitrary Python code on your computer.6970 If you have `debug` disabled or trust the users on your network, you can71 make the server publicly available simply by changing the call of the72 :meth:`~flask.Flask.run` method to look like this::7374 app.run(host='0.0.0.0')7576 This tells your operating system to listen on all public IPs.777879.. _debug-mode:8081Debug Mode82----------8384The :meth:`~flask.Flask.run` method is nice to start a local85development server, but you would have to restart it manually after each86change to your code. That is not very nice and Flask can do better. If87you enable debug support the server will reload itself on code changes,88and it will also provide you with a helpful debugger if things go wrong.8990There are two ways to enable debugging. Either set that flag on the91application object::9293 app.debug = True94 app.run()9596Or pass it as a parameter to run::9798 app.run(debug=True)99100Both methods have the exact same effect.101102.. admonition:: Attention103104 Even though the interactive debugger does not work in forking environments105 (which makes it nearly impossible to use on production servers), it still106 allows the execution of arbitrary code. This makes it a major security risk107 and therefore it **must never be used on production machines**.108109Screenshot of the debugger in action:110111.. image:: _static/debugger.png112 :align: center113 :class: screenshot114 :alt: screenshot of debugger in action115116Have another debugger in mind? See :ref:`working-with-debuggers`.117118119Routing120-------121122Modern web applications have beautiful URLs. This helps people remember123the URLs, which is especially handy for applications that are used from124mobile devices with slower network connections. If the user can directly125go to the desired page without having to hit the index page it is more126likely they will like the page and come back next time.127128As you have seen above, the :meth:`~flask.Flask.route` decorator is used to129bind a function to a URL. Here are some basic examples::130131 @app.route('/')132 def index():133 return 'Index Page'134135 @app.route('/hello')136 def hello():137 return 'Hello World'138139But there is more to it! You can make certain parts of the URL dynamic and140attach multiple rules to a function.141142Variable Rules143``````````````144145To add variable parts to a URL you can mark these special sections as

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption30d9efb

lines 146–147why, one step back
146``<variable_name>``. Such a part is then passed as a keyword argument to your
147function. Optionally a converter can be used by specifying a rule with

Allow loading template from iterableDmitry Shevchenkobefore adoption0b33693

lines 148–167why, one step back
148``<converter:variable_name>``. Here are some nice examples::
149150 @app.route('/user/<username>')151 def show_user_profile(username):152 # show the user profile for that user153 return 'User %s' % username154155 @app.route('/post/<int:post_id>')156 def show_post(post_id):157 # show the post with the given id, the id is an integer158 return 'Post %d' % post_id159160The following converters exist:161162=========== ===========================================163`int` accepts integers164`float` like `int` but for floating point values165`path` like the default but also accepts slashes166=========== ===========================================167

Use American English for "behavior" in docs.Ron DuPlainbefore adoptiona3cb2a3

line 168why, one step back
168.. admonition:: Unique URLs / Redirection Behavior

Allow loading template from iterableDmitry Shevchenkobefore adoption0b33693

line 169why, one step back
169

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

lines 170–171why, one step back
170 Flask's URL rules are based on Werkzeug's routing module. The idea
171 behind that module is to ensure beautiful and unique URLs based on

Allow loading template from iterableDmitry Shevchenkobefore adoption0b33693

lines 172–193why, one step back
172 precedents laid down by Apache and earlier HTTP servers.
173174 Take these two rules::175176 @app.route('/projects/')177 def projects():178 return 'The project page'179180 @app.route('/about')181 def about():182 return 'The about page'183184 Though they look rather similar, they differ in their use of the trailing185 slash in the URL *definition*. In the first case, the canonical URL for the186 `projects` endpoint has a trailing slash. In that sense, it is similar to187 a folder on a file system. Accessing it without a trailing slash will cause188 Flask to redirect to the canonical URL with the trailing slash.189190 In the second case, however, the URL is defined without a trailing slash,191 rather like the pathname of a file on UNIX-like systems. Accessing the URL192 with a trailing slash will produce a 404 "Not Found" error.193

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption30d9efb

lines 194–197why, one step back
194 This behavior allows relative URLs to continue working even if the trailing
195 slash is ommited, consistent with how Apache and other servers work. Also, 196 the URLs will stay unique, which helps search engines avoid indexing the 197 same page twice.

Allow loading template from iterableDmitry Shevchenkobefore adoption0b33693

lines 198–235why, one step back
198
199200.. _url-building:201202URL Building203````````````204205If it can match URLs, can Flask also generate them? Of course it can. To206build a URL to a specific function you can use the :func:`~flask.url_for`207function. It accepts the name of the function as first argument and a number208of keyword arguments, each corresponding to the variable part of the URL rule.209Unknown variable parts are appended to the URL as query parameters. Here are210some examples:211212>>> from flask import Flask, url_for213>>> app = Flask(__name__)214>>> @app.route('/')215... def index(): pass216...217>>> @app.route('/login')218... def login(): pass219...220>>> @app.route('/user/<username>')221... def profile(username): pass222...223>>> with app.test_request_context():224... print url_for('index')225... print url_for('login')226... print url_for('login', next='/')227... print url_for('profile', username='John Doe')228...229/230/login231/login?next=/232/user/John%20Doe233234(This also uses the :meth:`~flask.Flask.test_request_context` method, explained235below. It tells Flask to behave as though it is handling a request, even

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

line 236why, one step back
236though we are interacting with it through a Python shell. Have a look at the

Allow loading template from iterableDmitry Shevchenkobefore adoption0b33693

lines 237–334why, one step back
237explanation below. :ref:`context-locals`).
238239Why would you want to build URLs instead of hard-coding them into your240templates? There are three good reasons for this:2412421. Reversing is often more descriptive than hard-coding the URLs. More243 importantly, it allows you to change URLs in one go, without having to244 remember to change URLs all over the place.2452. URL building will handle escaping of special characters and Unicode246 data transparently for you, so you don't have to deal with them.2473. If your application is placed outside the URL root (say, in248 ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will handle249 that properly for you.250251252HTTP Methods253````````````254255HTTP (the protocol web applications are speaking) knows different methods for256accessing URLs. By default, a route only answers to `GET` requests, but that257can be changed by providing the `methods` argument to the258:meth:`~flask.Flask.route` decorator. Here are some examples::259260 @app.route('/login', methods=['GET', 'POST'])261 def login():262 if request.method == 'POST':263 do_the_login()264 else:265 show_the_login_form()266267If `GET` is present, `HEAD` will be added automatically for you. You268don't have to deal with that. It will also make sure that `HEAD` requests269are handled as the `HTTP RFC`_ (the document describing the HTTP270protocol) demands, so you can completely ignore that part of the HTTP271specification. Likewise, as of Flask 0.6, `OPTIONS` is implemented for you272automatically as well.273274You have no idea what an HTTP method is? Worry not, here is a quick275introduction to HTTP methods and why they matter:276277The HTTP method (also often called "the verb") tells the server what the278clients wants to *do* with the requested page. The following methods are279very common:280281`GET`282 The browser tells the server to just *get* the information stored on283 that page and send it. This is probably the most common method.284285`HEAD`286 The browser tells the server to get the information, but it is only287 interested in the *headers*, not the content of the page. An288 application is supposed to handle that as if a `GET` request was289 received but to not deliver the actual content. In Flask you don't290 have to deal with that at all, the underlying Werkzeug library handles291 that for you.292293`POST`294 The browser tells the server that it wants to *post* some new295 information to that URL and that the server must ensure the data is296 stored and only stored once. This is how HTML forms usually297 transmit data to the server.298299`PUT`300 Similar to `POST` but the server might trigger the store procedure301 multiple times by overwriting the old values more than once. Now you302 might be asking why this is useful, but there are some good reasons303 to do it this way. Consider that the connection is lost during304 transmission: in this situation a system between the browser and the305 server might receive the request safely a second time without breaking306 things. With `POST` that would not be possible because it must only307 be triggered once.308309`DELETE`310 Remove the information at the given location.311312`OPTIONS`313 Provides a quick way for a client to figure out which methods are314 supported by this URL. Starting with Flask 0.6, this is implemented315 for you automatically.316317Now the interesting part is that in HTML4 and XHTML1, the only methods a318form can submit to the server are `GET` and `POST`. But with JavaScript319and future HTML standards you can use the other methods as well. Furthermore320HTTP has become quite popular lately and browsers are no longer the only321clients that are using HTTP. For instance, many revision control system322use it.323324.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt325326Static Files327------------328329Dynamic web applications also need static files. That's usually where330the CSS and JavaScript files are coming from. Ideally your web server is331configured to serve them for you, but during development Flask can do that332as well. Just create a folder called `static` in your package or next to333your module and it will be available at `/static` on the application.334

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

line 335why, one step back
335To generate URLs for static files, use the special ``'static'`` endpoint name::

Allow loading template from iterableDmitry Shevchenkobefore adoption0b33693

lines 336–378why, one step back
336
337 url_for('static', filename='style.css')338339The file has to be stored on the filesystem as ``static/style.css``.340341Rendering Templates342-------------------343344Generating HTML from within Python is not fun, and actually pretty345cumbersome because you have to do the HTML escaping on your own to keep346the application secure. Because of that Flask configures the `Jinja2347<http://jinja.pocoo.org/2/>`_ template engine for you automatically.348349To render a template you can use the :func:`~flask.render_template`350method. All you have to do is provide the name of the template and the351variables you want to pass to the template engine as keyword arguments.352Here's a simple example of how to render a template::353354 from flask import render_template355356 @app.route('/hello/')357 @app.route('/hello/<name>')358 def hello(name=None):359 return render_template('hello.html', name=name)360361Flask will look for templates in the `templates` folder. So if your362application is a module, this folder is next to that module, if it's a363package it's actually inside your package:364365**Case 1**: a module::366367 /application.py368 /templates369 /hello.html370371**Case 2**: a package::372373 /application374 /__init__.py375 /templates376 /hello.html377378For templates you can use the full power of Jinja2 templates. Head over

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption7fc0ddb

line 379why, one step back
379to the official `Jinja2 Template Documentation

Allow loading template from iterableDmitry Shevchenkobefore adoption0b33693

lines 380–515why, one step back
380<http://jinja.pocoo.org/2/documentation/templates>`_ for more information.
381382Here is an example template:383384.. sourcecode:: html+jinja385386 <!doctype html>387 <title>Hello from Flask</title>388 {% if name %}389 <h1>Hello {{ name }}!</h1>390 {% else %}391 <h1>Hello World!</h1>392 {% endif %}393394Inside templates you also have access to the :class:`~flask.request`,395:class:`~flask.session` and :class:`~flask.g` [#]_ objects396as well as the :func:`~flask.get_flashed_messages` function.397398Templates are especially useful if inheritance is used. If you want to399know how that works, head over to the :ref:`template-inheritance` pattern400documentation. Basically template inheritance makes it possible to keep401certain elements on each page (like header, navigation and footer).402403Automatic escaping is enabled, so if `name` contains HTML it will be escaped404automatically. If you can trust a variable and you know that it will be405safe HTML (for example because it came from a module that converts wiki406markup to HTML) you can mark it as safe by using the407:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the408template. Head over to the Jinja 2 documentation for more examples.409410Here is a basic introduction to how the :class:`~jinja2.Markup` class works:411412>>> from flask import Markup413>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'414Markup(u'<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')415>>> Markup.escape('<blink>hacker</blink>')416Markup(u'&lt;blink&gt;hacker&lt;/blink&gt;')417>>> Markup('<em>Marked up</em> &raquo; HTML').striptags()418u'Marked up \xbb HTML'419420.. versionchanged:: 0.5421422 Autoescaping is no longer enabled for all templates. The following423 extensions for templates trigger autoescaping: ``.html``, ``.htm``,424 ``.xml``, ``.xhtml``. Templates loaded from a string will have425 autoescaping disabled.426427.. [#] Unsure what that :class:`~flask.g` object is? It's something in which428 you can store information for your own needs, check the documentation of429 that object (:class:`~flask.g`) and the :ref:`sqlite3` for more430 information.431432433Accessing Request Data434----------------------435436For web applications it's crucial to react to the data a client sent to437the server. In Flask this information is provided by the global438:class:`~flask.request` object. If you have some experience with Python439you might be wondering how that object can be global and how Flask440manages to still be threadsafe. The answer is context locals:441442443.. _context-locals:444445Context Locals446``````````````447448.. admonition:: Insider Information449450 If you want to understand how that works and how you can implement451 tests with context locals, read this section, otherwise just skip it.452453Certain objects in Flask are global objects, but not of the usual kind.454These objects are actually proxies to objects that are local to a specific455context. What a mouthful. But that is actually quite easy to understand.456457Imagine the context being the handling thread. A request comes in and the458web server decides to spawn a new thread (or something else, the459underlying object is capable of dealing with concurrency systems other460than threads). When Flask starts its internal request handling it461figures out that the current thread is the active context and binds the462current application and the WSGI environments to that context (thread).463It does that in an intelligent way so that one application can invoke another464application without breaking.465466So what does this mean to you? Basically you can completely ignore that467this is the case unless you are doing something like unit testing. You468will notice that code which depends on a request object will suddenly break469because there is no request object. The solution is creating a request470object yourself and binding it to the context. The easiest solution for471unit testing is to use the :meth:`~flask.Flask.test_request_context`472context manager. In combination with the `with` statement it will bind a473test request so that you can interact with it. Here is an example::474475 from flask import request476477 with app.test_request_context('/hello', method='POST'):478 # now you can do something with the request until the479 # end of the with block, such as basic assertions:480 assert request.path == '/hello'481 assert request.method == 'POST'482483The other possibility is passing a whole WSGI environment to the484:meth:`~flask.Flask.request_context` method::485486 from flask import request487488 with app.request_context(environ):489 assert request.method == 'POST'490491The Request Object492``````````````````493494The request object is documented in the API section and we will not cover495it here in detail (see :class:`~flask.request`). Here is a broad overview of496some of the most common operations. First of all you have to import it from497the `flask` module::498499 from flask import request500501The current request method is available by using the502:attr:`~flask.request.method` attribute. To access form data (data503transmitted in a `POST` or `PUT` request) you can use the504:attr:`~flask.request.form` attribute. Here is a full example of the two505attributes mentioned above::506507 @app.route('/login', methods=['POST', 'GET'])508 def login():509 error = None510 if request.method == 'POST':511 if valid_login(request.form['username'],512 request.form['password']):513 return log_the_user_in(request.form['username'])514 else:515 error = 'Invalid username/password'

Merge pull request #692 from mikegagnon/patch-1Armin Ronacherbefore adoption0a29c29

line 516why, one step back
516 # the code below is executed if the request method

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption2e816f5

lines 517–518why, one step back
517 # was GET or the credentials were invalid
518 return render_template('login.html', error=error)

Allow loading template from iterableDmitry Shevchenkobefore adoption0b33693

lines 519–528why, one step back
519
520What happens if the key does not exist in the `form` attribute? In that521case a special :exc:`KeyError` is raised. You can catch it like a522standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request523error page is shown instead. So for many situations you don't have to524deal with that problem.525526To access parameters submitted in the URL (``?key=value``) you can use the527:attr:`~flask.request.args` attribute::528

Merge pull request #498 from alekzvik/masterKenneth Reitzbefore adoptionccc6816

line 529why, one step back
529 searchword = request.args.get('key', '')

Allow loading template from iterableDmitry Shevchenkobefore adoption0b33693

lines 530–628why, one step back
530
531We recommend accessing URL parameters with `get` or by catching the532`KeyError` because users might change the URL and presenting them a 400533bad request page in that case is not user friendly.534535For a full list of methods and attributes of the request object, head over536to the :class:`~flask.request` documentation.537538539File Uploads540````````````541542You can handle uploaded files with Flask easily. Just make sure not to543forget to set the ``enctype="multipart/form-data"`` attribute on your HTML544form, otherwise the browser will not transmit your files at all.545546Uploaded files are stored in memory or at a temporary location on the547filesystem. You can access those files by looking at the548:attr:`~flask.request.files` attribute on the request object. Each549uploaded file is stored in that dictionary. It behaves just like a550standard Python :class:`file` object, but it also has a551:meth:`~werkzeug.datastructures.FileStorage.save` method that allows you to store that552file on the filesystem of the server. Here is a simple example showing how553that works::554555 from flask import request556557 @app.route('/upload', methods=['GET', 'POST'])558 def upload_file():559 if request.method == 'POST':560 f = request.files['the_file']561 f.save('/var/www/uploads/uploaded_file.txt')562 ...563564If you want to know how the file was named on the client before it was565uploaded to your application, you can access the566:attr:`~werkzeug.datastructures.FileStorage.filename` attribute. However please keep in567mind that this value can be forged so never ever trust that value. If you568want to use the filename of the client to store the file on the server,569pass it through the :func:`~werkzeug.utils.secure_filename` function that570Werkzeug provides for you::571572 from flask import request573 from werkzeug import secure_filename574575 @app.route('/upload', methods=['GET', 'POST'])576 def upload_file():577 if request.method == 'POST':578 f = request.files['the_file']579 f.save('/var/www/uploads/' + secure_filename(f.filename))580 ...581582For some better examples, checkout the :ref:`uploading-files` pattern.583584Cookies585```````586587To access cookies you can use the :attr:`~flask.Request.cookies`588attribute. To set cookies you can use the589:attr:`~flask.Response.set_cookie` method of response objects. The590:attr:`~flask.Request.cookies` attribute of request objects is a591dictionary with all the cookies the client transmits. If you want to use592sessions, do not use the cookies directly but instead use the593:ref:`sessions` in Flask that add some security on top of cookies for you.594595Reading cookies::596597 from flask import request598599 @app.route('/')600 def index():601 username = request.cookies.get('username')602 # use cookies.get(key) instead of cookies[key] to not get a603 # KeyError if the cookie is missing.604605Storing cookies::606607 from flask import make_response608609 @app.route('/')610 def index():611 resp = make_response(render_template(...))612 resp.set_cookie('username', 'the username')613 return resp614615Note that cookies are set on response objects. Since you normally616just return strings from the view functions Flask will convert them into617response objects for you. If you explicitly want to do that you can use618the :meth:`~flask.make_response` function and then modify it.619620Sometimes you might want to set a cookie at a point where the response621object does not exist yet. This is possible by utilizing the622:ref:`deferred-callbacks` pattern.623624For this also see :ref:`about-responses`.625626Redirects and Errors627--------------------628

Merge pull request #607 from jfinkels/patch-3Armin Ronacherbefore adoptionb2fc9fe

lines 629–631why, one step back
629To redirect a user to another endpoint, use the :func:`~flask.redirect`
630function; to abort a request early with an error code, use the631:func:`~flask.abort` function::

Allow loading template from iterableDmitry Shevchenkobefore adoption0b33693

lines 632–676why, one step back
632
633 from flask import abort, redirect, url_for634635 @app.route('/')636 def index():637 return redirect(url_for('login'))638639 @app.route('/login')640 def login():641 abort(401)642 this_is_never_executed()643644This is a rather pointless example because a user will be redirected from645the index to a page they cannot access (401 means access denied) but it646shows how that works.647648By default a black and white error page is shown for each error code. If649you want to customize the error page, you can use the650:meth:`~flask.Flask.errorhandler` decorator::651652 from flask import render_template653654 @app.errorhandler(404)655 def page_not_found(error):656 return render_template('page_not_found.html'), 404657658Note the ``404`` after the :func:`~flask.render_template` call. This659tells Flask that the status code of that page should be 404 which means660not found. By default 200 is assumed which translates to: all went well.661662.. _about-responses:663664About Responses665---------------666667The return value from a view function is automatically converted into a668response object for you. If the return value is a string it's converted669into a response object with the string as response body, an ``200 OK``670error code and a ``text/html`` mimetype. The logic that Flask applies to671converting return values into response objects is as follows:6726731. If a response object of the correct type is returned it's directly674 returned from the view.6752. If it's a string, a response object is created with that data and the676 default parameters.

Changed the implementation of returning tuples from functionsArmin Ronacherbefore adoptioncf1641e

lines 677–681why, one step back
6773. If a tuple is returned the items in the tuple can provide extra
678 information. Such tuples have to be in the form ``(response, status,679 headers)`` where at least one item has to be in the tuple. The680 `status` value will override the status code and `headers` can be a681 list or dictionary of additional header values.

Allow loading template from iterableDmitry Shevchenkobefore adoption0b33693

lines 682–696why, one step back
6824. If none of that works, Flask will assume the return value is a
683 valid WSGI application and convert that into a response object.684685If 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 with

Merge pull request #681 from dmizelle/docs-quickstartKenneth Reitzbefore adoptionb9118ca

line 697why, one step back
697:func:`~flask.make_response` and get the response object to modify it, then

Allow loading template from iterableDmitry Shevchenkobefore adoption0b33693

lines 698–746why, one step back
698return 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 resp707708.. _sessions:709710Sessions711--------712713In addition to the request object there is also a second object called714:class:`~flask.session` which allows you to store information specific to a715user 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():

Merge pull request #486 from PaulMcMillan/docs_fixRon DuPlainbefore adoption1a19ddc

line 747why, one step back
747 # remove the username from the session if it's there

Allow loading template from iterableDmitry Shevchenkobefore adoption0b33693

lines 748–830why, one step back
748 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'753754The :func:`~flask.escape` mentioned here does escaping for you if you are755not using the template engine (as in this example).756757.. admonition:: How to generate good secret keys758759 The problem with random is that it's hard to judge what is truly random. And760 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.769770A note on cookie-based sessions: Flask will take the values you put into the771session object and serialize them into a cookie. If you are finding some772values do not persist across requests, cookies are indeed enabled, and you are773not getting a clear error message, check the size of the cookie in your page774responses compared to the size supported by web browsers.775776777Message Flashing778----------------779780Good applications and user interfaces are all about feedback. If the user781does not get enough feedback they will probably end up hating the782application. Flask provides a really simple way to give feedback to a783user with the flashing system. The flashing system basically makes it784possible to record a message at the end of a request and access it on the next785(and only the next) request. This is usually combined with a layout786template to expose the message.787788To flash a message use the :func:`~flask.flash` method, to get hold of the789messages you can use :func:`~flask.get_flashed_messages` which is also790available in the templates. Check out the :ref:`message-flashing-pattern`791for a full example.792793Logging794-------795796.. versionadded:: 0.3797798Sometimes you might be in a situation where you deal with data that799should be correct, but actually is not. For example you may have some client-side800code that sends an HTTP request to the server but it's obviously801malformed. This might be caused by a user tampering with the data, or the802client code failing. Most of the time it's okay to reply with ``400 Bad803Request`` in that situation, but sometimes that won't do and the code has804to continue working.805806You may still want to log that something fishy happened. This is where807loggers come in handy. As of Flask 0.3 a logger is preconfigured for you808to use.809810Here are some example log calls::811812 app.logger.debug('A value for debugging')813 app.logger.warning('A warning occurred (%d apples)', 42)814 app.logger.error('An error occurred')815816The attached :attr:`~flask.Flask.logger` is a standard logging817:class:`~logging.Logger`, so head over to the official `logging818documentation <http://docs.python.org/library/logging.html>`_ for more819information.820821Hooking in WSGI Middlewares822---------------------------823824If you want to add a WSGI middleware to your application you can wrap the825internal WSGI application. For example if you want to use one of the826middlewares from the Werkzeug package to work around bugs in lighttpd, you827can do it like this::828829 from werkzeug.contrib.fixers import LighttpdCGIRootFix830 app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

lines 831–852why, one step back
831
832.. _quickstart_deployment:833834Deploying to a Web Server835-------------------------836837Ready to deploy your new Flask app? To wrap up the quickstart, you can838immediately deploy to a hosted platform, all of which offer a free plan for839small projects:840841- `Deploying Flask on Heroku <http://devcenter.heroku.com/articles/python>`_842- `Deploying WSGI on dotCloud <http://docs.dotcloud.com/services/python/>`_843 with `Flask-specific notes <http://flask.pocoo.org/snippets/48/>`_844845Other places where you can host your Flask app:846847- `Deploying Flask on Webfaction <http://flask.pocoo.org/snippets/65/>`_848- `Deploying Flask on Google App Engine <https://github.com/kamalgill/flask-appengine-template>`_849- `Sharing your Localhost Server with Localtunnel <http://flask.pocoo.org/snippets/89/>`_850851If you manage your own hosts and would like to host yourself, see the chapter852on :ref:`deployment`.