You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

420 lines
14 KiB

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