local.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. # -*- coding: utf-8 -*-
  2. """
  3. werkzeug.local
  4. ~~~~~~~~~~~~~~
  5. This module implements context-local objects.
  6. :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. from functools import update_wrapper
  10. from werkzeug.wsgi import ClosingIterator
  11. from werkzeug._compat import PY2, implements_bool
  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 depending on where it is.
  15. try:
  16. from greenlet import getcurrent as get_ident
  17. except ImportError:
  18. try:
  19. from thread import get_ident
  20. except ImportError:
  21. from _thread import get_ident
  22. def release_local(local):
  23. """Releases the contents of the local for the current context.
  24. This makes it possible to use locals without a manager.
  25. Example::
  26. >>> loc = Local()
  27. >>> loc.foo = 42
  28. >>> release_local(loc)
  29. >>> hasattr(loc, 'foo')
  30. False
  31. With this function one can release :class:`Local` objects as well
  32. as :class:`LocalStack` objects. However it is not possible to
  33. release data held by proxies that way, one always has to retain
  34. a reference to the underlying local object in order to be able
  35. to release it.
  36. .. versionadded:: 0.6.1
  37. """
  38. local.__release_local__()
  39. class Local(object):
  40. __slots__ = ('__storage__', '__ident_func__')
  41. def __init__(self):
  42. object.__setattr__(self, '__storage__', {})
  43. object.__setattr__(self, '__ident_func__', get_ident)
  44. def __iter__(self):
  45. return iter(self.__storage__.items())
  46. def __call__(self, proxy):
  47. """Create a proxy for a name."""
  48. return LocalProxy(self, proxy)
  49. def __release_local__(self):
  50. self.__storage__.pop(self.__ident_func__(), None)
  51. def __getattr__(self, name):
  52. try:
  53. return self.__storage__[self.__ident_func__()][name]
  54. except KeyError:
  55. raise AttributeError(name)
  56. def __setattr__(self, name, value):
  57. ident = self.__ident_func__()
  58. storage = self.__storage__
  59. try:
  60. storage[ident][name] = value
  61. except KeyError:
  62. storage[ident] = {name: value}
  63. def __delattr__(self, name):
  64. try:
  65. del self.__storage__[self.__ident_func__()][name]
  66. except KeyError:
  67. raise AttributeError(name)
  68. class LocalStack(object):
  69. """This class works similar to a :class:`Local` but keeps a stack
  70. of objects instead. This is best explained with an example::
  71. >>> ls = LocalStack()
  72. >>> ls.push(42)
  73. >>> ls.top
  74. 42
  75. >>> ls.push(23)
  76. >>> ls.top
  77. 23
  78. >>> ls.pop()
  79. 23
  80. >>> ls.top
  81. 42
  82. They can be force released by using a :class:`LocalManager` or with
  83. the :func:`release_local` function but the correct way is to pop the
  84. item from the stack after using. When the stack is empty it will
  85. no longer be bound to the current context (and as such released).
  86. By calling the stack without arguments it returns a proxy that resolves to
  87. the topmost item on the stack.
  88. .. versionadded:: 0.6.1
  89. """
  90. def __init__(self):
  91. self._local = Local()
  92. def __release_local__(self):
  93. self._local.__release_local__()
  94. def _get__ident_func__(self):
  95. return self._local.__ident_func__
  96. def _set__ident_func__(self, value):
  97. object.__setattr__(self._local, '__ident_func__', value)
  98. __ident_func__ = property(_get__ident_func__, _set__ident_func__)
  99. del _get__ident_func__, _set__ident_func__
  100. def __call__(self):
  101. def _lookup():
  102. rv = self.top
  103. if rv is None:
  104. raise RuntimeError('object unbound')
  105. return rv
  106. return LocalProxy(_lookup)
  107. def push(self, obj):
  108. """Pushes a new item to the stack"""
  109. rv = getattr(self._local, 'stack', None)
  110. if rv is None:
  111. self._local.stack = rv = []
  112. rv.append(obj)
  113. return rv
  114. def pop(self):
  115. """Removes the topmost item from the stack, will return the
  116. old value or `None` if the stack was already empty.
  117. """
  118. stack = getattr(self._local, 'stack', None)
  119. if stack is None:
  120. return None
  121. elif len(stack) == 1:
  122. release_local(self._local)
  123. return stack[-1]
  124. else:
  125. return stack.pop()
  126. @property
  127. def top(self):
  128. """The topmost item on the stack. If the stack is empty,
  129. `None` is returned.
  130. """
  131. try:
  132. return self._local.stack[-1]
  133. except (AttributeError, IndexError):
  134. return None
  135. class LocalManager(object):
  136. """Local objects cannot manage themselves. For that you need a local
  137. manager. You can pass a local manager multiple locals or add them later
  138. by appending them to `manager.locals`. Everytime the manager cleans up
  139. it, will clean up all the data left in the locals for this context.
  140. The `ident_func` parameter can be added to override the default ident
  141. function for the wrapped locals.
  142. .. versionchanged:: 0.6.1
  143. Instead of a manager the :func:`release_local` function can be used
  144. as well.
  145. .. versionchanged:: 0.7
  146. `ident_func` was added.
  147. """
  148. def __init__(self, locals=None, ident_func=None):
  149. if locals is None:
  150. self.locals = []
  151. elif isinstance(locals, Local):
  152. self.locals = [locals]
  153. else:
  154. self.locals = list(locals)
  155. if ident_func is not None:
  156. self.ident_func = ident_func
  157. for local in self.locals:
  158. object.__setattr__(local, '__ident_func__', ident_func)
  159. else:
  160. self.ident_func = get_ident
  161. def get_ident(self):
  162. """Return the context identifier the local objects use internally for
  163. this context. You cannot override this method to change the behavior
  164. but use it to link other context local objects (such as SQLAlchemy's
  165. scoped sessions) to the Werkzeug locals.
  166. .. versionchanged:: 0.7
  167. You can pass a different ident function to the local manager that
  168. will then be propagated to all the locals passed to the
  169. constructor.
  170. """
  171. return self.ident_func()
  172. def cleanup(self):
  173. """Manually clean up the data in the locals for this context. Call
  174. this at the end of the request or use `make_middleware()`.
  175. """
  176. for local in self.locals:
  177. release_local(local)
  178. def make_middleware(self, app):
  179. """Wrap a WSGI application so that cleaning up happens after
  180. request end.
  181. """
  182. def application(environ, start_response):
  183. return ClosingIterator(app(environ, start_response), self.cleanup)
  184. return application
  185. def middleware(self, func):
  186. """Like `make_middleware` but for decorating functions.
  187. Example usage::
  188. @manager.middleware
  189. def application(environ, start_response):
  190. ...
  191. The difference to `make_middleware` is that the function passed
  192. will have all the arguments copied from the inner application
  193. (name, docstring, module).
  194. """
  195. return update_wrapper(self.make_middleware(func), func)
  196. def __repr__(self):
  197. return '<%s storages: %d>' % (
  198. self.__class__.__name__,
  199. len(self.locals)
  200. )
  201. @implements_bool
  202. class LocalProxy(object):
  203. """Acts as a proxy for a werkzeug local. Forwards all operations to
  204. a proxied object. The only operations not supported for forwarding
  205. are right handed operands and any kind of assignment.
  206. Example usage::
  207. from werkzeug.local import Local
  208. l = Local()
  209. # these are proxies
  210. request = l('request')
  211. user = l('user')
  212. from werkzeug.local import LocalStack
  213. _response_local = LocalStack()
  214. # this is a proxy
  215. response = _response_local()
  216. Whenever something is bound to l.user / l.request the proxy objects
  217. will forward all operations. If no object is bound a :exc:`RuntimeError`
  218. will be raised.
  219. To create proxies to :class:`Local` or :class:`LocalStack` objects,
  220. call the object as shown above. If you want to have a proxy to an
  221. object looked up by a function, you can (as of Werkzeug 0.6.1) pass
  222. a function to the :class:`LocalProxy` constructor::
  223. session = LocalProxy(lambda: get_current_request().session)
  224. .. versionchanged:: 0.6.1
  225. The class can be instanciated with a callable as well now.
  226. """
  227. __slots__ = ('__local', '__dict__', '__name__')
  228. def __init__(self, local, name=None):
  229. object.__setattr__(self, '_LocalProxy__local', local)
  230. object.__setattr__(self, '__name__', name)
  231. def _get_current_object(self):
  232. """Return the current object. This is useful if you want the real
  233. object behind the proxy at a time for performance reasons or because
  234. you want to pass the object into a different context.
  235. """
  236. if not hasattr(self.__local, '__release_local__'):
  237. return self.__local()
  238. try:
  239. return getattr(self.__local, self.__name__)
  240. except AttributeError:
  241. raise RuntimeError('no object bound to %s' % self.__name__)
  242. @property
  243. def __dict__(self):
  244. try:
  245. return self._get_current_object().__dict__
  246. except RuntimeError:
  247. raise AttributeError('__dict__')
  248. def __repr__(self):
  249. try:
  250. obj = self._get_current_object()
  251. except RuntimeError:
  252. return '<%s unbound>' % self.__class__.__name__
  253. return repr(obj)
  254. def __bool__(self):
  255. try:
  256. return bool(self._get_current_object())
  257. except RuntimeError:
  258. return False
  259. def __unicode__(self):
  260. try:
  261. return unicode(self._get_current_object())
  262. except RuntimeError:
  263. return repr(self)
  264. def __dir__(self):
  265. try:
  266. return dir(self._get_current_object())
  267. except RuntimeError:
  268. return []
  269. def __getattr__(self, name):
  270. if name == '__members__':
  271. return dir(self._get_current_object())
  272. return getattr(self._get_current_object(), name)
  273. def __setitem__(self, key, value):
  274. self._get_current_object()[key] = value
  275. def __delitem__(self, key):
  276. del self._get_current_object()[key]
  277. if PY2:
  278. __getslice__ = lambda x, i, j: x._get_current_object()[i:j]
  279. def __setslice__(self, i, j, seq):
  280. self._get_current_object()[i:j] = seq
  281. def __delslice__(self, i, j):
  282. del self._get_current_object()[i:j]
  283. __setattr__ = lambda x, n, v: setattr(x._get_current_object(), n, v)
  284. __delattr__ = lambda x, n: delattr(x._get_current_object(), n)
  285. __str__ = lambda x: str(x._get_current_object())
  286. __lt__ = lambda x, o: x._get_current_object() < o
  287. __le__ = lambda x, o: x._get_current_object() <= o
  288. __eq__ = lambda x, o: x._get_current_object() == o
  289. __ne__ = lambda x, o: x._get_current_object() != o
  290. __gt__ = lambda x, o: x._get_current_object() > o
  291. __ge__ = lambda x, o: x._get_current_object() >= o
  292. __cmp__ = lambda x, o: cmp(x._get_current_object(), o)
  293. __hash__ = lambda x: hash(x._get_current_object())
  294. __call__ = lambda x, *a, **kw: x._get_current_object()(*a, **kw)
  295. __len__ = lambda x: len(x._get_current_object())
  296. __getitem__ = lambda x, i: x._get_current_object()[i]
  297. __iter__ = lambda x: iter(x._get_current_object())
  298. __contains__ = lambda x, i: i in x._get_current_object()
  299. __add__ = lambda x, o: x._get_current_object() + o
  300. __sub__ = lambda x, o: x._get_current_object() - o
  301. __mul__ = lambda x, o: x._get_current_object() * o
  302. __floordiv__ = lambda x, o: x._get_current_object() // o
  303. __mod__ = lambda x, o: x._get_current_object() % o
  304. __divmod__ = lambda x, o: x._get_current_object().__divmod__(o)
  305. __pow__ = lambda x, o: x._get_current_object() ** o
  306. __lshift__ = lambda x, o: x._get_current_object() << o
  307. __rshift__ = lambda x, o: x._get_current_object() >> o
  308. __and__ = lambda x, o: x._get_current_object() & o
  309. __xor__ = lambda x, o: x._get_current_object() ^ o
  310. __or__ = lambda x, o: x._get_current_object() | o
  311. __div__ = lambda x, o: x._get_current_object().__div__(o)
  312. __truediv__ = lambda x, o: x._get_current_object().__truediv__(o)
  313. __neg__ = lambda x: -(x._get_current_object())
  314. __pos__ = lambda x: +(x._get_current_object())
  315. __abs__ = lambda x: abs(x._get_current_object())
  316. __invert__ = lambda x: ~(x._get_current_object())
  317. __complex__ = lambda x: complex(x._get_current_object())
  318. __int__ = lambda x: int(x._get_current_object())
  319. __long__ = lambda x: long(x._get_current_object())
  320. __float__ = lambda x: float(x._get_current_object())
  321. __oct__ = lambda x: oct(x._get_current_object())
  322. __hex__ = lambda x: hex(x._get_current_object())
  323. __index__ = lambda x: x._get_current_object().__index__()
  324. __coerce__ = lambda x, o: x._get_current_object().__coerce__(x, o)
  325. __enter__ = lambda x: x._get_current_object().__enter__()
  326. __exit__ = lambda x, *a, **kw: x._get_current_object().__exit__(*a, **kw)
  327. __radd__ = lambda x, o: o + x._get_current_object()
  328. __rsub__ = lambda x, o: o - x._get_current_object()
  329. __rmul__ = lambda x, o: o * x._get_current_object()
  330. __rdiv__ = lambda x, o: o / x._get_current_object()
  331. if PY2:
  332. __rtruediv__ = lambda x, o: x._get_current_object().__rtruediv__(o)
  333. else:
  334. __rtruediv__ = __rdiv__
  335. __rfloordiv__ = lambda x, o: o // x._get_current_object()
  336. __rmod__ = lambda x, o: o % x._get_current_object()
  337. __rdivmod__ = lambda x, o: x._get_current_object().__rdivmod__(o)