Pav Sidhu
Pav Sidhu

Reputation: 6944

How to use decorators and functions with Flask blueprints

I have a pre-existing Flask application which is becoming quite large, so I've decided to switch to using blueprints, following the Flask documentation, to organise my views.

Most of my views share functions and decorators. When all my views were in one file, it was easy to access them. How now all the views are organised into separate files, I'm unsure where to locate information such as functions and views.

I have the following file structure:

run.py
website/
  __init__.py
  views/
    __init__.py
    admin.py
    home.py
    ...
  templates/
  static/

So, where do I locate functions and decorators and how do I access them? Thanks.

Upvotes: 3

Views: 1949

Answers (1)

Miguel Grinberg
Miguel Grinberg

Reputation: 67479

Any code that is shared by two or more blueprints can be put in separate modules. So for example, you can have decorators.py and functions.py, which can be located inside your views directory:

run.py
website/
  __init__.py
  views/
    __init__.py
    decorators.py   # <-- common code
    functions.py    # <-- common code
    admin.py
    home.py
    ...
  templates/
  static/

Then in your views you can import elements from these as follows:

from .decorators import my_decorator

If there's other code in other directories besides views that might need these common elements (such as a forms directory for Flask-WTF forms, for example), then you can put your common modules one level up in website.

run.py
website/
  __init__.py
  decorators.py   # <-- common code
  functions.py    # <-- common code
  views/
    __init__.py
    admin.py
    home.py
    ...
  templates/
  static/

And with this structure you can import from your views as follows:

from ..decorators import my_decorator

or:

from website.decorators import my_decorator

You can see an example of the above structure in the Flasky application that is featured in my Flask Web Development book. I have decorators.py, email.py and exceptions.py as common modules that can be accessed by all the blueprints.

If the number of common modules is large, you can also move the common modules inside their own package:

run.py
website/
  __init__.py
  common/
    __init__.py
    decorators.py
    functions.py
  views/
    __init__.py
    admin.py
    home.py
    ...
  templates/
  static/

And then the imports look like this:

from ..common.decorators import my_decorator

or:

from website.common.decorators import my_decorator

Upvotes: 4

Related Questions