Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: singleton per request?

Tags:

django

We have a wrapper around a suds (SOAP) request, that we use like this throughout our app:

from app.wrapper import ByDesign
bd = ByDesign()

Unfortunately, this instantiation is made at several points per request, causing suds to redownload the WSDL file, and I think we could save some time by making bd = ByDesign() return a singleton.

Since suds is not threadsafe, it'd have to be a singleton per request.

The only catch is, I'd like to make it so I don't have to change any code other than the app.wrapper.ByDesign class, so that I don't have to change any code that calls it. If there wasn't the 'singleton per request' requirement, I'd do something like this:

class ByDesignRenamed(object):
    pass

_BD_INSTANCE = None
def ByDesign():
    global _BD_INSTANCE
    if not _BD_INSTANCE:
       _BD_INSTANCE = ByDesignRenamed()
    return _BD_INSTANCE

But, this won't work in a threaded server environment. Any ideas for me?

like image 505
synic Avatar asked Jun 04 '11 01:06

synic


1 Answers

Check out threading.local(), which is somewhere between pure evil and the only way to get things going. It should probably be something like this:

import threading

_local = threading.local()

def ByDesign():
    if 'bd' not in _local.__dict__:
       _local.bd = ByDesignRenamed()
    return _local.bd

Further reading:

  • Why is using thread locals in Django bad?
  • Thread locals in Python - negatives, with regards to scalability?
like image 185
Udi Avatar answered Oct 24 '22 23:10

Udi