Python 注解方式实现缓存数据详解
作者:liuxing93619 发布时间:2023-07-15 22:11:22
标签:Python,注解,实现,缓存
背景
每次加载数据都要重新Load,想通过加入的注解方式开发缓存机制,每次缓存不用写代码了
缺点:目前仅支持一个返回值,虽然能弄成字典,但是已经满足个人需求,没动力改(狗头)。
拿来即用
新建文件 Cache.py
class Cache:
def __init__(self, cache_path='.', nocache=False):
self.cache_path = cache_path
self.cache = not nocache
def __call__(self, func):
@wraps(func)
def wrapper(*args, **kwargs):
s = f'{func.__code__.co_filename}.{func.__name__}'
s += ','.join(list(args[1:]) + [f'{k}={v}' for k, v in kwargs.items()])
md5 = hashlib.md5()
md5.update(s.encode('utf-8'))
cache_file = f'{self.cache_path}/{md5.hexdigest()}'
if self.cache and os.path.exists(cache_file):
print('Loading from cache')
return pickle.load(open(cache_file, 'rb'))
else:
if not os.path.exists(self.cache_path):
os.makedirs(self.cache_path)
data = func(*args, **kwargs)
pickle.dump(data, file=open(cache_file, 'wb'))
print(f'Dump finished {cache_file}')
return data
return wrapper
from .Cache import Cache
@Cache(root_path, nocache=True)
def load_data(self, inpath):
return 'Wula~a~a~!'
实践过程
第一次,来个简单的继承父类
class Cache(object):
def __init__(self, cache_path=None):
self.cache_path = cache_path if cache_path else '.'
self.cache_path = f'{self.cache_path}/cache'
self.data = self.load_cache()
def load_cache(self):
if os.path.exists(self.cache_path):
print('Loading from cache')
return pickle.load(open(self.cache_path, 'rb'))
else:
return None
def save_cache(self):
pickle.dump(self.data, file=open(self.cache_path, 'wb'))
print(f'Dump finished {self.cache_path}')
class Filter4Analyzer(Cache):
def __init__(self, rootpath, datapath):
super().__init__(rootpath)
self.root_path = rootpath
if self.data is None:
self.data = self.load_data(datapath)
self.save_cache()
只要继承Cache类就可以啦,但是有很多局限,例如只能指定某个参数被cache,例如还得在Filter4Analyzer里面写保存的代码。
下一步,python嵌套装饰器来改善这个问题
from functools import wraps
import hashlib
def cached(cache_path):
def wrapperper(func):
@wraps(func)
def wrapper(*args, **kwargs):
s = f'{func.__code__.co_filename}.{func.__name__}' + ','.join(args[1:])
s += ','.join(list(args[1:]) + [f'{k}={v}' for k, v in kwargs.items()])
md5 = hashlib.md5()
md5.update(s.encode('utf-8'))
cache_file = f'{cache_path}/{md5.hexdigest()}' if cache_path else './cache'
if os.path.exists(cache_file):
print('Loading from cache')
return pickle.load(open(cache_file, 'rb'))
else:
if not os.path.exists(cache_path):
os.makedirs(cache_path)
data = func(*args, **kwargs)
pickle.dump(data, file=open(cache_file, 'wb'))
print(f'Dump finished {cache_file}')
return data
return wrapper
return wrapperper
class Tester:
@cached(cache_path='./workpath_test')
def test(self, data_path):
return ['hiahia']
通过装饰器类简化代码
class Cache:
def __init__(self, cache_path='.', nocache=False):
self.cache_path = cache_path
self.cache = not nocache
def __call__(self, func):
@wraps(func)
def wrapper(*args, **kwargs):
s = f'{func.__code__.co_filename}.{func.__name__}'
s += ','.join(list(args[1:]) + [f'{k}={v}' for k, v in kwargs.items()])
md5 = hashlib.md5()
md5.update(s.encode('utf-8'))
cache_file = f'{self.cache_path}/{md5.hexdigest()}'
if self.cache and os.path.exists(cache_file):
print('Loading from cache')
return pickle.load(open(cache_file, 'rb'))
else:
if not os.path.exists(self.cache_path):
os.makedirs(self.cache_path)
data = func(*args, **kwargs)
pickle.dump(data, file=open(cache_file, 'wb'))
print(f'Dump finished {cache_file}')
return data
return wrapper
参考:
Python 函数装饰器
Python函数属性和PyCodeObject
来源:https://blog.csdn.net/liuxing93619/article/details/120837018
0
投稿
猜你喜欢
- 《Patterns for Sign Up &Ramp Up》很早就读完了,之所以今天才写读后感,细细读完了发现,它更为接近吸引注册
- Sample:http://www.happyshow.org/sample/20060613/nav/nav.html<!DOCTY
- 第一种方法: 代码如下:/* 创建链接服务器 */ exec sp_addlinkedserver 'srv_lnk
- 1. 生命游戏是什么生命游戏是英国数学家约翰·何顿·康威在1970年发明的细胞自动机。它包括一个二维矩形世界,这个世界中的每个方格居住着一个
- 细线边框是网页中定位区分内容常用的一种方法,配合特定图片的使用,往往能够达到不错的效果,那么如何制作细线边框呢?asp之家注:现在要实现这个
- Access SQL 函数 收藏 ▲日期/时间CDate 将字符串转化成为日期 select CDate("2005/
- 学习目的: 掌握最基本的Label、TextBox、Button控件用法 掌握用StringBuider类连接字符串 理解服务器的环境变量
- 随着网页技术的发展,网络视觉设计与之前以程序员为主导的审美特征相比,具有了极大的改观。同时,随着美术、音乐、舞蹈人才的加入,网络开始在这一社
- 什么是CSS Sprites?“Sprite”(精灵)这个词在计算机图形学中有它独特的定义,由于游戏、视频等画质越来越高,必须有一种技术可以
- 首先建一个access 数据库,库中有一个URLINDEX表,其中URL和Keywords字段分别添加了索引,如下:URL &nb
- 本文实例为大家分享了python抖音表白神器,供大家参考,具体内容如下# -*- coding: utf-8 -*-import sysfr
- 聚集索引,数据实际上是按顺序存储的,数据页就在索引页上。就好像参考手册将所有主题按顺序编排一样。一旦找到了所要搜索的数据,就完成了这次搜索,
- 对于SQL的新手,NULL值的概念常常会造成混淆,他们常认为NULL是与空字符串''相同的事。情况并非如此。例如,下述语句是
- 自个儿闲的发疯画几个老鼠的表情,送女朋友。。HOHO。经常欺负人。哎。其实被欺负是一种幸福。工作以美国时间为主,所以白天睡到晚上。我不傻,真
- 利用XMLHTTP无刷新自动实时更新数据,2秒自动刷新一次,2秒取得一次数据.demo.htm 前台显示<script la
- 如何用Access加密页面?很简单哦,看看这个用用Access和ASP做的加密程序: <%userid =&nbs
- AJAX:Asynchronous JavaScript And XML--------异步JavaScript和XML
- 偶写的几个ASP字符串处理函数,用于文章分页的小玩意函数名:StrLen作 用:取得字符串长度(汉字为2)参 
- 问:如何在SQL Enterprise Manager version 6.5下操作SQL Server 6.0的服务器?答:在使用SQL
- 这两个字符串真实长度和取固定长度的字符串函数是在 photo.163.com 的js文件里看到的。 作者&nb