问题
I am using cache.memoize
to memoize a function with Flask-Cache. How can I get the cache key which got set in the decorated function? How can I test that the function is cached during testing?
from flask import Flask
from flask.ext.cache import Cache
app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
@cache.memoize(timeout=10)
def get_news(nid, lang=None):
return nid, lang
@app.route('/news/<str:nid>')
def news(news_id):
return 'News: ' + get_news(news_id)
回答1:
When using memoize
, the cache key is generated behind the scenes and should never need to be accessed manually. Flask-Cache is handling caching and retrieving the result of the function for you. But if you're interested in how Flask-Cache does it, you can look at the source. It is a hash of the function name, arguments, and a uuid.
You shouldn't need to test cache hits, because Flask-Cache is already tested. You should test your own code, not library code. But if you're interested in how Flask-Cache does it, you can look at the tests. It memoizes a function that returns the current time, then checks if the return is the same after sleeping.
来源:https://stackoverflow.com/questions/37729077/testing-the-cache-hits-for-flask-cache