1
我試圖用memcached從aiohttp緩存一個函數。緩存我想做一個裝飾器。 調用裝飾的一個例子是這樣的:Aiohttp-Asyncio緩存功能
@cache("main_page", expire=25)
@asyncio.coroutine
def page(request):
return aiohttp_jinja2.render_template('index', request, {})
功能裝飾與緩存交易看起來是這樣的:
def cache_key(name, kwargs):
key = b'\xff'.join(bytes(k, 'utf-8') + b'\xff' + pickle.dumps(v) for k, v in kwargs.items())
key = bytes(hashlib.sha1(key).hexdigest(), 'ascii')
return key
def cache(name, expire=0):
def decorator(func):
@asyncio.coroutine
def wrapper(request=None, **kwargs):
assert isinstance(request, (aiohttp.web_reqrep.Request, type(None))), type(request)
args = [r for r in [request] if isinstance(r, aiohttp.web_reqrep.Request)]
assert isinstance(mc, aiomcache.Client)
key = cache_key(name, kwargs)
value = yield from mc.get(key)
if value is None:
value = yield from func(*args, **kwargs)
yield from mc.set(key, pickle.dumps(value, protocol=pickle.HIGHEST_PROTOCOL), exptime=expire)
else:
value = pickle.loads(value)
print(value)
return value
return wrapper
return decorator
但我在控制檯中看到的錯誤:
File "/usr/local/lib/python3.4/dist-packages/aiohttp_debugtoolbar/panels/headers.py", line 25, in process_response
sorted(response.headers.items())]
File "aiohttp/_multidict.pyx", line 464, in aiohttp._multidict._ItemsView.__iter__ (aiohttp/_multidict.c:8990)
TypeError: 'NoneType' object is not iterable
據我瞭解的問題:
如何序列化/反序列化響應,如果可能,並且如果不可能, 緩存結果該怎麼做 - 有一些解決方法?