packages.rst
This file
Path
docs/patterns/packages.rst
87 lines · 2.9 KiB
Last changed by
Breaking docs up into smaller piecesArmin Ronacherbefore adoption123a1ad
History of this fileTake it
1.. _larger-applications:23Larger Applications4===================56For larger applications it's a good idea to use a package instead of a7module. That is quite simple. Imagine a small application looks like8this::910 /yourapplication11 /yourapplication.py12 /static13 /style.css14 /templates15 layout.html16 index.html17 login.html18 ...1920To convert that into a larger one, just create a new folder21`yourapplication` inside the existing one and move everything below it.22Then rename `yourapplication.py` to `__init__.py`. (Make sure to delete23all `.pyc` files first, otherwise things would most likely break)2425You should then end up with something like that::2627 /yourapplication28 /yourapplication29 /__init__.py30 /static31 /style.css32 /templates33 layout.html34 index.html35 login.html36 ...3738But how do you run your application now? The naive ``python39yourapplication/__init__.py`` will not work. Let's just say that Python40does not want modules in packages to be the startup file. But that is not41a big problem, just add a new file called `runserver.py` next to the inner42`yourapplication` folder with the following contents::4344 from yourapplication import app45 app.run(debug=True)4647What did we gain from this? Now we can restructure the application a bit48into multiple modules. The only thing you have to remember is the49following quick checklist:50511. the `Flask` application object creation have to be in the52 `__init__.py` file. That way each module can import it safely and the53 `__name__` variable will resole to the correct package.542. all the view functions (the ones with a :meth:`~flask.Flask.route`55 decorator on top) have to be imported when in the `__init__.py` file.56 Not the objects itself, but the module it is in. Do the importing at57 the *bottom* of the file.5859Here an example `__init__.py`::6061 from flask import Flask62 app = Flask(__name__)6364 import yourapplication.views6566And this is what `views.py` would look like::6768 from yourapplication import app6970 @app.route('/')71 def index():72 return 'Hello World!'7374.. admonition:: Circular Imports7576 Every Python programmer hates them, and yet we just added some:77 circular imports (That's when two module depend on each one. In this78 case `views.py` depends on `__init__.py`). Be advised that this is a79 bad idea in general but here it is actually fine. The reason for this80 is81 that we are not actually using the views in `__init__.py` and just82 ensuring the module is imported and we are doing that at the bottom of83 the file.8485 There are still some problems with that approach but if you want to use86 decorators there is no way around that. Check out the87 :ref:`becomingbig` section for some inspiration how to deal with that.