BVB Source Codes

rq Show local.py Source code

Return Download rq: download local.py Source code - Download rq Source code - Type:.py
  1. # -*- coding: utf-8 -*-
  2. # flake8: noqa
  3. """
  4.    werkzeug.local
  5.    ~~~~~~~~~~~~~~
  6.  
  7.    This module implements context-local objects.
  8.  
  9.    :copyright: (c) 2011 by the Werkzeug Team, see AUTHORS for more details.
  10.    :license: BSD, see LICENSE for more details.
  11. """
  12. # Since each thread has its own greenlet we can just use those as identifiers
  13. # for the context.  If greenlets are not available we fall back to the
  14. # current thread ident.
  15. try:
  16.     from greenlet import getcurrent as get_ident
  17. except ImportError:  # noqa
  18.     try:
  19.         from thread import get_ident  # noqa
  20.     except ImportError:  # noqa
  21.         try:
  22.             from _thread import get_ident  # noqa
  23.         except ImportError:  # noqa
  24.             from dummy_thread import get_ident  # noqa
  25.  
  26.  
  27. def release_local(local):
  28.     """Releases the contents of the local for the current context.
  29.    This makes it possible to use locals without a manager.
  30.  
  31.    Example::
  32.  
  33.        >>> loc = Local()
  34.        >>> loc.foo = 42
  35.        >>> release_local(loc)
  36.        >>> hasattr(loc, 'foo')
  37.        False
  38.  
  39.    With this function one can release :class:`Local` objects as well
  40.    as :class:`StackLocal` objects.  However it is not possible to
  41.    release data held by proxies that way, one always has to retain
  42.    a reference to the underlying local object in order to be able
  43.    to release it.
  44.  
  45.    .. versionadded:: 0.6.1
  46.    """
  47.     local.__release_local__()
  48.  
  49.  
  50. class Local(object):
  51.     __slots__ = ('__storage__', '__ident_func__')
  52.  
  53.     def __init__(self):
  54.         object.__setattr__(self, '__storage__', {})
  55.         object.__setattr__(self, '__ident_func__', get_ident)
  56.  
  57.     def __iter__(self):
  58.         return iter(self.__storage__.items())
  59.  
  60.     def __call__(self, proxy):
  61.         """Create a proxy for a name."""
  62.         return LocalProxy(self, proxy)
  63.  
  64.     def __release_local__(self):
  65.         self.__storage__.pop(self.__ident_func__(), None)
  66.  
  67.     def __getattr__(self, name):
  68.         try:
  69.             return self.__storage__[self.__ident_func__()][name]
  70.         except KeyError:
  71.             raise AttributeError(name)
  72.  
  73.     def __setattr__(self, name, value):
  74.         ident = self.__ident_func__()
  75.         storage = self.__storage__
  76.         try:
  77.             storage[ident][name] = value
  78.         except KeyError:
  79.             storage[ident] = {name: value}
  80.  
  81.     def __delattr__(self, name):
  82.         try:
  83.             del self.__storage__[self.__ident_func__()][name]
  84.         except KeyError:
  85.             raise AttributeError(name)
  86.  
  87.  
  88. class LocalStack(object):
  89.     """This class works similar to a :class:`Local` but keeps a stack
  90.    of objects instead.  This is best explained with an example::
  91.  
  92.        >>> ls = LocalStack()
  93.        >>> ls.push(42)
  94.        >>> ls.top
  95.        42
  96.        >>> ls.push(23)
  97.        >>> ls.top
  98.        23
  99.        >>> ls.pop()
  100.        23
  101.        >>> ls.top
  102.        42
  103.  
  104.    They can be force released by using a :class:`LocalManager` or with
  105.    the :func:`release_local` function but the correct way is to pop the
  106.    item from the stack after using.  When the stack is empty it will
  107.    no longer be bound to the current context (and as such released).
  108.  
  109.    By calling the stack without arguments it returns a proxy that resolves to
  110.    the topmost item on the stack.
  111.  
  112.    .. versionadded:: 0.6.1
  113.    """
  114.  
  115.     def __init__(self):
  116.         self._local = Local()
  117.  
  118.     def __release_local__(self):
  119.         self._local.__release_local__()
  120.  
  121.     def _get__ident_func__(self):
  122.         return self._local.__ident_func__
  123.  
  124.     def _set__ident_func__(self, value):  # noqa
  125.         object.__setattr__(self._local, '__ident_func__', value)
  126.     __ident_func__ = property(_get__ident_func__, _set__ident_func__)
  127.     del _get__ident_func__, _set__ident_func__
  128.  
  129.     def __call__(self):
  130.         def _lookup():
  131.             rv = self.top
  132.             if rv is None:
  133.                 raise RuntimeError('object unbound')
  134.             return rv
  135.         return LocalProxy(_lookup)
  136.  
  137.     def push(self, obj):
  138.         """Pushes a new item to the stack"""
  139.         rv = getattr(self._local, 'stack', None)
  140.         if rv is None:
  141.             self._local.stack = rv = []
  142.         rv.append(obj)
  143.         return rv
  144.  
  145.     def pop(self):
  146.         """Removes the topmost item from the stack, will return the
  147.        old value or `None` if the stack was already empty.
  148.        """
  149.         stack = getattr(self._local, 'stack', None)
  150.         if stack is None:
  151.             return None
  152.         elif len(stack) == 1:
  153.             release_local(self._local)
  154.             return stack[-1]
  155.         else:
  156.             return stack.pop()
  157.  
  158.     @property
  159.     def top(self):
  160.         """The topmost item on the stack.  If the stack is empty,
  161.        `None` is returned.
  162.        """
  163.         try:
  164.             return self._local.stack[-1]
  165.         except (AttributeError, IndexError):
  166.             return None
  167.  
  168.     def __len__(self):
  169.         stack = getattr(self._local, 'stack', None)
  170.         if stack is None:
  171.             return 0
  172.         return len(stack)
  173.  
  174.  
  175. class LocalManager(object):
  176.     """Local objects cannot manage themselves. For that you need a local
  177.    manager.  You can pass a local manager multiple locals or add them later
  178.    by appending them to `manager.locals`.  Everytime the manager cleans up
  179.    it, will clean up all the data left in the locals for this context.
  180.  
  181.    The `ident_func` parameter can be added to override the default ident
  182.    function for the wrapped locals.
  183.  
  184.    .. versionchanged:: 0.6.1
  185.       Instead of a manager the :func:`release_local` function can be used
  186.       as well.
  187.  
  188.    .. versionchanged:: 0.7
  189.       `ident_func` was added.
  190.    """
  191.  
  192.     def __init__(self, locals=None, ident_func=None):
  193.         if locals is None:
  194.             self.locals = []
  195.         elif isinstance(locals, Local):
  196.             self.locals = [locals]
  197.         else:
  198.             self.locals = list(locals)
  199.         if ident_func is not None:
  200.             self.ident_func = ident_func
  201.             for local in self.locals:
  202.                 object.__setattr__(local, '__ident_func__', ident_func)
  203.         else:
  204.             self.ident_func = get_ident
  205.  
  206.     def get_ident(self):
  207.         """Return the context identifier the local objects use internally for
  208.        this context.  You cannot override this method to change the behavior
  209.        but use it to link other context local objects (such as SQLAlchemy's
  210.        scoped sessions) to the Werkzeug locals.
  211.  
  212.        .. versionchanged:: 0.7
  213.           You can pass a different ident function to the local manager that
  214.           will then be propagated to all the locals passed to the
  215.           constructor.
  216.        """
  217.         return self.ident_func()
  218.  
  219.     def cleanup(self):
  220.         """Manually clean up the data in the locals for this context.  Call
  221.        this at the end of the request or use `make_middleware()`.
  222.        """
  223.         for local in self.locals:
  224.             release_local(local)
  225.  
  226.     def __repr__(self):
  227.         return '<%s storages: %d>' % (
  228.             self.__class__.__name__,
  229.             len(self.locals)
  230.         )
  231.  
  232.  
  233. class LocalProxy(object):
  234.     """Acts as a proxy for a werkzeug local.  Forwards all operations to
  235.    a proxied object.  The only operations not supported for forwarding
  236.    are right handed operands and any kind of assignment.
  237.  
  238.    Example usage::
  239.  
  240.        from werkzeug.local import Local
  241.        l = Local()
  242.  
  243.        # these are proxies
  244.        request = l('request')
  245.        user = l('user')
  246.  
  247.  
  248.        from werkzeug.local import LocalStack
  249.        _response_local = LocalStack()
  250.  
  251.        # this is a proxy
  252.        response = _response_local()
  253.  
  254.    Whenever something is bound to l.user / l.request the proxy objects
  255.    will forward all operations.  If no object is bound a :exc:`RuntimeError`
  256.    will be raised.
  257.  
  258.    To create proxies to :class:`Local` or :class:`LocalStack` objects,
  259.    call the object as shown above.  If you want to have a proxy to an
  260.    object looked up by a function, you can (as of Werkzeug 0.6.1) pass
  261.    a function to the :class:`LocalProxy` constructor::
  262.  
  263.        session = LocalProxy(lambda: get_current_request().session)
  264.  
  265.    .. versionchanged:: 0.6.1
  266.       The class can be instanciated with a callable as well now.
  267.    """
  268.     __slots__ = ('__local', '__dict__', '__name__')
  269.  
  270.     def __init__(self, local, name=None):
  271.         object.__setattr__(self, '_LocalProxy__local', local)
  272.         object.__setattr__(self, '__name__', name)
  273.  
  274.     def _get_current_object(self):
  275.         """Return the current object.  This is useful if you want the real
  276.        object behind the proxy at a time for performance reasons or because
  277.        you want to pass the object into a different context.
  278.        """
  279.         if not hasattr(self.__local, '__release_local__'):
  280.             return self.__local()
  281.         try:
  282.             return getattr(self.__local, self.__name__)
  283.         except AttributeError:
  284.             raise RuntimeError('no object bound to %s' % self.__name__)
  285.  
  286.     @property
  287.     def __dict__(self):
  288.         try:
  289.             return self._get_current_object().__dict__
  290.         except RuntimeError:
  291.             raise AttributeError('__dict__')
  292.  
  293.     def __repr__(self):
  294.         try:
  295.             obj = self._get_current_object()
  296.         except RuntimeError:
  297.             return '<%s unbound>' % self.__class__.__name__
  298.         return repr(obj)
  299.  
  300.     def __nonzero__(self):
  301.         try:
  302.             return bool(self._get_current_object())
  303.         except RuntimeError:
  304.             return False
  305.  
  306.     def __unicode__(self):
  307.         try:
  308.             return unicode(self._get_current_object())
  309.         except RuntimeError:
  310.             return repr(self)
  311.  
  312.     def __dir__(self):
  313.         try:
  314.             return dir(self._get_current_object())
  315.         except RuntimeError:
  316.             return []
  317.  
  318.     def __getattr__(self, name):
  319.         if name == '__members__':
  320.             return dir(self._get_current_object())
  321.         return getattr(self._get_current_object(), name)
  322.  
  323.     def __setitem__(self, key, value):
  324.         self._get_current_object()[key] = value
  325.  
  326.     def __delitem__(self, key):
  327.         del self._get_current_object()[key]
  328.  
  329.     def __setslice__(self, i, j, seq):
  330.         self._get_current_object()[i:j] = seq
  331.  
  332.     def __delslice__(self, i, j):
  333.         del self._get_current_object()[i:j]
  334.  
  335.     __setattr__ = lambda x, n, v: setattr(x._get_current_object(), n, v)
  336.     __delattr__ = lambda x, n: delattr(x._get_current_object(), n)
  337.     __str__ = lambda x: str(x._get_current_object())
  338.     __lt__ = lambda x, o: x._get_current_object() < o
  339.     __le__ = lambda x, o: x._get_current_object() <= o
  340.     __eq__ = lambda x, o: x._get_current_object() == o
  341.     __ne__ = lambda x, o: x._get_current_object() != o
  342.     __gt__ = lambda x, o: x._get_current_object() > o
  343.     __ge__ = lambda x, o: x._get_current_object() >= o
  344.     __cmp__ = lambda x, o: cmp(x._get_current_object(), o)
  345.     __hash__ = lambda x: hash(x._get_current_object())
  346.     __call__ = lambda x, *a, **kw: x._get_current_object()(*a, **kw)
  347.     __len__ = lambda x: len(x._get_current_object())
  348.     __getitem__ = lambda x, i: x._get_current_object()[i]
  349.     __iter__ = lambda x: iter(x._get_current_object())
  350.     __contains__ = lambda x, i: i in x._get_current_object()
  351.     __getslice__ = lambda x, i, j: x._get_current_object()[i:j]
  352.     __add__ = lambda x, o: x._get_current_object() + o
  353.     __sub__ = lambda x, o: x._get_current_object() - o
  354.     __mul__ = lambda x, o: x._get_current_object() * o
  355.     __floordiv__ = lambda x, o: x._get_current_object() // o
  356.     __mod__ = lambda x, o: x._get_current_object() % o
  357.     __divmod__ = lambda x, o: x._get_current_object().__divmod__(o)
  358.     __pow__ = lambda x, o: x._get_current_object() ** o
  359.     __lshift__ = lambda x, o: x._get_current_object() << o
  360.     __rshift__ = lambda x, o: x._get_current_object() >> o
  361.     __and__ = lambda x, o: x._get_current_object() & o
  362.     __xor__ = lambda x, o: x._get_current_object() ^ o
  363.     __or__ = lambda x, o: x._get_current_object() | o
  364.     __div__ = lambda x, o: x._get_current_object().__div__(o)
  365.     __truediv__ = lambda x, o: x._get_current_object().__truediv__(o)
  366.     __neg__ = lambda x: -(x._get_current_object())
  367.     __pos__ = lambda x: +(x._get_current_object())
  368.     __abs__ = lambda x: abs(x._get_current_object())
  369.     __invert__ = lambda x: ~(x._get_current_object())
  370.     __complex__ = lambda x: complex(x._get_current_object())
  371.     __int__ = lambda x: int(x._get_current_object())
  372.     __long__ = lambda x: long(x._get_current_object())
  373.     __float__ = lambda x: float(x._get_current_object())
  374.     __oct__ = lambda x: oct(x._get_current_object())
  375.     __hex__ = lambda x: hex(x._get_current_object())
  376.     __index__ = lambda x: x._get_current_object().__index__()
  377.     __coerce__ = lambda x, o: x._get_current_object().__coerce__(x, o)
  378.     __enter__ = lambda x: x._get_current_object().__enter__()
  379.     __exit__ = lambda x, *a, **kw: x._get_current_object().__exit__(*a, **kw)
  380.  
