Hi Erik,

On 02/10/2015 10:28 AM, Erik Cederstrand wrote:
> Hmm, I'm beginning to think I don't understand Django transactions. I
> have the following two snippets, boiled down from my original code. The
> first one calls cache methods via helper functions, the other one calls
> the cache methods directly. If I run the code in parallel in two
> different processes, then the first example asserts almost instantly,
> while the second example survives several minutes. Can someone explain this?

I assume you're using the 'db' cache backend? Otherwise, it wouldn't
make sense to expect transactions to affect cache calls at all.

> import random
> from django.db import transaction
> from django.core.cache import cache
> 
> def get_val(key):
>     cache.get(key)
> 
> def set_val(key, val):
>     cache.add(key, val)
> 
> def del_val(key):
>     cache.delete(key)
> 
> 
> # First example, fails
> while True:
>     with transaction.atomic():
>         if not get_val('foo'):
>             print('no key found')
>             time.sleep(random.random())
>             if set_val('foo', 'bar'):
>                 print('key added')
>                 time.sleep(random.random())
>             else:
>                 assert False
>             del_val('foo')
>             print('key deleted')
>     time.sleep(random.random())
> 
> 
> # Second example, runs correctly
> while True:
>     with transaction.atomic():
>         if not cache.get('foo'):
>             print('no key found')
>             time.sleep(random.random())
>             if cache.add('foo', 'bar'):
>                 print('key added')
>                 time.sleep(random.random())
>             else:
>                 assert False
>             cache.delete('foo')
>             print('key deleted')
>     time.sleep(random.random())

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().

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/54DA4136.8020105%40oddbird.net.
For more options, visit https://groups.google.com/d/optout.

Attachment: signature.asc
Description: OpenPGP digital signature

Reply via email to