Jeeyoung Kim
Jeeyoung Kim

Reputation: 6098

Django and thread safety

If I read the django documentation, only the documents about the template tags mention the potential danger of thread safety.

However, I'm curious what kind of things I have to do / avoid to write thread-safe code in Django...

One example is, I have the following function to config the loggers used in django.

_LOGGER_CONFIGURED = False

def config_logger():
    global _LOGGER_CONFIGURED
    if _LOGGER_CONFIGURED: return
    _LOGGER_CONFIGURED = True

    rootlogger = logging.getLogger('')
    stderr_handler = StreamHandler(sys.stderr)
    rootlogger.addHandler(stderr_handler)

and at the end of my root urlconf, i have the following function call:

config_logger()

The question is:

  1. Is this code threadsafe?

  2. What kind of variables are shared between the django threads?

Upvotes: 3

Views: 3190

Answers (1)

SingleNegationElimination
SingleNegationElimination

Reputation: 156268

There's not really a whole lot you can do about django templates and their issues with threading, besides not using them, or at least not using the tags that are sensitive to threading issues. There aren't many django template tags that do have issues, only the stateful ones do, such as cycle.

In the example you have given, you are not doing anything about thread safety, and you shouldn't be anyway: the logging module is already perfectly thread safe, so long as you use it in the normal way, which is to call logging.getLogger in the modules that need it, and LOGGING or LOGGING_CONFIG is set appropriately in your settings.py. No need to be clever with this.

other things you might be concerned about are database integrity in the face of concurrent updates. Don't be, if you are using PostgreSQL or MySQL/INNOdb databases, then you are completely protected from concurrency shennanegans.

Upvotes: 1

Related Questions