Skip to content
Myr

factory.rst

This file

Path

docs/tutorial/factory.rst

159 lines · 5.7 KiB

Last changed by

Abort if the instance folder cannot be created (#5903)David Lordbefore adoption4e652d3

History of this file

Take it

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

Add a devcontainer configuration (#4969)emisargentbefore adoption182ce3d

lines 1–58why, 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 exists

Abort if the instance folder cannot be created (#5903)David Lordbefore adoption4e652d3

line 59why, one step back
59 os.makedirs(app.instance_path, exist_ok=True)

Add a devcontainer configuration (#4969)emisargentbefore adoption182ce3d

lines 60–159why, one step back
60
61 # a simple page that says hello62 @app.route('/hello')63 def hello():64 return 'Hello, World!'6566 return app6768``create_app`` is the application factory function. You'll add to it69later in the tutorial, but it already does a lot.7071#. ``app = Flask(__name__, instance_relative_config=True)`` creates the72 :class:`Flask` instance.7374 * ``__name__`` is the name of the current Python module. The app75 needs to know where it's located to set up some paths, and76 ``__name__`` is a convenient way to tell it that.7778 * ``instance_relative_config=True`` tells the app that79 configuration files are relative to the80 :ref:`instance folder <instance-folders>`. The instance folder81 is located outside the ``flaskr`` package and can hold local82 data that shouldn't be committed to version control, such as83 configuration secrets and the database file.8485#. :meth:`app.config.from_mapping() <Config.from_mapping>` sets86 some default configuration that the app will use:8788 * :data:`SECRET_KEY` is used by Flask and extensions to keep data89 safe. It's set to ``'dev'`` to provide a convenient value90 during development, but it should be overridden with a random91 value when deploying.9293 * ``DATABASE`` is the path where the SQLite database file will be94 saved. It's under95 :attr:`app.instance_path <Flask.instance_path>`, which is the96 path that Flask has chosen for the instance folder. You'll learn97 more about the database in the next section.9899#. :meth:`app.config.from_pyfile() <Config.from_pyfile>` overrides100 the default configuration with values taken from the ``config.py``101 file in the instance folder if it exists. For example, when102 deploying, this can be used to set a real ``SECRET_KEY``.103104 * ``test_config`` can also be passed to the factory, and will be105 used instead of the instance configuration. This is so the tests106 you'll write later in the tutorial can be configured107 independently of any development values you have configured.108109#. :func:`os.makedirs` ensures that110 :attr:`app.instance_path <Flask.instance_path>` exists. Flask111 doesn't create the instance folder automatically, but it needs to be112 created because your project will create the SQLite database file113 there.114115#. :meth:`@app.route() <Flask.route>` creates a simple route so you can116 see the application working before getting into the rest of the117 tutorial. It creates a connection between the URL ``/hello`` and a118 function that returns a response, the string ``'Hello, World!'`` in119 this case.120121122Run The Application123-------------------124125Now you can run your application using the ``flask`` command. From the126terminal, tell Flask where to find your application, then run it in127debug mode. Remember, you should still be in the top-level128``flask-tutorial`` directory, not the ``flaskr`` package.129130Debug mode shows an interactive debugger whenever a page raises an131exception, and restarts the server whenever you make changes to the132code. You can leave it running and just reload the browser page as you133follow the tutorial.134135.. code-block:: text136137 $ flask --app flaskr run --debug138139You'll see output similar to this:140141.. code-block:: text142143 * Serving Flask app "flaskr"144 * Debug mode: on145 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)146 * Restarting with stat147 * Debugger is active!148 * Debugger PIN: nnn-nnn-nnn149150Visit http://127.0.0.1:5000/hello in a browser and you should see the151"Hello, World!" message. Congratulations, you're now running your Flask152web application!153154If another program is already using port 5000, you'll see155``OSError: [Errno 98]`` or ``OSError: [WinError 10013]`` when the156server tries to start. See :ref:`address-already-in-use` for how to157handle that.158159Continue to :doc:`database`.