如何继承所有Flask-SQLAlChemy模型的自定义构造函数

2022-03-10 00:00:00 python flask flask-sqlalchemy

问题描述

我的代码:

# db.py
class NewModel(Model):
    user = sa.Column(sa.String(256), nullable = False, default = 'User')
    uploaded = sa.Column(sa.DateTime, nullable = False, default = datetime.utcnow)

    def __init__(self, **kwargs):
        kwargs['user'] = session['username']

        super().__init__(**kwargs)

    def save(self):
        db.session.add(self)
        db.session.commit()

db = SQLAlchemy(model_class = NewModel)
# upload_file.py
class UploadFile(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    filename = db.Column(db.String(256), nullable = False)
    path = db.Column(db.String(256), nullable = False, unique = True)

    def __init__(self, file):
        self.file = file

        kwargs = {
            'filename': file.filename,
            'path': secure_filename(file.filename)
        }

        super().__init__(**kwargs)

    def valid(self):
        return self.file is not None and 
            self.file.filename.strip() != ''

当我尝试创建UploadFile的实例时,它可以工作,但它不调用NewModel的构造函数。为什么?

我找到this issue,但没有解决我的问题。
我试图使用orm.restructor装饰器,但也不起作用。


解决方案

问题中的方法不起作用,因为SQLAlChemy将自己的__init__方法修补到模型超类上。default implementation根据关键字参数分配实例属性值,这就是代码在未调用已定义的__init__方法的情况下仍然起作用的原因。

这可以通过declarative_base函数配置,但遗憾的是,Flask-SQLAlChemy不会直接公开这一点。

可以通过创建abstract模型类并从其继承应用程序的模型来获得所需的结果。

db = SQLAlchemy(app)


class NewModel(db.Model):

    __abstract__ = True

    user = sa.Column(sa.String(256), nullable=False, default="User")
    uploaded = sa.Column(sa.DateTime, nullable=False, default=datetime.utcnow)

    def __init__(self, **kwargs):
        kwargs["user"] = session["username"]
        super().__init__(**kwargs)

    def save(self):
        db.session.add(self)
        db.session.commit()


# upload_file.py
class UploadFile(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    filename = db.Column(db.String(256), nullable=False)
    path = db.Column(db.String(256), nullable=False, unique=True)

    def __init__(self, file):
        kwargs = {
            'filename': file.filename,
            'path': secure_filename(file.filename)
        }

        super().__init__(**kwargs)

要在模型超类(NewModel)上获得有效的__init__实现,我们需要创建一个自定义构造函数并使用它、Flask的DefaultMeta元类和NewModel类来创建可以传递给SQLAlchemy构造函数的新声明性基类。

import sqlalchemy as sa
from sqlalchemy import orm
from flask import Flask
from flask_sqlalchemy import SQLAlchemy, Model, DefaultMeta

class NewModel(Model):

    user = sa.Column(sa.String(256), nullable=False, default="User")
    uploaded = sa.Column(sa.DateTime, nullable=False, default=datetime.utcnow)

    def save(self):
        db.session.add(self)
        db.session.commit()

def my_declarative_constructor(self, **kwargs):
    """This will be the `__init__` method for all models."""
    # Set attrs from kwargs using SQLALchemy's default constructor function.
    orm.decl_api._declarative_constructor(self, **kwargs)
    # Do custom attribute assignments.
    self.user = session['username']

# Create a new declarative base class that combines our constructor function,
# Flask's default metaclass and our NewModel class.
Base = orm.declarative_base(
    constructor=my_declarative_constructor, metaclass=DefaultMeta, cls=NewModel
)

# Use our declarative base class to create the db integration.
db = SQLAlchemy(app, model_class=Base)


# upload_file.py
class UploadFile(db.Model):
    ...

相关文章