Skip to content
Myr

factory.rst

This file

Path

docs/tutorial/factory.rst

193 lines · 6.4 KiB

Last changed by

Merge branch '2.0.x'David Lordbefore adoptione37e871

History of this file

Take it

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

parametrize some tests (#3786)Paul Sandersbefore adoption8c6baee

lines 1–137why, 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 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.137

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

line 138why, one step back
138.. tabs::

parametrize some tests (#3786)Paul Sandersbefore adoption8c6baee

line 139why, one step back
139

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

line 140why, one step back
140 .. group-tab:: Bash

parametrize some tests (#3786)Paul Sandersbefore adoption8c6baee

line 141why, one step back
141

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

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

parametrize some tests (#3786)Paul Sandersbefore adoption8c6baee

line 143why, one step back
143

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

lines 144–146why, one step back
144 $ export FLASK_APP=flaskr
145 $ export FLASK_ENV=development146 $ flask run

parametrize some tests (#3786)Paul Sandersbefore adoption8c6baee

line 147why, one step back
147

Merge branch '2.0.x'David Lordbefore adoptione37e871

lines 148–155why, one step back
148 .. group-tab:: Fish
149150 .. code-block:: text151152 $ set -x FLASK_APP flaskr153 $ set -x FLASK_ENV development154 $ flask run155

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

line 156why, one step back
156 .. group-tab:: CMD

parametrize some tests (#3786)Paul Sandersbefore adoption8c6baee

line 157why, one step back
157

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

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

parametrize some tests (#3786)Paul Sandersbefore adoption8c6baee

line 159why, one step back
159

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

lines 160–162why, one step back
160 > set FLASK_APP=flaskr
161 > set FLASK_ENV=development162 > flask run

parametrize some tests (#3786)Paul Sandersbefore adoption8c6baee

line 163why, one step back
163

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

line 164why, one step back
164 .. group-tab:: Powershell

parametrize some tests (#3786)Paul Sandersbefore adoption8c6baee

line 165why, one step back
165

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

lines 166–170why, one step back
166 .. code-block:: text
167168 > $env:FLASK_APP = "flaskr"169 > $env:FLASK_ENV = "development"170 > flask run

parametrize some tests (#3786)Paul Sandersbefore adoption8c6baee

lines 171–187why, one step back
171
172You'll see output similar to this:173174.. code-block:: none175176 * Serving Flask app "flaskr"177 * Environment: development178 * Debug mode: on179 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)180 * Restarting with stat181 * Debugger is active!182 * Debugger PIN: 855-212-761183184Visit http://127.0.0.1:5000/hello in a browser and you should see the185"Hello, World!" message. Congratulations, you're now running your Flask186web application!187

Merge branch '2.0.x'David Lordbefore adoptionedac7e3

lines 188–192why, one step back
188If another program is already using port 5000, you'll see
189``OSError: [Errno 98]`` or ``OSError: [WinError 10013]`` when the190server tries to start. See :ref:`address-already-in-use` for how to191handle that.192

parametrize some tests (#3786)Paul Sandersbefore adoption8c6baee

line 193why, one step back
193Continue to :doc:`database`.