实例存储之shelve

对于传统的数据库,大家都很清楚是拿来存储数字,字符串,json等等, 但是有一点这一类的数据是静态的。如果想保存动态数据,比如对象的实例,有没有可能呢。答案是肯定的。

shelve模块就提供了这种可能性,它是基于pickle模块,是数据持久化的解决方案。

installation

shelve是python内置模块,无需额外安装。

保存实例到文件

import shelve

db_name = 'test.db'

class Session(object):
def __init__(self, user, password):
self.user = user
self.password = password

def run(self, command):
print('executing command: {}'.format(command))


class Host(object):
def __init__(self, user, password, times):
self.user = user
self.password = password
self.times = times

self.child = Session(user, password)

def perform(self):
print('user: {}'.format(self.user))
print('password: {}'.format(self.password))

for i in range(1, self.times+1):
self.child.run('hello command {}'.format(i))

s = shelve.open(db_name)
s['host'] = Host('rock', '123456', 10)
s.close()

从文件中读取实例

import shelve

from shelve_test01 import Session, Host

db_name = 'test.db'
s = shelve.open(db_name)

host = s['host']
host.perform()
print(host.child.user)
user: rock
password: 123456
executing command: hello command 1
executing command: hello command 2
executing command: hello command 3
executing command: hello command 4
executing command: hello command 5
executing command: hello command 6
executing command: hello command 7
executing command: hello command 8
executing command: hello command 9
executing command: hello command 10
rock

是不是觉得很惊艳,看看自己的项目,有没有觉得如果用上shelve,可以做很多创新?

文章来源于互联网:实例存储之shelve

THE END
分享
二维码