最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python 注解方式實(shí)現(xiàn)緩存數(shù)據(jù)詳解

 更新時(shí)間:2021年10月19日 14:35:22   作者:liuxing93619  
這篇文章主要介紹了Python 注解方式實(shí)現(xiàn)緩存數(shù),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

背景

每次加載數(shù)據(jù)都要重新Load,想通過(guò)加入的注解方式開(kāi)發(fā)緩存機(jī)制,每次緩存不用寫代碼了

缺點(diǎn):目前僅支持一個(gè)返回值,雖然能弄成字典,但是已經(jīng)滿足個(gè)人需求,沒(méi)動(dòng)力改(狗頭)。

拿來(lái)即用

新建文件 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~!'

實(shí)踐過(guò)程

第一次,來(lái)個(gè)簡(jiǎn)單的繼承父類

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類就可以啦,但是有很多局限,例如只能指定某個(gè)參數(shù)被cache,例如還得在Filter4Analyzer里面寫保存的代碼。

下一步,python嵌套裝飾器來(lái)改善這個(gè)問(wèn)題

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']

通過(guò)裝飾器類簡(jiǎn)化代碼

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 函數(shù)裝飾器

Python函數(shù)屬性和PyCodeObject

總結(jié)

本篇文章就到這里了,希望能夠給你帶來(lái)幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!

相關(guān)文章

  • Python 搭建Web站點(diǎn)之Web服務(wù)器網(wǎng)關(guān)接口

    Python 搭建Web站點(diǎn)之Web服務(wù)器網(wǎng)關(guān)接口

    本文是Python 搭建Web站點(diǎn)系列文章的第二篇,接上文,主要給大家來(lái)講述Web服務(wù)器網(wǎng)關(guān)接口WSGI的相關(guān)資料,非常詳細(xì),有需要的小伙伴可以參考下
    2016-11-11
  • Pandas提取含有指定字符串的行(完全匹配,部分匹配)

    Pandas提取含有指定字符串的行(完全匹配,部分匹配)

    本文主要介紹了Pandas提取含有指定字符串的行(完全匹配,部分匹配),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-02-02
  • 一篇文章詳解json中文編碼問(wèn)題

    一篇文章詳解json中文編碼問(wèn)題

    在使用Flask編寫后端接口時(shí),如果設(shè)置的接口返回格式是JSON,可能會(huì)遇到中文編碼問(wèn)題,這篇文章主要介紹了json中文編碼問(wèn)題的相關(guān)資料,需要的朋友可以參考下
    2025-03-03
  • python實(shí)現(xiàn)決策樹(shù)分類算法

    python實(shí)現(xiàn)決策樹(shù)分類算法

    這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)決策樹(shù)分類算法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-12-12
  • python,Django實(shí)現(xiàn)的淘寶客登錄功能示例

    python,Django實(shí)現(xiàn)的淘寶客登錄功能示例

    這篇文章主要介紹了python,Django實(shí)現(xiàn)的淘寶客登錄功能,結(jié)合實(shí)例形式分析了Django框架基于淘寶接口的登錄功能相關(guān)操作技巧,需要的朋友可以參考下
    2019-06-06
  • Python中flask框架跨域問(wèn)題的解決方法

    Python中flask框架跨域問(wèn)題的解決方法

    本文主要介紹了Python中flask框架跨域問(wèn)題的解決方法,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-08-08
  • Mac安裝python3的方法步驟

    Mac安裝python3的方法步驟

    這篇文章主要介紹了Mac安裝python3的方法步驟,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-08-08
  • python中Genarator函數(shù)用法分析

    python中Genarator函數(shù)用法分析

    這篇文章主要介紹了python中Genarator函數(shù)用法,實(shí)例分析了Genarator函數(shù)的使用原理與相關(guān)技巧,需要的朋友可以參考下
    2015-04-04
  • python Tornado事件循環(huán)示例源碼解析

    python Tornado事件循環(huán)示例源碼解析

    這篇文章主要為大家介紹了python Tornado事件循環(huán)示例源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-09-09
  • Python如何實(shí)現(xiàn)感知器的邏輯電路

    Python如何實(shí)現(xiàn)感知器的邏輯電路

    這篇文章主要介紹了Python如何實(shí)現(xiàn)感知器的邏輯電路,幫助大家更好的理解和使用python,感興趣的朋友可以了解下
    2020-12-12

最新評(píng)論

开封市| 赣州市| 明星| 紫阳县| 珲春市| 宁陕县| 兴仁县| 礼泉县| 建始县| 定州市| 天柱县| 四子王旗| 彭阳县| 上蔡县| 隆回县| 常山县| 长武县| 连云港市| 鹤岗市| 普宁市| 泗阳县| 浦城县| 策勒县| 舟山市| 竹山县| 安多县| 青冈县| 宜良县| 金沙县| 贺兰县| 南华县| 房产| 巴彦县| 文成县| 东阳市| 龙泉市| 怀来县| 东城区| 香格里拉县| 铜陵市| 江华|