peewee的简单封装,peewee简单封装,[Python]代码im
peewee的简单封装,peewee简单封装,[Python]代码im
[Python]代码
import peeweeimport sysclass Database(object): def __init__(self,kw): self.config = kw self.load_database(); self.Model = self.get_model_class() def load_database(self): try: self.db = self.config.pop('db') self.engine = self.config.pop('engine') except KeyError: raise Exception('Please specify a "db" and "engine" for your database') try: self.database_class = load_class(self.engine) assert issubclass(self.database_class, peewee.Database) except ImportError: raise Exception('Unable to import: "%s"' % self.engine) except AttributeError: raise Exception('Database engine not found: "%s"' % self.engine) except AssertionError: raise Exception('Database engine not a subclass of peewee.Database: "%s"' % self.engine) self.database = self.database_class(self.db, **self.config) def get_model_class(self): class BaseModel(peewee.Model): class Meta: database = self.database return BaseModel def connect(self): self.database.connect() def close(self): self.database.close()def load_class(s): path, klass = s.rsplit('.', 1) __import__(path) mod = sys.modules[path] return getattr(mod, klass)
简单的使用
db = Database({'db':'danteng', 'engine':'peewee.MySQLDatabase', 'user':'root', 'passwd':'root'})class User(db.Model): class Meta: db_table = 't_users' id = peewee.PrimaryKeyField() nickname = peewee.CharField() shorten = peewee.CharField() email = peewee.CharField()u=User(nickname='admin',shorten='admin',email='admin@gmail.com')u.save()print u.id
相关内容
- python 生成IP段,python生成ip,[Python]代码#!
- Python 扫描IP段 指定端口是否开放,pythonip,TCP21.py#!/u
- 使用python Tk的实现tablepanel+treeview,pythontablepanel,window
- python BeautifulSoup 抓取网页内指定内容,,# _*_ coding
- 获得本机硬件信息,获得机硬件信息,注意:这段代码需
- Python 对文件通配符匹配,python通配符匹配,有时候,我
- 爱的方程式(3D),方程式3d,from mpl_too
- python 实现简单的SYSLOG服务器,并写入MYSQL数据库,sys
- python正则替换html代码里的全部javascript,pythonjavascript
- python用线程封装的一个简单的定时器类,python定时器
评论关闭