quickstart.rst
This file
Path
docs/quickstart.rst
900 lines · 31.4 KiB
Last changed by
Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
History of this fileTake it
The walk stopped after 200 commits: lines older than 213afec point at it.
add rst extension for changelogDavid Lordbefore adoption213afec
lines 1–5why, one step back1.. _quickstart:23Quickstart4==========5Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 6–7why, one step back6Eager to get started? This page gives a good introduction to Flask.7Follow :doc:`installation` to set up a project and install Flask first.add rst extension for changelogDavid Lordbefore adoption213afec
lines 8–12why, one step back8910A Minimal Application11---------------------12Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 13why, one step back13A minimal Flask application looks something like this:add rst extension for changelogDavid Lordbefore adoption213afec
line 14why, one step back14Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 15–16why, one step back15.. code-block:: python16add rst extension for changelogDavid Lordbefore adoption213afec
line 17why, one step back17 from flask import FlaskMerge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 18–19why, one step back18 from markupsafe import escape19add rst extension for changelogDavid Lordbefore adoption213afec
lines 20–21why, one step back20 app = Flask(__name__)21Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 22why, one step back22 @app.route("/")add rst extension for changelogDavid Lordbefore adoption213afec
line 23why, one step back23 def hello_world():Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 24why, one step back24 return f"<p>Hello, {escape(name)}!</p>"add rst extension for changelogDavid Lordbefore adoption213afec
lines 25–27why, one step back2526So what did that code do?27Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 28–39why, one step back281. First we imported the :class:`~flask.Flask` class. An instance of29 this class will be our WSGI application.302. Next we create an instance of this class. The first argument is the31 name of the application's module or package. ``__name__`` is a32 convenient shortcut for this that is appropriate for most cases.33 This is needed so that Flask knows where to look for resources such34 as templates and static files.353. We then use the :meth:`~flask.Flask.route` decorator to tell Flask36 what URL should trigger our function.374. The function returns the message we want to display in the user's38 browser. The default content type is HTML, so HTML in the string39 will be rendered by the browser.add rst extension for changelogDavid Lordbefore adoption213afec
line 40why, one step back40Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 41–49why, one step back41.. note:: HTML escaping4243 When returning HTML (the default response type in Flask), any user44 input rendered in the output must be escaped to protect from45 injection attacks. HTML templates in Jinja, introduced later, will46 do this automatically. :func:`~markupsafe.escape`, shown above, can47 be used manually. It's omitted for brevity in the examples below.4849Save it as :file:`hello.py` or something similar. Make sure to not calladd rst extension for changelogDavid Lordbefore adoption213afec
lines 50–52why, one step back50your application :file:`flask.py` because this would conflict with Flask51itself.52Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 53–54why, one step back53To run the application, use the :command:`flask` command or54:command:`python -m flask`. Before you can do that you needadd rst extension for changelogDavid Lordbefore adoption213afec
line 55why, one step back55to tell your terminal the application to work with by exporting theMerge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 56why, one step back56``FLASK_APP`` environment variable:add rst extension for changelogDavid Lordbefore adoption213afec
line 57why, one step back57Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 58–59why, one step back58.. code-block:: text59add rst extension for changelogDavid Lordbefore adoption213afec
lines 60–76why, one step back60 $ export FLASK_APP=hello.py61 $ flask run62 * Running on http://127.0.0.1:5000/6364If you are on Windows, the environment variable syntax depends on command line65interpreter. On Command Prompt::6667 C:\path\to\app>set FLASK_APP=hello.py6869And on PowerShell::7071 PS C:\path\to\app> $env:FLASK_APP = "hello.py"7273This launches a very simple builtin server, which is good enough for testing74but probably not what you want to use in production. For deployment options see75:ref:`deployment`.76Merge branch '1.0.x'David Lordbefore adoption1351d0a
lines 77–78why, one step back77Now head over to http://127.0.0.1:5000/, and you should see your hello78world greeting.add rst extension for changelogDavid Lordbefore adoption213afec
lines 79–92why, one step back7980.. _public-server:8182.. admonition:: Externally Visible Server8384 If you run the server you will notice that the server is only accessible85 from your own computer, not from any other in the network. This is the86 default because in debugging mode a user of the application can execute87 arbitrary Python code on your computer.8889 If you have the debugger disabled or trust the users on your network,90 you can make the server publicly available simply by adding91 ``--host=0.0.0.0`` to the command line::92Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6
line 93why, one step back93 $ flask run --host=0.0.0.0add rst extension for changelogDavid Lordbefore adoption213afec
lines 94–100why, one step back9495 This tells your operating system to listen on all public IPs.969798What to do if the Server does not Start99---------------------------------------100Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
lines 101–103why, one step back101In case the :command:`python -m flask` fails or :command:`flask`102does not exist, there are multiple reasons this might be the case.103First of all you need to look at the error message.add rst extension for changelogDavid Lordbefore adoption213afec
lines 104–174why, one step back104105Old Version of Flask106````````````````````107108Versions of Flask older than 0.11 use to have different ways to start the109application. In short, the :command:`flask` command did not exist, and110neither did :command:`python -m flask`. In that case you have two options:111either upgrade to newer Flask versions or have a look at the :ref:`server`112docs to see the alternative method for running a server.113114Invalid Import Name115```````````````````116117The ``FLASK_APP`` environment variable is the name of the module to import at118:command:`flask run`. In case that module is incorrectly named you will get an119import error upon start (or if debug is enabled when you navigate to the120application). It will tell you what it tried to import and why it failed.121122The most common reason is a typo or because you did not actually create an123``app`` object.124125.. _debug-mode:126127Debug Mode128----------129130(Want to just log errors and stack traces? See :ref:`application-errors`)131132The :command:`flask` script is nice to start a local development server, but133you would have to restart it manually after each change to your code.134That is not very nice and Flask can do better. If you enable debug135support the server will reload itself on code changes, and it will also136provide you with a helpful debugger if things go wrong.137138To enable all development features (including debug mode) you can export139the ``FLASK_ENV`` environment variable and set it to ``development``140before running the server::141142 $ export FLASK_ENV=development143 $ flask run144145(On Windows you need to use ``set`` instead of ``export``.)146147This does the following things:1481491. it activates the debugger1502. it activates the automatic reloader1513. it enables the debug mode on the Flask application.152153You can also control debug mode separately from the environment by154exporting ``FLASK_DEBUG=1``.155156There are more parameters that are explained in the :ref:`server` docs.157158.. admonition:: Attention159160 Even though the interactive debugger does not work in forking environments161 (which makes it nearly impossible to use on production servers), it still162 allows the execution of arbitrary code. This makes it a major security risk163 and therefore it **must never be used on production machines**.164165Screenshot of the debugger in action:166167.. image:: _static/debugger.png168 :align: center169 :class: screenshot170 :alt: screenshot of debugger in action171172More information on using the debugger can be found in the `Werkzeug173documentation`_.174Merge branch '1.0.x'David Lordbefore adoption1351d0a
line 175why, one step back175.. _Werkzeug documentation: https://werkzeug.palletsprojects.com/debug/#using-the-debuggeradd rst extension for changelogDavid Lordbefore adoption213afec
lines 176–210why, one step back176177Have another debugger in mind? See :ref:`working-with-debuggers`.178179180Routing181-------182183Modern web applications use meaningful URLs to help users. Users are more184likely to like a page and come back if the page uses a meaningful URL they can185remember and use to directly visit a page.186187Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::188189 @app.route('/')190 def index():191 return 'Index Page'192193 @app.route('/hello')194 def hello():195 return 'Hello, World'196197You can do more! You can make parts of the URL dynamic and attach multiple198rules to a function.199200Variable Rules201``````````````202203You can add variable sections to a URL by marking sections with204``<variable_name>``. Your function then receives the ``<variable_name>``205as a keyword argument. Optionally, you can use a converter to specify the type206of the argument like ``<converter:variable_name>``. ::207208 @app.route('/user/<username>')209 def show_user_profile(username):210 # show the user profile for that userMerge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 211why, one step back211 return f'User {username}'add rst extension for changelogDavid Lordbefore adoption213afec
lines 212–215why, one step back212213 @app.route('/post/<int:post_id>')214 def show_post(post_id):215 # show the post with the given id, the id is an integerMerge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 216why, one step back216 return f'Post {post_id}'add rst extension for changelogDavid Lordbefore adoption213afec
lines 217–220why, one step back217218 @app.route('/path/<path:subpath>')219 def show_subpath(subpath):220 # show the subpath after /path/Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 221why, one step back221 return f'Subpath {subpath}'add rst extension for changelogDavid Lordbefore adoption213afec
lines 222–235why, one step back222223Converter types:224225========== ==========================================226``string`` (default) accepts any text without a slash227``int`` accepts positive integers228``float`` accepts positive floating point values229``path`` like ``string`` but also accepts slashes230``uuid`` accepts UUID strings231========== ==========================================232233Unique URLs / Redirection Behavior234``````````````````````````````````235Merge pull request #2637 from pallets/quickstart-unique-urlsDavid Lordbefore adoptionb0c1da1
line 236why, one step back236The following two rules differ in their use of a trailing slash. ::add rst extension for changelogDavid Lordbefore adoption213afec
lines 237–245why, one step back237238 @app.route('/projects/')239 def projects():240 return 'The project page'241242 @app.route('/about')243 def about():244 return 'The about page'245Merge pull request #2637 from pallets/quickstart-unique-urlsDavid Lordbefore adoptionb0c1da1
lines 246–249why, one step back246The canonical URL for the ``projects`` endpoint has a trailing slash.247It's similar to a folder in a file system. If you access the URL without248a trailing slash, Flask redirects you to the canonical URL with the249trailing slash.add rst extension for changelogDavid Lordbefore adoption213afec
line 250why, one step back250Merge pull request #2637 from pallets/quickstart-unique-urlsDavid Lordbefore adoptionb0c1da1
lines 251–255why, one step back251The canonical URL for the ``about`` endpoint does not have a trailing252slash. It's similar to the pathname of a file. Accessing the URL with a253trailing slash produces a 404 "Not Found" error. This helps keep URLs254unique for these resources, which helps search engines avoid indexing255the same page twice.add rst extension for changelogDavid Lordbefore adoption213afec
lines 256–272why, one step back256257258.. _url-building:259260URL Building261````````````262263To build a URL to a specific function, use the :func:`~flask.url_for` function.264It accepts the name of the function as its first argument and any number of265keyword arguments, each corresponding to a variable part of the URL rule.266Unknown variable parts are appended to the URL as query parameters.267268Why would you want to build URLs using the URL reversing function269:func:`~flask.url_for` instead of hard-coding them into your templates?2702711. Reversing is often more descriptive than hard-coding the URLs.2722. You can change your URLs in one go instead of needing to remember toMerge pull request #3101 from tbm/docs-formattingDavid Lordbefore adoptionc795adf
line 273why, one step back273 manually change hard-coded URLs.add rst extension for changelogDavid Lordbefore adoption213afec
line 274why, one step back2743. URL building handles escaping of special characters and Unicode dataMerge pull request #3101 from tbm/docs-formattingDavid Lordbefore adoptionc795adf
line 275why, one step back275 transparently.Merge pull request #2637 from pallets/quickstart-unique-urlsDavid Lordbefore adoptionb0c1da1
lines 276–278why, one step back2764. The generated paths are always absolute, avoiding unexpected behavior277 of relative paths in browsers.2785. If your application is placed outside the URL root, for example, inMerge pull request #3101 from tbm/docs-formattingDavid Lordbefore adoptionc795adf
lines 279–280why, one step back279 ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly280 handles that for you.add rst extension for changelogDavid Lordbefore adoption213afec
lines 281–284why, one step back281282For example, here we use the :meth:`~flask.Flask.test_request_context` method283to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`284tells Flask to behave as though it's handling a request even while we use asplit code and outputDavid Lordbefore adoption0b7a74d
line 285why, one step back285Python shell. See :ref:`context-locals`.add rst extension for changelogDavid Lordbefore adoption213afec
line 286why, one step back286split code and outputDavid Lordbefore adoption0b7a74d
lines 287–288why, one step back287.. code-block:: python288Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 289why, one step back289 from flask import url_foradd rst extension for changelogDavid Lordbefore adoption213afec
lines 290–300why, one step back290291 @app.route('/')292 def index():293 return 'index'294295 @app.route('/login')296 def login():297 return 'login'298299 @app.route('/user/<username>')300 def profile(username):Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 301why, one step back301 return f'{username}\'s profile'add rst extension for changelogDavid Lordbefore adoption213afec
lines 302–308why, one step back302303 with app.test_request_context():304 print(url_for('index'))305 print(url_for('login'))306 print(url_for('login', next='/'))307 print(url_for('profile', username='John Doe'))308split code and outputDavid Lordbefore adoption0b7a74d
lines 309–315why, one step back309.. code-block:: text310311 /312 /login313 /login?next=/314 /user/John%20Doe315add rst extension for changelogDavid Lordbefore adoption213afec
lines 316–325why, one step back316317HTTP Methods318````````````319320Web applications use different HTTP methods when accessing URLs. You should321familiarize yourself with the HTTP methods as you work with Flask. By default,322a route only answers to ``GET`` requests. You can use the ``methods`` argument323of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.324::325Merge branch '1.0-maintenance'David Lordbefore adoption1fa9185
lines 326–327why, one step back326 from flask import request327add rst extension for changelogDavid Lordbefore adoption213afec
lines 328–335why, one step back328 @app.route('/login', methods=['GET', 'POST'])329 def login():330 if request.method == 'POST':331 return do_the_login()332 else:333 return show_the_login_form()334335If ``GET`` is present, Flask automatically adds support for the ``HEAD`` methodMerge branch '1.0-maintenance'David Lordbefore adoption1fa9185
line 336why, one step back336and handles ``HEAD`` requests according to the `HTTP RFC`_. Likewise,add rst extension for changelogDavid Lordbefore adoption213afec
lines 337–394why, one step back337``OPTIONS`` is automatically implemented for you.338339.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt340341Static Files342------------343344Dynamic web applications also need static files. That's usually where345the CSS and JavaScript files are coming from. Ideally your web server is346configured to serve them for you, but during development Flask can do that347as well. Just create a folder called :file:`static` in your package or next to348your module and it will be available at ``/static`` on the application.349350To generate URLs for static files, use the special ``'static'`` endpoint name::351352 url_for('static', filename='style.css')353354The file has to be stored on the filesystem as :file:`static/style.css`.355356Rendering Templates357-------------------358359Generating HTML from within Python is not fun, and actually pretty360cumbersome because you have to do the HTML escaping on your own to keep361the application secure. Because of that Flask configures the `Jinja2362<http://jinja.pocoo.org/>`_ template engine for you automatically.363364To render a template you can use the :func:`~flask.render_template`365method. All you have to do is provide the name of the template and the366variables you want to pass to the template engine as keyword arguments.367Here's a simple example of how to render a template::368369 from flask import render_template370371 @app.route('/hello/')372 @app.route('/hello/<name>')373 def hello(name=None):374 return render_template('hello.html', name=name)375376Flask will look for templates in the :file:`templates` folder. So if your377application is a module, this folder is next to that module, if it's a378package it's actually inside your package:379380**Case 1**: a module::381382 /application.py383 /templates384 /hello.html385386**Case 2**: a package::387388 /application389 /__init__.py390 /templates391 /hello.html392393For templates you can use the full power of Jinja2 templates. Head over394to the official `Jinja2 Template DocumentationMerge branch '1.0.x'David Lordbefore adoption1351d0a
line 395why, one step back395<http://jinja.pocoo.org/docs/templates/>`_ for more information.add rst extension for changelogDavid Lordbefore adoption213afec
lines 396–421why, one step back396397Here is an example template:398399.. sourcecode:: html+jinja400401 <!doctype html>402 <title>Hello from Flask</title>403 {% if name %}404 <h1>Hello {{ name }}!</h1>405 {% else %}406 <h1>Hello, World!</h1>407 {% endif %}408409Inside templates you also have access to the :class:`~flask.request`,410:class:`~flask.session` and :class:`~flask.g` [#]_ objects411as well as the :func:`~flask.get_flashed_messages` function.412413Templates are especially useful if inheritance is used. If you want to414know how that works, head over to the :ref:`template-inheritance` pattern415documentation. Basically template inheritance makes it possible to keep416certain elements on each page (like header, navigation and footer).417418Automatic escaping is enabled, so if ``name`` contains HTML it will be escaped419automatically. If you can trust a variable and you know that it will be420safe HTML (for example because it came from a module that converts wiki421markup to HTML) you can mark it as safe by using theMerge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 422why, one step back422:class:`~markupsafe.Markup` class or by using the ``|safe`` filter in theadd rst extension for changelogDavid Lordbefore adoption213afec
lines 423–426why, one step back423template. Head over to the Jinja 2 documentation for more examples.424425Here is a basic introduction to how the :class:`~jinja2.Markup` class works::426Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 427why, one step back427 >>> from markupsafe import Markupadd rst extension for changelogDavid Lordbefore adoption213afec
lines 428–563why, one step back428 >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'429 Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')430 >>> Markup.escape('<blink>hacker</blink>')431 Markup(u'<blink>hacker</blink>')432 >>> Markup('<em>Marked up</em> » HTML').striptags()433 u'Marked up \xbb HTML'434435.. versionchanged:: 0.5436437 Autoescaping is no longer enabled for all templates. The following438 extensions for templates trigger autoescaping: ``.html``, ``.htm``,439 ``.xml``, ``.xhtml``. Templates loaded from a string will have440 autoescaping disabled.441442.. [#] Unsure what that :class:`~flask.g` object is? It's something in which443 you can store information for your own needs, check the documentation of444 that object (:class:`~flask.g`) and the :ref:`sqlite3` for more445 information.446447448Accessing Request Data449----------------------450451For web applications it's crucial to react to the data a client sends to452the server. In Flask this information is provided by the global453:class:`~flask.request` object. If you have some experience with Python454you might be wondering how that object can be global and how Flask455manages to still be threadsafe. The answer is context locals:456457458.. _context-locals:459460Context Locals461``````````````462463.. admonition:: Insider Information464465 If you want to understand how that works and how you can implement466 tests with context locals, read this section, otherwise just skip it.467468Certain objects in Flask are global objects, but not of the usual kind.469These objects are actually proxies to objects that are local to a specific470context. What a mouthful. But that is actually quite easy to understand.471472Imagine the context being the handling thread. A request comes in and the473web server decides to spawn a new thread (or something else, the474underlying object is capable of dealing with concurrency systems other475than threads). When Flask starts its internal request handling it476figures out that the current thread is the active context and binds the477current application and the WSGI environments to that context (thread).478It does that in an intelligent way so that one application can invoke another479application without breaking.480481So what does this mean to you? Basically you can completely ignore that482this is the case unless you are doing something like unit testing. You483will notice that code which depends on a request object will suddenly break484because there is no request object. The solution is creating a request485object yourself and binding it to the context. The easiest solution for486unit testing is to use the :meth:`~flask.Flask.test_request_context`487context manager. In combination with the ``with`` statement it will bind a488test request so that you can interact with it. Here is an example::489490 from flask import request491492 with app.test_request_context('/hello', method='POST'):493 # now you can do something with the request until the494 # end of the with block, such as basic assertions:495 assert request.path == '/hello'496 assert request.method == 'POST'497498The other possibility is passing a whole WSGI environment to the499:meth:`~flask.Flask.request_context` method::500501 with app.request_context(environ):502 assert request.method == 'POST'503504The Request Object505``````````````````506507The request object is documented in the API section and we will not cover508it here in detail (see :class:`~flask.Request`). Here is a broad overview of509some of the most common operations. First of all you have to import it from510the ``flask`` module::511512 from flask import request513514The current request method is available by using the515:attr:`~flask.Request.method` attribute. To access form data (data516transmitted in a ``POST`` or ``PUT`` request) you can use the517:attr:`~flask.Request.form` attribute. Here is a full example of the two518attributes mentioned above::519520 @app.route('/login', methods=['POST', 'GET'])521 def login():522 error = None523 if request.method == 'POST':524 if valid_login(request.form['username'],525 request.form['password']):526 return log_the_user_in(request.form['username'])527 else:528 error = 'Invalid username/password'529 # the code below is executed if the request method530 # was GET or the credentials were invalid531 return render_template('login.html', error=error)532533What happens if the key does not exist in the ``form`` attribute? In that534case a special :exc:`KeyError` is raised. You can catch it like a535standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request536error page is shown instead. So for many situations you don't have to537deal with that problem.538539To access parameters submitted in the URL (``?key=value``) you can use the540:attr:`~flask.Request.args` attribute::541542 searchword = request.args.get('key', '')543544We recommend accessing URL parameters with `get` or by catching the545:exc:`KeyError` because users might change the URL and presenting them a 400546bad request page in that case is not user friendly.547548For a full list of methods and attributes of the request object, head over549to the :class:`~flask.Request` documentation.550551552File Uploads553````````````554555You can handle uploaded files with Flask easily. Just make sure not to556forget to set the ``enctype="multipart/form-data"`` attribute on your HTML557form, otherwise the browser will not transmit your files at all.558559Uploaded files are stored in memory or at a temporary location on the560filesystem. You can access those files by looking at the561:attr:`~flask.request.files` attribute on the request object. Each562uploaded file is stored in that dictionary. It behaves just like a563standard Python :class:`file` object, but it also has aMerge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
lines 564–566why, one step back564:meth:`~werkzeug.datastructures.FileStorage.save` method that565allows you to store that file on the filesystem of the server.566Here is a simple example showing how that works::add rst extension for changelogDavid Lordbefore adoption213afec
lines 567–578why, one step back567568 from flask import request569570 @app.route('/upload', methods=['GET', 'POST'])571 def upload_file():572 if request.method == 'POST':573 f = request.files['the_file']574 f.save('/var/www/uploads/uploaded_file.txt')575 ...576577If you want to know how the file was named on the client before it was578uploaded to your application, you can access theMerge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
lines 579–583why, one step back579:attr:`~werkzeug.datastructures.FileStorage.filename` attribute.580However please keep in mind that this value can be forged581so never ever trust that value. If you want to use the filename582of the client to store the file on the server, pass it through the583:func:`~werkzeug.utils.secure_filename` function thatadd rst extension for changelogDavid Lordbefore adoption213afec
lines 584–681why, one step back584Werkzeug provides for you::585586 from werkzeug.utils import secure_filename587588 @app.route('/upload', methods=['GET', 'POST'])589 def upload_file():590 if request.method == 'POST':591 f = request.files['the_file']592 f.save('/var/www/uploads/' + secure_filename(f.filename))593 ...594595For some better examples, checkout the :ref:`uploading-files` pattern.596597Cookies598```````599600To access cookies you can use the :attr:`~flask.Request.cookies`601attribute. To set cookies you can use the602:attr:`~flask.Response.set_cookie` method of response objects. The603:attr:`~flask.Request.cookies` attribute of request objects is a604dictionary with all the cookies the client transmits. If you want to use605sessions, do not use the cookies directly but instead use the606:ref:`sessions` in Flask that add some security on top of cookies for you.607608Reading cookies::609610 from flask import request611612 @app.route('/')613 def index():614 username = request.cookies.get('username')615 # use cookies.get(key) instead of cookies[key] to not get a616 # KeyError if the cookie is missing.617618Storing cookies::619620 from flask import make_response621622 @app.route('/')623 def index():624 resp = make_response(render_template(...))625 resp.set_cookie('username', 'the username')626 return resp627628Note that cookies are set on response objects. Since you normally629just return strings from the view functions Flask will convert them into630response objects for you. If you explicitly want to do that you can use631the :meth:`~flask.make_response` function and then modify it.632633Sometimes you might want to set a cookie at a point where the response634object does not exist yet. This is possible by utilizing the635:ref:`deferred-callbacks` pattern.636637For this also see :ref:`about-responses`.638639Redirects and Errors640--------------------641642To redirect a user to another endpoint, use the :func:`~flask.redirect`643function; to abort a request early with an error code, use the644:func:`~flask.abort` function::645646 from flask import abort, redirect, url_for647648 @app.route('/')649 def index():650 return redirect(url_for('login'))651652 @app.route('/login')653 def login():654 abort(401)655 this_is_never_executed()656657This is a rather pointless example because a user will be redirected from658the index to a page they cannot access (401 means access denied) but it659shows how that works.660661By default a black and white error page is shown for each error code. If662you want to customize the error page, you can use the663:meth:`~flask.Flask.errorhandler` decorator::664665 from flask import render_template666667 @app.errorhandler(404)668 def page_not_found(error):669 return render_template('page_not_found.html'), 404670671Note the ``404`` after the :func:`~flask.render_template` call. This672tells Flask that the status code of that page should be 404 which means673not found. By default 200 is assumed which translates to: all went well.674675See :ref:`error-handlers` for more details.676677.. _about-responses:678679About Responses680---------------681Merge pull request #3111 from pgjones/masterDavid Lordbefore adoption855d59b
lines 682–688why, one step back682The return value from a view function is automatically converted into683a response object for you. If the return value is a string it's684converted into a response object with the string as response body, a685``200 OK`` status code and a :mimetype:`text/html` mimetype. If the686return value is a dict, :func:`jsonify` is called to produce a response.687The logic that Flask applies to converting return values into response688objects is as follows:add rst extension for changelogDavid Lordbefore adoption213afec
lines 689–691why, one step back6896901. If a response object of the correct type is returned it's directly691 returned from the view.Merge pull request #3111 from pgjones/masterDavid Lordbefore adoption855d59b
lines 692–701why, one step back6922. If it's a string, a response object is created with that data and693 the default parameters.6943. If it's a dict, a response object is created using ``jsonify``.6954. If a tuple is returned the items in the tuple can provide extra696 information. Such tuples have to be in the form697 ``(response, status)``, ``(response, headers)``, or698 ``(response, status, headers)``. The ``status`` value will override699 the status code and ``headers`` can be a list or dictionary of700 additional header values.7015. If none of that works, Flask will assume the return value is aadd rst extension for changelogDavid Lordbefore adoption213afec
lines 702–708why, one step back702 valid WSGI application and convert that into a response object.703704If you want to get hold of the resulting response object inside the view705you can use the :func:`~flask.make_response` function.706707Imagine you have a view like this::708Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 709–710why, one step back709 from flask import render_template710add rst extension for changelogDavid Lordbefore adoption213afec
lines 711–718why, one step back711 @app.errorhandler(404)712 def not_found(error):713 return render_template('error.html'), 404714715You just need to wrap the return expression with716:func:`~flask.make_response` and get the response object to modify it, then717return it::718Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 719–720why, one step back719 from flask import make_response720add rst extension for changelogDavid Lordbefore adoption213afec
lines 721–725why, one step back721 @app.errorhandler(404)722 def not_found(error):723 resp = make_response(render_template('error.html'), 404)724 resp.headers['X-Something'] = 'A value'725 return respMerge pull request #3111 from pgjones/masterDavid Lordbefore adoption855d59b
lines 726–753why, one step back726727728APIs with JSON729``````````````730731A common response format when writing an API is JSON. It's easy to get732started writing such an API with Flask. If you return a ``dict`` from a733view, it will be converted to a JSON response.734735.. code-block:: python736737 @app.route("/me")738 def me_api():739 user = get_current_user()740 return {741 "username": user.username,742 "theme": user.theme,743 "image": url_for("user_image", filename=user.image),744 }745746Depending on your API design, you may want to create JSON responses for747types other than ``dict``. In that case, use the748:func:`~flask.json.jsonify` function, which will serialize any supported749JSON data type. Or look into Flask community extensions that support750more complex applications.751752.. code-block:: python753Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
lines 754–755why, one step back754 from flask import jsonify755Merge pull request #3111 from pgjones/masterDavid Lordbefore adoption855d59b
lines 756–760why, one step back756 @app.route("/users")757 def users_api():758 users = get_all_users()759 return jsonify([user.to_json() for user in users])760add rst extension for changelogDavid Lordbefore adoption213afec
lines 761–776why, one step back761762.. _sessions:763764Sessions765--------766767In addition to the request object there is also a second object called768:class:`~flask.session` which allows you to store information specific to a769user from one request to the next. This is implemented on top of cookies770for you and signs the cookies cryptographically. What this means is that771the user could look at the contents of your cookie but not modify it,772unless they know the secret key used for signing.773774In order to use sessions you have to set a secret key. Here is how775sessions work::776Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 777why, one step back777 from flask import sessionadd rst extension for changelogDavid Lordbefore adoption213afec
lines 778–784why, one step back778779 # Set the secret key to some random bytes. Keep this really secret!780 app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'781782 @app.route('/')783 def index():784 if 'username' in session:Merge pull request #3391 from pallets/explain-escapeDavid Lordbefore adoption4bceecc
line 785why, one step back785 return f'Logged in as {session["username"]}'add rst extension for changelogDavid Lordbefore adoption213afec
lines 786–847why, one step back786 return 'You are not logged in'787788 @app.route('/login', methods=['GET', 'POST'])789 def login():790 if request.method == 'POST':791 session['username'] = request.form['username']792 return redirect(url_for('index'))793 return '''794 <form method="post">795 <p><input type=text name=username>796 <p><input type=submit value=Login>797 </form>798 '''799800 @app.route('/logout')801 def logout():802 # remove the username from the session if it's there803 session.pop('username', None)804 return redirect(url_for('index'))805806.. admonition:: How to generate good secret keys807808 A secret key should be as random as possible. Your operating system has809 ways to generate pretty random data based on a cryptographic random810 generator. Use the following command to quickly generate a value for811 :attr:`Flask.secret_key` (or :data:`SECRET_KEY`)::812813 $ python -c 'import os; print(os.urandom(16))'814 b'_5#y2L"F4Q8z\n\xec]/'815816A note on cookie-based sessions: Flask will take the values you put into the817session object and serialize them into a cookie. If you are finding some818values do not persist across requests, cookies are indeed enabled, and you are819not getting a clear error message, check the size of the cookie in your page820responses compared to the size supported by web browsers.821822Besides the default client-side based sessions, if you want to handle823sessions on the server-side instead, there are several824Flask extensions that support this.825826Message Flashing827----------------828829Good applications and user interfaces are all about feedback. If the user830does not get enough feedback they will probably end up hating the831application. Flask provides a really simple way to give feedback to a832user with the flashing system. The flashing system basically makes it833possible to record a message at the end of a request and access it on the next834(and only the next) request. This is usually combined with a layout835template to expose the message.836837To flash a message use the :func:`~flask.flash` method, to get hold of the838messages you can use :func:`~flask.get_flashed_messages` which is also839available in the templates. Check out the :ref:`message-flashing-pattern`840for a full example.841842Logging843-------844845.. versionadded:: 0.3846847Sometimes you might be in a situation where you deal with data thatMerge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
lines 848–853why, one step back848should be correct, but actually is not. For example you may have849some client-side code that sends an HTTP request to the server850but it's obviously malformed. This might be caused by a user tampering851with the data, or the client code failing. Most of the time it's okay852to reply with ``400 Bad Request`` in that situation, but sometimes853that won't do and the code has to continue working.add rst extension for changelogDavid Lordbefore adoption213afec
lines 854–865why, one step back854855You may still want to log that something fishy happened. This is where856loggers come in handy. As of Flask 0.3 a logger is preconfigured for you857to use.858859Here are some example log calls::860861 app.logger.debug('A value for debugging')862 app.logger.warning('A warning occurred (%d apples)', 42)863 app.logger.error('An error occurred')864865The attached :attr:`~flask.Flask.logger` is a standard loggingMerge branch '1.0.x'David Lordbefore adoption1351d0a
lines 866–867why, one step back866:class:`~logging.Logger`, so head over to the official :mod:`logging`867docs for more information.add rst extension for changelogDavid Lordbefore adoption213afec
lines 868–870why, one step back868869Read more on :ref:`application-errors`.870Merge branch '1.1.x'David Lordbefore adoption40eadfc
lines 871–872why, one step back871Hooking in WSGI Middleware872--------------------------add rst extension for changelogDavid Lordbefore adoption213afec
line 873why, one step back873Merge branch '1.1.x'David Lordbefore adoption40eadfc
lines 874–877why, one step back874To add WSGI middleware to your Flask application, wrap the application's875``wsgi_app`` attribute. For example, to apply Werkzeug's876:class:`~werkzeug.middlware.proxy_fix.ProxyFix` middleware for running877behind Nginx:add rst extension for changelogDavid Lordbefore adoption213afec
line 878why, one step back878Merge branch '1.1.x'David Lordbefore adoption40eadfc
lines 879–886why, one step back879.. code-block:: python880881 from werkzeug.middleware.proxy_fix import ProxyFix882 app.wsgi_app = ProxyFix(app.wsgi_app)883884Wrapping ``app.wsgi_app`` instead of ``app`` means that ``app`` still885points at your Flask application, not at the middleware, so you can886continue to use and configure ``app`` directly.add rst extension for changelogDavid Lordbefore adoption213afec
lines 887–900why, one step back887888Using Flask Extensions889----------------------890891Extensions are packages that help you accomplish common tasks. For892example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple893and easy to use with Flask.894895For more on Flask extensions, have a look at :ref:`extensions`.896897Deploying to a Web Server898-------------------------899900Ready to deploy your new Flask app? Go to :ref:`deployment`.