local.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. import copy
  2. import math
  3. import operator
  4. import typing as t
  5. from contextvars import ContextVar
  6. from functools import partial
  7. from functools import update_wrapper
  8. from .wsgi import ClosingIterator
  9. if t.TYPE_CHECKING:
  10. from _typeshed.wsgi import StartResponse
  11. from _typeshed.wsgi import WSGIApplication
  12. from _typeshed.wsgi import WSGIEnvironment
  13. F = t.TypeVar("F", bound=t.Callable[..., t.Any])
  14. def release_local(local: t.Union["Local", "LocalStack"]) -> None:
  15. """Releases the contents of the local for the current context.
  16. This makes it possible to use locals without a manager.
  17. Example::
  18. >>> loc = Local()
  19. >>> loc.foo = 42
  20. >>> release_local(loc)
  21. >>> hasattr(loc, 'foo')
  22. False
  23. With this function one can release :class:`Local` objects as well
  24. as :class:`LocalStack` objects. However it is not possible to
  25. release data held by proxies that way, one always has to retain
  26. a reference to the underlying local object in order to be able
  27. to release it.
  28. .. versionadded:: 0.6.1
  29. """
  30. local.__release_local__()
  31. class Local:
  32. __slots__ = ("_storage",)
  33. def __init__(self) -> None:
  34. object.__setattr__(self, "_storage", ContextVar("local_storage"))
  35. def __iter__(self) -> t.Iterator[t.Tuple[int, t.Any]]:
  36. return iter(self._storage.get({}).items())
  37. def __call__(self, proxy: str) -> "LocalProxy":
  38. """Create a proxy for a name."""
  39. return LocalProxy(self, proxy)
  40. def __release_local__(self) -> None:
  41. self._storage.set({})
  42. def __getattr__(self, name: str) -> t.Any:
  43. values = self._storage.get({})
  44. try:
  45. return values[name]
  46. except KeyError:
  47. raise AttributeError(name) from None
  48. def __setattr__(self, name: str, value: t.Any) -> None:
  49. values = self._storage.get({}).copy()
  50. values[name] = value
  51. self._storage.set(values)
  52. def __delattr__(self, name: str) -> None:
  53. values = self._storage.get({}).copy()
  54. try:
  55. del values[name]
  56. self._storage.set(values)
  57. except KeyError:
  58. raise AttributeError(name) from None
  59. class LocalStack:
  60. """This class works similar to a :class:`Local` but keeps a stack
  61. of objects instead. This is best explained with an example::
  62. >>> ls = LocalStack()
  63. >>> ls.push(42)
  64. >>> ls.top
  65. 42
  66. >>> ls.push(23)
  67. >>> ls.top
  68. 23
  69. >>> ls.pop()
  70. 23
  71. >>> ls.top
  72. 42
  73. They can be force released by using a :class:`LocalManager` or with
  74. the :func:`release_local` function but the correct way is to pop the
  75. item from the stack after using. When the stack is empty it will
  76. no longer be bound to the current context (and as such released).
  77. By calling the stack without arguments it returns a proxy that resolves to
  78. the topmost item on the stack.
  79. .. versionadded:: 0.6.1
  80. """
  81. def __init__(self) -> None:
  82. self._local = Local()
  83. def __release_local__(self) -> None:
  84. self._local.__release_local__()
  85. def __call__(self) -> "LocalProxy":
  86. def _lookup() -> t.Any:
  87. rv = self.top
  88. if rv is None:
  89. raise RuntimeError("object unbound")
  90. return rv
  91. return LocalProxy(_lookup)
  92. def push(self, obj: t.Any) -> t.List[t.Any]:
  93. """Pushes a new item to the stack"""
  94. rv = getattr(self._local, "stack", []).copy()
  95. rv.append(obj)
  96. self._local.stack = rv
  97. return rv
  98. def pop(self) -> t.Any:
  99. """Removes the topmost item from the stack, will return the
  100. old value or `None` if the stack was already empty.
  101. """
  102. stack = getattr(self._local, "stack", None)
  103. if stack is None:
  104. return None
  105. elif len(stack) == 1:
  106. release_local(self._local)
  107. return stack[-1]
  108. else:
  109. return stack.pop()
  110. @property
  111. def top(self) -> t.Any:
  112. """The topmost item on the stack. If the stack is empty,
  113. `None` is returned.
  114. """
  115. try:
  116. return self._local.stack[-1]
  117. except (AttributeError, IndexError):
  118. return None
  119. class LocalManager:
  120. """Local objects cannot manage themselves. For that you need a local
  121. manager. You can pass a local manager multiple locals or add them
  122. later by appending them to `manager.locals`. Every time the manager
  123. cleans up, it will clean up all the data left in the locals for this
  124. context.
  125. .. versionchanged:: 2.0
  126. ``ident_func`` is deprecated and will be removed in Werkzeug
  127. 2.1.
  128. .. versionchanged:: 0.6.1
  129. The :func:`release_local` function can be used instead of a
  130. manager.
  131. .. versionchanged:: 0.7
  132. The ``ident_func`` parameter was added.
  133. """
  134. def __init__(
  135. self, locals: t.Optional[t.Iterable[t.Union[Local, LocalStack]]] = None
  136. ) -> None:
  137. if locals is None:
  138. self.locals = []
  139. elif isinstance(locals, Local):
  140. self.locals = [locals]
  141. else:
  142. self.locals = list(locals)
  143. def cleanup(self) -> None:
  144. """Manually clean up the data in the locals for this context. Call
  145. this at the end of the request or use `make_middleware()`.
  146. """
  147. for local in self.locals:
  148. release_local(local)
  149. def make_middleware(self, app: "WSGIApplication") -> "WSGIApplication":
  150. """Wrap a WSGI application so that cleaning up happens after
  151. request end.
  152. """
  153. def application(
  154. environ: "WSGIEnvironment", start_response: "StartResponse"
  155. ) -> t.Iterable[bytes]:
  156. return ClosingIterator(app(environ, start_response), self.cleanup)
  157. return application
  158. def middleware(self, func: "WSGIApplication") -> "WSGIApplication":
  159. """Like `make_middleware` but for decorating functions.
  160. Example usage::
  161. @manager.middleware
  162. def application(environ, start_response):
  163. ...
  164. The difference to `make_middleware` is that the function passed
  165. will have all the arguments copied from the inner application
  166. (name, docstring, module).
  167. """
  168. return update_wrapper(self.make_middleware(func), func)
  169. def __repr__(self) -> str:
  170. return f"<{type(self).__name__} storages: {len(self.locals)}>"
  171. class _ProxyLookup:
  172. """Descriptor that handles proxied attribute lookup for
  173. :class:`LocalProxy`.
  174. :param f: The built-in function this attribute is accessed through.
  175. Instead of looking up the special method, the function call
  176. is redone on the object.
  177. :param fallback: Return this function if the proxy is unbound
  178. instead of raising a :exc:`RuntimeError`.
  179. :param is_attr: This proxied name is an attribute, not a function.
  180. Call the fallback immediately to get the value.
  181. :param class_value: Value to return when accessed from the
  182. ``LocalProxy`` class directly. Used for ``__doc__`` so building
  183. docs still works.
  184. """
  185. __slots__ = ("bind_f", "fallback", "is_attr", "class_value", "name")
  186. def __init__(
  187. self,
  188. f: t.Optional[t.Callable] = None,
  189. fallback: t.Optional[t.Callable] = None,
  190. class_value: t.Optional[t.Any] = None,
  191. is_attr: bool = False,
  192. ) -> None:
  193. bind_f: t.Optional[t.Callable[["LocalProxy", t.Any], t.Callable]]
  194. if hasattr(f, "__get__"):
  195. # A Python function, can be turned into a bound method.
  196. def bind_f(instance: "LocalProxy", obj: t.Any) -> t.Callable:
  197. return f.__get__(obj, type(obj)) # type: ignore
  198. elif f is not None:
  199. # A C function, use partial to bind the first argument.
  200. def bind_f(instance: "LocalProxy", obj: t.Any) -> t.Callable:
  201. return partial(f, obj) # type: ignore
  202. else:
  203. # Use getattr, which will produce a bound method.
  204. bind_f = None
  205. self.bind_f = bind_f
  206. self.fallback = fallback
  207. self.class_value = class_value
  208. self.is_attr = is_attr
  209. def __set_name__(self, owner: "LocalProxy", name: str) -> None:
  210. self.name = name
  211. def __get__(self, instance: "LocalProxy", owner: t.Optional[type] = None) -> t.Any:
  212. if instance is None:
  213. if self.class_value is not None:
  214. return self.class_value
  215. return self
  216. try:
  217. obj = instance._get_current_object()
  218. except RuntimeError:
  219. if self.fallback is None:
  220. raise
  221. fallback = self.fallback.__get__(instance, owner)
  222. if self.is_attr:
  223. # __class__ and __doc__ are attributes, not methods.
  224. # Call the fallback to get the value.
  225. return fallback()
  226. return fallback
  227. if self.bind_f is not None:
  228. return self.bind_f(instance, obj)
  229. return getattr(obj, self.name)
  230. def __repr__(self) -> str:
  231. return f"proxy {self.name}"
  232. def __call__(self, instance: "LocalProxy", *args: t.Any, **kwargs: t.Any) -> t.Any:
  233. """Support calling unbound methods from the class. For example,
  234. this happens with ``copy.copy``, which does
  235. ``type(x).__copy__(x)``. ``type(x)`` can't be proxied, so it
  236. returns the proxy type and descriptor.
  237. """
  238. return self.__get__(instance, type(instance))(*args, **kwargs)
  239. class _ProxyIOp(_ProxyLookup):
  240. """Look up an augmented assignment method on a proxied object. The
  241. method is wrapped to return the proxy instead of the object.
  242. """
  243. __slots__ = ()
  244. def __init__(
  245. self, f: t.Optional[t.Callable] = None, fallback: t.Optional[t.Callable] = None
  246. ) -> None:
  247. super().__init__(f, fallback)
  248. def bind_f(instance: "LocalProxy", obj: t.Any) -> t.Callable:
  249. def i_op(self: t.Any, other: t.Any) -> "LocalProxy":
  250. f(self, other) # type: ignore
  251. return instance
  252. return i_op.__get__(obj, type(obj)) # type: ignore
  253. self.bind_f = bind_f
  254. def _l_to_r_op(op: F) -> F:
  255. """Swap the argument order to turn an l-op into an r-op."""
  256. def r_op(obj: t.Any, other: t.Any) -> t.Any:
  257. return op(other, obj)
  258. return t.cast(F, r_op)
  259. class LocalProxy:
  260. """A proxy to the object bound to a :class:`Local`. All operations
  261. on the proxy are forwarded to the bound object. If no object is
  262. bound, a :exc:`RuntimeError` is raised.
  263. .. code-block:: python
  264. from werkzeug.local import Local
  265. l = Local()
  266. # a proxy to whatever l.user is set to
  267. user = l("user")
  268. from werkzeug.local import LocalStack
  269. _request_stack = LocalStack()
  270. # a proxy to _request_stack.top
  271. request = _request_stack()
  272. # a proxy to the session attribute of the request proxy
  273. session = LocalProxy(lambda: request.session)
  274. ``__repr__`` and ``__class__`` are forwarded, so ``repr(x)`` and
  275. ``isinstance(x, cls)`` will look like the proxied object. Use
  276. ``issubclass(type(x), LocalProxy)`` to check if an object is a
  277. proxy.
  278. .. code-block:: python
  279. repr(user) # <User admin>
  280. isinstance(user, User) # True
  281. issubclass(type(user), LocalProxy) # True
  282. :param local: The :class:`Local` or callable that provides the
  283. proxied object.
  284. :param name: The attribute name to look up on a :class:`Local`. Not
  285. used if a callable is given.
  286. .. versionchanged:: 2.0
  287. Updated proxied attributes and methods to reflect the current
  288. data model.
  289. .. versionchanged:: 0.6.1
  290. The class can be instantiated with a callable.
  291. """
  292. __slots__ = ("__local", "__name", "__wrapped__")
  293. def __init__(
  294. self,
  295. local: t.Union["Local", t.Callable[[], t.Any]],
  296. name: t.Optional[str] = None,
  297. ) -> None:
  298. object.__setattr__(self, "_LocalProxy__local", local)
  299. object.__setattr__(self, "_LocalProxy__name", name)
  300. if callable(local) and not hasattr(local, "__release_local__"):
  301. # "local" is a callable that is not an instance of Local or
  302. # LocalManager: mark it as a wrapped function.
  303. object.__setattr__(self, "__wrapped__", local)
  304. def _get_current_object(self) -> t.Any:
  305. """Return the current object. This is useful if you want the real
  306. object behind the proxy at a time for performance reasons or because
  307. you want to pass the object into a different context.
  308. """
  309. if not hasattr(self.__local, "__release_local__"): # type: ignore
  310. return self.__local() # type: ignore
  311. try:
  312. return getattr(self.__local, self.__name) # type: ignore
  313. except AttributeError:
  314. name = self.__name # type: ignore
  315. raise RuntimeError(f"no object bound to {name}") from None
  316. __doc__ = _ProxyLookup( # type: ignore
  317. class_value=__doc__, fallback=lambda self: type(self).__doc__, is_attr=True
  318. )
  319. # __del__ should only delete the proxy
  320. __repr__ = _ProxyLookup( # type: ignore
  321. repr, fallback=lambda self: f"<{type(self).__name__} unbound>"
  322. )
  323. __str__ = _ProxyLookup(str) # type: ignore
  324. __bytes__ = _ProxyLookup(bytes)
  325. __format__ = _ProxyLookup() # type: ignore
  326. __lt__ = _ProxyLookup(operator.lt)
  327. __le__ = _ProxyLookup(operator.le)
  328. __eq__ = _ProxyLookup(operator.eq) # type: ignore
  329. __ne__ = _ProxyLookup(operator.ne) # type: ignore
  330. __gt__ = _ProxyLookup(operator.gt)
  331. __ge__ = _ProxyLookup(operator.ge)
  332. __hash__ = _ProxyLookup(hash) # type: ignore
  333. __bool__ = _ProxyLookup(bool, fallback=lambda self: False)
  334. __getattr__ = _ProxyLookup(getattr)
  335. # __getattribute__ triggered through __getattr__
  336. __setattr__ = _ProxyLookup(setattr) # type: ignore
  337. __delattr__ = _ProxyLookup(delattr) # type: ignore
  338. __dir__ = _ProxyLookup(dir, fallback=lambda self: []) # type: ignore
  339. # __get__ (proxying descriptor not supported)
  340. # __set__ (descriptor)
  341. # __delete__ (descriptor)
  342. # __set_name__ (descriptor)
  343. # __objclass__ (descriptor)
  344. # __slots__ used by proxy itself
  345. # __dict__ (__getattr__)
  346. # __weakref__ (__getattr__)
  347. # __init_subclass__ (proxying metaclass not supported)
  348. # __prepare__ (metaclass)
  349. __class__ = _ProxyLookup(
  350. fallback=lambda self: type(self), is_attr=True
  351. ) # type: ignore
  352. __instancecheck__ = _ProxyLookup(lambda self, other: isinstance(other, self))
  353. __subclasscheck__ = _ProxyLookup(lambda self, other: issubclass(other, self))
  354. # __class_getitem__ triggered through __getitem__
  355. __call__ = _ProxyLookup(lambda self, *args, **kwargs: self(*args, **kwargs))
  356. __len__ = _ProxyLookup(len)
  357. __length_hint__ = _ProxyLookup(operator.length_hint)
  358. __getitem__ = _ProxyLookup(operator.getitem)
  359. __setitem__ = _ProxyLookup(operator.setitem)
  360. __delitem__ = _ProxyLookup(operator.delitem)
  361. # __missing__ triggered through __getitem__
  362. __iter__ = _ProxyLookup(iter)
  363. __next__ = _ProxyLookup(next)
  364. __reversed__ = _ProxyLookup(reversed)
  365. __contains__ = _ProxyLookup(operator.contains)
  366. __add__ = _ProxyLookup(operator.add)
  367. __sub__ = _ProxyLookup(operator.sub)
  368. __mul__ = _ProxyLookup(operator.mul)
  369. __matmul__ = _ProxyLookup(operator.matmul)
  370. __truediv__ = _ProxyLookup(operator.truediv)
  371. __floordiv__ = _ProxyLookup(operator.floordiv)
  372. __mod__ = _ProxyLookup(operator.mod)
  373. __divmod__ = _ProxyLookup(divmod)
  374. __pow__ = _ProxyLookup(pow)
  375. __lshift__ = _ProxyLookup(operator.lshift)
  376. __rshift__ = _ProxyLookup(operator.rshift)
  377. __and__ = _ProxyLookup(operator.and_)
  378. __xor__ = _ProxyLookup(operator.xor)
  379. __or__ = _ProxyLookup(operator.or_)
  380. __radd__ = _ProxyLookup(_l_to_r_op(operator.add))
  381. __rsub__ = _ProxyLookup(_l_to_r_op(operator.sub))
  382. __rmul__ = _ProxyLookup(_l_to_r_op(operator.mul))
  383. __rmatmul__ = _ProxyLookup(_l_to_r_op(operator.matmul))
  384. __rtruediv__ = _ProxyLookup(_l_to_r_op(operator.truediv))
  385. __rfloordiv__ = _ProxyLookup(_l_to_r_op(operator.floordiv))
  386. __rmod__ = _ProxyLookup(_l_to_r_op(operator.mod))
  387. __rdivmod__ = _ProxyLookup(_l_to_r_op(divmod))
  388. __rpow__ = _ProxyLookup(_l_to_r_op(pow))
  389. __rlshift__ = _ProxyLookup(_l_to_r_op(operator.lshift))
  390. __rrshift__ = _ProxyLookup(_l_to_r_op(operator.rshift))
  391. __rand__ = _ProxyLookup(_l_to_r_op(operator.and_))
  392. __rxor__ = _ProxyLookup(_l_to_r_op(operator.xor))
  393. __ror__ = _ProxyLookup(_l_to_r_op(operator.or_))
  394. __iadd__ = _ProxyIOp(operator.iadd)
  395. __isub__ = _ProxyIOp(operator.isub)
  396. __imul__ = _ProxyIOp(operator.imul)
  397. __imatmul__ = _ProxyIOp(operator.imatmul)
  398. __itruediv__ = _ProxyIOp(operator.itruediv)
  399. __ifloordiv__ = _ProxyIOp(operator.ifloordiv)
  400. __imod__ = _ProxyIOp(operator.imod)
  401. __ipow__ = _ProxyIOp(operator.ipow)
  402. __ilshift__ = _ProxyIOp(operator.ilshift)
  403. __irshift__ = _ProxyIOp(operator.irshift)
  404. __iand__ = _ProxyIOp(operator.iand)
  405. __ixor__ = _ProxyIOp(operator.ixor)
  406. __ior__ = _ProxyIOp(operator.ior)
  407. __neg__ = _ProxyLookup(operator.neg)
  408. __pos__ = _ProxyLookup(operator.pos)
  409. __abs__ = _ProxyLookup(abs)
  410. __invert__ = _ProxyLookup(operator.invert)
  411. __complex__ = _ProxyLookup(complex)
  412. __int__ = _ProxyLookup(int)
  413. __float__ = _ProxyLookup(float)
  414. __index__ = _ProxyLookup(operator.index)
  415. __round__ = _ProxyLookup(round)
  416. __trunc__ = _ProxyLookup(math.trunc)
  417. __floor__ = _ProxyLookup(math.floor)
  418. __ceil__ = _ProxyLookup(math.ceil)
  419. __enter__ = _ProxyLookup()
  420. __exit__ = _ProxyLookup()
  421. __await__ = _ProxyLookup()
  422. __aiter__ = _ProxyLookup()
  423. __anext__ = _ProxyLookup()
  424. __aenter__ = _ProxyLookup()
  425. __aexit__ = _ProxyLookup()
  426. __copy__ = _ProxyLookup(copy.copy)
  427. __deepcopy__ = _ProxyLookup(copy.deepcopy)
  428. # __getnewargs_ex__ (pickle through proxy not supported)
  429. # __getnewargs__ (pickle)
  430. # __getstate__ (pickle)
  431. # __setstate__ (pickle)
  432. # __reduce__ (pickle)
  433. # __reduce_ex__ (pickle)