#coding:utf-8 __author__ = 'similarface' #email:similarface@outlook.com ''' shelve模块: 映射容器 存储对象,被存储的对象都会被序列化并且被写入文件 反序列化然后从文件获取任意对象 method:shelve.open() 'r' Open existing database for reading only (default) 'w' Open existing database for reading and writing 'c' Open database for reading and writing, creating it if it doesn’t exist 'n' Always create a new, empty database, open for reading and writing ''' import shelve import logging logging.basicConfig(level=logging.DEBUG) console = logging.StreamHandler() logging.getLogger('').addHandler(console) class Person: ''' 定义个简单的类 ''' def __init__(self,name,*posts): self.name=name def as_dict(self): return dict(name=self.name,underline="="*len(self.name),) p1=Person(name='Tom') #创建shelf对象 shelf=shelve.open('person') #设置键 p1._id='person:1' #存储 shelf[p1._id]=p1 #获取 p=shelf[p1._id] logging.info(p) logging.info(p.name) logging.info(p._id) logging.info(list(shelf.keys())) shelf.close() #获取存储对象 shelf=shelve.open('person') #获取指定的对象 根据类和属性来获取 results=(shelf[k] for k in shelf.keys() if k.startswith('person:') and shelf[k].name=='Tom' ) #logging.info(list(results)) for i in results: r0=i logging.info(r0._id) logging.info(r0.name) ''' INFO:root:<__main__.Person instance at 0x00000000026DBAC8> <__main__.Person instance at 0x00000000026DBAC8> INFO:root:Tom Tom INFO:root:person:1 person:1 INFO:root:['person:1'] ['person:1'] INFO:root:person:1 person:1 INFO:root:Tom Tom ''' ''' 存在继承的对象的持久化 使用外键引用对象 ''' import datetime class Teacher: def __init__(self,profession,name,desc,tags): self.profession=profession self.name=name self.desc=desc self.tags=tags def as_dict(self): return dict( profession=self.profession, name=self.name, underline="-"*len(self.name), desc=self.desc, tags=" ".join(self.tags) ) t1=Teacher('math','Lucy','beauifu teacher',['senior']) t2=Teacher('english','Tom','Stronger',['lower']) import shelve shelf=shelve.open('person') owner=shelf['person:1'] t1._parent=owner._id t1._id=t1._parent+':teacher:1' shelf[t1._id]=t1 t2._parent=owner._id t2._id=t2._parent+':teachar:2' shelf[t2._id]=t2 logging.info(list(shelf.keys())) logging.info(t1._parent) logging.info(t2._id) ''' INFO:root:['person:1:teachar:2', 'person:1', 'person:1:teacher:1'] ['person:1:teachar:2', 'person:1', 'person:1:teacher:1'] INFO:root:person:1 person:1 INFO:root:person:1:teachar:2 person:1:teachar:2 '''