downloadlocal.py Source code - Download rq Source code
Related Source Codes/Software:
amazon-dsstne - Deep Scalable Sparse Tensor Network Engine (DSSTNE... 2017-01-08
webpack-demos - a collection of simple demos of Webpack 2017-01-08
Squire - HTML5 rich text editor. Try the demo integration a... 2017-01-08
thor - Thor is a toolkit for building powerful command-li... 2017-01-08
glide - Package Management for Golang h... 2017-01-08
emmet-vim - emmet for vim: http://emmet.io/ ... 2017-01-08
prose - A Content Editor for GitHub. ht... 2017-01-08
sshrc - ring your .bashrc, .vimrc, etc. with you when you ... 2017-01-08
typed.js - A jQuery typing animation script. ... 2017-01-08
find - High-precision indoor positioning framework for mo... 2017-01-08
profiling - An interactive continuous Python profiler. 2017-02-18
AQGridView - A grid view for iPhone/iPad, designed to look simi... 2017-02-18
SCLAlertView - Beautiful animated Alert View. Written in Objectiv... 2017-02-18
csvkit - A suite of utilities for converting to and working... 2017-02-18
Messenger - This is a native iOS Messenger app, making realtim... 2017-02-18
meteor-up - Production Quality Meteor Deployment 2017-02-18
book-of-modern-frontend-tooling - The Front-end Tooling Book 2017-02-17
sorcery - Magical authentication for Rails 3 & 4 2017-02-17
iScript - Xiami.com script--about shrimp, Baidu's Web site, ... 2017-02-17
AndroidViewHover - An elegant way to show your menu or messages. 2017-02-17

 Back to top