码迷,mamicode.com
首页 > 其他好文 > 详细

shelve模块

时间:2016-06-10 09:39:23      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

#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
‘‘‘

  

shelve模块

标签:

原文地址:http://www.cnblogs.com/similarface/p/5573195.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!