Francis C
Francis C

Reputation: 281

Converting a flask app to an application factory pattern screws up all imports

So i've been building a flask app just using an app.py file and running it. It has quite a big app now and i'm now just trying to convert it into an application factory because I need to use SQLAlchemy in my Celery tasks.

here is my init.py in my app folder

def create_app():
    load_dotenv(".env")
    app = Flask(__name__)

    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///data.db"
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    app.config["PROPAGATE_EXCEPTIONS"] = True
    app.config["BROKER_URL"] = os.getenv("REDIS_BACKEND_BROKER")
    app.config["CELERY_BROKER_URL"] = os.getenv("REDIS_BACKEND_BROKER")
    app.config["CELERY_IMPORTS"] = "celery_tasks"
    app.secret_key = os.getenv("SECRET_KEY")

    CORS(app)
    api = Api(app)
    jwt = JWTManager(app)

    db.init_app(app)
    ma.init_app(app)
    celery.init_app(app)

    @app.before_first_request
    def create_tables():
        db.create_all()

    @jwt.invalid_token_loader
    def invalid_token_callback(self):
        return {"message": "invalid"}, 401

    with app.app_context():

        from .resources.auth import Auth, CheckUser
        from .resources.period import Period
        from .resources.project import Project
        from .resources.session import Session

        api.add_resource(Auth, "/auth")
        api.add_resource(CheckUser, "/check")
        api.add_resource(Project, "/createproject")
        api.add_resource(Period, "/createperiod")
        api.add_resource(Session, "/createsession")
        return app

The problem is that all the resources that being imported breaks because they can no longer import based on modules either.

For example resources.period also imports SQLAlchemy models and Masrhmallow schemas

resources/period.py

#THESE ARE NO LONGER IMPORTED SUCCESSFULLY

from models.project import ProjectModel
from schemas.task import TaskSchema
from schemas.period import PeriodSchema

Here is my file structure

Upvotes: 0

Views: 932

Answers (2)

Oin
Oin

Reputation: 7559

Since you're importing from resources/period.py using relative imports, you need to go up a level:

from ..models.project import ProjectModel
from ..schemas.task import TaskSchema
from ..schemas.period import PeriodSchema

Upvotes: 0

Futureflo
Futureflo

Reputation: 66

This is an awesome tutorial by Miguel Grinberg where he refactores a complete application like you want it, too:

https://www.youtube.com/watch?v=NH-8oLHUyDc&t=2934s

Did you try to make an "absolute" import like:

from app.models.project import ProjectModel

Upvotes: 2

Related Questions