I set a database instance shared by many models:
Database.py:
from flask_sqlalchemy import SQLAlchemy
from models.shared import load_db
def init_db(app):
db = SQLAlchemy(app)
load_db(db)
from models.user import User
from models.another_model import AnotherModel
from ...
init_db
is called from create_app
in my main server.py
file.
Shared.py:
db = None
def load_db(_db):
db = _db
print(db)
User.py:
from .shared import db
print("User model defined.")
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(15), unique=True, nullable=False)
hash = db.Column(db.String(32), nullable=False)
email = db.Column(db.String(100), unique=True, nullable=False)
def __repr__(self):
return '<User %r>' % self.username
When init_db
is called from the create_app
method in my main file I get:
AttributeError: 'NoneType' object has no attribute 'Model'
Why am I getting this error? When importing the model modules from inside init_db
shouldn't their code run after I call load_db
? Looking at the order of the print statements db
is clearly set before any model uses it:
<SQLAlchemy engine=mysql://root:***@localhost/db_name?charset=utf8>
User model defined.