且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

flask-cache记忆URL查询字符串参数

更新时间:2023-02-24 09:12:32

今天我遇到同样的问题,在互联网上没有找到任何例子,所以我玩了一下。

这是我的make_cache_key:

$ def $ make_cache_key(* args, ** kwargs):
path = request.path
args = str(hash(frozenset(request.args.items())))
lang = get_locale()
return (path + args + lang).encode('utf-8')

你可以使用request。网址而不是路径和散列参数。

缓存视图:

  @ app.route(/ test)
@ cache.cached(timeout = 50)
def test():$ b $ = request.args.get a')
b = request.args.get('b')
return a + b
test.make_cache_key = make_cache_key

它可以工作,但是我认为这很麻烦。事实证明,key_prefix可以是一个可生成整个cache_key的可调用对象。因此,我们可以做到这一点:$ b​​
$ pre code $ @ app.route(/ test2)
@ cache.cached(timeout = 50,key_prefix = make_cache_key)
def test2():
a = request.args.get('a')
b = request.args.get('b')
返回a + b

我只是想出了这个,还没有用于生产 - 所以它可能不适用于所有情况。

The flask-cache extension has a @cache.memoize decorator to cache a view including the view's *args and **kwargs. Some of my views however take a URL query string as well, for example /foo/image?width=640. The decorator adds a make_cache_key method to the decorated view function that can be used to customise the cache key

However I do not know how to get the request.args outside of the normal request context.

Any ideas how to make the @cache.memoize work with URL query strings as well?

I had the same problem today and didn't find any example on the internet so I played around a little.

This is my make_cache_key:

def make_cache_key(*args, **kwargs):
    path = request.path
    args = str(hash(frozenset(request.args.items())))
    lang = get_locale()
    return (path + args + lang).encode('utf-8')

You could use request.url instead of path and the hashed args. I needed to add the users language to the key as well.

Caching a view:

@app.route("/test")
@cache.cached(timeout=50)
def test():
    a = request.args.get('a')
    b = request.args.get('b')
    return a + b
test.make_cache_key = make_cache_key

It works but i think it's kind of cumbersome. It turned out, that the key_prefix can be a callable which generates the whole cache_key. Therefore we can do this:

@app.route("/test2")
@cache.cached(timeout=50, key_prefix=make_cache_key)
def test2():
    a = request.args.get('a')
    b = request.args.get('b')
    return a + b

I just came up with this and haven't used it in production yet – so it may not work in all cases.