How to use decorators and functions with flag drawings

I have a pre-existing Flask application that is getting pretty big, so I decided to switch to using blueprints by following the Flask documentation to organize my views.

Most of my views separate functions and decorators. When all my views were in one file, they were easy to access. As all the views are now organized into separate files, I'm not sure where to find information like 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 can I find functions and decorators and how do I access them? Thank.

+3


source to share


1 answer


Any code common to two or more drawings can be placed in separate modules. For example, you can have decorators.py

and functions.py

, which can be located inside your directory views

:

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 items from them like this:

from .decorators import my_decorator

      

If other directories besides views

have other code that might need these shared elements (for example, the directory forms

for Flask-WTF forms, for example), you can place your shared 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 like this:

from ..decorators import my_decorator

      

or



from website.decorators import my_decorator

      

You can see an example of the above structure in the Flasky app that is featured in my Flask Design Book. I have decorators.py

, email.py

and exceptions.py

as common modules that can be accessed across all drawings.

If the number of shared modules is large, you can also move shared modules within your 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 import looks like this:

from ..common.decorators import my_decorator

      

or



from website.common.decorators import my_decorator

      

+4


source







All Articles