views:

29

answers:

1

In my django app, I have one AJAX view that gets flooded with calls to an update method, which I'll call IncrementMagicNumber:

def IncrementMagicNumber(request) :
   number = request.GET['increment']
   request.session['magicnumber'] = request.session['magicnumber'] + int(number)
   return HttpResponse("OK!")

This works fine for one update at a time, but when a client is calling SetMagicNumber several times in a row, things get messy. Let's say magicnumber is initially 0. The client sends out 3 successive AJAX requests to IncrementMagicNumber:

IncrementMagicNumber(2)
IncrementMagicNumber(5)
IncrementMagicNumber(4)

The client expects the value to be 11 now, but apache is processing all these requests concurrently, so only the final update gets retained. Any tips/tricks for synchronizing a Django session?

Things I'd like to avoid if at all possible:
- Client side batching (I realize this would fix it, but this is a backend problem and is best fixed there)
- Some sort of database locking; I'd rather avoid this approach if possible.

A: 

we do something like this and use database row locking. why do you want to avoid that? I'd say some kind of locking mechanism was required here.

jambox
I should have clarified. I didn't want to do table-level locking. Row level locking would be fine. Could you share any details about your implementation?
J.Courtney
ah right, i haven't done this in django, but i have done it in an old ISAM we have at work, so the code for that wouldn't help you much! Googling "django row locking" throws up quite a few snippets, have you run into problems with standard approaches? Main consider
jambox
Oops! cat on keyboard. Main consideration is whether your IncrementMagicNumber is meaningful, or just an arbitrary number, like a serial ID. if the latter, you could always create a new table with one row and column, just to hold that number. or you could look into transactions, but that isn't a panacea AFAIK. also this: http://stackoverflow.com/questions/1030270/race-conditions-in-django
jambox
My only concern is that the sessions seem quite magical, and I'm not sure whether it's saving to the database or to memory each time. Either way, it seems like I'll need to get under the covers of django to find out what's going on. Thanks for the help :)
J.Courtney
Yeah the snippets I found dealt with side-stepping the ORM cache.
jambox