Django:每个请求单身? [英] Django: singleton per request?
问题描述
从应用程序.wrapper import ByDesign
bd = ByDesign()
不幸的是,这个实例化是在几个每个请求的点数,导致重新下载WSDL文件,我想我们可以通过使 bd = ByDesign()
返回单例来节省一些时间。
由于suds不是线程安全的,它必须是每个请求的单例。
唯一的catch是,我想为此,我不需要更改除 app.wrapper.ByDesign
类之外的任何代码,以便我不必更改任何调用它的代码。如果没有每个请求的单例要求,我会这样做:
class ByDesignRenamed(object) :
pass
_BD_INSTANCE =无
def ByDesign():
全局_BD_INSTANCE
如果不是_BD_INSTANCE:
_BD_INSTANCE = ByDesignRenamed()
return _BD_INSTANCE
但是,这在线程服务器环境中不起作用。任何想法对我来说
查看threading.local(),这是纯粹的邪恶与唯一的方法事情去了它应该是这样的:
导入线程
_local = threading.local()
def ByDesign():
如果'bd'不在_local中.__ dict__:
_local.bd = ByDesignRenamed()
return _local.bd
进一步阅读:
- <一个href =https://stackoverflow.com/questions/3227180/why-is-using-thread-locals-in-django-bad>为什么在Django中使用线程本地不好?
- 线程本地人在Python - 负面,关于可扩展性?
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?
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?
这篇关于Django:每个请求单身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!