Testing the cache hits for Flask-Cache

房东的猫 提交于 2020-06-23 15:58:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!