JasonTS
JasonTS

Reputation: 2589

Are django models thread safe?

I used to populate a database using a django based front end and then use the data in my daemon software accessing the mysql db directly.

Now I want to integrate the django models into the daemon software directly to make developement more easy.

So wrote this class:

class DjangoMysqlConnector:
  def __init__(self,SystemLogger=False):
    path_list = ["/home/user/django/bildverteiler_project/", "/home/user/git/apps/"]

    for path in path_list:
      if path not in sys.path:
        sys.path.append(path)

    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bildverteiler_project.settings")
    django.setup()

    from bildverteiler import models
    self.models = models

  def get_all_servers(self):
    return models.Server.objects.all()
  def get_all_verteilers(self):
    return models.Verteiler.objects.all()

Now I'm wondering: Is this thread safe?

Can I create one object from that class and pass it to multiple threads?

Will this stay true when I add functions that write to the db as well?

Upvotes: 1

Views: 2789

Answers (1)

Martol1ni
Martol1ni

Reputation: 4702

You need to elaborate a bit about what you mean with thread safe. If you're not planning on using a lock, then of course it's not thread safe. For instance,

s = SomeModel.objects.get(pk=1)
s.field = 2
s.save()

will obviously not be consistent if 3 threads are doing it at the same time. However, SomeModel.objects.filter(pk=1).update(field=2) is actually threadsafe. Use transaction.atomic() to maintain thread safety. Although, there could be a problem spawning alot of threads and connecting to the database at the same time, make sure you're allowed to open as many connections as planned.

An efficient way to do this would be to have one thread that's doing all the database interactions, while the other threads are doing calculations or whatever your plan is. Pass the objects on a Queue to synchronize.

Upvotes: 2

Related Questions