M
M
Michael2015-09-15 09:22:09
Django
Michael, 2015-09-15 09:22:09

How to make a piece of code atomic in django?

Hello,
I need to implement approximately the following algorithm:

def Counter(model):
    count = model.getCount()
    count = count + 1
    model.setCount(model)

There are no problems while I'm testing the code alone, but if a lot of people immediately connect to it, then the counter does not work. at one point in time, several clients can access this code and, accordingly, in model.getCount(), they will both receive the old value of the count parameter.
How can this section be protected from simultaneous access by 2 users. Thanks

Answer the question

In order to leave comments, you need to log in

5 answer(s)
I
IvanOne, 2015-09-15
@IvanOne

The situation is not clear to me personally, but you probably need to watch transactions. https://docs.djangoproject.com/en/1.8/topics/db/tr...

Z
zelsky, 2015-09-15
@zelsky

Pass a unique user id cookie, csrf or similar to the request

S
sim3x, 2015-09-15
@sim3x

It's better like this
redis.io/commands/incr
but it's also possible like this
www.postgresql.org/docs/9.1/static/datatype-numeri...
And in general, the problem cannot be solved if you do not specify restrictions, as long as the http response is being formed, value may have changed

O
Oleg, 2015-09-15
@Bahusss

The issue of simultaneous access to data most often does not have a general solution that is suitable for any case and each specific case must be considered separately.
For the above case of atomic writing to the database, an example has already been given to you. For another case, there will be some other solution. If we are talking about sharing data in a relational database, then you can try to put a different transaction isolation level , for example, at the Serializable level and using transactions - they will all be executed sequentially and, accordingly, there will be no problems with simultaneous access, but new ones will appear.

D
devel787, 2015-09-17
@devel787

Perhaps something will help habrahabr.ru/post/252563

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question