Skip to content
Myr

packages.rst

This file

Path

docs/patterns/packages.rst

175 lines · 4.9 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

1Large Applications as Packages2==============================34Imagine a simple flask application structure that looks like this::56    /yourapplication7        yourapplication.py8        /static9            style.css10        /templates11            layout.html12            index.html13            login.html14            ...1516While this is fine for small applications, for larger applications17it's a good idea to use a package instead of a module.18The :doc:`/tutorial/index` is structured to use the package pattern,19see the :gh:`example code <examples/tutorial>`.2021Simple Packages22---------------2324To convert that into a larger one, just create a new folder25:file:`yourapplication` inside the existing one and move everything below it.26Then rename :file:`yourapplication.py` to :file:`__init__.py`.  (Make sure to delete27all ``.pyc`` files first, otherwise things would most likely break)2829You should then end up with something like that::3031    /yourapplication32        /yourapplication33            __init__.py34            /static35                style.css36            /templates37                layout.html38                index.html39                login.html40                ...4142But how do you run your application now?  The naive ``python43yourapplication/__init__.py`` will not work.  Let's just say that Python44does not want modules in packages to be the startup file.  But that is not45a big problem, just add a new file called :file:`setup.py` next to the inner46:file:`yourapplication` folder with the following contents::4748    from setuptools import setup4950    setup(51        name='yourapplication',52        packages=['yourapplication'],53        include_package_data=True,54        install_requires=[55            'flask',56        ],57    )5859In order to run the application you need to export an environment variable60that tells Flask where to find the application instance:6162.. tabs::6364   .. group-tab:: Bash6566      .. code-block:: text6768         $ export FLASK_APP=yourapplication6970   .. group-tab:: CMD7172      .. code-block:: text7374         > set FLASK_APP=yourapplication7576   .. group-tab:: Powershell7778      .. code-block:: text7980         > $env:FLASK_APP = "yourapplication"8182If you are outside of the project directory make sure to provide the exact83path to your application directory. Similarly you can turn on the84development features like this:8586.. tabs::8788   .. group-tab:: Bash8990      .. code-block:: text9192         $ export FLASK_ENV=development9394   .. group-tab:: CMD9596      .. code-block:: text9798         > set FLASK_ENV=development99100   .. group-tab:: Powershell101102      .. code-block:: text103104         > $env:FLASK_ENV = "development"105106In order to install and run the application you need to issue the following107commands::108109    $ pip install -e .110    $ flask run111112What did we gain from this?  Now we can restructure the application a bit113into multiple modules.  The only thing you have to remember is the114following quick checklist:1151161. the `Flask` application object creation has to be in the117   :file:`__init__.py` file.  That way each module can import it safely and the118   `__name__` variable will resolve to the correct package.1192. all the view functions (the ones with a :meth:`~flask.Flask.route`120   decorator on top) have to be imported in the :file:`__init__.py` file.121   Not the object itself, but the module it is in. Import the view module122   **after the application object is created**.123124Here's an example :file:`__init__.py`::125126    from flask import Flask127    app = Flask(__name__)128129    import yourapplication.views130131And this is what :file:`views.py` would look like::132133    from yourapplication import app134135    @app.route('/')136    def index():137        return 'Hello World!'138139You should then end up with something like that::140141    /yourapplication142        setup.py143        /yourapplication144            __init__.py145            views.py146            /static147                style.css148            /templates149                layout.html150                index.html151                login.html152                ...153154.. admonition:: Circular Imports155156   Every Python programmer hates them, and yet we just added some:157   circular imports (That's when two modules depend on each other.  In this158   case :file:`views.py` depends on :file:`__init__.py`).  Be advised that this is a159   bad idea in general but here it is actually fine.  The reason for this is160   that we are not actually using the views in :file:`__init__.py` and just161   ensuring the module is imported and we are doing that at the bottom of162   the file.163164   There are still some problems with that approach but if you want to use165   decorators there is no way around that.  Check out the166   :doc:`/becomingbig` section for some inspiration how to deal with that.167168169Working with Blueprints170-----------------------171172If you have larger applications it's recommended to divide them into173smaller groups where each group is implemented with the help of a174blueprint.  For a gentle introduction into this topic refer to the175:doc:`/blueprints` chapter of the documentation.