Last active
August 29, 2015 14:23
-
-
Save kaka19ace/b7d79df4711b8b54fb63 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# | |
# @file base.py | |
# @author kaka_ace <[email protected]> | |
# @date Jun 13 2015 | |
# @breif | |
# | |
import flask_sqlalchemy | |
from flask_sqlalchemy import ( | |
SQLAlchemy, | |
_BoundDeclarativeMeta, | |
) | |
class ModelMeta(_BoundDeclarativeMeta): | |
pass | |
flask_sqlalchemy._BoundDeclarativeMeta = ModelMeta | |
db = SQLAlchemy() | |
class BaseModel(db.Model): | |
__abstract__ = True | |
_column_name_sets = NotImplemented | |
def get_py_dict(self): | |
""" | |
""" | |
return dict((column_name, getattr(self, column_name, None)) for column_name in self._column_name_sets) | |
@classmethod | |
def get_column_name_sets(cls): | |
""" | |
""" | |
return cls.__column_name_sets | |
__str__ = lambda self: str(self.get_py_dict()) | |
__repr__ = lambda self: repr(self.get_py_dict()) | |
def modelmeta__new__(cls, name, bases, namespace, **kwds): | |
column_name_sets = set() | |
for k, v in namespace.items(): | |
if getattr(v, '__class__', None) is None: | |
continue | |
if v.__class__.__name__ == 'Column': | |
column_name_sets.add(k) | |
obj = type.__new__(cls, name, bases, dict(namespace)) | |
obj._column_name_sets = column_name_sets | |
return obj | |
# modify BaseModel' metatype ModelMeta' __new__ definition | |
setattr(ModelMeta, '__new__', modelmeta__new__) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment