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?).
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.
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.
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.
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) ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With