Skip to content
Myr

factory.rst

This file

Path

docs/tutorial/factory.rst

180 lines · 6.0 KiB

Last changed by

Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc

History of this file

Take it

1.. currentmodule:: flask23Application Setup4=================56A Flask application is an instance of the :class:`Flask` class.7Everything about the application, such as configuration and URLs, will8be registered with this class.910The most straightforward way to create a Flask application is to create11a global :class:`Flask` instance directly at the top of your code, like12how the "Hello, World!" example did on the previous page. While this is13simple and useful in some cases, it can cause some tricky issues as the14project grows.1516Instead of creating a :class:`Flask` instance globally, you will create17it inside a function. This function is known as the *application18factory*. Any configuration, registration, and other setup the19application needs will happen inside the function, then the application20will be returned.212223The Application Factory24-----------------------2526It's time to start coding! Create the ``flaskr`` directory and add the27``__init__.py`` file. The ``__init__.py`` serves double duty: it will28contain the application factory, and it tells Python that the ``flaskr``29directory should be treated as a package.3031.. code-block:: none3233    $ mkdir flaskr3435.. code-block:: python36    :caption: ``flaskr/__init__.py``3738    import os3940    from flask import Flask414243    def create_app(test_config=None):44        # create and configure the app45        app = Flask(__name__, instance_relative_config=True)46        app.config.from_mapping(47            SECRET_KEY='dev',48            DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),49        )5051        if test_config is None:52            # load the instance config, if it exists, when not testing53            app.config.from_pyfile('config.py', silent=True)54        else:55            # load the test config if passed in56            app.config.from_mapping(test_config)5758        # ensure the instance folder exists59        try:60            os.makedirs(app.instance_path)61        except OSError:62            pass6364        # a simple page that says hello65        @app.route('/hello')66        def hello():67            return 'Hello, World!'6869        return app7071``create_app`` is the application factory function. You'll add to it72later in the tutorial, but it already does a lot.7374#.  ``app = Flask(__name__, instance_relative_config=True)`` creates the75    :class:`Flask` instance.7677    *   ``__name__`` is the name of the current Python module. The app78        needs to know where it's located to set up some paths, and79        ``__name__`` is a convenient way to tell it that.8081    *   ``instance_relative_config=True`` tells the app that82        configuration files are relative to the83        :ref:`instance folder <instance-folders>`. The instance folder84        is located outside the ``flaskr`` package and can hold local85        data that shouldn't be committed to version control, such as86        configuration secrets and the database file.8788#.  :meth:`app.config.from_mapping() <Config.from_mapping>` sets89    some default configuration that the app will use:9091    *   :data:`SECRET_KEY` is used by Flask and extensions to keep data92        safe. It's set to ``'dev'`` to provide a convenient value93        during development, but it should be overridden with a random94        value when deploying.9596    *   ``DATABASE`` is the path where the SQLite database file will be97        saved. It's under98        :attr:`app.instance_path <Flask.instance_path>`, which is the99        path that Flask has chosen for the instance folder. You'll learn100        more about the database in the next section.101102#.  :meth:`app.config.from_pyfile() <Config.from_pyfile>` overrides103    the default configuration with values taken from the ``config.py``104    file in the instance folder if it exists. For example, when105    deploying, this can be used to set a real ``SECRET_KEY``.106107    *   ``test_config`` can also be passed to the factory, and will be108        used instead of the instance configuration. This is so the tests109        you'll write later in the tutorial can be configured110        independently of any development values you have configured.111112#.  :func:`os.makedirs` ensures that113    :attr:`app.instance_path <Flask.instance_path>` exists. Flask114    doesn't create the instance folder automatically, but it needs to be115    created because your project will create the SQLite database file116    there.117118#.  :meth:`@app.route() <Flask.route>` creates a simple route so you can119    see the application working before getting into the rest of the120    tutorial. It creates a connection between the URL ``/hello`` and a121    function that returns a response, the string ``'Hello, World!'`` in122    this case.123124125Run The Application126-------------------127128Now you can run your application using the ``flask`` command. From the129terminal, tell Flask where to find your application, then run it in130development mode. Remember, you should still be in the top-level131``flask-tutorial`` directory, not the ``flaskr`` package.132133Development mode shows an interactive debugger whenever a page raises an134exception, and restarts the server whenever you make changes to the135code. You can leave it running and just reload the browser page as you136follow the tutorial.137138.. tabs::139140   .. group-tab:: Bash141142      .. code-block:: text143144         $ export FLASK_APP=flaskr145         $ export FLASK_ENV=development146         $ flask run147148   .. group-tab:: CMD149150      .. code-block:: text151152         > set FLASK_APP=flaskr153         > set FLASK_ENV=development154         > flask run155156   .. group-tab:: Powershell157158      .. code-block:: text159160         > $env:FLASK_APP = "flaskr"161         > $env:FLASK_ENV = "development"162         > flask run163164You'll see output similar to this:165166.. code-block:: none167168     * Serving Flask app "flaskr"169     * Environment: development170     * Debug mode: on171     * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)172     * Restarting with stat173     * Debugger is active!174     * Debugger PIN: 855-212-761175176Visit http://127.0.0.1:5000/hello in a browser and you should see the177"Hello, World!" message. Congratulations, you're now running your Flask178web application!179180Continue to :doc:`database`.