Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

concurrency - What is the simplest way to lock an object in Django

I want to raise error when a user tries to delete an object when some other users are active in update_object view. I feel some sort of mutex-like locking mechanism is needed for that. Do you have any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

select_for_update is the simplest way to acquire a lock on an object, provided your database supports it. PostgreSQL, Oracle, and MySQL, at least, support it, according to the Django docs.

Example code:

import time

from django.contrib.auth import get_user_model
from django.db import transaction


User = get_user_model()


@transaction.atomic
def my_example_function():
    my_user = User.objects.all()[0]

    print("Acquiring lock...")
    locked_user = User.objects.select_for_update().get(pk=my_user.pk)
    print(locked_user)

    while True:
        print("sleeping {}".format(time.time()))
        print("holding lock on {}".format(locked_user))
        time.sleep(5)

Note that you have to use select_for_update within a transaction, hence the @transaction.atomic decorator.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...