On 02/10/2015 02:46 PM, Carl Meyer wrote:
> On 02/10/2015 01:27 PM, Erik Cederstrand wrote:
>>> Den 10/02/2015 kl. 18.34 skrev Carl Meyer <c...@oddbird.net
>>> <mailto:c...@oddbird.net>>:
>>>
>>> I assume you're using the 'db' cache backend? Otherwise, it wouldn't
>>> make sense to expect transactions to affect cache calls at all.
>>
>> Yes, I'm using the db backend.
>>
>>> The difference between the snippets is that you are doing a conditional
>>> branch based on the return value of the cache add, but your set_val
>>> helper method always returns None, it doesn't return the return value of
>>> cache.add().
>>
>> Wow, *that* was embarrassing :-) You see what you want to see, I guess...
>>
>> I'm still having issues with this, though. I reduced my own code to the
>> following. The intent of the code is to use the cache to implement
>> multiprocess/multiserver locking:
>>
>> from django.db import transaction
>> from django.core.cache import cache
>>
>> class CacheError(Exception):
>>     pass
>>
>> cache.delete('foo')
>> while True:
>>     print('Trying to cache foo')
>>     try:
>>         with transaction.atomic():
>>             if cache.get('foo'):
>>                 raise CacheError()
>>             print('adding foo to cache')
>>             assert cache.add(key='foo', value='bar')
>>             print('foo cached')
>>         time.sleep(random.random())
>>         with transaction.atomic():
>>             if cache.get('foo'):
>>                 cache.delete('foo')
>>     except CacheError:
>>         print('Failed to cache foo')
>>     time.sleep(random.random())

You might find it useful to look at the implementation of Django's
QuerySet.get_or_create() method, if you want to see how to (mostly)
safely implement a get-or-create pattern like this without race
conditions under READ COMMITTED isolation level.

Carl

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/54DA7D14.9030208%40oddbird.net.
For more options, visit https://groups.google.com/d/optout.

Attachment: signature.asc
Description: OpenPGP digital signature

Reply via email to