python - Redis 获取和设置装饰器

标签 python caching redis decorator

目前正在研究 python 和 redis。我将 Flask 作为我的框架并处理蓝图。

考虑使用 redis 为我的 API 实现缓存,我尝试了 Flask-Cacheredis-simple-cache。 缺点是 Flask-Cache即使您更改函数的参数,也会保存函数。每个函数只保存一次。 根据 redis-simple-cache , 它将其 key 保存为 SimpleCache-<key name>这对我来说是不可取的。

所以我的问题是,您如何创建一个装饰器来保存和检索或检查是否存在特定键的键。 我知道保存装饰器是可能的。但是检索或检查装饰器可能吗?如果我错了,请纠正我。谢谢。

最佳答案

您似乎没有阅读 Flask-Cache documentation很接近的。缓存不会忽略参数并且缓存键是可定制的。项目提供的装饰器已经为您提供了您寻求的功能。

来自Caching View Functions section :

This decorator will use request.path by default for the cache_key.

所以默认缓存键是request.path,但您可以指定一个不同的键。由于 Flask view 函数从路径元素获取参数,因此默认的 request.path 是一个很好的键。

来自@cached() decorator documentation :

cached(timeout=None, key_prefix='view/%s', unless=None)

By default the cache key is view/request.path. You are able to use this decorator with any function by changing the key_prefix. If the token %s is located within the key_prefix then it will replace that with request.path. You are able to use this decorator with any function by changing the key_prefix.

key_prefix[...] Can optionally be a callable which takes no arguments but returns a string that will be used as the cache_key.

因此您可以将 key_prefix 设置为一个函数,它将被调用(不带参数)以生成 key 。

另外:

The returned decorated function now has three function attributes assigned to it. These attributes are readable/writable:

[...]

make_cache_key
A function used in generating the cache_key used.

此函数传递的参数与 View 函数传递的参数相同。总之,这允许您生成任何您想要的缓存键;使用 key_prefix 并从 requestg 或其他来源中提取更多信息,或者分配给 view_function.make_cache_key 并访问 View 函数接收的相同参数。

然后是@memoize() decorator :

memoize(timeout=None, make_name=None, unless=None)

Use this to cache the result of a function, taking its arguments into account in the cache key.

所以这个装饰器完全根据传递给函数的参数来缓存返回值。它也支持 make_cache_key 函数。

我已经使用这两个装饰器使一个 Google App Engine Flask 项目扩展到 CMS 支持的站点每月两位数的数百万次查看,并将结果存储在 Google memcached 结构中。使用 Redis 执行此操作只需要设置一个配置选项。

关于python - Redis 获取和设置装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39160075/

相关文章:

python - 根据另外两个字典替换一个字典值列表

java - Ignite for Hibernate L2 非常慢

PHP内置开发服务器: disable caching

ios - WKWebView 最大缓存对象大小

Redis 原子 GET 和 EXPIRE

ruby-on-rails - Redis 支持文件缓存吗?

go - 错误 - redigo.Scan : Cannot convert from Redis bulk string to *string

python - Tensorflow:可以释放 GPU 资源的模型包装器

python - 如何在 Robot Framework 中比较两个字符串是否相等

python - 如何使用python opencv从图像中删除隐藏标记?