Вопрос

I'm creating a REST-like API to get data in and out of a legacy database. At the moment I don't have the option to alter the db structure. Nearly every table in the database has the exact same structure. Here's how I'm currently handling it using Flask-SQLAlchemy:

class MyDatasetBase(object):
    timestamp = db.Column('colname', db.Float, primary_key=True)
    val1 = db.Column(db.Float)
    val2 = db.Column(db.Float)
    val3 = db.Column(db.Float)
    fkeyid = db.Column(db.Integer)

    @declared_attr
    def foreigntable(self):
        return db.relationship('ForeignTableClass', uselist=False)

class Table1(MyDatasetBase, db.Model):
    __tablename__ = 'table1'

class Table2(MyDatasetBase, db.Model):
    __tablename__ = 'table2'

class ForeignTableClass(db.Model):
    __tablename__ = 'ForeignTable'
    id = db.Column(db.Integer, db.ForeignKey('table1.fkeyid'), db.ForeignKey('table2.fkeyid'), primary_key=True)
    name = db.Column(db.String)

This all works, but some of these datasets contain a lot of tables and I feel like there has to be a more efficient way to do a few of these things.

Is there a way to get around explicitly defining a class for each of the tables derived from MyDatasetBase? If there is, will that cause problems with the foreign key stuff, where in ForeignTableClass I have to define id as being a foreign key for every table listed above?

Это было полезно?

Решение

one way to do that is to use type method :

names = ['table1', 'table2', 'table3']

for name in names:
    type(name.title(), (MyDatasetBase, db.Model), { '__tablename__' : name })
# generate <class 'flask_sqlalchemy.Table1'> ... 

There is maybe a more pythonic/elegant way to do that with the Metedata and Table.tometadata() method.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top