Code

Opened 6 years ago

Closed 6 years ago

#6950 closed (fixed)

django.template.loader is not thread-safe

Reported by: bear330 Owned by: nobody
Component: Template system Version: master
Severity: Keywords: template thread
Cc: Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:

Description

In multithreaded environment, the django.template.loader is not thread-safe.

If browser sends many requests to django, sometimes it will raise TemplateDoesNotExist exception even the template actually existed.

This exception only raises in first requests, after that, everything will be fine.

This is because the django.template.loader use the global variable 'template_source_loaders'.

If many threads try to load template simultaneously, 'template_source_loaders' will not be initialized correctly.

I made a simple patch for that to fix this bug.

Thanks.

Attachments (3)

loader.patch (595 bytes) - added by bear330 6 years ago.
A simple patch to make sure template_source_loaders is initialized correctly.
threadsafe_template_loader.diff (1.1 KB) - added by mrts 6 years ago.
threadsafe_template_loader-const-correct.diff (1.0 KB) - added by mrts 6 years ago.
minor stylistic improvements (tuple instead of list for const-correctness)

Download all attachments as: .zip

Change History (6)

Changed 6 years ago by bear330

A simple patch to make sure template_source_loaders is initialized correctly.

comment:1 Changed 6 years ago by mrts

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

An improved patch based on the findings of threading review. Initializes a temporary list instead of modifying the global list and assigns the temporary list in one "atomic" operation to the global list.

More to come to other parts of the template system.

Changed 6 years ago by mrts

Changed 6 years ago by mrts

minor stylistic improvements (tuple instead of list for const-correctness)

comment:2 Changed 6 years ago by mrts

  • Triage Stage changed from Unreviewed to Ready for checkin

Marking as ready for checkin -- the last patch directly mimics source:django/trunk/django/template/context.py@7415#L86 , so it is the already prevalent way of doing things.

comment:3 Changed 6 years ago by russellm

  • Resolution set to fixed
  • Status changed from new to closed

(In [7563]) Fixed #6950 -- Modified initialization of template loaders to use a temporary variable instead of directly modifying the global loader list. Thanks, mrts.

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.