Skip to content

Instantly share code, notes, and snippets.

@britalmeida
Last active November 26, 2015 00:05
Show Gist options
  • Save britalmeida/e86b9fd50964dc4a9f09 to your computer and use it in GitHub Desktop.
Save britalmeida/e86b9fd50964dc4a9f09 to your computer and use it in GitHub Desktop.
flask-sqlalchemy: polymorphic and python mixin
class Asset(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(120), nullable=False)
asset_type_id = db.Column(db.Integer(), db.ForeignKey('asset_type.id'), nullable=False)
asset_type = db.relationship('AssetType', backref='assets')
# I would like a nicer way to do this
@property
def versions(self):
if self.asset_type.name=='video':
return self.asset_video_versions
elif self.asset_type.name=='image':
return self.asset_image_versions
else: # =='file'
return self.asset_file_versions
def __str__(self):
return self.name
class AssetType(db.Model):
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(120), nullable=False)
def __str__(self):
return self.name
class AssetVersionMixin(object):
@declared_attr
def __tablename__(cls):
return re.sub('(?!^)([A-Z]+)', r'_\1', cls.__name__).lower()
id = db.Column(db.Integer, primary_key=True)
filetype = db.Column(db.String(7), nullable=False)
size = db.Column(db.BigInteger)
@declared_attr
def asset_id(cls): return db.Column(db.Integer, db.ForeignKey('asset.id'))
# can this be just 'versions'?
@declared_attr
def asset(cls): return db.relationship(Asset, backref=cls.__tablename__+'_versions')
@property
def direct_link(self):
return self.asset.link +'.'+ self.filetype
@property
def serialize(self):
return {
'id':self.id,
'size':self.size,
'filetype':self.filetype,
'link':self.direct_link
}
def __str__(self):
return '%s %s' % (cls.__tablename__, self.id,)
class AssetFile(db.Model, AssetVersionMixin):
@property
def serialize(self):
return super(AssetFile, self).serialize
class AssetImage(db.Model, AssetVersionMixin):
res_x = db.Column(db.Integer)
res_y = db.Column(db.Integer)
@property
def serialize(self):
property_dict = super(AssetImage, self).serialize
property_dict.update({'res_x':self.res_x, 'res_y':self.res_y})
return property_dict
class AssetVideo(db.Model, AssetVersionMixin):
res_x = db.Column(db.Integer)
res_y = db.Column(db.Integer)
duration = db.Column(db.Integer)
format = db.Column(db.String(15))
@property
def serialize(self):
property_dict = super(AssetVideo, self).serialize
property_dict.update({'res_x':self.res_x, 'res_y':self.res_y, 'duration':self.duration, 'format':self.format})
return property_dict
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment