factory.rst
This file
Path
docs/tutorial/factory.rst
162 lines · 5.8 KiB
Last changed by
new run debug docsDavid Lordbefore adoption74e5263
History of this fileTake it
The walk stopped after 200 commits: lines older than 41aaaf7 point at it.
clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7
lines 1–129why, one step back1.. 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 inMerge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
line 130why, one step back130debug mode. Remember, you should still be in the top-levelclean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7
lines 131–132why, one step back131``flask-tutorial`` directory, not the ``flaskr`` package.132Merge pull request #4720 from pallets/deprecate-envDavid Lordbefore adoption98ca00d
line 133why, one step back133Debug mode shows an interactive debugger whenever a page raises anclean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7
lines 134–137why, one step back134exception, 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.137Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727
line 138why, one step back138.. code-block:: textclean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7
line 139why, one step back139new run debug docsDavid Lordbefore adoption74e5263
line 140why, one step back140 $ flask --app flaskr run --debugclean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7
lines 141–143why, one step back141142You'll see output similar to this:143Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727
line 144why, one step back144.. code-block:: textclean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7
lines 145–150why, one step back145146 * Serving Flask app "flaskr"147 * Debug mode: on148 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)149 * Restarting with stat150 * Debugger is active!Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727
line 151why, one step back151 * Debugger PIN: nnn-nnn-nnnclean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7
lines 152–162why, one step back152153Visit http://127.0.0.1:5000/hello in a browser and you should see the154"Hello, World!" message. Congratulations, you're now running your Flask155web application!156157If another program is already using port 5000, you'll see158``OSError: [Errno 98]`` or ``OSError: [WinError 10013]`` when the159server tries to start. See :ref:`address-already-in-use` for how to160handle that.161162Continue to :doc:`database`.