python - werkzeug(或celery)中关于Proxy的这段注释是什么意思?

 吴秋仪6_913 发布于 2022-11-01 17:27

celery的源码local.py中有这么一个类Proxy,作者说是Code stolen from werkzeug.local.Proxy.,我核对了一下,代码确实是一样的,其中有这么一个方法:

def _get_current_object(self):        
    """Return the current object.  This is useful if you want the real       
    object behind the proxy at a time for performance reasons or because     
    you want to pass the object into a different context."""                         
    loc = object.__getattribute__(self, '_Proxy__local')                             
    if not hasattr(loc, '__release_local__'):                                        
        return loc(*self.__args, **self.__kwargs)                                    
    try:  # pragma: no cover                                                         
        # not sure what this is about                                                
        return getattr(loc, self.__name__)                                           
    except AttributeError:  # pragma: no cover                                       
        raise RuntimeError('no object bound to {0.__name__}'.format(self))

注释说这个方法有助于性能提升,还可以在不同的context中的传递对象。

我想问一下,这个函数或者说用Proxy提升性能的原理是什么?

望不吝赐教,谢谢!

1 个回答
  • 这里题主的理解可能有点问题,作者并没有说提升性能,而是说性能原因,因为 Proxy 是线程隔离的代理,所以当你使用 Proxy 的时候,应用要使用对应的对象,例如 current_app 那么势必被代理一次,获取代理的对象是需要开销的,如果你调用这个方法:_get_current_object 获得真实的对象,那么使用的时候就不会有代理的开销了,这样的话可以说是为了性能原因去调用 _get_current_object

    2022-11-02 18:41 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有