Skip to content
Myr

quickstart.rst

This file

Path

docs/quickstart.rst

907 lines · 31.5 KiB

Last changed by

new run debug docsDavid Lordbefore adoption74e5263

History of this file

Take it

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

Merge branch '2.0.x'David Lordbefore adoption0fb5c2f

lines 1–41why, one step back
1Quickstart
2==========34Eager to get started? This page gives a good introduction to Flask.5Follow :doc:`installation` to set up a project and install Flask first.678A Minimal Application9---------------------1011A minimal Flask application looks something like this:1213.. code-block:: python1415 from flask import Flask1617 app = Flask(__name__)1819 @app.route("/")20 def hello_world():21 return "<p>Hello, World!</p>"2223So what did that code do?24251. First we imported the :class:`~flask.Flask` class. An instance of26 this class will be our WSGI application.272. Next we create an instance of this class. The first argument is the28 name of the application's module or package. ``__name__`` is a29 convenient shortcut for this that is appropriate for most cases.30 This is needed so that Flask knows where to look for resources such31 as templates and static files.323. We then use the :meth:`~flask.Flask.route` decorator to tell Flask33 what URL should trigger our function.344. The function returns the message we want to display in the user's35 browser. The default content type is HTML, so HTML in the string36 will be rendered by the browser.3738Save it as :file:`hello.py` or something similar. Make sure to not call39your application :file:`flask.py` because this would conflict with Flask40itself.41

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

lines 42–43why, one step back
42To run the application, use the ``flask`` command or
43``python -m flask``. You need to tell the Flask where your application

Merge branch '2.2.x'David Lordbefore adoption73b9bac

line 44why, one step back
44is with the ``--app`` option.

Merge branch '2.0.x'David Lordbefore adoption0fb5c2f

line 45why, one step back
45

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

line 46why, one step back
46.. code-block:: text

Merge branch '2.0.x'David Lordbefore adoption0fb5c2f

line 47why, one step back
47

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

line 48why, one step back
48 $ flask --app hello run

Merge pull request #4718 from pallets/remove-lazy-optionDavid Lordbefore adoption633f421

line 49why, one step back
49 * Serving Flask app 'hello'

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

line 50why, one step back
50 * Running on http://127.0.0.1:5000 (Press CTRL+C to quit)

Merge branch '2.0.x'David Lordbefore adoption0fb5c2f

lines 51–54why, one step back
51
52.. admonition:: Application Discovery Behavior5354 As a shortcut, if the file is named ``app.py`` or ``wsgi.py``, you

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

line 55why, one step back
55 don't have to use ``--app``. See :doc:`/cli` for more details.

Merge branch '2.0.x'David Lordbefore adoption0fb5c2f

lines 56–106why, one step back
56
57This launches a very simple builtin server, which is good enough for58testing but probably not what you want to use in production. For59deployment options see :doc:`deploying/index`.6061Now head over to http://127.0.0.1:5000/, and you should see your hello62world greeting.6364If another program is already using port 5000, you'll see65``OSError: [Errno 98]`` or ``OSError: [WinError 10013]`` when the66server tries to start. See :ref:`address-already-in-use` for how to67handle that.6869.. _public-server:7071.. admonition:: Externally Visible Server7273 If you run the server you will notice that the server is only accessible74 from your own computer, not from any other in the network. This is the75 default because in debugging mode a user of the application can execute76 arbitrary Python code on your computer.7778 If you have the debugger disabled or trust the users on your network,79 you can make the server publicly available simply by adding80 ``--host=0.0.0.0`` to the command line::8182 $ flask run --host=0.0.0.08384 This tells your operating system to listen on all public IPs.858687Debug Mode88----------8990The ``flask run`` command can do more than just start the development91server. By enabling debug mode, the server will automatically reload if92code changes, and will show an interactive debugger in the browser if an93error occurs during a request.9495.. image:: _static/debugger.png96 :align: center97 :class: screenshot98 :alt: The interactive debugger in action.99100.. warning::101102 The debugger allows executing arbitrary Python code from the103 browser. It is protected by a pin, but still represents a major104 security risk. Do not run the development server or debugger in a105 production environment.106

Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d

line 107why, one step back
107To enable debug mode, use the ``--debug`` option.

Merge branch '2.0.x'David Lordbefore adoption0fb5c2f

line 108why, one step back
108

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

