Circular import

1

A doc of Flask, although it uses in its examples, it alerts to the bottom of the page about the bad practice of using circular imports. Another thing that bothers me is to create "global objects" within a __init__.py file.

What would be the other solution?

File __init__.py of the main module, ie the main application folder:

from flask import Flask
app = Flask(__name__)

import yourapplication.views

The views.py file (The application view):

from yourapplication import app

@app.route('/')
def index():
    return 'Hello World!'

The structure of the project:

/yourapplication
    setup.py
    /yourapplication
        __init__.py
        views.py
        /static
            style.css
        /templates
            layout.html
            index.html
            login.html
            ...

Sample Code Credits: link

    
asked by anonymous 03.07.2018 / 17:27

1 answer

1

Well, the flask is meant to be completely modularized and free so that you feel comfortable setting the best structure. One of the good practices of the framework is to work with the so-called "Application factory" ( link ).

When you create an "app factory", you do not need to have global objects, and the entire setup process and initialization takes place within the function of the app factory. For example:

def create_app(test_config=None):

    # cria e configura a aplicacao
    app = Flask(__name__, instance_relative_config=True)

    app.config.from_object(DevelopmentConfig)

    from .blueprint_um import views
    app.register_blueprint(views.bp)

    db.init_app(app)
    CORS(app)

    return app

In this example I create a factory with the function create_app and I make all my necessary initializations, including the registration of my blueprints, which is very important. This function can be within __init__.py that is inside the main application package of your project. This is an important practice for you to be able to import your app-building function smoothly. For example, when using waitress to run your application, just run      waitress-serve --call --listen=0.0.0.0:5000 app:create_app so that waitress understands that within its app package there is a create_app function that can be called.

Anyway, there are many different ways to do this and that's why the flask is so cool. Be sure to check out the different documentation and implementations so you know the possibilities (I'm learning a lot about flask too). I have a small project available there in gitlab, if you want you can take a look and even improve something (there is a lot to improve) link

    
04.10.2018 / 23:46