pboot 3.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pboot/ctx.py ADDED
@@ -0,0 +1,540 @@
1
+ from __future__ import annotations
2
+
3
+ import contextvars
4
+ import typing as t
5
+ from functools import update_wrapper
6
+ from types import TracebackType
7
+
8
+ from werkzeug.exceptions import HTTPException
9
+ from werkzeug.routing import MapAdapter
10
+
11
+ from . import typing as ft
12
+ from .globals import _cv_app
13
+ from .helpers import _CollectErrors
14
+ from .signals import appcontext_popped
15
+ from .signals import appcontext_pushed
16
+
17
+ if t.TYPE_CHECKING:
18
+ import typing_extensions as te
19
+ from _typeshed.wsgi import WSGIEnvironment
20
+
21
+ from .app import Pboot
22
+ from .sessions import SessionMixin
23
+ from .wrappers import Request
24
+
25
+
26
+ # a singleton sentinel value for parameter defaults
27
+ _sentinel = object()
28
+
29
+
30
+ class _AppCtxGlobals:
31
+ """A plain object. Used as a namespace for storing data during an
32
+ application context.
33
+
34
+ Creating an app context automatically creates this object, which is
35
+ made available as the :data:`.g` proxy.
36
+
37
+ .. describe:: 'key' in g
38
+
39
+ Check whether an attribute is present.
40
+
41
+ .. versionadded:: 0.10
42
+
43
+ .. describe:: iter(g)
44
+
45
+ Return an iterator over the attribute names.
46
+
47
+ .. versionadded:: 0.10
48
+ """
49
+
50
+ # Define attr methods to let mypy know this is a namespace object
51
+ # that has arbitrary attributes.
52
+
53
+ def __getattr__(self, name: str) -> t.Any:
54
+ try:
55
+ return self.__dict__[name]
56
+ except KeyError:
57
+ raise AttributeError(name) from None
58
+
59
+ def __setattr__(self, name: str, value: t.Any) -> None:
60
+ self.__dict__[name] = value
61
+
62
+ def __delattr__(self, name: str) -> None:
63
+ try:
64
+ del self.__dict__[name]
65
+ except KeyError:
66
+ raise AttributeError(name) from None
67
+
68
+ def get(self, name: str, default: t.Any | None = None) -> t.Any:
69
+ """Get an attribute by name, or a default value. Like
70
+ :meth:`dict.get`.
71
+
72
+ :param name: Name of attribute to get.
73
+ :param default: Value to return if the attribute is not present.
74
+
75
+ .. versionadded:: 0.10
76
+ """
77
+ return self.__dict__.get(name, default)
78
+
79
+ def pop(self, name: str, default: t.Any = _sentinel) -> t.Any:
80
+ """Get and remove an attribute by name. Like :meth:`dict.pop`.
81
+
82
+ :param name: Name of attribute to pop.
83
+ :param default: Value to return if the attribute is not present,
84
+ instead of raising a ``KeyError``.
85
+
86
+ .. versionadded:: 0.11
87
+ """
88
+ if default is _sentinel:
89
+ return self.__dict__.pop(name)
90
+ else:
91
+ return self.__dict__.pop(name, default)
92
+
93
+ def setdefault(self, name: str, default: t.Any = None) -> t.Any:
94
+ """Get the value of an attribute if it is present, otherwise
95
+ set and return a default value. Like :meth:`dict.setdefault`.
96
+
97
+ :param name: Name of attribute to get.
98
+ :param default: Value to set and return if the attribute is not
99
+ present.
100
+
101
+ .. versionadded:: 0.11
102
+ """
103
+ return self.__dict__.setdefault(name, default)
104
+
105
+ def __contains__(self, item: str) -> bool:
106
+ return item in self.__dict__
107
+
108
+ def __iter__(self) -> t.Iterator[str]:
109
+ return iter(self.__dict__)
110
+
111
+ def __repr__(self) -> str:
112
+ ctx = _cv_app.get(None)
113
+ if ctx is not None:
114
+ return f"<pboot.g of '{ctx.app.name}'>"
115
+ return object.__repr__(self)
116
+
117
+
118
+ def after_this_request(
119
+ f: ft.AfterRequestCallable[t.Any],
120
+ ) -> ft.AfterRequestCallable[t.Any]:
121
+ """Decorate a function to run after the current request. The behavior is the
122
+ same as :meth:`.Pboot.after_request`, except it only applies to the current
123
+ request, rather than every request. Therefore, it must be used within a
124
+ request context, rather than during setup.
125
+
126
+ .. code-block:: python
127
+
128
+ @app.route("/")
129
+ def index():
130
+ @after_this_request
131
+ def add_header(response):
132
+ response.headers["X-Foo"] = "Parachute"
133
+ return response
134
+
135
+ return "Hello, World!"
136
+
137
+ .. versionadded:: 0.9
138
+ """
139
+ ctx = _cv_app.get(None)
140
+
141
+ if ctx is None or not ctx.has_request:
142
+ raise RuntimeError(
143
+ "'after_this_request' can only be used when a request"
144
+ " context is active, such as in a view function."
145
+ )
146
+
147
+ ctx._after_request_functions.append(f)
148
+ return f
149
+
150
+
151
+ F = t.TypeVar("F", bound=t.Callable[..., t.Any])
152
+
153
+
154
+ def copy_current_request_context(f: F) -> F:
155
+ """Decorate a function to run inside the current request context. This can
156
+ be used when starting a background task, otherwise it will not see the app
157
+ and request objects that were active in the parent.
158
+
159
+ .. warning::
160
+
161
+ Due to the following caveats, it is often safer (and simpler) to pass
162
+ the data you need when starting the task, rather than using this and
163
+ relying on the context objects.
164
+
165
+ In order to avoid execution switching partially though reading data, either
166
+ read the request body (access ``form``, ``json``, ``data``, etc) before
167
+ starting the task, or use a lock. This can be an issue when using threading,
168
+ but shouldn't be an issue when using greenlet/gevent or asyncio.
169
+
170
+ If the task will access ``session``, be sure to do so in the parent as well
171
+ so that the ``Vary: cookie`` header will be set. Modifying ``session`` in
172
+ the task should be avoided, as it may execute after the response cookie has
173
+ already been written.
174
+
175
+ .. code-block:: python
176
+
177
+ import gevent
178
+ from pboot import copy_current_request_context
179
+
180
+ @app.route('/')
181
+ def index():
182
+ @copy_current_request_context
183
+ def do_some_work():
184
+ # do some work here, it can access pboot.request or
185
+ # pboot.session like you would otherwise in the view function.
186
+ ...
187
+ gevent.spawn(do_some_work)
188
+ return 'Regular response'
189
+
190
+ .. versionadded:: 0.10
191
+ """
192
+ # Store the context that was active when the decorator was applied.
193
+ original = _cv_app.get(None)
194
+
195
+ if original is None:
196
+ raise RuntimeError(
197
+ "'copy_current_request_context' can only be used when a"
198
+ " request context is active, such as in a view function."
199
+ )
200
+
201
+ def wrapper(*args: t.Any, **kwargs: t.Any) -> t.Any:
202
+ # Copy the context before pushing, so each worker acts independently.
203
+ with original.copy() as ctx:
204
+ return ctx.app.ensure_sync(f)(*args, **kwargs)
205
+
206
+ return update_wrapper(wrapper, f) # type: ignore[return-value]
207
+
208
+
209
+ def has_request_context() -> bool:
210
+ """Test if an app context is active and if it has request information.
211
+
212
+ .. code-block:: python
213
+
214
+ from pboot import has_request_context, request
215
+
216
+ if has_request_context():
217
+ remote_addr = request.remote_addr
218
+
219
+ If a request context is active, the :data:`.request` and :data:`.session`
220
+ context proxies will available and ``True``, otherwise ``False``. You can
221
+ use that to test the data you use, rather than using this function.
222
+
223
+ .. code-block:: python
224
+
225
+ from pboot import request
226
+
227
+ if request:
228
+ remote_addr = request.remote_addr
229
+
230
+ .. versionadded:: 0.7
231
+ """
232
+ return (ctx := _cv_app.get(None)) is not None and ctx.has_request
233
+
234
+
235
+ def has_app_context() -> bool:
236
+ """Test if an app context is active. Unlike :func:`has_request_context`
237
+ this can be true outside a request, such as in a CLI command.
238
+
239
+ .. code-block:: python
240
+
241
+ from pboot import has_app_context, g
242
+
243
+ if has_app_context():
244
+ g.cached_data = ...
245
+
246
+ If an app context is active, the :data:`.g` and :data:`.current_app` context
247
+ proxies will available and ``True``, otherwise ``False``. You can use that
248
+ to test the data you use, rather than using this function.
249
+
250
+ from pboot import g
251
+
252
+ if g:
253
+ g.cached_data = ...
254
+
255
+ .. versionadded:: 0.9
256
+ """
257
+ return _cv_app.get(None) is not None
258
+
259
+
260
+ class AppContext:
261
+ """An app context contains information about an app, and about the request
262
+ when handling a request. A context is pushed at the beginning of each
263
+ request and CLI command, and popped at the end. The context is referred to
264
+ as a "request context" if it has request information, and an "app context"
265
+ if not.
266
+
267
+ Do not use this class directly. Use :meth:`.Pboot.app_context` to create an
268
+ app context if needed during setup, and :meth:`.Pboot.test_request_context`
269
+ to create a request context if needed during tests.
270
+
271
+ When the context is popped, it will evaluate all the teardown functions
272
+ registered with :meth:`~pboot.Pboot.teardown_request` (if handling a
273
+ request) then :meth:`.Pboot.teardown_appcontext`.
274
+
275
+ When using the interactive debugger, the context will be restored so
276
+ ``request`` is still accessible. Similarly, the test client can preserve the
277
+ context after the request ends. However, teardown functions may already have
278
+ closed some resources such as database connections, and will run again when
279
+ the restored context is popped.
280
+
281
+ :param app: The application this context represents.
282
+ :param request: The request data this context represents.
283
+ :param session: The session data this context represents. If not given,
284
+ loaded from the request on first access.
285
+
286
+ .. versionchanged:: 3.2
287
+ Merged with ``RequestContext``. The ``RequestContext`` alias will be
288
+ removed in Pboot 4.0.
289
+
290
+ .. versionchanged:: 3.2
291
+ A combined app and request context is pushed for every request and CLI
292
+ command, rather than trying to detect if an app context is already
293
+ pushed.
294
+
295
+ .. versionchanged:: 3.2
296
+ The session is loaded the first time it is accessed, rather than when
297
+ the context is pushed.
298
+ """
299
+
300
+ def __init__(
301
+ self,
302
+ app: Pboot,
303
+ *,
304
+ request: Request | None = None,
305
+ session: SessionMixin | None = None,
306
+ ) -> None:
307
+ self.app = app
308
+ """The application represented by this context. Accessed through
309
+ :data:`.current_app`.
310
+ """
311
+
312
+ self.g: _AppCtxGlobals = app.app_ctx_globals_class()
313
+ """The global data for this context. Accessed through :data:`.g`."""
314
+
315
+ self.url_adapter: MapAdapter | None = None
316
+ """The URL adapter bound to the request, or the app if not in a request.
317
+ May be ``None`` if binding failed.
318
+ """
319
+
320
+ self._request: Request | None = request
321
+ self._session: SessionMixin | None = session
322
+ self._flashes: list[tuple[str, str]] | None = None
323
+ self._after_request_functions: list[ft.AfterRequestCallable[t.Any]] = []
324
+
325
+ try:
326
+ self.url_adapter = app.create_url_adapter(self._request)
327
+ except HTTPException as e:
328
+ if self._request is not None:
329
+ self._request.routing_exception = e
330
+
331
+ self._cv_token: contextvars.Token[AppContext] | None = None
332
+ """The previous state to restore when popping."""
333
+
334
+ self._push_count: int = 0
335
+ """Track nested pushes of this context. Cleanup will only run once the
336
+ original push has been popped.
337
+ """
338
+
339
+ @classmethod
340
+ def from_environ(cls, app: Pboot, environ: WSGIEnvironment, /) -> te.Self:
341
+ """Create an app context with request data from the given WSGI environ.
342
+
343
+ :param app: The application this context represents.
344
+ :param environ: The request data this context represents.
345
+ """
346
+ request = app.request_class(environ)
347
+ request.json_module = app.json
348
+ return cls(app, request=request)
349
+
350
+ @property
351
+ def has_request(self) -> bool:
352
+ """True if this context was created with request data."""
353
+ return self._request is not None
354
+
355
+ def copy(self) -> te.Self:
356
+ """Create a new context with the same data objects as this context. See
357
+ :func:`.copy_current_request_context`.
358
+
359
+ .. versionchanged:: 1.1
360
+ The current session data is used instead of reloading the original data.
361
+
362
+ .. versionadded:: 0.10
363
+ """
364
+ return self.__class__(
365
+ self.app,
366
+ request=self._request,
367
+ session=self._session,
368
+ )
369
+
370
+ @property
371
+ def request(self) -> Request:
372
+ """The request object associated with this context. Accessed through
373
+ :data:`.request`. Only available in request contexts, otherwise raises
374
+ :exc:`RuntimeError`.
375
+ """
376
+ if self._request is None:
377
+ raise RuntimeError("There is no request in this context.")
378
+
379
+ return self._request
380
+
381
+ def _get_session(self) -> SessionMixin:
382
+ """Open the session if it is not already open for this request context."""
383
+ if self._request is None:
384
+ raise RuntimeError("There is no request in this context.")
385
+
386
+ if self._session is None:
387
+ si = self.app.session_interface
388
+ self._session = si.open_session(self.app, self.request)
389
+
390
+ if self._session is None:
391
+ self._session = si.make_null_session(self.app)
392
+
393
+ return self._session
394
+
395
+ @property
396
+ def session(self) -> SessionMixin:
397
+ """The session object associated with this context. Accessed through
398
+ :data:`.session`. Only available in request contexts, otherwise raises
399
+ :exc:`RuntimeError`. Accessing this sets :attr:`.SessionMixin.accessed`.
400
+ """
401
+ session = self._get_session()
402
+ session.accessed = True
403
+ return session
404
+
405
+ def match_request(self) -> None:
406
+ """Apply routing to the current request, storing either the matched
407
+ endpoint and args, or a routing exception.
408
+ """
409
+ try:
410
+ result = self.url_adapter.match(return_rule=True) # type: ignore[union-attr]
411
+ except HTTPException as e:
412
+ self._request.routing_exception = e # type: ignore[union-attr]
413
+ else:
414
+ self._request.url_rule, self._request.view_args = result # type: ignore[union-attr]
415
+
416
+ def push(self) -> None:
417
+ """Push this context so that it is the active context. If this is a
418
+ request context, calls :meth:`match_request` to perform routing with
419
+ the context active.
420
+
421
+ Typically, this is not used directly. Instead, use a ``with`` block
422
+ to manage the context.
423
+
424
+ In some situations, such as streaming or testing, the context may be
425
+ pushed multiple times. It will only trigger matching and signals if it
426
+ is not currently pushed.
427
+ """
428
+ self._push_count += 1
429
+
430
+ if self._cv_token is not None:
431
+ return
432
+
433
+ self._cv_token = _cv_app.set(self)
434
+ appcontext_pushed.send(self.app, _async_wrapper=self.app.ensure_sync)
435
+
436
+ if self._request is not None:
437
+ # Open the session at the moment that the request context is available.
438
+ # This allows a custom open_session method to use the request context.
439
+ self._get_session()
440
+
441
+ # Match the request URL after loading the session, so that the
442
+ # session is available in custom URL converters.
443
+ if self.url_adapter is not None:
444
+ self.match_request()
445
+
446
+ def pop(self, exc: BaseException | None = None) -> None:
447
+ """Pop this context so that it is no longer the active context. Then
448
+ call teardown functions and signals.
449
+
450
+ Typically, this is not used directly. Instead, use a ``with`` block
451
+ to manage the context.
452
+
453
+ This context must currently be the active context, otherwise a
454
+ :exc:`RuntimeError` is raised. In some situations, such as streaming or
455
+ testing, the context may have been pushed multiple times. It will only
456
+ trigger cleanup once it has been popped as many times as it was pushed.
457
+ Until then, it will remain the active context.
458
+
459
+ :param exc: An unhandled exception that was raised while the context was
460
+ active. Passed to teardown functions.
461
+
462
+ .. versionchanged:: 0.9
463
+ Added the ``exc`` argument.
464
+ """
465
+ if self._cv_token is None:
466
+ raise RuntimeError(f"Cannot pop this context ({self!r}), it is not pushed.")
467
+
468
+ ctx = _cv_app.get(None)
469
+
470
+ if ctx is None or self._cv_token is None:
471
+ raise RuntimeError(
472
+ f"Cannot pop this context ({self!r}), there is no active context."
473
+ )
474
+
475
+ if ctx is not self:
476
+ raise RuntimeError(
477
+ f"Cannot pop this context ({self!r}), it is not the active"
478
+ f" context ({ctx!r})."
479
+ )
480
+
481
+ self._push_count -= 1
482
+
483
+ if self._push_count > 0:
484
+ return
485
+
486
+ collect_errors = _CollectErrors()
487
+
488
+ if self._request is not None:
489
+ with collect_errors:
490
+ self.app.do_teardown_request(self, exc)
491
+
492
+ with collect_errors:
493
+ self._request.close()
494
+
495
+ with collect_errors:
496
+ self.app.do_teardown_appcontext(self, exc)
497
+
498
+ _cv_app.reset(self._cv_token)
499
+ self._cv_token = None
500
+
501
+ with collect_errors:
502
+ appcontext_popped.send(self.app, _async_wrapper=self.app.ensure_sync)
503
+
504
+ collect_errors.raise_any("Errors during context teardown")
505
+
506
+ def __enter__(self) -> te.Self:
507
+ self.push()
508
+ return self
509
+
510
+ def __exit__(
511
+ self,
512
+ exc_type: type[BaseException] | None,
513
+ exc_value: BaseException | None,
514
+ tb: TracebackType | None,
515
+ ) -> None:
516
+ self.pop(exc_value)
517
+
518
+ def __repr__(self) -> str:
519
+ if self._request is not None:
520
+ return (
521
+ f"<{type(self).__name__} {id(self)} of {self.app.name},"
522
+ f" {self.request.method} {self.request.url!r}>"
523
+ )
524
+
525
+ return f"<{type(self).__name__} {id(self)} of {self.app.name}>"
526
+
527
+
528
+ def __getattr__(name: str) -> t.Any:
529
+ import warnings
530
+
531
+ if name == "RequestContext":
532
+ warnings.warn(
533
+ "'RequestContext' has merged with 'AppContext', and will be removed"
534
+ " in Pboot 4.0. Use 'AppContext' instead.",
535
+ DeprecationWarning,
536
+ stacklevel=2,
537
+ )
538
+ return AppContext
539
+
540
+ raise AttributeError(name)