line 109why, one step back
109.. code-block:: text

Merge branch '2.0.x'David Lordbefore adoption0fb5c2f

line 110why, one step back
110

new run debug docsDavid Lordbefore adoption74e5263

line 111why, one step back
111 $ flask --app hello run --debug

Merge pull request #4718 from pallets/remove-lazy-optionDavid Lordbefore adoption633f421

line 112why, one step back
112 * Serving Flask app 'hello'

Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727

lines 113–117why, one step back
113 * Debug mode: on
114 * Running on http://127.0.0.1:5000 (Press CTRL+C to quit)115 * Restarting with stat116 * Debugger is active!117 * Debugger PIN: nnn-nnn-nnn

Merge branch '2.0.x'David Lordbefore adoption0fb5c2f

lines 118–120why, one step back
118
119See also:120

Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d

line 121why, one step back
121- :doc:`/server` and :doc:`/cli` for information about running in debug mode.

Merge branch '2.0.x'David Lordbefore adoption0fb5c2f

lines 122–312why, one step back
122- :doc:`/debugging` for information about using the built-in debugger
123 and other debuggers.124- :doc:`/logging` and :doc:`/errorhandling` to log errors and display125 nice error pages.126127128HTML Escaping129-------------130131When returning HTML (the default response type in Flask), any132user-provided values rendered in the output must be escaped to protect133from injection attacks. HTML templates rendered with Jinja, introduced134later, will do this automatically.135136:func:`~markupsafe.escape`, shown here, can be used manually. It is137omitted in most examples for brevity, but you should always be aware of138how you're using untrusted data.139140.. code-block:: python141142 from markupsafe import escape143144 @app.route("/<name>")145 def hello(name):146 return f"Hello, {escape(name)}!"147148If a user managed to submit the name ``<script>alert("bad")</script>``,149escaping causes it to be rendered as text, rather than running the150script in the user's browser.151152``<name>`` in the route captures a value from the URL and passes it to153the view function. These variable rules are explained below.154155156Routing157-------158159Modern web applications use meaningful URLs to help users. Users are more160likely to like a page and come back if the page uses a meaningful URL they can161remember and use to directly visit a page.162163Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::164165 @app.route('/')166 def index():167 return 'Index Page'168169 @app.route('/hello')170 def hello():171 return 'Hello, World'172173You can do more! You can make parts of the URL dynamic and attach multiple174rules to a function.175176Variable Rules177``````````````178179You can add variable sections to a URL by marking sections with180``<variable_name>``. Your function then receives the ``<variable_name>``181as a keyword argument. Optionally, you can use a converter to specify the type182of the argument like ``<converter:variable_name>``. ::183184 from markupsafe import escape185186 @app.route('/user/<username>')187 def show_user_profile(username):188 # show the user profile for that user189 return f'User {escape(username)}'190191 @app.route('/post/<int:post_id>')192 def show_post(post_id):193 # show the post with the given id, the id is an integer194 return f'Post {post_id}'195196 @app.route('/path/<path:subpath>')197 def show_subpath(subpath):198 # show the subpath after /path/199 return f'Subpath {escape(subpath)}'200201Converter types:202203========== ==========================================204``string`` (default) accepts any text without a slash205``int`` accepts positive integers206``float`` accepts positive floating point values207``path`` like ``string`` but also accepts slashes208``uuid`` accepts UUID strings209========== ==========================================210211212Unique URLs / Redirection Behavior213``````````````````````````````````214215The following two rules differ in their use of a trailing slash. ::216217 @app.route('/projects/')218 def projects():219 return 'The project page'220221 @app.route('/about')222 def about():223 return 'The about page'224225The canonical URL for the ``projects`` endpoint has a trailing slash.226It's similar to a folder in a file system. If you access the URL without227a trailing slash (``/projects``), Flask redirects you to the canonical URL228with the trailing slash (``/projects/``).229230The canonical URL for the ``about`` endpoint does not have a trailing231slash. It's similar to the pathname of a file. Accessing the URL with a232trailing slash (``/about/``) produces a 404 "Not Found" error. This helps233keep URLs unique for these resources, which helps search engines avoid234indexing the same page twice.235236237.. _url-building:238239URL Building240````````````241242To build a URL to a specific function, use the :func:`~flask.url_for` function.243It accepts the name of the function as its first argument and any number of244keyword arguments, each corresponding to a variable part of the URL rule.245Unknown variable parts are appended to the URL as query parameters.246247Why would you want to build URLs using the URL reversing function248:func:`~flask.url_for` instead of hard-coding them into your templates?2492501. Reversing is often more descriptive than hard-coding the URLs.2512. You can change your URLs in one go instead of needing to remember to252 manually change hard-coded URLs.2533. URL building handles escaping of special characters transparently.2544. The generated paths are always absolute, avoiding unexpected behavior255 of relative paths in browsers.2565. If your application is placed outside the URL root, for example, in257 ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly258 handles that for you.259260For example, here we use the :meth:`~flask.Flask.test_request_context` method261to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`262tells Flask to behave as though it's handling a request even while we use a263Python shell. See :ref:`context-locals`.264265.. code-block:: python266267 from flask import url_for268269 @app.route('/')270 def index():271 return 'index'272273 @app.route('/login')274 def login():275 return 'login'276277 @app.route('/user/<username>')278 def profile(username):279 return f'{username}\'s profile'280281 with app.test_request_context():282 print(url_for('index'))283 print(url_for('login'))284 print(url_for('login', next='/'))285 print(url_for('profile', username='John Doe'))286287.. code-block:: text288289 /290 /login291 /login?next=/292 /user/John%20Doe293294295HTTP Methods296````````````297298Web applications use different HTTP methods when accessing URLs. You should299familiarize yourself with the HTTP methods as you work with Flask. By default,300a route only answers to ``GET`` requests. You can use the ``methods`` argument301of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.302::303304 from flask import request305306 @app.route('/login', methods=['GET', 'POST'])307 def login():308 if request.method == 'POST':309 return do_the_login()310 else:311 return show_the_login_form()312

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 313–330why, one step back
313The example above keeps all methods for the route within one function,
314which can be useful if each part uses some common data.315316You can also separate views for different methods into different317functions. Flask provides a shortcut for decorating such routes with318:meth:`~flask.Flask.get`, :meth:`~flask.Flask.post`, etc. for each319common HTTP method.320321.. code-block:: python322323 @app.get('/login')324 def login_get():325 return show_the_login_form()326327 @app.post('/login')328 def login_post():329 return do_the_login()330

