Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I avoid circular imports in Flask and SQLAlchemy

app/init.py:

from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__ name __) db = SQLAlchemy(app)   from app import views, models 

app/models.py:

from app import db  # I want to avoid this everywhere 

I really don't like my submodules having a dependency on their parent. Also can the global package variables be avoided too? I want a more OO solution.

One alternative for app is to use Blueprints I think, but then I loose the route decorator. Also the same cannot be done for db with SQLAlchemy (or can it?).

like image 430
ovg Avatar asked Mar 20 '17 17:03

ovg


People also ask

How do you stop circular imports in Flask?

At the same time, there is a risk that cyclic imports will occur and it will be difficult to maintain a project. Flask documentation and basic tutorials suggest to write a project initialization code in __init__.py to solve the problem. This code creates Flask instance of a class and configures an app.

How do you avoid circular import errors?

Changing the name of the Working file different from the module which is imported in the script can avoid the Circular Imports problem. Import the module: Avoid importing objects or functions from a module that can cause Circular Imports. It is good to import the whole module to avoid the Circular Import.

Can I use SQLAlchemy in Flask?

Flask-SQLAlchemy is a Flask extension that makes using SQLAlchemy with Flask easier, providing you tools and methods to interact with your database in your Flask applications through SQLAlchemy. In this tutorial, you'll build a small student management system that demonstrates how to use the Flask-SQLAlchemy extension.


1 Answers

Take a look at this project: https://github.com/sloria/cookiecutter-flask
It's a great example for doing things the right way. Many of great Flask features are used: blueprints, application factories and more.

Here is how they register extensions, such as SQLAlchemy Database:

# app/extensions.py from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() ...   # app/app.py from app.extensions import db  def create_app(config_object=ProdConfig):     app = Flask(__name__.split('.')[0])     app.config.from_object(config_object)     register_extensions(app)     ...  def register_extensions(app):     db.init_app(app)     ... 
like image 65
leovp Avatar answered Sep 28 '22 07:09

leovp