Skip to content
Myr

factory.rst

This file

Path

docs/tutorial/factory.rst

178 lines · 6.0 KiB

Last changed by

Merge branch '1.0-maintenance'David Lordbefore adoptionac6746d

History of this file

Take it

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

Merge pull request #2994 from jarek/werkzeug-640-exceptions-during-bindDavid Lordbefore adoptionca23b7b

lines 1–129why, one step back
1.. currentmodule:: flask
23Application 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 in

Merge branch '1.0-maintenance'David Lordbefore adoptionac6746d

lines 130–131why, one step back
130development mode. Remember, you should still be in the top-level
131``flask-tutorial`` directory, not the ``flaskr`` package.

Merge pull request #2994 from jarek/werkzeug-640-exceptions-during-bindDavid Lordbefore adoptionca23b7b

lines 132–178why, one step back
132
133Development 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.137138For Linux and Mac:139140.. code-block:: none141142 $ export FLASK_APP=flaskr143 $ export FLASK_ENV=development144 $ flask run145146For Windows cmd, use ``set`` instead of ``export``:147148.. code-block:: none149150 > set FLASK_APP=flaskr151 > set FLASK_ENV=development152 > flask run153154For Windows PowerShell, use ``$env:`` instead of ``export``:155156.. code-block:: none157158 > $env:FLASK_APP = "flaskr"159 > $env:FLASK_ENV = "development"160 > flask run161162You'll see output similar to this:163164.. code-block:: none165166 * Serving Flask app "flaskr"167 * Environment: development168 * Debug mode: on169 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)170 * Restarting with stat171 * Debugger is active!172 * Debugger PIN: 855-212-761173174Visit http://127.0.0.1:5000/hello in a browser and you should see the175"Hello, World!" message. Congratulations, you're now running your Flask176web application!177178Continue to :doc:`database`.