Merge branch '2.0.x'David Lordbefore adoption0fb5c2f

lines 331–359why, one step back
331If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method
332and handles ``HEAD`` requests according to the `HTTP RFC`_. Likewise,333``OPTIONS`` is automatically implemented for you.334335.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt336337Static Files338------------339340Dynamic web applications also need static files. That's usually where341the CSS and JavaScript files are coming from. Ideally your web server is342configured to serve them for you, but during development Flask can do that343as well. Just create a folder called :file:`static` in your package or next to344your module and it will be available at ``/static`` on the application.345346To generate URLs for static files, use the special ``'static'`` endpoint name::347348 url_for('static', filename='style.css')349350The file has to be stored on the filesystem as :file:`static/style.css`.351352Rendering Templates353-------------------354355Generating HTML from within Python is not fun, and actually pretty356cumbersome because you have to do the HTML escaping on your own to keep357the application secure. Because of that Flask configures the `Jinja2358<https://palletsprojects.com/p/jinja/>`_ template engine for you automatically.359

Merge branch '2.2.x'David Lordbefore adoption87584e8

lines 360–361why, one step back
360Templates can be used to generate any type of text file. For web applications, you'll
361primarily be generating HTML pages, but you can also generate markdown, plain text for

Merge pull request #4835 from TehBrian/2.2.xDavid Lordbefore adoption3dc6db9

line 362why, one step back
362emails, and anything else.

Merge branch '2.2.x'David Lordbefore adoption87584e8

lines 363–367why, one step back
363
364For a reference to HTML, CSS, and other web APIs, use the `MDN Web Docs`_.365366.. _MDN Web Docs: https://developer.mozilla.org/367

Merge branch '2.0.x'David Lordbefore adoption0fb5c2f

