实例存储之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,可以做很多创新?

Original: https://blog.51cto.com/u_15698861/5554333
Author: wx62b90c63c9df5
Title: 实例存储之shelve

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/504377/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球