Flask Blueprints sharing

713 views Asked by At

I want to make an API with Flask and it also needs to have an admin panel. I guess that Blueprints are the way to go, but I don't want to make models twice.

My structure is going to be this:

- app - api - admin - models

So my question is: How can I access the models in the models folder in my api blueprint and my admin blueprint?

Thanks in advance.

2

There are 2 answers

2
abigperson On

if you'd in a module within the api or admin folders you can import anything from a module in the models folder using this notation

from ..models.module_name import model1, model2, etc

for small projects i usually keep all the models in a single models.py file like:

[app]
  [blueprint_1]
     __init__.py
     views.py
  [blueprint_2]
  [static]
  [templates]
  __init__.py
  models.py

then from within any of your blueprint files just:

from ..models import model1, model2, etc
0
metmirr On

About the import, If your directory include __init__.py then it is a python package so . use for current dir. For example:

auth/ 
     __init__.py 
     forms.py 
     views.py 
#views.py
from forms import Form name 
from . import auth_blueprint # imports from __init__.py 

So if you wants to import from another directory you have to use .. to imports from __init__.py file let's say your models directory include those files :

models/ 
    __init__.py 
    UserModel.py 

Now let's import models for auth module :

#auth/views.py 
from .. import models # import froms models/__init__.py 
from ..models import UserModel