lines 368–688why, one step back
368To render a template you can use the :func:`~flask.render_template`
369method. All you have to do is provide the name of the template and the370variables you want to pass to the template engine as keyword arguments.371Here's a simple example of how to render a template::372373 from flask import render_template374375 @app.route('/hello/')376 @app.route('/hello/<name>')377 def hello(name=None):378 return render_template('hello.html', name=name)379380Flask will look for templates in the :file:`templates` folder. So if your381application is a module, this folder is next to that module, if it's a382package it's actually inside your package:383384**Case 1**: a module::385386 /application.py387 /templates388 /hello.html389390**Case 2**: a package::391392 /application393 /__init__.py394 /templates395 /hello.html396397For templates you can use the full power of Jinja2 templates. Head over398to the official `Jinja2 Template Documentation399<https://jinja.palletsprojects.com/templates/>`_ for more information.400401Here is an example template:402403.. sourcecode:: html+jinja404405 <!doctype html>406 <title>Hello from Flask</title>407 {% if name %}408 <h1>Hello {{ name }}!</h1>409 {% else %}410 <h1>Hello, World!</h1>411 {% endif %}412413Inside templates you also have access to the :data:`~flask.Flask.config`,414:class:`~flask.request`, :class:`~flask.session` and :class:`~flask.g` [#]_ objects415as well as the :func:`~flask.url_for` and :func:`~flask.get_flashed_messages` functions.416417Templates are especially useful if inheritance is used. If you want to418know how that works, see :doc:`patterns/templateinheritance`. Basically419template inheritance makes it possible to keep certain elements on each420page (like header, navigation and footer).421422Automatic escaping is enabled, so if ``name`` contains HTML it will be escaped423automatically. If you can trust a variable and you know that it will be424safe HTML (for example because it came from a module that converts wiki425markup to HTML) you can mark it as safe by using the426:class:`~markupsafe.Markup` class or by using the ``|safe`` filter in the427template. Head over to the Jinja 2 documentation for more examples.428429Here is a basic introduction to how the :class:`~markupsafe.Markup` class works::430431 >>> from markupsafe import Markup432 >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'433 Markup('<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')434 >>> Markup.escape('<blink>hacker</blink>')435 Markup('&lt;blink&gt;hacker&lt;/blink&gt;')436 >>> Markup('<em>Marked up</em> &raquo; HTML').striptags()437 'Marked up » HTML'438439.. versionchanged:: 0.5440441 Autoescaping is no longer enabled for all templates. The following442 extensions for templates trigger autoescaping: ``.html``, ``.htm``,443 ``.xml``, ``.xhtml``. Templates loaded from a string will have444 autoescaping disabled.445446.. [#] Unsure what that :class:`~flask.g` object is? It's something in which447 you can store information for your own needs. See the documentation448 for :class:`flask.g` and :doc:`patterns/sqlite3`.449450451Accessing Request Data452----------------------453454For web applications it's crucial to react to the data a client sends to455the server. In Flask this information is provided by the global456:class:`~flask.request` object. If you have some experience with Python457you might be wondering how that object can be global and how Flask458manages to still be threadsafe. The answer is context locals:459460461.. _context-locals:462463Context Locals464``````````````465466.. admonition:: Insider Information467468 If you want to understand how that works and how you can implement469 tests with context locals, read this section, otherwise just skip it.470471Certain objects in Flask are global objects, but not of the usual kind.472These objects are actually proxies to objects that are local to a specific473context. What a mouthful. But that is actually quite easy to understand.474475Imagine the context being the handling thread. A request comes in and the476web server decides to spawn a new thread (or something else, the477underlying object is capable of dealing with concurrency systems other478than threads). When Flask starts its internal request handling it479figures out that the current thread is the active context and binds the480current application and the WSGI environments to that context (thread).481It does that in an intelligent way so that one application can invoke another482application without breaking.483484So what does this mean to you? Basically you can completely ignore that485this is the case unless you are doing something like unit testing. You486will notice that code which depends on a request object will suddenly break487because there is no request object. The solution is creating a request488object yourself and binding it to the context. The easiest solution for489unit testing is to use the :meth:`~flask.Flask.test_request_context`490context manager. In combination with the ``with`` statement it will bind a491test request so that you can interact with it. Here is an example::492493 from flask import request494495 with app.test_request_context('/hello', method='POST'):496 # now you can do something with the request until the497 # end of the with block, such as basic assertions:498 assert request.path == '/hello'499 assert request.method == 'POST'500501The other possibility is passing a whole WSGI environment to the502:meth:`~flask.Flask.request_context` method::503504 with app.request_context(environ):505 assert request.method == 'POST'506507The Request Object508``````````````````509510The request object is documented in the API section and we will not cover511it here in detail (see :class:`~flask.Request`). Here is a broad overview of512some of the most common operations. First of all you have to import it from513the ``flask`` module::514515 from flask import request516517The current request method is available by using the518:attr:`~flask.Request.method` attribute. To access form data (data519transmitted in a ``POST`` or ``PUT`` request) you can use the520:attr:`~flask.Request.form` attribute. Here is a full example of the two521attributes mentioned above::522523 @app.route('/login', methods=['POST', 'GET'])524 def login():525 error = None526 if request.method == 'POST':527 if valid_login(request.form['username'],528 request.form['password']):529 return log_the_user_in(request.form['username'])530 else:531 error = 'Invalid username/password'532 # the code below is executed if the request method533 # was GET or the credentials were invalid534 return render_template('login.html', error=error)535536What happens if the key does not exist in the ``form`` attribute? In that537case a special :exc:`KeyError` is raised. You can catch it like a538standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request539error page is shown instead. So for many situations you don't have to540deal with that problem.541542To access parameters submitted in the URL (``?key=value``) you can use the543:attr:`~flask.Request.args` attribute::544545 searchword = request.args.get('key', '')546547We recommend accessing URL parameters with `get` or by catching the548:exc:`KeyError` because users might change the URL and presenting them a 400549bad request page in that case is not user friendly.550551For a full list of methods and attributes of the request object, head over552to the :class:`~flask.Request` documentation.553554555File Uploads556````````````557558You can handle uploaded files with Flask easily. Just make sure not to559forget to set the ``enctype="multipart/form-data"`` attribute on your HTML560form, otherwise the browser will not transmit your files at all.561562Uploaded files are stored in memory or at a temporary location on the563filesystem. You can access those files by looking at the564:attr:`~flask.request.files` attribute on the request object. Each565uploaded file is stored in that dictionary. It behaves just like a566standard Python :class:`file` object, but it also has a567:meth:`~werkzeug.datastructures.FileStorage.save` method that568allows you to store that file on the filesystem of the server.569Here is a simple example showing how that works::570571 from flask import request572573 @app.route('/upload', methods=['GET', 'POST'])574 def upload_file():575 if request.method == 'POST':576 f = request.files['the_file']577 f.save('/var/www/uploads/uploaded_file.txt')578 ...579580If you want to know how the file was named on the client before it was581uploaded to your application, you can access the582:attr:`~werkzeug.datastructures.FileStorage.filename` attribute.583However please keep in mind that this value can be forged584so never ever trust that value. If you want to use the filename585of the client to store the file on the server, pass it through the586:func:`~werkzeug.utils.secure_filename` function that587Werkzeug provides for you::588589 from werkzeug.utils import secure_filename590591 @app.route('/upload', methods=['GET', 'POST'])592 def upload_file():593 if request.method == 'POST':594 file = request.files['the_file']595 file.save(f"/var/www/uploads/{secure_filename(file.filename)}")596 ...597598For some better examples, see :doc:`patterns/fileuploads`.599600Cookies601```````602603To access cookies you can use the :attr:`~flask.Request.cookies`604attribute. To set cookies you can use the605:attr:`~flask.Response.set_cookie` method of response objects. The606:attr:`~flask.Request.cookies` attribute of request objects is a607dictionary with all the cookies the client transmits. If you want to use608sessions, do not use the cookies directly but instead use the609:ref:`sessions` in Flask that add some security on top of cookies for you.610611Reading cookies::612613 from flask import request614615 @app.route('/')616 def index():617 username = request.cookies.get('username')618 # use cookies.get(key) instead of cookies[key] to not get a619 # KeyError if the cookie is missing.620621Storing cookies::622623 from flask import make_response624625 @app.route('/')626 def index():627 resp = make_response(render_template(...))628 resp.set_cookie('username', 'the username')629 return resp630631Note that cookies are set on response objects. Since you normally632just return strings from the view functions Flask will convert them into633response objects for you. If you explicitly want to do that you can use634the :meth:`~flask.make_response` function and then modify it.635636Sometimes you might want to set a cookie at a point where the response637object does not exist yet. This is possible by utilizing the638:doc:`patterns/deferredcallbacks` pattern.639640For this also see :ref:`about-responses`.641642Redirects and Errors643--------------------644645To redirect a user to another endpoint, use the :func:`~flask.redirect`646function; to abort a request early with an error code, use the647:func:`~flask.abort` function::648649 from flask import abort, redirect, url_for650651 @app.route('/')652 def index():653 return redirect(url_for('login'))654655 @app.route('/login')656 def login():657 abort(401)658 this_is_never_executed()659660This is a rather pointless example because a user will be redirected from661the index to a page they cannot access (401 means access denied) but it662shows how that works.663664By default a black and white error page is shown for each error code. If665you want to customize the error page, you can use the666:meth:`~flask.Flask.errorhandler` decorator::667668 from flask import render_template669670 @app.errorhandler(404)671 def page_not_found(error):672 return render_template('page_not_found.html'), 404673674Note the ``404`` after the :func:`~flask.render_template` call. This675tells Flask that the status code of that page should be 404 which means676not found. By default 200 is assumed which translates to: all went well.677678See :doc:`errorhandling` for more details.679680.. _about-responses:681682About Responses683---------------684685The return value from a view function is automatically converted into686a response object for you. If the return value is a string it's687converted into a response object with the string as response body, a688``200 OK`` status code and a :mimetype:`text/html` mimetype. If the

Merge pull request #4672 from greyli/return-listDavid Lordbefore adoption559a845

lines 689–691why, one step back
689return value is a dict or list, :func:`jsonify` is called to produce a
690response. The logic that Flask applies to converting return values into691response objects is as follows:

Merge branch '2.0.x'David Lordbefore adoption0fb5c2f

lines 692–696why, one step back
692
6931. If a response object of the correct type is returned it's directly694 returned from the view.6952. If it's a string, a response object is created with that data and696 the default parameters.

Merge pull request #4672 from greyli/return-listDavid Lordbefore adoption559a845

lines 697–701why, one step back
6973. If it's an iterator or generator returning strings or bytes, it is
698 treated as a streaming response.6994. If it's a dict or list, a response object is created using700 :func:`~flask.json.jsonify`.7015. If a tuple is returned the items in the tuple can provide extra

Merge branch '2.0.x'David Lordbefore adoption0fb5c2f

lines 702–706why, one step back
702 information. Such tuples have to be in the form
703 ``(response, status)``, ``(response, headers)``, or704 ``(response, status, headers)``. The ``status`` value will override705 the status code and ``headers`` can be a list or dictionary of706 additional header values.

Merge pull request #4672 from greyli/return-listDavid Lordbefore adoption559a845

line 707why, one step back
7076. If none of that works, Flask will assume the return value is a

Merge branch '2.0.x'David Lordbefore adoption0fb5c2f

lines 708–737why, one step back
708 valid WSGI application and convert that into a response object.
709710If you want to get hold of the resulting response object inside the view711you can use the :func:`~flask.make_response` function.712713Imagine you have a view like this::714715 from flask import render_template716717 @app.errorhandler(404)718 def not_found(error):719 return render_template('error.html'), 404720721You just need to wrap the return expression with722:func:`~flask.make_response` and get the response object to modify it, then723return it::724725 from flask import make_response726727 @app.errorhandler(404)728 def not_found(error):729 resp = make_response(render_template('error.html'), 404)730 resp.headers['X-Something'] = 'A value'731 return resp732733734APIs with JSON735``````````````736737A common response format when writing an API is JSON. It's easy to get

Merge pull request #4672 from greyli/return-listDavid Lordbefore adoption559a845

lines 738–739why, one step back
738started writing such an API with Flask. If you return a ``dict`` or
739``list`` from a view, it will be converted to a JSON response.

Merge branch '2.0.x'David Lordbefore adoption0fb5c2f

lines 740–754why, one step back
740
741.. code-block:: python742743 @app.route("/me")744 def me_api():745 user = get_current_user()746 return {747 "username": user.username,748 "theme": user.theme,749 "image": url_for("user_image", filename=user.image),750 }751752 @app.route("/users")753 def users_api():754 users = get_all_users()

Merge pull request #4672 from greyli/return-listDavid Lordbefore adoption559a845

lines 755–765why, one step back
755 return [user.to_json() for user in users]
756757This is a shortcut to passing the data to the758:func:`~flask.json.jsonify` function, which will serialize any supported759JSON data type. That means that all the data in the dict or list must be760JSON serializable.761762For complex types such as database models, you'll want to use a763serialization library to convert the data to valid JSON types first.764There are many serialization libraries and Flask API extensions765maintained by the community that support more complex applications.

Merge branch '2.0.x'David Lordbefore adoption0fb5c2f

lines 766–907why, one step back
766
767768.. _sessions:769770Sessions771--------772773In addition to the request object there is also a second object called774:class:`~flask.session` which allows you to store information specific to a775user from one request to the next. This is implemented on top of cookies776for you and signs the cookies cryptographically. What this means is that777the user could look at the contents of your cookie but not modify it,778unless they know the secret key used for signing.779780In order to use sessions you have to set a secret key. Here is how781sessions work::782783 from flask import session784785 # Set the secret key to some random bytes. Keep this really secret!786 app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'787788 @app.route('/')789 def index():790 if 'username' in session:791 return f'Logged in as {session["username"]}'792 return 'You are not logged in'793794 @app.route('/login', methods=['GET', 'POST'])795 def login():796 if request.method == 'POST':797 session['username'] = request.form['username']798 return redirect(url_for('index'))799 return '''800 <form method="post">801 <p><input type=text name=username>802 <p><input type=submit value=Login>803 </form>804 '''805806 @app.route('/logout')807 def logout():808 # remove the username from the session if it's there809 session.pop('username', None)810 return redirect(url_for('index'))811812.. admonition:: How to generate good secret keys813814 A secret key should be as random as possible. Your operating system has815 ways to generate pretty random data based on a cryptographic random816 generator. Use the following command to quickly generate a value for817 :attr:`Flask.secret_key` (or :data:`SECRET_KEY`)::818819 $ python -c 'import secrets; print(secrets.token_hex())'820 '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'821822A note on cookie-based sessions: Flask will take the values you put into the823session object and serialize them into a cookie. If you are finding some824values do not persist across requests, cookies are indeed enabled, and you are825not getting a clear error message, check the size of the cookie in your page826responses compared to the size supported by web browsers.827828Besides the default client-side based sessions, if you want to handle829sessions on the server-side instead, there are several830Flask extensions that support this.831832Message Flashing833----------------834835Good applications and user interfaces are all about feedback. If the user836does not get enough feedback they will probably end up hating the837application. Flask provides a really simple way to give feedback to a838user with the flashing system. The flashing system basically makes it839possible to record a message at the end of a request and access it on the next840(and only the next) request. This is usually combined with a layout841template to expose the message.842843To flash a message use the :func:`~flask.flash` method, to get hold of the844messages you can use :func:`~flask.get_flashed_messages` which is also845available in the templates. See :doc:`patterns/flashing` for a full846example.847848Logging849-------850851.. versionadded:: 0.3852853Sometimes you might be in a situation where you deal with data that854should be correct, but actually is not. For example you may have855some client-side code that sends an HTTP request to the server856but it's obviously malformed. This might be caused by a user tampering857with the data, or the client code failing. Most of the time it's okay858to reply with ``400 Bad Request`` in that situation, but sometimes859that won't do and the code has to continue working.860861You may still want to log that something fishy happened. This is where862loggers come in handy. As of Flask 0.3 a logger is preconfigured for you863to use.864865Here are some example log calls::866867 app.logger.debug('A value for debugging')868 app.logger.warning('A warning occurred (%d apples)', 42)869 app.logger.error('An error occurred')870871The attached :attr:`~flask.Flask.logger` is a standard logging872:class:`~logging.Logger`, so head over to the official :mod:`logging`873docs for more information.874875See :doc:`errorhandling`.876877878Hooking in WSGI Middleware879--------------------------880881To add WSGI middleware to your Flask application, wrap the application's882``wsgi_app`` attribute. For example, to apply Werkzeug's883:class:`~werkzeug.middleware.proxy_fix.ProxyFix` middleware for running884behind Nginx:885886.. code-block:: python887888 from werkzeug.middleware.proxy_fix import ProxyFix889 app.wsgi_app = ProxyFix(app.wsgi_app)890891Wrapping ``app.wsgi_app`` instead of ``app`` means that ``app`` still892points at your Flask application, not at the middleware, so you can893continue to use and configure ``app`` directly.894895Using Flask Extensions896----------------------897898Extensions are packages that help you accomplish common tasks. For899example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple900and easy to use with Flask.901902For more on Flask extensions, see :doc:`extensions`.903904Deploying to a Web Server905-------------------------906907Ready to deploy your new Flask app? See :doc:`deploying/index`.