简体   繁体   中英

Testing the cache hits for Flask-Cache

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM