You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
48 lines
1.3 KiB
48 lines
1.3 KiB
11 years ago
|
# -*- coding: utf-8 -*-
|
||
|
'''Database module, including the SQLAlchemy database object and DB-related
|
||
|
mixins.
|
||
|
'''
|
||
|
|
||
11 years ago
|
from .extensions import db
|
||
11 years ago
|
|
||
11 years ago
|
class CRUDMixin(object):
|
||
11 years ago
|
"""Mixin that adds convenience methods for CRUD (create, read, update, delete)
|
||
|
operations.
|
||
|
"""
|
||
11 years ago
|
__table_args__ = {'extend_existing': True}
|
||
|
|
||
|
id = db.Column(db.Integer, primary_key=True)
|
||
|
|
||
|
@classmethod
|
||
|
def get_by_id(cls, id):
|
||
|
if any(
|
||
|
(isinstance(id, basestring) and id.isdigit(),
|
||
|
isinstance(id, (int, float))),
|
||
|
):
|
||
|
return cls.query.get(int(id))
|
||
|
return None
|
||
|
|
||
|
@classmethod
|
||
|
def create(cls, **kwargs):
|
||
11 years ago
|
'''Create a new record and save it the database.'''
|
||
11 years ago
|
instance = cls(**kwargs)
|
||
|
return instance.save()
|
||
|
|
||
|
def update(self, commit=True, **kwargs):
|
||
11 years ago
|
'''Update specific fields of a record.'''
|
||
11 years ago
|
for attr, value in kwargs.iteritems():
|
||
|
setattr(self, attr, value)
|
||
|
return commit and self.save() or self
|
||
|
|
||
|
def save(self, commit=True):
|
||
11 years ago
|
'''Save the record.'''
|
||
11 years ago
|
db.session.add(self)
|
||
|
if commit:
|
||
|
db.session.commit()
|
||
|
return self
|
||
|
|
||
|
def delete(self, commit=True):
|
||
11 years ago
|
'''Remove the record from the database.'''
|
||
11 years ago
|
db.session.delete(self)
|
||
|
return commit and db.session.commit()
|