Skip to content
Myr

quickstart.rst

This file

Path

docs/quickstart.rst

858 lines · 29.4 KiB

Last changed by

fix codespell findingsDavid Lordbefore adoption9b74a90

History of this file

Take it

1Quickstart2==========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.4142To run the application, use the ``flask`` command or43``python -m flask``. You need to tell the Flask where your application44is with the ``--app`` option.4546.. code-block:: text4748    $ flask --app hello run49     * Serving Flask app 'hello'50     * Running on http://127.0.0.1:5000 (Press CTRL+C to quit)5152.. admonition:: Application Discovery Behavior5354    As a shortcut, if the file is named ``app.py`` or ``wsgi.py``, you55    don't have to use ``--app``. See :doc:`/cli` for more details.5657This 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.106107To enable debug mode, use the ``--debug`` option.108109.. code-block:: text110111    $ flask --app hello run --debug112     * Serving Flask app 'hello'113     * Debug mode: on114     * 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-nnn118119See also:120121-   :doc:`/server` and :doc:`/cli` for information about running in debug mode.122-   :doc:`/debugging` for information about using the built-in debugger123    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 flask import request143    from markupsafe import escape144145    @app.route("/hello")146    def hello():147        name = request.args.get("name", "Flask")148        return f"Hello, {escape(name)}!"149150If a user submits ``/hello?name=<script>alert("bad")</script>``, escaping causes151it to be rendered as text, rather than running the script in the user's browser.152153154Routing155-------156157Modern web applications use meaningful URLs to help users. Users are more158likely to like a page and come back if the page uses a meaningful URL they can159remember and use to directly visit a page.160161Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::162163    @app.route('/')164    def index():165        return 'Index Page'166167    @app.route('/hello')168    def hello():169        return 'Hello, World'170171You can do more! You can make parts of the URL dynamic and attach multiple172rules to a function.173174Variable Rules175``````````````176177You can add variable sections to a URL by marking sections with178``<variable_name>``. Your function then receives the ``<variable_name>``179as a keyword argument. Optionally, you can use a converter to specify the type180of the argument like ``<converter:variable_name>``. ::181182    from markupsafe import escape183184    @app.route('/user/<username>')185    def show_user_profile(username):186        # show the user profile for that user187        return f'User {escape(username)}'188189    @app.route('/post/<int:post_id>')190    def show_post(post_id):191        # show the post with the given id, the id is an integer192        return f'Post {post_id}'193194    @app.route('/path/<path:subpath>')195    def show_subpath(subpath):196        # show the subpath after /path/197        return f'Subpath {escape(subpath)}'198199Converter types:200201========== ==========================================202``string`` (default) accepts any text without a slash203``int``    accepts positive integers204``float``  accepts positive floating point values205``path``   like ``string`` but also accepts slashes206``uuid``   accepts UUID strings207========== ==========================================208209210Unique URLs / Redirection Behavior211``````````````````````````````````212213The following two rules differ in their use of a trailing slash. ::214215    @app.route('/projects/')216    def projects():217        return 'The project page'218219    @app.route('/about')220    def about():221        return 'The about page'222223The canonical URL for the ``projects`` endpoint has a trailing slash.224It's similar to a folder in a file system. If you access the URL without225a trailing slash (``/projects``), Flask redirects you to the canonical URL226with the trailing slash (``/projects/``).227228The canonical URL for the ``about`` endpoint does not have a trailing229slash. It's similar to the pathname of a file. Accessing the URL with a230trailing slash (``/about/``) produces a 404 "Not Found" error. This helps231keep URLs unique for these resources, which helps search engines avoid232indexing the same page twice.233234235.. _url-building:236237URL Building238````````````239240To build a URL to a specific function, use the :func:`~flask.url_for` function.241It accepts the name of the function as its first argument and any number of242keyword arguments, each corresponding to a variable part of the URL rule.243Unknown variable parts are appended to the URL as query parameters.244245Why would you want to build URLs using the URL reversing function246:func:`~flask.url_for` instead of hard-coding them into your templates?2472481. Reversing is often more descriptive than hard-coding the URLs.2492. You can change your URLs in one go instead of needing to remember to250   manually change hard-coded URLs.2513. URL building handles escaping of special characters transparently.2524. The generated paths are always absolute, avoiding unexpected behavior253   of relative paths in browsers.2545. If your application is placed outside the URL root, for example, in255   ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly256   handles that for you.257258For example, here we use the :meth:`~flask.Flask.test_request_context` method259to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`260tells Flask to behave as though it's handling a request even while we use a261Python shell. See :doc:`/appcontext`.262263.. code-block:: python264265    from flask import url_for266267    @app.route('/')268    def index():269        return 'index'270271    @app.route('/login')272    def login():273        return 'login'274275    @app.route('/user/<username>')276    def profile(username):277        return f'{username}\'s profile'278279    with app.test_request_context():280        print(url_for('index'))281        print(url_for('login'))282        print(url_for('login', next='/'))283        print(url_for('profile', username='John Doe'))284285.. code-block:: text286287    /288    /login289    /login?next=/290    /user/John%20Doe291292293HTTP Methods294````````````295296Web applications use different HTTP methods when accessing URLs. You should297familiarize yourself with the HTTP methods as you work with Flask. By default,298a route only answers to ``GET`` requests. You can use the ``methods`` argument299of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.300::301302    from flask import request303304    @app.route('/login', methods=['GET', 'POST'])305    def login():306        if request.method == 'POST':307            return do_the_login()308        else:309            return show_the_login_form()310311The example above keeps all methods for the route within one function,312which can be useful if each part uses some common data.313314You can also separate views for different methods into different315functions. Flask provides a shortcut for decorating such routes with316:meth:`~flask.Flask.get`, :meth:`~flask.Flask.post`, etc. for each317common HTTP method.318319.. code-block:: python320321    @app.get('/login')322    def login_get():323        return show_the_login_form()324325    @app.post('/login')326    def login_post():327        return do_the_login()328329If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method330and handles ``HEAD`` requests according to the `HTTP RFC`_. Likewise,331``OPTIONS`` is automatically implemented for you.332333.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt334335Static Files336------------337338Dynamic web applications also need static files.  That's usually where339the CSS and JavaScript files are coming from.  Ideally your web server is340configured to serve them for you, but during development Flask can do that341as well.  Just create a folder called :file:`static` in your package or next to342your module and it will be available at ``/static`` on the application.343344To generate URLs for static files, use the special ``'static'`` endpoint name::345346    url_for('static', filename='style.css')347348The file has to be stored on the filesystem as :file:`static/style.css`.349350Rendering Templates351-------------------352353Generating HTML from within Python is not fun, and actually pretty354cumbersome because you have to do the HTML escaping on your own to keep355the application secure.  Because of that Flask configures the `Jinja356<https://palletsprojects.com/p/jinja/>`_ template engine for you automatically.357358Templates can be used to generate any type of text file. For web applications, you'll359primarily be generating HTML pages, but you can also generate markdown, plain text for360emails, and anything else.361362For a reference to HTML, CSS, and other web APIs, use the `MDN Web Docs`_.363364.. _MDN Web Docs: https://developer.mozilla.org/365366To render a template you can use the :func:`~flask.render_template`367method.  All you have to do is provide the name of the template and the368variables you want to pass to the template engine as keyword arguments.369Here's a simple example of how to render a template::370371    from flask import render_template372373    @app.route('/hello/')374    @app.route('/hello/<name>')375    def hello(name=None):376        return render_template('hello.html', person=name)377378Flask will look for templates in the :file:`templates` folder.  So if your379application is a module, this folder is next to that module, if it's a380package it's actually inside your package:381382**Case 1**: a module::383384    /application.py385    /templates386        /hello.html387388**Case 2**: a package::389390    /application391        /__init__.py392        /templates393            /hello.html394395For templates you can use the full power of Jinja templates.  Head over396to the official `Jinja Template Documentation397<https://jinja.palletsprojects.com/templates/>`_ for more information.398399Here is an example template:400401.. sourcecode:: html+jinja402403    <!doctype html>404    <title>Hello from Flask</title>405    {% if person %}406      <h1>Hello {{ person }}!</h1>407    {% else %}408      <h1>Hello, World!</h1>409    {% endif %}410411Inside templates you also have access to the :data:`~flask.Flask.config`,412:class:`~flask.request`, :class:`~flask.session` and :class:`~flask.g` [#]_ objects413as well as the :func:`~flask.url_for` and :func:`~flask.get_flashed_messages` functions.414415Templates are especially useful if inheritance is used.  If you want to416know how that works, see :doc:`patterns/templateinheritance`. Basically417template inheritance makes it possible to keep certain elements on each418page (like header, navigation and footer).419420Automatic escaping is enabled, so if ``person`` contains HTML it will be escaped421automatically.  If you can trust a variable and you know that it will be422safe HTML (for example because it came from a module that converts wiki423markup to HTML) you can mark it as safe by using the424:class:`~markupsafe.Markup` class or by using the ``|safe`` filter in the425template.  Head over to the Jinja 2 documentation for more examples.426427Here is a basic introduction to how the :class:`~markupsafe.Markup` class works::428429    >>> from markupsafe import Markup430    >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'431    Markup('<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')432    >>> Markup.escape('<blink>hacker</blink>')433    Markup('&lt;blink&gt;hacker&lt;/blink&gt;')434    >>> Markup('<em>Marked up</em> &raquo; HTML').striptags()435    'Marked up » HTML'436437.. versionchanged:: 0.5438439   Autoescaping is no longer enabled for all templates.  The following440   extensions for templates trigger autoescaping: ``.html``, ``.htm``,441   ``.xml``, ``.xhtml``.  Templates loaded from a string will have442   autoescaping disabled.443444.. [#] Unsure what that :class:`~flask.g` object is? It's something in which445   you can store information for your own needs. See the documentation446   for :class:`flask.g` and :doc:`patterns/sqlite3`.447448449Accessing Request Data450----------------------451452For web applications it's crucial to react to the data a client sends to the453server. In Flask this information is provided by the global :data:`.request`454object, which is an instance of :class:`.Request`. This object has many455attributes and methods to work with the incoming request data, but here is a456broad overview. First it needs to be imported.457458.. code-block:: python459460    from flask import request461462If you have some experience with Python you might be wondering how that object463can be global when Flask handles multiple requests at a time. The answer is464that :data:`.request` is actually a proxy, pointing at whatever request is465currently being handled by a given worker, which is managed internally by Flask466and Python. See :doc:`/appcontext` for much more information.467468The current request method is available in the :attr:`~.Request.method`469attribute. To access form data (data transmitted in a ``POST`` or ``PUT``470request), use the :attr:`~flask.Request.form` attribute, which behaves like a471dict.472473.. code-block:: python474475    @app.route("/login", methods=["GET", "POST"])476    def login():477        error = None478479        if request.method == "POST":480            if valid_login(request.form["username"], request.form["password"]):481                return store_login(request.form["username"])482            else:483                error = "Invalid username or password"484485        # Executed if the request method was GET or the credentials were invalid.486        return render_template("login.html", error=error)487488If the key does not exist in ``form``, a special :exc:`KeyError` is raised. You489can catch it like a normal ``KeyError``, otherwise it will return a HTTP 400490Bad Request error page. You can also use the491:meth:`~werkzeug.datastructures.MultiDict.get` method to get a default492instead of an error.493494To access parameters submitted in the URL (``?key=value``), use the495:attr:`~.Request.args` attribute. Key errors behave the same as ``form``,496returning a 400 response if not caught.497498.. code-block:: python499500    searchword = request.args.get('key', '')501502For a full list of methods and attributes of the request object, see the503:class:`~.Request` documentation.504505506File Uploads507````````````508509You can handle uploaded files with Flask easily.  Just make sure not to510forget to set the ``enctype="multipart/form-data"`` attribute on your HTML511form, otherwise the browser will not transmit your files at all.512513Uploaded files are stored in memory or at a temporary location on the514filesystem.  You can access those files by looking at the515:attr:`~flask.request.files` attribute on the request object.  Each516uploaded file is stored in that dictionary.  It behaves just like a517standard Python :class:`file` object, but it also has a518:meth:`~werkzeug.datastructures.FileStorage.save` method that519allows you to store that file on the filesystem of the server.520Here is a simple example showing how that works::521522    from flask import request523524    @app.route('/upload', methods=['GET', 'POST'])525    def upload_file():526        if request.method == 'POST':527            f = request.files['the_file']528            f.save('/var/www/uploads/uploaded_file.txt')529        ...530531If you want to know how the file was named on the client before it was532uploaded to your application, you can access the533:attr:`~werkzeug.datastructures.FileStorage.filename` attribute.534However please keep in mind that this value can be forged535so never ever trust that value.  If you want to use the filename536of the client to store the file on the server, pass it through the537:func:`~werkzeug.utils.secure_filename` function that538Werkzeug provides for you::539540    from werkzeug.utils import secure_filename541542    @app.route('/upload', methods=['GET', 'POST'])543    def upload_file():544        if request.method == 'POST':545            file = request.files['the_file']546            file.save(f"/var/www/uploads/{secure_filename(file.filename)}")547        ...548549For some better examples, see :doc:`patterns/fileuploads`.550551Cookies552```````553554To access cookies you can use the :attr:`~flask.Request.cookies`555attribute.  To set cookies you can use the556:attr:`~flask.Response.set_cookie` method of response objects.  The557:attr:`~flask.Request.cookies` attribute of request objects is a558dictionary with all the cookies the client transmits.  If you want to use559sessions, do not use the cookies directly but instead use the560:ref:`sessions` in Flask that add some security on top of cookies for you.561562Reading cookies::563564    from flask import request565566    @app.route('/')567    def index():568        username = request.cookies.get('username')569        # use cookies.get(key) instead of cookies[key] to not get a570        # KeyError if the cookie is missing.571572Storing cookies::573574    from flask import make_response575576    @app.route('/')577    def index():578        resp = make_response(render_template(...))579        resp.set_cookie('username', 'the username')580        return resp581582Note that cookies are set on response objects.  Since you normally583just return strings from the view functions Flask will convert them into584response objects for you.  If you explicitly want to do that you can use585the :meth:`~flask.make_response` function and then modify it.586587Sometimes you might want to set a cookie at a point where the response588object does not exist yet.  This is possible by utilizing the589:doc:`patterns/deferredcallbacks` pattern.590591For this also see :ref:`about-responses`.592593Redirects and Errors594--------------------595596To redirect a user to another endpoint, use the :func:`~flask.redirect`597function; to abort a request early with an error code, use the598:func:`~flask.abort` function::599600    from flask import abort, redirect, url_for601602    @app.route('/')603    def index():604        return redirect(url_for('login'))605606    @app.route('/login')607    def login():608        abort(401)609        this_is_never_executed()610611This is a rather pointless example because a user will be redirected from612the index to a page they cannot access (401 means access denied) but it613shows how that works.614615By default a black and white error page is shown for each error code.  If616you want to customize the error page, you can use the617:meth:`~flask.Flask.errorhandler` decorator::618619    from flask import render_template620621    @app.errorhandler(404)622    def page_not_found(error):623        return render_template('page_not_found.html'), 404624625Note the ``404`` after the :func:`~flask.render_template` call.  This626tells Flask that the status code of that page should be 404 which means627not found.  By default 200 is assumed which translates to: all went well.628629See :doc:`errorhandling` for more details.630631.. _about-responses:632633About Responses634---------------635636The return value from a view function is automatically converted into637a response object for you. If the return value is a string it's638converted into a response object with the string as response body, a639``200 OK`` status code and a :mimetype:`text/html` mimetype. If the640return value is a dict or list, :func:`jsonify` is called to produce a641response. The logic that Flask applies to converting return values into642response objects is as follows:6436441.  If a response object of the correct type is returned it's directly645    returned from the view.6462.  If it's a string, a response object is created with that data and647    the default parameters.6483.  If it's an iterator or generator returning strings or bytes, it is649    treated as a streaming response.6504.  If it's a dict or list, a response object is created using651    :func:`~flask.json.jsonify`.6525.  If a tuple is returned the items in the tuple can provide extra653    information. Such tuples have to be in the form654    ``(response, status)``, ``(response, headers)``, or655    ``(response, status, headers)``. The ``status`` value will override656    the status code and ``headers`` can be a list or dictionary of657    additional header values.6586.  If none of that works, Flask will assume the return value is a659    valid WSGI application and convert that into a response object.660661If you want to get hold of the resulting response object inside the view662you can use the :func:`~flask.make_response` function.663664Imagine you have a view like this::665666    from flask import render_template667668    @app.errorhandler(404)669    def not_found(error):670        return render_template('error.html'), 404671672You just need to wrap the return expression with673:func:`~flask.make_response` and get the response object to modify it, then674return it::675676    from flask import make_response677678    @app.errorhandler(404)679    def not_found(error):680        resp = make_response(render_template('error.html'), 404)681        resp.headers['X-Something'] = 'A value'682        return resp683684685APIs with JSON686``````````````687688A common response format when writing an API is JSON. It's easy to get689started writing such an API with Flask. If you return a ``dict`` or690``list`` from a view, it will be converted to a JSON response.691692.. code-block:: python693694    @app.route("/me")695    def me_api():696        user = get_current_user()697        return {698            "username": user.username,699            "theme": user.theme,700            "image": url_for("user_image", filename=user.image),701        }702703    @app.route("/users")704    def users_api():705        users = get_all_users()706        return [user.to_json() for user in users]707708This is a shortcut to passing the data to the709:func:`~flask.json.jsonify` function, which will serialize any supported710JSON data type. That means that all the data in the dict or list must be711JSON serializable.712713For complex types such as database models, you'll want to use a714serialization library to convert the data to valid JSON types first.715There are many serialization libraries and Flask API extensions716maintained by the community that support more complex applications.717718719.. _sessions:720721Sessions722--------723724In addition to the request object there is also a second object called725:class:`~flask.session` which allows you to store information specific to a726user from one request to the next.  This is implemented on top of cookies727for you and signs the cookies cryptographically.  What this means is that728the user could look at the contents of your cookie but not modify it,729unless they know the secret key used for signing.730731In order to use sessions you have to set a secret key.  Here is how732sessions work::733734    from flask import session735736    # Set the secret key to some random bytes. Keep this really secret!737    app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'738739    @app.route('/')740    def index():741        if 'username' in session:742            return f'Logged in as {session["username"]}'743        return 'You are not logged in'744745    @app.route('/login', methods=['GET', 'POST'])746    def login():747        if request.method == 'POST':748            session['username'] = request.form['username']749            return redirect(url_for('index'))750        return '''751            <form method="post">752                <p><input type=text name=username>753                <p><input type=submit value=Login>754            </form>755        '''756757    @app.route('/logout')758    def logout():759        # remove the username from the session if it's there760        session.pop('username', None)761        return redirect(url_for('index'))762763.. admonition:: How to generate good secret keys764765    A secret key should be as random as possible. Your operating system has766    ways to generate pretty random data based on a cryptographic random767    generator. Use the following command to quickly generate a value for768    :attr:`Flask.secret_key` (or :data:`SECRET_KEY`)::769770        $ python -c 'import secrets; print(secrets.token_hex())'771        '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'772773A note on cookie-based sessions: Flask will take the values you put into the774session object and serialize them into a cookie.  If you are finding some775values do not persist across requests, cookies are indeed enabled, and you are776not getting a clear error message, check the size of the cookie in your page777responses compared to the size supported by web browsers.778779Besides the default client-side based sessions, if you want to handle780sessions on the server-side instead, there are several781Flask extensions that support this.782783Message Flashing784----------------785786Good applications and user interfaces are all about feedback.  If the user787does not get enough feedback they will probably end up hating the788application.  Flask provides a really simple way to give feedback to a789user with the flashing system.  The flashing system basically makes it790possible to record a message at the end of a request and access it on the next791(and only the next) request.  This is usually combined with a layout792template to expose the message.793794To flash a message use the :func:`~flask.flash` method, to get hold of the795messages you can use :func:`~flask.get_flashed_messages` which is also796available in the templates. See :doc:`patterns/flashing` for a full797example.798799Logging800-------801802.. versionadded:: 0.3803804Sometimes you might be in a situation where you deal with data that805should be correct, but actually is not.  For example you may have806some client-side code that sends an HTTP request to the server807but it's obviously malformed.  This might be caused by a user tampering808with the data, or the client code failing.  Most of the time it's okay809to reply with ``400 Bad Request`` in that situation, but sometimes810that won't do and the code has to continue working.811812You may still want to log that something fishy happened.  This is where813loggers come in handy.  As of Flask 0.3 a logger is preconfigured for you814to use.815816Here are some example log calls::817818    app.logger.debug('A value for debugging')819    app.logger.warning('A warning occurred (%d apples)', 42)820    app.logger.error('An error occurred')821822The attached :attr:`~flask.Flask.logger` is a standard logging823:class:`~logging.Logger`, so head over to the official :mod:`logging`824docs for more information.825826See :doc:`errorhandling`.827828829Hooking in WSGI Middleware830--------------------------831832To add WSGI middleware to your Flask application, wrap the application's833``wsgi_app`` attribute. For example, to apply Werkzeug's834:class:`~werkzeug.middleware.proxy_fix.ProxyFix` middleware for running835behind Nginx:836837.. code-block:: python838839    from werkzeug.middleware.proxy_fix import ProxyFix840    app.wsgi_app = ProxyFix(app.wsgi_app)841842Wrapping ``app.wsgi_app`` instead of ``app`` means that ``app`` still843points at your Flask application, not at the middleware, so you can844continue to use and configure ``app`` directly.845846Using Flask Extensions847----------------------848849Extensions are packages that help you accomplish common tasks. For850example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple851and easy to use with Flask.852853For more on Flask extensions, see :doc:`extensions`.854855Deploying to a Web Server856-------------------------857858Ready to deploy your new Flask app? See :doc:`deploying/index`.