ó
ú2ec           @   sÆ   d  Z  d d l Z d d l j j Z d d d d g Z d e f d „  ƒ  YZ d e f d	 „  ƒ  YZ d
 e f d „  ƒ  YZ	 d e f d „  ƒ  YZ
 d e f d „  ƒ  YZ e ƒ  Z d „  Z e
 j  e _  d S(   s  Registry for handling request-local module globals sanely

Dealing with module globals in a thread-safe way is good if your
application is the sole responder in a thread, however that approach fails
to properly account for various scenarios that occur with WSGI applications
and middleware.

What is actually needed in the case where a module global is desired that
is always set properly depending on the current request, is a stacked
thread-local object. Such an object is popped or pushed during the request
cycle so that it properly represents the object that should be active for
the current request.

To make it easy to deal with such variables, this module provides a special
StackedObjectProxy class which you can instantiate and attach to your
module where you'd like others to access it. The object you'd like this to
actually "be" during the request is then registered with the
RegistryManager middleware, which ensures that for the scope of the current
WSGI application everything will work properly.

Example:

.. code-block:: python

    #yourpackage/__init__.py

    from paste.registry import RegistryManager, StackedObjectProxy
    myglobal = StackedObjectProxy()

    #wsgi app stack
    app = RegistryManager(yourapp)

    #inside your wsgi app
    class yourapp(object):
        def __call__(self, environ, start_response):
            obj = someobject  # The request-local object you want to access
                              # via yourpackage.myglobal
            if environ.has_key('paste.registry'):
                environ['paste.registry'].register(myglobal, obj)

You will then be able to import yourpackage anywhere in your WSGI app or in
the calling stack below it and be assured that it is using the object you
registered with Registry.

RegistryManager can be in the WSGI stack multiple times, each time it
appears it registers a new request context.


Performance
===========

The overhead of the proxy object is very minimal, however if you are using
proxy objects extensively (Thousands of accesses per request or more), there
are some ways to avoid them. A proxy object runs approximately 3-20x slower
than direct access to the object, this is rarely your performance bottleneck
when developing web applications.

Should you be developing a system which may be accessing the proxy object
thousands of times per request, the performance of the proxy will start to
become more noticeable. In that circumstance, the problem can be avoided by
getting at the actual object via the proxy with the ``_current_obj`` function:

.. code-block:: python

    #sessions.py
    Session = StackedObjectProxy()
    # ... initialization code, etc.

    # somemodule.py
    import sessions

    def somefunc():
        session = sessions.Session._current_obj()
        # ... tons of session access

This way the proxy is used only once to retrieve the object for the current
context and the overhead is minimized while still making it easy to access
the underlying object. The ``_current_obj`` function is preceded by an
underscore to more likely avoid clashing with the contained object's
attributes.

**NOTE:** This is *highly* unlikely to be an issue in the vast majority of
cases, and requires incredibly large amounts of proxy object access before
one should consider the proxy object to be causing slow-downs. This section
is provided solely in the extremely rare case that it is an issue so that a
quick way to work around it is documented.

iÿÿÿÿNt   StackedObjectProxyt   RegistryManagert   StackedObjectRestorert   restorert	   NoDefaultc           B   s   e  Z RS(    (   t   __name__t
   __module__(    (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyR   b   s    c           B   s  e  Z d  Z e d d „ Z d „  Z d „  Z d „  Z d „  Z d „  Z	 d „  Z
 d	 „  Z d
 „  Z d „  Z d „  Z d „  Z d „  Z d „  Z d „  Z d „  Z d „  Z d d „ Z d „  Z d „  Z d e j e _ d „  Z d e j e _ d d „ Z d e j e _ RS(   s»  Track an object instance internally using a stack

    The StackedObjectProxy proxies access to an object internally using a
    stacked thread-local. This makes it safe for complex WSGI environments
    where access to the object may be desired in multiple places without
    having to pass the actual object around.

    New objects are added to the top of the stack with _push_object while
    objects can be removed with _pop_object.

    t   Defaultc         C   s@   | |  j  d <t j ƒ  |  j  d <| t k	 r< | |  j  d <n  d S(   s‘   Create a new StackedObjectProxy

        If a default is given, its used in every thread if no other object
        has been pushed on.

        t
   ____name__t   ____local__t   ____default_object__N(   t   __dict__t   threadinglocalt   localR   (   t   selft   defaultt   name(    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   __init__p   s    c         C   sa   t  |  j ƒ t |  j j ƒ  ƒ } y | j t  |  j ƒ  ƒ ƒ Wn t k
 rR n X| j ƒ  | S(   sf   Return a list of the StackedObjectProxy's and proxied
        object's (if one exists) names.
        (	   t   dirt	   __class__t   listR   t   keyst   extendt   _current_objt	   TypeErrort   sort(   R   t   dir_list(    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   __dir__|   s    "
c         C   s   t  |  j ƒ  | ƒ S(   N(   t   getattrR   (   R   t   attr(    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   __getattr__ˆ   s    c         C   s   t  |  j ƒ  | | ƒ d  S(   N(   t   setattrR   (   R   R   t   value(    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   __setattr__‹   s    c         C   s   t  |  j ƒ  | ƒ d  S(   N(   t   delattrR   (   R   R   (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   __delattr__Ž   s    c         C   s   |  j  ƒ  | S(   N(   R   (   R   t   key(    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   __getitem__‘   s    c         C   s   | |  j  ƒ  | <d  S(   N(   R   (   R   R$   R    (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   __setitem__”   s    c         C   s   |  j  ƒ  | =d  S(   N(   R   (   R   R$   (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   __delitem__—   s    c         O   s   |  j  ƒ  | | Ž  S(   N(   R   (   R   t   argst   kw(    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   __call__š   s    c         C   sR   y t  |  j ƒ  ƒ SWn7 t t f k
 rM d |  j j |  j j t |  ƒ f SXd  S(   Ns   <%s.%s object at 0x%x>(   t   reprR   R   t   AttributeErrorR   R   R   t   id(   R   (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   __repr__   s    	c         C   s   t  |  j ƒ  ƒ S(   N(   t   iterR   (   R   (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   __iter__¥   s    c         C   s   t  |  j ƒ  ƒ S(   N(   t   boolR   (   R   (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   __bool__¨   s    c         C   s   t  |  j ƒ  ƒ S(   N(   t   lenR   (   R   (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   __len__«   s    c         C   s   | |  j  ƒ  k S(   N(   R   (   R   R$   (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   __contains__®   s    c         C   s   t  |  j ƒ  ƒ S(   N(   R1   R   (   R   (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   __nonzero__±   s    c         C   st   y |  j  j } Wn t k
 r) d } n X| r8 | d S|  j j d t ƒ } | t k	 r] | St d |  j ƒ ‚ d S(   sÉ   Returns the current active object being proxied to

        In the event that no object was pushed, the default object if
        provided will be used. Otherwise, a TypeError will be raised.

        iÿÿÿÿR
   s8   No object (name: %s) has been registered for this threadN(	   R	   t   objectsR,   t   NoneR   t   getR   R   R   (   R   R7   t   obj(    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyR   ´   s    
c         C   sN   y |  j  j j | ƒ Wn0 t k
 rI g  |  j  _ |  j  j j | ƒ n Xd S(   sp  Make ``obj`` the active object for this thread-local.

        This should be used like:

        .. code-block:: python

            obj = yourobject()
            module.glob = StackedObjectProxy()
            module.glob._push_object(obj)
            try:
                ... do stuff ...
            finally:
                module.glob._pop_object(conf)

        N(   R	   R7   t   appendR,   (   R   R:   (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   _push_objectÊ   s
    c         C   se   yA |  j  j j ƒ  } | r@ | | k	 r@ t d | | f ƒ ‚ n  Wn t k
 r` t d ƒ ‚ n Xd S(   s¢   Remove a thread-local object.

        If ``obj`` is given, it is checked against the popped object and an
        error is emitted if they don't match.

        sB   The object popped (%s) is not the same as the object expected (%s)s-   No object has been registered for this threadN(   R	   R7   t   popt   AssertionErrorR,   (   R   R:   t   popped(    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   _pop_objectà   s    c         C   sG   y. y |  j  j } Wn t k
 r' g  SX| SWn t k
 rB g  SXd S(   sj   Returns all of the objects stacked in this container

        (Might return [] if there are none)
        N(   R	   R7   R,   R>   (   R   t   objs(    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   _object_stackð   s    	c         C   s,   t  j ƒ  } | r" t  j |  | ƒ S|  j ƒ  S(   N(   R   t   in_restorationt   get_saved_proxied_objt   _current_obj_orig(   R   t
   request_id(    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   _current_obj_restoration  s    s.   %s
(StackedObjectRestorer restoration enabled)c         C   s    t  j ƒ  s |  j | ƒ n  d  S(   N(   R   RC   t   _push_object_orig(   R   R:   (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   _push_object_restoration  s    c         C   s    t  j ƒ  s |  j | ƒ n  d  S(   N(   R   RC   t   _pop_object_orig(   R   R:   (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   _pop_object_restoration  s    N(   R   R   t   __doc__R   R   R   R   R!   R#   R%   R&   R'   R*   R.   R0   R2   R4   R5   R6   R   R<   R8   R@   RB   RG   RI   RK   (    (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyR    d   s:   																			t   Registryc           B   sA   e  Z d  Z d „  Z d „  Z d „  Z d „  Z e Z d „  Z RS(   sw  Track objects and stacked object proxies for removal

    The Registry object is instantiated a single time for the request no
    matter how many times the RegistryManager is used in a WSGI stack. Each
    RegistryManager must call ``prepare`` before continuing the call to
    start a new context for object registering.

    Each context is tracked with a dict inside a list. The last list
    element is the currently executing context. Each context dict is keyed
    by the id of the StackedObjectProxy instance being proxied, the value
    is a tuple of the StackedObjectProxy instance and the object being
    tracked.

    c         C   s   g  |  _  d S(   s•   Create a new Registry object

        ``prepare`` must still be called before this Registry object can be
        used to register objects.

        N(   t   reglist(   R   (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyR   (  s    c         C   s   |  j  j i  ƒ d S(   så   Used to create a new registry context

        Anytime a new RegistryManager is called, ``prepare`` needs to be
        called on the existing Registry object. This sets up a new context
        for registering objects.

        N(   RN   R;   (   R   (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   prepare1  s    c         C   se   |  j  d } t | ƒ } | | k rD | j | | d ƒ | | =n  | j | ƒ | | f | | <d S(   s,   Register an object with a StackedObjectProxyiÿÿÿÿi   N(   RN   R-   R@   R<   (   R   t   stackedR:   t	   myreglistt
   stacked_id(    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   register;  s    
c         C   s|   |  j  d } xh | D]` \ } } t | ƒ } | | k rW | j | | d ƒ | | =n  | j | ƒ | | f | | <q Wd S(   sç   Register a list of tuples

        Similar call semantics as register, except this registers
        multiple objects at once.

        Example::

            registry.multiregister([(sop, obj), (anothersop, anotherobj)])

        iÿÿÿÿi   N(   RN   R-   R@   R<   (   R   t	   stacklistRQ   RP   R:   RR   (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   multiregisterE  s    
c         C   sE   x1 t  j |  j d ƒ D] \ } } | j | ƒ q W|  j j ƒ  d S(   sk   Remove all objects from all StackedObjectProxy instances that
        were tracked at this Registry contextiÿÿÿÿN(   t   sixt
   itervaluesRN   R@   R=   (   R   RP   R:   (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   cleanup\  s    #(	   R   R   RL   R   RO   RS   RU   t   replaceRX   (    (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyRM     s   			
	
	c           B   s,   e  Z d  Z e d „ Z d „  Z d „  Z RS(   s7  Creates and maintains a Registry context

    RegistryManager creates a new registry context for the registration of
    StackedObjectProxy instances. Multiple RegistryManager's can be in a
    WSGI stack and will manage the context so that the StackedObjectProxies
    always proxy to the proper object.

    The object being registered can be any object sub-class, list, or dict.

    Registering objects is done inside a WSGI application under the
    RegistryManager instance, using the ``environ['paste.registry']``
    object which is a Registry instance.

    c         C   s   | |  _  | |  _ d  S(   N(   t   applicationt	   streaming(   R   RZ   R[   (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyR   r  s    	c         C   s  d  } | j d t ƒ  ƒ } | j ƒ  |  j rA |  j | | | ƒ Sy |  j | | ƒ } Wnµ t k
 rÜ } | j d ƒ rÌ t	 } x2 | j d g  ƒ D] } t
 | | ƒ r‘ t } q‘ q‘ W| sÌ t j | ƒ qÌ n  | j ƒ  ‚  n= | j d ƒ rþ t j | ƒ n  | j ƒ  ‚  n X| j ƒ  | S(   Ns   paste.registrys   paste.evalexceptions   paste.expected_exceptions(   R8   t
   setdefaultRM   RO   R[   t   streaming_iterRZ   t	   ExceptionR9   t   Falset
   isinstancet   TrueR   t   save_registry_stateRX   (   R   t   environt   start_responset   app_itert   regt   et   expectedt   expect(    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyR*   v  s0    
	


c         c   sì   y& x |  j  | | ƒ D] } | Vq WWnµ t k
 r« } | j d ƒ r› t } x2 | j d g  ƒ D] } t | | ƒ r` t } q` q` W| s› t j | ƒ q› n  | j ƒ  ‚  n= | j d ƒ rÍ t j | ƒ n  | j ƒ  ‚  n X| j ƒ  d  S(   Ns   paste.evalexceptions   paste.expected_exceptions(	   RZ   R^   R9   R_   R`   Ra   R   Rb   RX   (   R   Rf   Rc   Rd   t   itemRg   Rh   Ri   (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyR]   š  s&    

(   R   R   RL   R_   R   R*   R]   (    (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyR   c  s   	$c           B   sV   e  Z d  Z d „  Z d „  Z d „  Z d „  Z d „  Z d „  Z d „  Z	 d „  Z
 RS(	   s   Track StackedObjectProxies and their proxied objects for automatic
    restoration within EvalException's interactive debugger.

    An instance of this class tracks all StackedObjectProxy state in existence
    when unexpected exceptions are raised by WSGI applications housed by
    EvalException and RegistryManager. Like EvalException, this information is
    stored for the life of the process.

    When an unexpected exception occurs and EvalException is present in the
    WSGI stack, save_registry_state is intended to be called to store the
    Registry state and enable automatic restoration on all currently registered
    StackedObjectProxies.

    With restoration enabled, those StackedObjectProxies' _current_obj
    (overwritten by _current_obj_restoration) method's strategy is modified:
    it will return its appropriate proxied object from the restorer when
    a restoration context is active in the current thread.

    The StackedObjectProxies' _push/pop_object methods strategies are also
    changed: they no-op when a restoration context is active in the current
    thread (because the pushing/popping work is all handled by the
    Registry/restorer).

    The request's Registry objects' reglists are restored from the restorer
    when a restoration context begins, enabling the Registry methods to work
    while their changes are tracked by the restorer.

    The overhead of enabling restoration is negligible (another threadlocal
    access for the changed StackedObjectProxy methods) for normal use outside
    of a restoration context, but worth mentioning when combined with
    StackedObjectProxies normal overhead. Once enabled it does not turn off,
    however:

    o Enabling restoration only occurs after an unexpected exception is
    detected. The server is likely to be restarted shortly after the exception
    is raised to fix the cause

    o StackedObjectRestorer is only enabled when EvalException is enabled (not
    on a production server) and RegistryManager exists in the middleware
    stackc         C   s   i  |  _  t j ƒ  |  _ d  S(   N(   t   saved_registry_statesR   R   t   restoration_context_id(   R   (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyR   á  s    	c         C   s§   | j  d ƒ } | s> t | j ƒ s> |  j | ƒ |  j k rB d S| | j f |  j |  j | ƒ <x> | j D]3 } x* t j | ƒ D] \ } } |  j | ƒ q‚ Wql Wd S(   s§   Save the state of this request's Registry (if it hasn't already been
        saved) to the saved_registry_states dict, keyed by the request's unique
        identifiers   paste.registryN(   R9   R3   RN   t   get_request_idRk   RV   RW   t   enable_restoration(   R   Rc   t   registryRN   RP   R:   (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyRb   æ  s     c         C   s€   |  j  | d } t | ƒ d } t | ƒ } xD t rs | d k  rL | j ƒ  S| | } | | k rf Pn  | d 8} q0 W| | d S(   sv   Retrieve the saved object proxied by the specified
        StackedObjectProxy for the request identified by request_idi   i    (   Rk   R3   R-   Ra   RE   (   R   RP   RF   RN   t   stack_levelRR   t   context(    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyRD   û  s    	

c         C   sh   d | j  k r d SxN d D]F } t | | ƒ } t | | d ƒ } | | j  | d <| | j  | <q Wd S(	   s¹  Replace the specified StackedObjectProxy's methods with their
        respective restoration versions.

        _current_obj_restoration forces recovery of the saved proxied object
        when a restoration context is active in the current thread.

        _push/pop_object_restoration avoid pushing/popping data
        (pushing/popping is only done at the Registry level) when a restoration
        context is active in the current threadRE   NR   R<   R@   t   _restorationt   _orig(   R   R<   R@   (   R   R   (   R   RP   t	   func_namet	   orig_funct   restoration_func(    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyRn     s    
c         C   s   d d l  m } | | ƒ S(   s2   Return a unique identifier for the current requestiÿÿÿÿ(   t   get_debug_count(   t   paste.evalexception.middlewareRw   (   R   Rc   Rw   (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyRm   &  s    c         C   s>   | |  j  k r. |  j  | \ } } | | _ n  | |  j _ d S(   sW   Enable a restoration context in the current thread for the specified
        request_idN(   Rk   RN   Rl   RF   (   R   RF   Ro   RN   (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   restoration_begin+  s    c         C   s%   y |  j  ` Wn t k
 r  n Xd S(   s9   Register a restoration context as finished, if one existsN(   Rl   RF   R,   (   R   (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   restoration_end5  s    c         C   s   t  |  j d t ƒ S(   sŠ   Determine if a restoration context is active for the current thread.
        Returns the request_id it's active for if so, otherwise FalseRF   (   R   Rl   R_   (   R   (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyRC   <  s    (   R   R   RL   R   Rb   RD   Rn   Rm   Ry   Rz   RC   (    (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyR   ¸  s   (						
	c         C   s
   t  |  ƒ S(   N(   R   (   t   appt   global_conf(    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   make_registry_managerE  s    (   RL   RV   t   paste.util.threadinglocalt   utilR   t   __all__t   objectR   R    RM   R   R   R   R}   (    (    (    s8   /usr/local/lib/python2.7/dist-packages/paste/registry.pyt   <module>[   s   		µJU‰		