M
M
Michael2014-11-20 13:09:13
MongoDB
Michael, 2014-11-20 13:09:13

How to organize the application structure to avoid cyclical imports?

Hello, how do I organize my blueprint application to avoid circular imports?
For example, there is a file that contains the code

from flask import Flask
from flask_mail import Mail
from flask_mongoengine import MongoEngine
from core.flask_core.modules.admin.admin_bp import admin
from core.flask_core.modules.main.main_bp import main
from core.flask_core.modules.registration.registration_bp import registration
from core.flask_core.modules.news.news_bp import news
from core.flask_core.modules.test.test_bp import test
from core.flask_core.modules.login.login_bp import login
from core.flask_core.modules.ajax.ajax_bp import ajax



mail = Mail()
db = MongoEngine()



def add_blueprints(app):
    app.register_blueprint(admin, url_prefix='/admin')
    app.register_blueprint(main, url_prefix='/')
    app.register_blueprint(registration, url_prefix='/registration')
    app.register_blueprint(news, url_prefix='/news')
    app.register_blueprint(login, url_prefix='/login')
    app.register_blueprint(test, url_prefix='/test')
    app.register_blueprint(ajax, url_prefix='/ajax')



def create_app():
    app = Flask(__name__)
    mail.init_app(app)

    app.config.from_object('config')
    db.init_app(app)
    add_blueprints(app=app)
    return app


flask_app = create_app()


so, it imports blueprints, initializes mongo and flask mail, and creates an application, and now the question is, as soon as we are going to use mongo in one of the blueprints, we get a cyclic import, how to avoid this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
bromzh, 2014-11-20
@nextel

1) take out the creation of mongo and other modules in a separate file
2) import this file inside create_app and initialize it
3) import it in blueprints in the usual
way 4) create some kind of run.py in which you import create_app, create and run the application
5) ...
6) PROFIT

# app.py
def create_app():
    app = Flask(__name__)
    app.config.from_object('config')

    from mail import mail
    mail.init_app(app)
  
    from models import db
    db.init_app(app)
    add_blueprints(app=app)
    return app

# models.py
from flask.ext.mongoengine import MongoEngine
db = MongoEngine()

# mail.py
from flask.ext.mail import Mail
mail = Mail()

# run.py
from app import create_app
app = create_app()
if __name__ == '__main__':
    app.run()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question