# -*- coding:utf-8 -*-frompymongoimportMongoClientfrombson.objectidimportObjectIdimportdatetimeclient=MongoClient()db=client.testclassModel(object):_model=''_fields=[]_base_fields=['created_date','updated_date']_required_fields=[]def__init__(self,**value):self.id=Noneall_fields=list(set(self.__class__._fields+self.__class__._base_fields))forattrinall_fields:ifvalue.get(attr,None)isNone:#auto fullfill value(s)default_val=Noneifattr=='created_date':default_val=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')ifattr=='updated_date':continuevalue.update({attr:default_val})ifnothasattr(self,attr):#add attributes to current objectsetattr(self,attr,value.get(attr))self.value=valuedefsave(self):assertself.__class__._model,'_model attribute of %s is null or empty'%(cls.__name__)assertself.__class__._modelindb.collection_names(),'collection %s does not exist!'%self.__class__._modelself.check_required_fields()model=getattr(db,self.__class__._model,None)self.__to_json()#update data from attrbitutes to self.valueifnotself.id:#newoid=model.insert(self.value)ifmodelelseNoneself.id=oid#str(oid) if oid else Noneelse:#updateself.value.update({'updated_date':datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')})model.update_one({"_id":self.id},{"$set":self.value,# "$currentDate": {"updated_date": True}})returnself.id#str(oid) if oid else None@classmethoddefget(cls,**where):assertcls._model,'_model attribute of %s is null or empty'%(cls.__name__)assertcls._modelindb.collection_names(),'collection %s does not exist!'%cls._modelmodel=getattr(db,cls._model,None)returnmodel.find_one(where)ifmodelelseNone@classmethoddefselect(cls,**where):assertcls._model,'_model attribute of %s is null or empty'%(cls.__name__)assertcls._modelindb.collection_names(),'collection %s does not exist!'%cls._modelmodel=getattr(db,cls._model,None)returnmodel.find(where)ifmodelelse[]@classmethoddefupdate(cls,new_value={},**where):assertcls._model,'_model attribute of %s is null or empty'%(cls.__name__)assertcls._modelindb.collection_names(),'collection %s does not exist!'%cls._modelmodel=getattr(db,cls._model,None)returnmodel.update_many(where,{"$set":new_value,})defcheck_required_fields(self):forcolinself.__class__._required_fields:assertgetattr(self,col,None)isnotNone,'field "%s" of model %s is required!'%(col,self.__class__._model)def__to_json(self):[self.value.update({attr:getattr(self,attr)})forattrindir(self)ifattrinself._fields]classUser(Model):_model='user'_fields=['name','age','sex']_required_fields=['sex']if__name__=='__main__':#u = User.get(_id=ObjectId("56d7bb80e5e7bd21663942e4"))#save testu=User(name='tommy',age=29)oid=u.save()#update test( update one)u.age=30#get testprintUser.get(_id=oid)#select testforuinUser.select():printu#update test (update many)printUser.update({'sex':'M'},name='tommy')