实例存储之shelve

Posted wx62b90c63c9df5

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实例存储之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的主要内容,如果未能解决你的问题,请参考以下文章

shelve 之VS. pickle

day5模块学习--shelve模块

python内置模块(shelve)--035

python 模块之-shelve

Python3标准库:shelve对象的持久存储

python之shelve模块