V
V
Viktor Usachov2016-03-05 05:32:42
Flask
Viktor Usachov, 2016-03-05 05:32:42

How can a package inherit from db.Model defined in the application?

Hello, friends.
I describe the subject area in python, moved the classes of the main business objects into a separate package.
As an ORM - SQLAlchemy, classes should inherit from db.Model, but they should not know anything about a particular db instance. Add. the difficulty is that db.Model is an instance, not a class.
Question: how can the package inherit from db.Model if db is defined in the application?
The package must be independent of the application itself, but it is always assumed to inherit from some anydb.Model, where db is declared in a particular application. Below is an as-is example.
project/app/__init__.py:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()
# ...
def create_app(config_name):
    app = Flask(__name__)
    # ...
    db.init_app(app)
    return app

project/components/role/models.py:
from app import db

class Base(db.Model):
    """Basic class for all classes which to presents as database tables"""
    __abstract__ = True
    id = db.Column(db.Integer, primary_key=True)
    date_created = db.Column(db.DateTime, default=db.func.current_timestamp())
    date_modified = db.Column(db.DateTime, default=db.func.current_timestamp(),
                              onupdate=db.func.current_timestamp())
class Role(Base):
    __tablename__ = 'role'
    name = db.Column(db.String(64), unique=True, index=True)
    default = db.Column(db.Boolean, default=False, index=True)
    mask = db.Column(db.Integer, default=0)

and somewhere in the application code this class is used, for example:
user.role = Role.query.get(form.role.data)

Forgive me if I ask banal things, I have little experience.
Searched for a lot, probably thinking "not there."

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
n4nn31355, 2016-03-07
@victor_usachev

Can you explain an adequate reason why the database instance should be created in the application?
If work with models is carried out in a separate package, then it is quite logical to declare a database instance in the same place. So the integrity will not be broken if you decide, for example, to connect the package to an application that uses something other than Flask-SQLAlchemy as the main ORM. Those. it will not depend on the application itself:
project/app/__init__.py:

from flask import Flask
from components.role.models import db
# ...
def create_app(config_name):
    app = Flask(__name__)
    # ...
    db.init_app(app)
    return app

project/components/role/models.py:
from flask.ext.sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class Base(db.Model):
   pass

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question