Chapter 7. Large Application Structure

Although having small web applications stored in a single script can be very convenient, this approach does not scale well. As the application grows in complexity, working with a single large source file becomes problematic.

Unlike most other web frameworks, Flask does not impose a specific organization for large projects; the way to structure the application is left entirely to the developer. In this chapter, a possible way to organize a large application in packages and modules is presented. This structure will be used in the remaining examples of the book.

Project Structure

Example 7-1 shows the basic layout for a Flask application.

Example 7-1. Basic multiple-file Flask application structure
|-flasky
  |-app/
    |-templates/
    |-static/
    |-main/
      |-__init__.py
      |-errors.py
      |-forms.py
      |-views.py
    |-__init__.py
    |-email.py
    |-models.py
  |-migrations/
  |-tests/
    |-__init__.py
    |-test*.py
  |-venv/
  |-requirements.txt
  |-config.py
  |-manage.py

This structure has four top-level folders:

  • The Flask application lives inside a package generically named app.
  • The migrations folder contains the database migration scripts, as before.
  • Unit tests are written in a tests package.
  • The venv folder contains the Python virtual environment, as before.

There are also a few new files:

  • requirements.txt lists the package dependencies so that it is easy to regenerate an identical virtual environment on a different computer.
  • config.py stores the configuration settings.
  • manage.py launches ...

Get Flask Web Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.