flask-cache记忆URL查询字符串参数 [英] flask-cache memoize URL query string parameters as well

查看:117
本文介绍了flask-cache记忆URL查询字符串参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

flask-cache扩展有一个 @ cache.memoize 装饰器来缓存一个视图,包括视图的 * args ** kwargs 。然而,我的一些观点也使用URL查询字符串,例如 / foo / image?width = 640 。装饰器为装饰视图函数添加了一个 make_cache_key 方法,可以用来自定义缓存键



不知道如何在正常的请求上下文之外获取 request.args



任何想法如何使 @ cache.memoize 也可以使用URL查询字符串?

解决方案

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

这是我的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.

这篇关于flask-cache记忆URL查询字符串参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