简体   繁体   中英

Django transactions and concurrency

I have a view that needs to perform updates to the database involving a shared resource that needs locking (the implementation is complex, but nothing more than a shared counter at heart).

To shield myself from race conditions, I'm using code that looks roughly like this:

@transaction.commit_manually
def do_it(request):
    affected_models = Something.objects.select_for_update(blah = 1)

    for model in affected_models:
        model.modify()
        model.save()

    transaction.commit()

Is this usage of commit_manually , select_for_update() and save() ok? How can I write a test that confirms this? I can't find, say, a signal that Django fires between transactions; and I can't just run it and hope concurrency issues arise and are dealt with.

Why not to use commit_on_success there?

I think the query itself should look like:

Something.objects.select_for_update().filter(...)

I don't think django does anything special on select_for_update what you could assert on. Only assertion comes to my head is assertTrue(queryset.query.select_for_update) . It tests nothing and might be usefull only if somebody accidentaly(?) removes the call.

Even if you come up with some unit test for this run condition problem I don't think it would be wise to put that into the project.

Rather focus on testing your code, not the db behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM