python - Django 原子增加初始值

标签 python django count memcached atomic

我正在尝试在 Django 缓存中进行原子增加或创建操作。我正在使用内存缓存作为后端。 Memcache 客户端的 incr_async() 函数采用 initial_value 参数。意思是:

If the key does not yet exist in the cache and you specify an initial_value, the key's value will be set to this initial value and then incremented.

但是,我不知道如何在 Django 中执行此操作,如 cache.incr() 文档所述:

A ValueError will be raised if you attempt to increment or decrement a nonexistent cache key.

当然可以:

cache.add(key,initial_value)
cache.incr(key)

但这不是原子的,可能会导致竞争条件。

有没有办法解决这个问题,从而保持操作的原子性?

最佳答案

据我所知,Django 的缓存 API 不支持这个。您必须下拉到内存缓存 API 并直接执行此操作:

from django.core.cache import cache

client = cache._client  # <--direct reference to memcached.Client object

关于python - Django 原子增加初始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8185648/

相关文章:

python - 应如何将指标添加到多头 TensorFlow 估计器中?

python - 模块未找到错误: No module named 'posts' in Django

django - 如何引入独特且有冲突的数据?

sql - 如何计算SQL中的唯一值对?

pandas - 组内的 Cumsum 并在 Pandas 条件下重置

python - 两个连续的 yield 语句如何在 python 中工作?

python - Aerospike Python 客户端中的段错误

django - 在非主键关系上加入和查询 Django 模型?

MongoDB - distinct and count,最简单的情况

python - 如何在Python中不将数据类成员实例化为类变量?