我正在尝试在 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/