quickstart.rst
This file
Path
docs/quickstart.rst
892 lines · 32.8 KiB
Last changed by
Merge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01
History of this fileTake it
The walk stopped after 200 commits: lines older than e59e005 point at it.
Fixed a documentation typoArmin Ronacherbefore adoptione59e005
lines 1–26why, one step back1.. _quickstart:23Quickstart4==========56Eager to get started? This page gives a good introduction to Flask. It7assumes you already have Flask installed. If you do not, head over to the8:ref:`installation` section.91011A Minimal Application12---------------------1314A minimal Flask application looks something like this::1516 from flask import Flask17 app = Flask(__name__)1819 @app.route('/')20 def hello_world():21 return 'Hello World!'2223Just save it as `hello.py` (or something similar) and run it with your Python24interpreter. Make sure to not call your application `flask.py` because this25would conflict with Flask itself.26Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
lines 27–28why, one step back27To run the application you can either use the ``flask`` command or28python's ``-m`` switch with Flask::Fixed a documentation typoArmin Ronacherbefore adoptione59e005
line 29why, one step back29Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
line 30why, one step back30 $ flask -a hello runFixed a documentation typoArmin Ronacherbefore adoptione59e005
lines 31–32why, one step back31 * Running on http://127.0.0.1:5000/32Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
lines 33–37why, one step back33or alternatively::3435 $ python -m flask -a hello run36 * Running on http://127.0.0.1:5000/37Fixed a documentation typoArmin Ronacherbefore adoptione59e005
lines 38–43why, one step back38Now head over to `http://127.0.0.1:5000/ <http://127.0.0.1:5000/>`_, and you39should see your hello world greeting.4041So what did that code do?42431. First we imported the :class:`~flask.Flask` class. An instance of thisMerge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01
line 44why, one step back44 class will be our WSGI application.Fixed a documentation typoArmin Ronacherbefore adoptione59e005
lines 45–56why, one step back452. Next we create an instance of this class. The first argument is the name of46 the application's module or package. If you are using a single module (as47 in this example), you should use `__name__` because depending on if it's48 started as application or imported as module the name will be different49 (``'__main__'`` versus the actual import name). This is needed so that50 Flask knows where to look for templates, static files, and so on. For more51 information have a look at the :class:`~flask.Flask` documentation.523. We then use the :meth:`~flask.Flask.route` decorator to tell Flask what URL53 should trigger our function.544. The function is given a name which is also used to generate URLs for that55 particular function, and returns the message we want to display in the56 user's browser.Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
lines 57–58why, one step back575. Finally we use the Flask development server to run the local server58 with our application.Fixed a documentation typoArmin Ronacherbefore adoptione59e005
lines 59–70why, one step back5960To stop the server, hit control-C.6162.. _public-server:6364.. admonition:: Externally Visible Server6566 If you run the server you will notice that the server is only accessible67 from your own computer, not from any other in the network. This is the68 default because in debugging mode a user of the application can execute69 arbitrary Python code on your computer.70Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
lines 71–73why, one step back71 If you have the debugger disabled or trust the users on your network,72 you can make the server publicly available simply by adding73 ``--host=0.0.0.0`` to the command line::Fixed a documentation typoArmin Ronacherbefore adoptione59e005
line 74why, one step back74Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
line 75why, one step back75 flask -a hello run --host=0.0.0.0Fixed a documentation typoArmin Ronacherbefore adoptione59e005
lines 76–78why, one step back7677 This tells your operating system to listen on all public IPs.78Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
lines 79–80why, one step back79What to do if the Server does not Start80---------------------------------------Fixed a documentation typoArmin Ronacherbefore adoptione59e005
line 81why, one step back81Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
lines 82–114why, one step back82In case the ``python -m flask`` fails or ``flask`` does not exist,83there are multiple reasons this might be the case. First of all you need84to look at the error message.8586Old Version of Flask87````````````````````8889Versions of Flask older than 1.0 use to have different ways to start the90application. In short, the ``flask`` command did not exist, and91neither did ``python -m flask``. In that case you have two options:92either upgrade to newer Flask versions or have a look at the :ref:`server`93docs to see the alternative method for running a server.9495Python older 2.796````````````````9798In case you have a version of Python older than 2.7 ``python -m flask``99does not work. You can either use ``flask`` or ``python -m100flask.cli`` as an alternative. This is because Python before 2.7 does no101permit packages to act as executable modules. For more information see102:ref:`cli`.103104Invalid Import Name105```````````````````106107The ``-a`` argument to ``flask`` is the name of the module to import. In108case that module is incorrectly named you will get an import error upon109start (or if debug is enabled when you navigate to the application). It110will tell you what it tried to import and why it failed.111112The most common reason is a typo or because you did not actually create an113``app`` object.114Fixed a documentation typoArmin Ronacherbefore adoptione59e005
lines 115–119why, one step back115.. _debug-mode:116117Debug Mode118----------119Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
lines 120–124why, one step back120The ``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.Fixed a documentation typoArmin Ronacherbefore adoptione59e005
line 125why, one step back125Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
lines 126–127why, one step back126There are different ways to enable the debug mode. The most obvious one127is the ``--debug`` parameter to the ``flask`` command::Fixed a documentation typoArmin Ronacherbefore adoptione59e005
line 128why, one step back128Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
line 129why, one step back129 flask --debug -a hello runFixed a documentation typoArmin Ronacherbefore adoptione59e005
line 130why, one step back130Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
line 131why, one step back131This does the following things:Fixed a documentation typoArmin Ronacherbefore adoptione59e005
line 132why, one step back132Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
lines 133–135why, one step back1331. it activates the debugger1342. it activates the automatic reloader1353. it enables the debug mode on the Flask application.Fixed a documentation typoArmin Ronacherbefore adoptione59e005
line 136why, one step back136Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
line 137why, one step back137There are more parameters that are explained in the :ref:`server` docs.Fixed a documentation typoArmin Ronacherbefore adoptione59e005
lines 138–231why, one step back138139.. admonition:: Attention140141 Even though the interactive debugger does not work in forking environments142 (which makes it nearly impossible to use on production servers), it still143 allows the execution of arbitrary code. This makes it a major security risk144 and therefore it **must never be used on production machines**.145146Screenshot of the debugger in action:147148.. image:: _static/debugger.png149 :align: center150 :class: screenshot151 :alt: screenshot of debugger in action152153Have another debugger in mind? See :ref:`working-with-debuggers`.154155156Routing157-------158159Modern web applications have beautiful URLs. This helps people remember160the URLs, which is especially handy for applications that are used from161mobile devices with slower network connections. If the user can directly162go to the desired page without having to hit the index page it is more163likely they will like the page and come back next time.164165As you have seen above, the :meth:`~flask.Flask.route` decorator is used to166bind a function to a URL. Here are some basic examples::167168 @app.route('/')169 def index():170 return 'Index Page'171172 @app.route('/hello')173 def hello():174 return 'Hello World'175176But there is more to it! You can make certain parts of the URL dynamic and177attach multiple rules to a function.178179Variable Rules180``````````````181182To add variable parts to a URL you can mark these special sections as183``<variable_name>``. Such a part is then passed as a keyword argument to your184function. Optionally a converter can be used by specifying a rule with185``<converter:variable_name>``. Here are some nice examples::186187 @app.route('/user/<username>')188 def show_user_profile(username):189 # show the user profile for that user190 return 'User %s' % username191192 @app.route('/post/<int:post_id>')193 def show_post(post_id):194 # show the post with the given id, the id is an integer195 return 'Post %d' % post_id196197The following converters exist:198199=========== ===========================================200`int` accepts integers201`float` like `int` but for floating point values202`path` like the default but also accepts slashes203=========== ===========================================204205.. admonition:: Unique URLs / Redirection Behavior206207 Flask's URL rules are based on Werkzeug's routing module. The idea208 behind that module is to ensure beautiful and unique URLs based on209 precedents laid down by Apache and earlier HTTP servers.210211 Take these two rules::212213 @app.route('/projects/')214 def projects():215 return 'The project page'216217 @app.route('/about')218 def about():219 return 'The about page'220221 Though they look rather similar, they differ in their use of the trailing222 slash in the URL *definition*. In the first case, the canonical URL for the223 `projects` endpoint has a trailing slash. In that sense, it is similar to224 a folder on a file system. Accessing it without a trailing slash will cause225 Flask to redirect to the canonical URL with the trailing slash.226227 In the second case, however, the URL is defined without a trailing slash,228 rather like the pathname of a file on UNIX-like systems. Accessing the URL229 with a trailing slash will produce a 404 "Not Found" error.230231 This behavior allows relative URLs to continue working even if the trailingFix #856 ommited typo in quickstartDaniel Neuhäuserbefore adoption5207c69
lines 232–233why, one step back232 slash is omitted, consistent with how Apache and other servers work. Also,233 the URLs will stay unique, which helps search engines avoid indexing theFixed a documentation typoArmin Ronacherbefore adoptione59e005
lines 234–275why, one step back234 same page twice.235236237.. _url-building:238239URL Building240````````````241242If it can match URLs, can Flask also generate them? Of course it can. To243build a URL to a specific function you can use the :func:`~flask.url_for`244function. It accepts the name of the function as first argument and a number245of keyword arguments, each corresponding to the variable part of the URL rule.246Unknown variable parts are appended to the URL as query parameters. Here are247some examples:248249>>> from flask import Flask, url_for250>>> app = Flask(__name__)251>>> @app.route('/')252... def index(): pass253...254>>> @app.route('/login')255... def login(): pass256...257>>> @app.route('/user/<username>')258... def profile(username): pass259...260>>> with app.test_request_context():261... print url_for('index')262... print url_for('login')263... print url_for('login', next='/')264... print url_for('profile', username='John Doe')265...266/267/login268/login?next=/269/user/John%20Doe270271(This also uses the :meth:`~flask.Flask.test_request_context` method, explained272below. It tells Flask to behave as though it is handling a request, even273though we are interacting with it through a Python shell. Have a look at the274explanation below. :ref:`context-locals`).275Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4
lines 276–278why, one step back276Why would you want to build URLs using the URL reversing function277:func:`~flask.url_for` instead of hard-coding them into your templates?278There are three good reasons for this:Fixed a documentation typoArmin Ronacherbefore adoptione59e005
lines 279–297why, one step back2792801. Reversing is often more descriptive than hard-coding the URLs. More281 importantly, it allows you to change URLs in one go, without having to282 remember to change URLs all over the place.2832. URL building will handle escaping of special characters and Unicode284 data transparently for you, so you don't have to deal with them.2853. If your application is placed outside the URL root (say, in286 ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will handle287 that properly for you.288289290HTTP Methods291````````````292293HTTP (the protocol web applications are speaking) knows different methods for294accessing URLs. By default, a route only answers to `GET` requests, but that295can be changed by providing the `methods` argument to the296:meth:`~flask.Flask.route` decorator. Here are some examples::297Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption36e86be
lines 298–299why, one step back298 from flask import request299Fixed a documentation typoArmin Ronacherbefore adoptione59e005
lines 300–360why, one step back300 @app.route('/login', methods=['GET', 'POST'])301 def login():302 if request.method == 'POST':303 do_the_login()304 else:305 show_the_login_form()306307If `GET` is present, `HEAD` will be added automatically for you. You308don't have to deal with that. It will also make sure that `HEAD` requests309are handled as the `HTTP RFC`_ (the document describing the HTTP310protocol) demands, so you can completely ignore that part of the HTTP311specification. Likewise, as of Flask 0.6, `OPTIONS` is implemented for you312automatically as well.313314You have no idea what an HTTP method is? Worry not, here is a quick315introduction to HTTP methods and why they matter:316317The HTTP method (also often called "the verb") tells the server what the318clients wants to *do* with the requested page. The following methods are319very common:320321`GET`322 The browser tells the server to just *get* the information stored on323 that page and send it. This is probably the most common method.324325`HEAD`326 The browser tells the server to get the information, but it is only327 interested in the *headers*, not the content of the page. An328 application is supposed to handle that as if a `GET` request was329 received but to not deliver the actual content. In Flask you don't330 have to deal with that at all, the underlying Werkzeug library handles331 that for you.332333`POST`334 The browser tells the server that it wants to *post* some new335 information to that URL and that the server must ensure the data is336 stored and only stored once. This is how HTML forms usually337 transmit data to the server.338339`PUT`340 Similar to `POST` but the server might trigger the store procedure341 multiple times by overwriting the old values more than once. Now you342 might be asking why this is useful, but there are some good reasons343 to do it this way. Consider that the connection is lost during344 transmission: in this situation a system between the browser and the345 server might receive the request safely a second time without breaking346 things. With `POST` that would not be possible because it must only347 be triggered once.348349`DELETE`350 Remove the information at the given location.351352`OPTIONS`353 Provides a quick way for a client to figure out which methods are354 supported by this URL. Starting with Flask 0.6, this is implemented355 for you automatically.356357Now the interesting part is that in HTML4 and XHTML1, the only methods a358form can submit to the server are `GET` and `POST`. But with JavaScript359and future HTML standards you can use the other methods as well. Furthermore360HTTP has become quite popular lately and browsers are no longer the onlyMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption6a62144
line 361why, one step back361clients that are using HTTP. For instance, many revision control systemsFixed a documentation typoArmin Ronacherbefore adoptione59e005
lines 362–386why, one step back362use it.363364.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt365366Static Files367------------368369Dynamic web applications also need static files. That's usually where370the CSS and JavaScript files are coming from. Ideally your web server is371configured to serve them for you, but during development Flask can do that372as well. Just create a folder called `static` in your package or next to373your module and it will be available at `/static` on the application.374375To generate URLs for static files, use the special ``'static'`` endpoint name::376377 url_for('static', filename='style.css')378379The file has to be stored on the filesystem as ``static/style.css``.380381Rendering Templates382-------------------383384Generating HTML from within Python is not fun, and actually pretty385cumbersome because you have to do the HTML escaping on your own to keep386the application secure. Because of that Flask configures the `Jinja2Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption67e4d3e
line 387why, one step back387<http://jinja.pocoo.org/>`_ template engine for you automatically.Fixed a documentation typoArmin Ronacherbefore adoptione59e005
lines 388–419why, one step back388389To render a template you can use the :func:`~flask.render_template`390method. All you have to do is provide the name of the template and the391variables you want to pass to the template engine as keyword arguments.392Here's a simple example of how to render a template::393394 from flask import render_template395396 @app.route('/hello/')397 @app.route('/hello/<name>')398 def hello(name=None):399 return render_template('hello.html', name=name)400401Flask will look for templates in the `templates` folder. So if your402application is a module, this folder is next to that module, if it's a403package it's actually inside your package:404405**Case 1**: a module::406407 /application.py408 /templates409 /hello.html410411**Case 2**: a package::412413 /application414 /__init__.py415 /templates416 /hello.html417418For templates you can use the full power of Jinja2 templates. Head over419to the official `Jinja2 Template DocumentationMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption67e4d3e
line 420why, one step back420<http://jinja.pocoo.org/docs/templates>`_ for more information.Fixed a documentation typoArmin Ronacherbefore adoptione59e005
lines 421–708why, one step back421422Here is an example template:423424.. sourcecode:: html+jinja425426 <!doctype html>427 <title>Hello from Flask</title>428 {% if name %}429 <h1>Hello {{ name }}!</h1>430 {% else %}431 <h1>Hello World!</h1>432 {% endif %}433434Inside templates you also have access to the :class:`~flask.request`,435:class:`~flask.session` and :class:`~flask.g` [#]_ objects436as well as the :func:`~flask.get_flashed_messages` function.437438Templates are especially useful if inheritance is used. If you want to439know how that works, head over to the :ref:`template-inheritance` pattern440documentation. Basically template inheritance makes it possible to keep441certain elements on each page (like header, navigation and footer).442443Automatic escaping is enabled, so if `name` contains HTML it will be escaped444automatically. If you can trust a variable and you know that it will be445safe HTML (for example because it came from a module that converts wiki446markup to HTML) you can mark it as safe by using the447:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the448template. Head over to the Jinja 2 documentation for more examples.449450Here is a basic introduction to how the :class:`~jinja2.Markup` class works:451452>>> from flask import Markup453>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'454Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')455>>> Markup.escape('<blink>hacker</blink>')456Markup(u'<blink>hacker</blink>')457>>> Markup('<em>Marked up</em> » HTML').striptags()458u'Marked up \xbb HTML'459460.. versionchanged:: 0.5461462 Autoescaping is no longer enabled for all templates. The following463 extensions for templates trigger autoescaping: ``.html``, ``.htm``,464 ``.xml``, ``.xhtml``. Templates loaded from a string will have465 autoescaping disabled.466467.. [#] Unsure what that :class:`~flask.g` object is? It's something in which468 you can store information for your own needs, check the documentation of469 that object (:class:`~flask.g`) and the :ref:`sqlite3` for more470 information.471472473Accessing Request Data474----------------------475476For web applications it's crucial to react to the data a client sent to477the server. In Flask this information is provided by the global478:class:`~flask.request` object. If you have some experience with Python479you might be wondering how that object can be global and how Flask480manages to still be threadsafe. The answer is context locals:481482483.. _context-locals:484485Context Locals486``````````````487488.. admonition:: Insider Information489490 If you want to understand how that works and how you can implement491 tests with context locals, read this section, otherwise just skip it.492493Certain objects in Flask are global objects, but not of the usual kind.494These objects are actually proxies to objects that are local to a specific495context. What a mouthful. But that is actually quite easy to understand.496497Imagine the context being the handling thread. A request comes in and the498web server decides to spawn a new thread (or something else, the499underlying object is capable of dealing with concurrency systems other500than threads). When Flask starts its internal request handling it501figures out that the current thread is the active context and binds the502current application and the WSGI environments to that context (thread).503It does that in an intelligent way so that one application can invoke another504application without breaking.505506So what does this mean to you? Basically you can completely ignore that507this is the case unless you are doing something like unit testing. You508will notice that code which depends on a request object will suddenly break509because there is no request object. The solution is creating a request510object yourself and binding it to the context. The easiest solution for511unit testing is to use the :meth:`~flask.Flask.test_request_context`512context manager. In combination with the `with` statement it will bind a513test request so that you can interact with it. Here is an example::514515 from flask import request516517 with app.test_request_context('/hello', method='POST'):518 # now you can do something with the request until the519 # end of the with block, such as basic assertions:520 assert request.path == '/hello'521 assert request.method == 'POST'522523The other possibility is passing a whole WSGI environment to the524:meth:`~flask.Flask.request_context` method::525526 from flask import request527528 with app.request_context(environ):529 assert request.method == 'POST'530531The Request Object532``````````````````533534The request object is documented in the API section and we will not cover535it here in detail (see :class:`~flask.request`). Here is a broad overview of536some of the most common operations. First of all you have to import it from537the `flask` module::538539 from flask import request540541The current request method is available by using the542:attr:`~flask.request.method` attribute. To access form data (data543transmitted in a `POST` or `PUT` request) you can use the544:attr:`~flask.request.form` attribute. Here is a full example of the two545attributes mentioned above::546547 @app.route('/login', methods=['POST', 'GET'])548 def login():549 error = None550 if request.method == 'POST':551 if valid_login(request.form['username'],552 request.form['password']):553 return log_the_user_in(request.form['username'])554 else:555 error = 'Invalid username/password'556 # the code below is executed if the request method557 # was GET or the credentials were invalid558 return render_template('login.html', error=error)559560What happens if the key does not exist in the `form` attribute? In that561case a special :exc:`KeyError` is raised. You can catch it like a562standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request563error page is shown instead. So for many situations you don't have to564deal with that problem.565566To access parameters submitted in the URL (``?key=value``) you can use the567:attr:`~flask.request.args` attribute::568569 searchword = request.args.get('key', '')570571We recommend accessing URL parameters with `get` or by catching the572`KeyError` because users might change the URL and presenting them a 400573bad request page in that case is not user friendly.574575For a full list of methods and attributes of the request object, head over576to the :class:`~flask.request` documentation.577578579File Uploads580````````````581582You can handle uploaded files with Flask easily. Just make sure not to583forget to set the ``enctype="multipart/form-data"`` attribute on your HTML584form, otherwise the browser will not transmit your files at all.585586Uploaded files are stored in memory or at a temporary location on the587filesystem. You can access those files by looking at the588:attr:`~flask.request.files` attribute on the request object. Each589uploaded file is stored in that dictionary. It behaves just like a590standard Python :class:`file` object, but it also has a591:meth:`~werkzeug.datastructures.FileStorage.save` method that allows you to store that592file on the filesystem of the server. Here is a simple example showing how593that works::594595 from flask import request596597 @app.route('/upload', methods=['GET', 'POST'])598 def upload_file():599 if request.method == 'POST':600 f = request.files['the_file']601 f.save('/var/www/uploads/uploaded_file.txt')602 ...603604If you want to know how the file was named on the client before it was605uploaded to your application, you can access the606:attr:`~werkzeug.datastructures.FileStorage.filename` attribute. However please keep in607mind that this value can be forged so never ever trust that value. If you608want to use the filename of the client to store the file on the server,609pass it through the :func:`~werkzeug.utils.secure_filename` function that610Werkzeug provides for you::611612 from flask import request613 from werkzeug import secure_filename614615 @app.route('/upload', methods=['GET', 'POST'])616 def upload_file():617 if request.method == 'POST':618 f = request.files['the_file']619 f.save('/var/www/uploads/' + secure_filename(f.filename))620 ...621622For some better examples, checkout the :ref:`uploading-files` pattern.623624Cookies625```````626627To access cookies you can use the :attr:`~flask.Request.cookies`628attribute. To set cookies you can use the629:attr:`~flask.Response.set_cookie` method of response objects. The630:attr:`~flask.Request.cookies` attribute of request objects is a631dictionary with all the cookies the client transmits. If you want to use632sessions, do not use the cookies directly but instead use the633:ref:`sessions` in Flask that add some security on top of cookies for you.634635Reading cookies::636637 from flask import request638639 @app.route('/')640 def index():641 username = request.cookies.get('username')642 # use cookies.get(key) instead of cookies[key] to not get a643 # KeyError if the cookie is missing.644645Storing cookies::646647 from flask import make_response648649 @app.route('/')650 def index():651 resp = make_response(render_template(...))652 resp.set_cookie('username', 'the username')653 return resp654655Note that cookies are set on response objects. Since you normally656just return strings from the view functions Flask will convert them into657response objects for you. If you explicitly want to do that you can use658the :meth:`~flask.make_response` function and then modify it.659660Sometimes you might want to set a cookie at a point where the response661object does not exist yet. This is possible by utilizing the662:ref:`deferred-callbacks` pattern.663664For this also see :ref:`about-responses`.665666Redirects and Errors667--------------------668669To redirect a user to another endpoint, use the :func:`~flask.redirect`670function; to abort a request early with an error code, use the671:func:`~flask.abort` function::672673 from flask import abort, redirect, url_for674675 @app.route('/')676 def index():677 return redirect(url_for('login'))678679 @app.route('/login')680 def login():681 abort(401)682 this_is_never_executed()683684This is a rather pointless example because a user will be redirected from685the index to a page they cannot access (401 means access denied) but it686shows how that works.687688By default a black and white error page is shown for each error code. If689you want to customize the error page, you can use the690:meth:`~flask.Flask.errorhandler` decorator::691692 from flask import render_template693694 @app.errorhandler(404)695 def page_not_found(error):696 return render_template('page_not_found.html'), 404697698Note the ``404`` after the :func:`~flask.render_template` call. This699tells Flask that the status code of that page should be 404 which means700not found. By default 200 is assumed which translates to: all went well.701702.. _about-responses:703704About Responses705---------------706707The return value from a view function is automatically converted into a708response object for you. If the return value is a string it's convertedMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption6a62144
lines 709–710why, one step back709into a response object with the string as response body, a ``200 OK``710status code and a ``text/html`` mimetype. The logic that Flask applies toFixed a documentation typoArmin Ronacherbefore adoptione59e005
lines 711–718why, one step back711converting return values into response objects is as follows:7127131. If a response object of the correct type is returned it's directly714 returned from the view.7152. If it's a string, a response object is created with that data and the716 default parameters.7173. If a tuple is returned the items in the tuple can provide extra718 information. Such tuples have to be in the form ``(response, status,Merge pull request #938 from ahlen/response-with-headers-without-statusArmin Ronacherbefore adoptionc9bf907
lines 719–721why, one step back719 headers)`` or ``(response, headers)`` where at least one item has720 to be in the tuple. The `status` value will override the status code721 and `headers` can be a list or dictionary of additional header values.Fixed a documentation typoArmin Ronacherbefore adoptione59e005
lines 722–857why, one step back7224. If none of that works, Flask will assume the return value is a723 valid WSGI application and convert that into a response object.724725If you want to get hold of the resulting response object inside the view726you can use the :func:`~flask.make_response` function.727728Imagine you have a view like this:729730.. sourcecode:: python731732 @app.errorhandler(404)733 def not_found(error):734 return render_template('error.html'), 404735736You just need to wrap the return expression with737:func:`~flask.make_response` and get the response object to modify it, then738return it:739740.. sourcecode:: python741742 @app.errorhandler(404)743 def not_found(error):744 resp = make_response(render_template('error.html'), 404)745 resp.headers['X-Something'] = 'A value'746 return resp747748.. _sessions:749750Sessions751--------752753In addition to the request object there is also a second object called754:class:`~flask.session` which allows you to store information specific to a755user from one request to the next. This is implemented on top of cookies756for you and signs the cookies cryptographically. What this means is that757the user could look at the contents of your cookie but not modify it,758unless they know the secret key used for signing.759760In order to use sessions you have to set a secret key. Here is how761sessions work::762763 from flask import Flask, session, redirect, url_for, escape, request764765 app = Flask(__name__)766767 @app.route('/')768 def index():769 if 'username' in session:770 return 'Logged in as %s' % escape(session['username'])771 return 'You are not logged in'772773 @app.route('/login', methods=['GET', 'POST'])774 def login():775 if request.method == 'POST':776 session['username'] = request.form['username']777 return redirect(url_for('index'))778 return '''779 <form action="" method="post">780 <p><input type=text name=username>781 <p><input type=submit value=Login>782 </form>783 '''784785 @app.route('/logout')786 def logout():787 # remove the username from the session if it's there788 session.pop('username', None)789 return redirect(url_for('index'))790791 # set the secret key. keep this really secret:792 app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'793794The :func:`~flask.escape` mentioned here does escaping for you if you are795not using the template engine (as in this example).796797.. admonition:: How to generate good secret keys798799 The problem with random is that it's hard to judge what is truly random. And800 a secret key should be as random as possible. Your operating system801 has ways to generate pretty random stuff based on a cryptographic802 random generator which can be used to get such a key:803804 >>> import os805 >>> os.urandom(24)806 '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'807808 Just take that thing and copy/paste it into your code and you're done.809810A note on cookie-based sessions: Flask will take the values you put into the811session object and serialize them into a cookie. If you are finding some812values do not persist across requests, cookies are indeed enabled, and you are813not getting a clear error message, check the size of the cookie in your page814responses compared to the size supported by web browsers.815816817Message Flashing818----------------819820Good applications and user interfaces are all about feedback. If the user821does not get enough feedback they will probably end up hating the822application. Flask provides a really simple way to give feedback to a823user with the flashing system. The flashing system basically makes it824possible to record a message at the end of a request and access it on the next825(and only the next) request. This is usually combined with a layout826template to expose the message.827828To flash a message use the :func:`~flask.flash` method, to get hold of the829messages you can use :func:`~flask.get_flashed_messages` which is also830available in the templates. Check out the :ref:`message-flashing-pattern`831for a full example.832833Logging834-------835836.. versionadded:: 0.3837838Sometimes you might be in a situation where you deal with data that839should be correct, but actually is not. For example you may have some client-side840code that sends an HTTP request to the server but it's obviously841malformed. This might be caused by a user tampering with the data, or the842client code failing. Most of the time it's okay to reply with ``400 Bad843Request`` in that situation, but sometimes that won't do and the code has844to continue working.845846You may still want to log that something fishy happened. This is where847loggers come in handy. As of Flask 0.3 a logger is preconfigured for you848to use.849850Here are some example log calls::851852 app.logger.debug('A value for debugging')853 app.logger.warning('A warning occurred (%d apples)', 42)854 app.logger.error('An error occurred')855856The attached :attr:`~flask.Flask.logger` is a standard logging857:class:`~logging.Logger`, so head over to the official `loggingMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption67e4d3e
line 858why, one step back858documentation <https://docs.python.org/library/logging.html>`_ for moreFixed a documentation typoArmin Ronacherbefore adoptione59e005
lines 859–880why, one step back859information.860861Hooking in WSGI Middlewares862---------------------------863864If you want to add a WSGI middleware to your application you can wrap the865internal WSGI application. For example if you want to use one of the866middlewares from the Werkzeug package to work around bugs in lighttpd, you867can do it like this::868869 from werkzeug.contrib.fixers import LighttpdCGIRootFix870 app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)871872.. _quickstart_deployment:873874Deploying to a Web Server875-------------------------876877Ready to deploy your new Flask app? To wrap up the quickstart, you can878immediately deploy to a hosted platform, all of which offer a free plan for879small projects:880Merge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01
line 881why, one step back881- `Deploying Flask on Heroku <https://devcenter.heroku.com/articles/getting-started-with-python>`_Fixed a documentation typoArmin Ronacherbefore adoptione59e005
lines 882–892why, one step back882- `Deploying WSGI on dotCloud <http://docs.dotcloud.com/services/python/>`_883 with `Flask-specific notes <http://flask.pocoo.org/snippets/48/>`_884885Other places where you can host your Flask app:886887- `Deploying Flask on Webfaction <http://flask.pocoo.org/snippets/65/>`_888- `Deploying Flask on Google App Engine <https://github.com/kamalgill/flask-appengine-template>`_889- `Sharing your Localhost Server with Localtunnel <http://flask.pocoo.org/snippets/89/>`_890891If you manage your own hosts and would like to host yourself, see the chapter892on :ref:`deployment`.