实例存储之shelve(存储器内部实现示例)

网友投稿 374 2022-08-23


实例存储之shelve(存储器内部实现示例)

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

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

installation

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

保存实例到文件

import shelvedb_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 shelvefrom shelve_test01 import Session, Hostdb_name = 'test.db's = shelve.open(db_name)host = s['host']host.perform()print(host.child.user)

user: rockpassword: 123456executing command: hello command 1executing command: hello command 2executing command: hello command 3executing command: hello command 4executing command: hello command 5executing command: hello command 6executing command: hello command 7executing command: hello command 8executing command: hello command 9executing command: hello command 10rock

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


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:【整理】最常见的10道Python面试题及答案!(python面试题选择题)
下一篇:都2022年了,Python Web框架你不会只知道Django和Flask吧?(都2022年了,还有人不知道蚝油要放冰箱?)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~