python - werkzeug(或celery)中关于Proxy的这段注释是什么意思?
PHPz
PHPz 2017-04-18 09:33:52
0
1
324

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提升性能的原理是什么?

望不吝赐教,谢谢!

PHPz
PHPz

学习是最好的投资!

모든 응답(1)
黄舟

여기서 질문을 이해하는 데 문제가 있을 수 있습니다. 저자는 성능 향상에 대해 이야기한 것이 아니라 성능 이유에 대해 이야기했습니다. Proxy은 스레드 격리 프록시이므로 Proxy을 사용할 때 애플리케이션은 current_app과 같은 해당 객체를 사용해야 하며 프록시 객체를 얻으려면 오버헤드가 필요합니다. 실제 객체를 얻기 위해 _get_current_object 메소드를 호출하면 이를 사용할 때 프록시 오버헤드가 발생하지 않습니다. . 이 경우에는 성능상의 이유로 _get_current_object이 호출된다고 할 수 있습니다.

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