Django:每个请求单身? [英] Django: singleton per request?

查看:125
本文介绍了Django:每个请求单身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在我们的应用程序中使用像SOAP(SOAP)请求一样的包装:

 从应用程序.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

进一步阅读:




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:

这篇关于Django:每个请求单身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