一個基于Python裝飾器的緩存庫 wrapcache

jopen 8年前發布 | 12K 次閱讀 wrapcache Python開發

wrapcache

A python Function / Method OUTPUT cache system base on function Decorators.


Source code: https://github.com/hustcc/wrapcache

What's wrapcache?

wrapcache is a decorator that enables caching of return values for functions.

The cache keys are dependent completely on the arguments passed to the function. very simple to use.

Also has some API to Programmatic get cache or remove cache. Support python 2.6 ~ python3.5.

Here's an example of how you might use wrapcache:

import wrapcache

from time import sleep
import random

@wrapcache.wrapcache(timeout = 3)
def need_cache_function(input, t = 2, o = 3):
    sleep(2)
    return random.randint(1, 100)

if __name__ == "__main__":
    for i in range(10):
        sleep(1)
        print(need_cache_function(1, t = 2, o = 3))

    #get cache Programmatic
    key_func = wrapcache.keyof(need_cache_function, 1, o = 3, t = 2)
    print(wrapcache.get(key_func))
    #remove cache Programmatic
    print(wrapcache.remove(wrapcache.keyof(need_cache_function, 1, o = 3, t = 2)))

How to Install and Use?

Install

Three way to install:

1. Use tool install

  • easy_install wrapcache

or

  • pip install wrapcache / pip3 install wrapcache

2. Download to install

3. Manual installation

  • Manual installation: Put wrapcache folder into current directory or site-packages, then import wrapcache to use.

Usage

Decorators

import wrapcache
@wrapcache.wrapcache(timeout = 3)
def need_cache_function():
    return 'hello wrapcache'

API

  1. wrapcache.keyof(func, *args, **kws): get the key of function output cache.
  2. wrapcache.get(key, adapter = MemoryAdapter): get the value of cache.
  3. wrapcache.set(key, value, adapter = MemoryAdapter): set cache use code.
  4. wrapcache.remove(key, adapter = MemoryAdapter): remove a cache.
  5. wrapcache.flush(adapter = MemoryAdapter): clear all the cache.

The API 2~5, need to input a adapter to set which db to flush.

TODO

  • add redis and memcache supported.
  • package to pip server.

項目地址: https://github.com/hustcc/wrapcache

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!