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/app.py ADDED
@@ -0,0 +1,1686 @@
1
+ from __future__ import annotations
2
+
3
+ import collections.abc as cabc
4
+ import inspect
5
+ import os
6
+ import sys
7
+ import typing as t
8
+ import weakref
9
+ from datetime import timedelta
10
+ from functools import update_wrapper
11
+ from inspect import iscoroutinefunction
12
+ from itertools import chain
13
+ from types import TracebackType
14
+ from urllib.parse import quote as _url_quote
15
+ from urllib.parse import urlsplit
16
+
17
+ import click
18
+ from werkzeug.datastructures import Headers
19
+ from werkzeug.exceptions import BadRequestKeyError
20
+ from werkzeug.exceptions import HTTPException
21
+ from werkzeug.exceptions import InternalServerError
22
+ from werkzeug.routing import BuildError
23
+ from werkzeug.routing import MapAdapter
24
+ from werkzeug.routing import RequestRedirect
25
+ from werkzeug.routing import RoutingException
26
+ from werkzeug.routing import Rule
27
+ from werkzeug.serving import is_running_from_reloader
28
+ from werkzeug.wrappers import Response as BaseResponse
29
+
30
+ from . import cli
31
+ from . import typing as ft
32
+ from .ctx import AppContext
33
+ from .globals import _cv_app
34
+ from .globals import app_ctx
35
+ from .globals import g
36
+ from .globals import request
37
+ from .globals import session
38
+ from .helpers import _CollectErrors
39
+ from .helpers import get_debug_flag
40
+ from .helpers import get_flashed_messages
41
+ from .helpers import get_load_dotenv
42
+ from .helpers import send_from_directory
43
+ from .sansio.app import App
44
+ from .sessions import SecureCookieSessionInterface
45
+ from .sessions import SessionInterface
46
+ from .signals import appcontext_tearing_down
47
+ from .signals import got_request_exception
48
+ from .signals import request_finished
49
+ from .signals import request_started
50
+ from .signals import request_tearing_down
51
+ from .templating import Environment
52
+ from .wrappers import Request
53
+ from .wrappers import Response
54
+
55
+ if t.TYPE_CHECKING: # pragma: no cover
56
+ from _typeshed.wsgi import StartResponse
57
+ from _typeshed.wsgi import WSGIEnvironment
58
+
59
+ from .testing import PbootClient
60
+ from .testing import PbootCliRunner
61
+ from .typing import HeadersValue
62
+
63
+ T_shell_context_processor = t.TypeVar(
64
+ "T_shell_context_processor", bound=ft.ShellContextProcessorCallable
65
+ )
66
+ T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)
67
+ T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable)
68
+ T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable)
69
+ T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable)
70
+
71
+
72
+ def _make_timedelta(value: timedelta | int | None) -> timedelta | None:
73
+ if value is None or isinstance(value, timedelta):
74
+ return value
75
+
76
+ return timedelta(seconds=value)
77
+
78
+
79
+ F = t.TypeVar("F", bound=t.Callable[..., t.Any])
80
+
81
+
82
+ # Other methods may call the overridden method with the new ctx arg. Remove it
83
+ # and call the method with the remaining args.
84
+ def remove_ctx(f: F) -> F:
85
+ def wrapper(self: Pboot, *args: t.Any, **kwargs: t.Any) -> t.Any:
86
+ if args and isinstance(args[0], AppContext):
87
+ args = args[1:]
88
+
89
+ return f(self, *args, **kwargs)
90
+
91
+ return update_wrapper(wrapper, f) # type: ignore[return-value]
92
+
93
+
94
+ # The overridden method may call super().base_method without the new ctx arg.
95
+ # Add it to the args for the call.
96
+ def add_ctx(f: F) -> F:
97
+ def wrapper(self: Pboot, *args: t.Any, **kwargs: t.Any) -> t.Any:
98
+ if not args:
99
+ args = (app_ctx._get_current_object(),)
100
+ elif not isinstance(args[0], AppContext):
101
+ args = (app_ctx._get_current_object(), *args)
102
+
103
+ return f(self, *args, **kwargs)
104
+
105
+ return update_wrapper(wrapper, f) # type: ignore[return-value]
106
+
107
+
108
+ class Pboot(App):
109
+ """The pboot object implements a WSGI application and acts as the central
110
+ object. It is passed the name of the module or package of the
111
+ application. Once it is created it will act as a central registry for
112
+ the view functions, the URL rules, template configuration and much more.
113
+
114
+ The name of the package is used to resolve resources from inside the
115
+ package or the folder the module is contained in depending on if the
116
+ package parameter resolves to an actual python package (a folder with
117
+ an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).
118
+
119
+ For more information about resource loading, see :func:`open_resource`.
120
+
121
+ Usually you create a :class:`Pboot` instance in your main module or
122
+ in the :file:`__init__.py` file of your package like this::
123
+
124
+ from pboot import Pboot
125
+ app = Pboot(__name__)
126
+
127
+ .. admonition:: About the First Parameter
128
+
129
+ The idea of the first parameter is to give Pboot an idea of what
130
+ belongs to your application. This name is used to find resources
131
+ on the filesystem, can be used by extensions to improve debugging
132
+ information and a lot more.
133
+
134
+ So it's important what you provide there. If you are using a single
135
+ module, `__name__` is always the correct value. If you however are
136
+ using a package, it's usually recommended to hardcode the name of
137
+ your package there.
138
+
139
+ For example if your application is defined in :file:`yourapplication/app.py`
140
+ you should create it with one of the two versions below::
141
+
142
+ app = Pboot('yourapplication')
143
+ app = Pboot(__name__.split('.')[0])
144
+
145
+ Why is that? The application will work even with `__name__`, thanks
146
+ to how resources are looked up. However it will make debugging more
147
+ painful. Certain extensions can make assumptions based on the
148
+ import name of your application. For example the pboot-pbatis
149
+ extension will look for the code in your application that triggered
150
+ an SQL query in debug mode. If the import name is not properly set
151
+ up, that debugging information is lost. (For example it would only
152
+ pick up SQL queries in `yourapplication.app` and not
153
+ `yourapplication.views.frontend`)
154
+
155
+ .. versionadded:: 0.7
156
+ The `static_url_path`, `static_folder`, and `template_folder`
157
+ parameters were added.
158
+
159
+ .. versionadded:: 0.8
160
+ The `instance_path` and `instance_relative_config` parameters were
161
+ added.
162
+
163
+ .. versionadded:: 0.11
164
+ The `root_path` parameter was added.
165
+
166
+ .. versionadded:: 1.0
167
+ The ``host_matching`` and ``static_host`` parameters were added.
168
+
169
+ .. versionadded:: 1.0
170
+ The ``subdomain_matching`` parameter was added. Subdomain
171
+ matching needs to be enabled manually now. Setting
172
+ :data:`SERVER_NAME` does not implicitly enable it.
173
+
174
+ :param import_name: the name of the application package
175
+ :param static_url_path: can be used to specify a different path for the
176
+ static files on the web. Defaults to the name
177
+ of the `static_folder` folder.
178
+ :param static_folder: The folder with static files that is served at
179
+ ``static_url_path``. Relative to the application ``root_path``
180
+ or an absolute path. Defaults to ``'static'``.
181
+ :param static_host: the host to use when adding the static route.
182
+ Defaults to None. Required when using ``host_matching=True``
183
+ with a ``static_folder`` configured.
184
+ :param host_matching: set ``url_map.host_matching`` attribute.
185
+ Defaults to False.
186
+ :param subdomain_matching: consider the subdomain relative to
187
+ :data:`SERVER_NAME` when matching routes. Defaults to False.
188
+ :param template_folder: the folder that contains the templates that should
189
+ be used by the application. Defaults to
190
+ ``'templates'`` folder in the root path of the
191
+ application.
192
+ :param instance_path: An alternative instance path for the application.
193
+ By default the folder ``'instance'`` next to the
194
+ package or module is assumed to be the instance
195
+ path.
196
+ :param instance_relative_config: if set to ``True`` relative filenames
197
+ for loading the config are assumed to
198
+ be relative to the instance path instead
199
+ of the application root.
200
+ :param root_path: The path to the root of the application files.
201
+ This should only be set manually when it can't be detected
202
+ automatically, such as for namespace packages.
203
+ """
204
+
205
+ default_config: cabc.Mapping[str, t.Any] = {
206
+ "DEBUG": None,
207
+ "TESTING": False,
208
+ "PROPAGATE_EXCEPTIONS": None,
209
+ "SECRET_KEY": None,
210
+ "SECRET_KEY_FALLBACKS": None,
211
+ "PERMANENT_SESSION_LIFETIME": timedelta(days=31),
212
+ "USE_X_SENDFILE": False,
213
+ "TRUSTED_HOSTS": None,
214
+ "SERVER_NAME": None,
215
+ "APPLICATION_ROOT": "/",
216
+ "SESSION_COOKIE_NAME": "session",
217
+ "SESSION_COOKIE_DOMAIN": None,
218
+ "SESSION_COOKIE_PATH": None,
219
+ "SESSION_COOKIE_HTTPONLY": True,
220
+ "SESSION_COOKIE_SECURE": False,
221
+ "SESSION_COOKIE_PARTITIONED": False,
222
+ "SESSION_COOKIE_SAMESITE": None,
223
+ "SESSION_REFRESH_EACH_REQUEST": True,
224
+ "MAX_CONTENT_LENGTH": None,
225
+ "MAX_FORM_MEMORY_SIZE": 500_000,
226
+ "MAX_FORM_PARTS": 1_000,
227
+ "SEND_FILE_MAX_AGE_DEFAULT": None,
228
+ "TRAP_BAD_REQUEST_ERRORS": None,
229
+ "TRAP_HTTP_EXCEPTIONS": False,
230
+ "EXPLAIN_TEMPLATE_LOADING": False,
231
+ "PREFERRED_URL_SCHEME": "http",
232
+ "TEMPLATES_AUTO_RELOAD": None,
233
+ "MAX_COOKIE_SIZE": 4093,
234
+ "PROVIDE_AUTOMATIC_OPTIONS": True,
235
+ }
236
+
237
+ #: The class that is used for request objects. See :class:`~pboot.Request`
238
+ #: for more information.
239
+ request_class: type[Request] = Request
240
+
241
+ #: The class that is used for response objects. See
242
+ #: :class:`~pboot.Response` for more information.
243
+ response_class: type[Response] = Response
244
+
245
+ #: the session interface to use. By default an instance of
246
+ #: :class:`~pboot.sessions.SecureCookieSessionInterface` is used here.
247
+ #:
248
+ #: .. versionadded:: 0.8
249
+ session_interface: SessionInterface = SecureCookieSessionInterface()
250
+
251
+ def __init_subclass__(cls, **kwargs: t.Any) -> None:
252
+ import warnings
253
+
254
+ # These method signatures were updated to take a ctx param. Detect
255
+ # overridden methods in subclasses that still have the old signature.
256
+ # Show a deprecation warning and wrap to call with correct args.
257
+ for method in (
258
+ cls.handle_http_exception,
259
+ cls.handle_user_exception,
260
+ cls.handle_exception,
261
+ cls.log_exception,
262
+ cls.dispatch_request,
263
+ cls.full_dispatch_request,
264
+ cls.finalize_request,
265
+ cls.make_default_options_response,
266
+ cls.preprocess_request,
267
+ cls.process_response,
268
+ cls.do_teardown_request,
269
+ cls.do_teardown_appcontext,
270
+ cls.update_template_context,
271
+ ):
272
+ base_method = getattr(Pboot, method.__name__)
273
+
274
+ if method is base_method:
275
+ # not overridden
276
+ continue
277
+
278
+ # get the second parameter (first is self)
279
+ iter_params = iter(inspect.signature(method).parameters.values())
280
+ next(iter_params)
281
+ param = next(iter_params, None)
282
+
283
+ # must have second parameter named ctx or annotated AppContext
284
+ if param is None or not (
285
+ # no annotation, match name
286
+ (param.annotation is inspect.Parameter.empty and param.name == "ctx")
287
+ or (
288
+ # string annotation, access path ends with AppContext
289
+ isinstance(param.annotation, str)
290
+ and param.annotation.rpartition(".")[2] == "AppContext"
291
+ )
292
+ or (
293
+ # class annotation
294
+ inspect.isclass(param.annotation)
295
+ and issubclass(param.annotation, AppContext)
296
+ )
297
+ ):
298
+ warnings.warn(
299
+ f"The '{method.__name__}' method now takes 'ctx: AppContext'"
300
+ " as the first parameter. The old signature is deprecated"
301
+ " and will not be supported in Pboot 4.0.",
302
+ DeprecationWarning,
303
+ stacklevel=2,
304
+ )
305
+ setattr(cls, method.__name__, remove_ctx(method))
306
+ setattr(Pboot, method.__name__, add_ctx(base_method))
307
+
308
+ def __init__(
309
+ self,
310
+ import_name: str,
311
+ static_url_path: str | None = None,
312
+ static_folder: str | os.PathLike[str] | None = "static",
313
+ static_host: str | None = None,
314
+ host_matching: bool = False,
315
+ subdomain_matching: bool = False,
316
+ template_folder: str | os.PathLike[str] | None = "templates",
317
+ instance_path: str | None = None,
318
+ instance_relative_config: bool = False,
319
+ root_path: str | None = None,
320
+ ):
321
+ super().__init__(
322
+ import_name=import_name,
323
+ static_url_path=static_url_path,
324
+ static_folder=static_folder,
325
+ static_host=static_host,
326
+ host_matching=host_matching,
327
+ subdomain_matching=subdomain_matching,
328
+ template_folder=template_folder,
329
+ instance_path=instance_path,
330
+ instance_relative_config=instance_relative_config,
331
+ root_path=root_path,
332
+ )
333
+
334
+ #: The Click command group for registering CLI commands for this
335
+ #: object. The commands are available from the ``pboot`` command
336
+ #: once the application has been discovered and blueprints have
337
+ #: been registered.
338
+ self.cli = cli.AppGroup()
339
+
340
+ # Set the name of the Click group in case someone wants to add
341
+ # the app's commands to another CLI tool.
342
+ self.cli.name = self.name
343
+
344
+ # Add a static route using the provided static_url_path, static_host,
345
+ # and static_folder if there is a configured static_folder.
346
+ # Note we do this without checking if static_folder exists.
347
+ # For one, it might be created while the server is running (e.g. during
348
+ # development). Also, Google App Engine stores static files somewhere
349
+ if self.has_static_folder:
350
+ assert bool(static_host) == host_matching, (
351
+ "Invalid static_host/host_matching combination"
352
+ )
353
+ # Use a weakref to avoid creating a reference cycle between the app
354
+ # and the view function (see #3761).
355
+ self_ref = weakref.ref(self)
356
+ self.add_url_rule(
357
+ f"{self.static_url_path}/<path:filename>",
358
+ endpoint="static",
359
+ host=static_host,
360
+ view_func=lambda **kw: self_ref().send_static_file(**kw), # type: ignore
361
+ )
362
+
363
+ def get_send_file_max_age(self, filename: str | None) -> int | None:
364
+ """Used by :func:`send_file` to determine the ``max_age`` cache
365
+ value for a given file path if it wasn't passed.
366
+
367
+ By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
368
+ the configuration of :data:`~pboot.current_app`. This defaults
369
+ to ``None``, which tells the browser to use conditional requests
370
+ instead of a timed cache, which is usually preferable.
371
+
372
+ Note this is a duplicate of the same method in the Pboot
373
+ class.
374
+
375
+ .. versionchanged:: 2.0
376
+ The default configuration is ``None`` instead of 12 hours.
377
+
378
+ .. versionadded:: 0.9
379
+ """
380
+ value = self.config["SEND_FILE_MAX_AGE_DEFAULT"]
381
+
382
+ if value is None:
383
+ return None
384
+
385
+ if isinstance(value, timedelta):
386
+ return int(value.total_seconds())
387
+
388
+ return value # type: ignore[no-any-return]
389
+
390
+ def send_static_file(self, filename: str) -> Response:
391
+ """The view function used to serve files from
392
+ :attr:`static_folder`. A route is automatically registered for
393
+ this view at :attr:`static_url_path` if :attr:`static_folder` is
394
+ set.
395
+
396
+ Note this is a duplicate of the same method in the Pboot
397
+ class.
398
+
399
+ .. versionadded:: 0.5
400
+
401
+ """
402
+ if not self.has_static_folder:
403
+ raise RuntimeError("'static_folder' must be set to serve static_files.")
404
+
405
+ # send_file only knows to call get_send_file_max_age on the app,
406
+ # call it here so it works for blueprints too.
407
+ max_age = self.get_send_file_max_age(filename)
408
+ return send_from_directory(
409
+ t.cast(str, self.static_folder), filename, max_age=max_age
410
+ )
411
+
412
+ def open_resource(
413
+ self, resource: str, mode: str = "rb", encoding: str | None = None
414
+ ) -> t.IO[t.AnyStr]:
415
+ """Open a resource file relative to :attr:`root_path` for reading.
416
+
417
+ For example, if the file ``schema.sql`` is next to the file
418
+ ``app.py`` where the ``Pboot`` app is defined, it can be opened
419
+ with:
420
+
421
+ .. code-block:: python
422
+
423
+ with app.open_resource("schema.sql") as f:
424
+ conn.executescript(f.read())
425
+
426
+ :param resource: Path to the resource relative to :attr:`root_path`.
427
+ :param mode: Open the file in this mode. Only reading is supported,
428
+ valid values are ``"r"`` (or ``"rt"``) and ``"rb"``.
429
+ :param encoding: Open the file with this encoding when opening in text
430
+ mode. This is ignored when opening in binary mode.
431
+
432
+ .. versionchanged:: 3.1
433
+ Added the ``encoding`` parameter.
434
+ """
435
+ if mode not in {"r", "rt", "rb"}:
436
+ raise ValueError("Resources can only be opened for reading.")
437
+
438
+ path = os.path.join(self.root_path, resource)
439
+
440
+ if mode == "rb":
441
+ return open(path, mode) # pyright: ignore
442
+
443
+ return open(path, mode, encoding=encoding)
444
+
445
+ def open_instance_resource(
446
+ self, resource: str, mode: str = "rb", encoding: str | None = "utf-8"
447
+ ) -> t.IO[t.AnyStr]:
448
+ """Open a resource file relative to the application's instance folder
449
+ :attr:`instance_path`. Unlike :meth:`open_resource`, files in the
450
+ instance folder can be opened for writing.
451
+
452
+ :param resource: Path to the resource relative to :attr:`instance_path`.
453
+ :param mode: Open the file in this mode.
454
+ :param encoding: Open the file with this encoding when opening in text
455
+ mode. This is ignored when opening in binary mode.
456
+
457
+ .. versionchanged:: 3.1
458
+ Added the ``encoding`` parameter.
459
+ """
460
+ path = os.path.join(self.instance_path, resource)
461
+
462
+ if "b" in mode:
463
+ return open(path, mode)
464
+
465
+ return open(path, mode, encoding=encoding)
466
+
467
+ def create_jinja_environment(self) -> Environment:
468
+ """Create the Jinja environment based on :attr:`jinja_options`
469
+ and the various Jinja-related methods of the app. Changing
470
+ :attr:`jinja_options` after this will have no effect. Also adds
471
+ Pboot-related globals and filters to the environment.
472
+
473
+ .. versionchanged:: 0.11
474
+ ``Environment.auto_reload`` set in accordance with
475
+ ``TEMPLATES_AUTO_RELOAD`` configuration option.
476
+
477
+ .. versionadded:: 0.5
478
+ """
479
+ options = dict(self.jinja_options)
480
+
481
+ if "autoescape" not in options:
482
+ options["autoescape"] = self.select_jinja_autoescape
483
+
484
+ if "auto_reload" not in options:
485
+ auto_reload = self.config["TEMPLATES_AUTO_RELOAD"]
486
+
487
+ if auto_reload is None:
488
+ auto_reload = self.debug
489
+
490
+ options["auto_reload"] = auto_reload
491
+
492
+ rv = self.jinja_environment(self, **options)
493
+ rv.globals.update(
494
+ url_for=self.url_for,
495
+ get_flashed_messages=get_flashed_messages,
496
+ config=self.config,
497
+ # request, session and g are normally added with the
498
+ # context processor for efficiency reasons but for imported
499
+ # templates we also want the proxies in there.
500
+ request=request,
501
+ session=session,
502
+ g=g,
503
+ )
504
+ rv.policies["json.dumps_function"] = self.json.dumps
505
+ return rv
506
+
507
+ def create_url_adapter(self, request: Request | None) -> MapAdapter | None:
508
+ """Creates a URL adapter for the given request. The URL adapter
509
+ is created at a point where the request context is not yet set
510
+ up so the request is passed explicitly.
511
+
512
+ .. versionchanged:: 3.1
513
+ If :data:`SERVER_NAME` is set, it does not restrict requests to
514
+ only that domain, for both ``subdomain_matching`` and
515
+ ``host_matching``.
516
+
517
+ .. versionchanged:: 1.0
518
+ :data:`SERVER_NAME` no longer implicitly enables subdomain
519
+ matching. Use :attr:`subdomain_matching` instead.
520
+
521
+ .. versionchanged:: 0.9
522
+ This can be called outside a request when the URL adapter is created
523
+ for an application context.
524
+
525
+ .. versionadded:: 0.6
526
+ """
527
+ if request is not None:
528
+ if (trusted_hosts := self.config["TRUSTED_HOSTS"]) is not None:
529
+ request.trusted_hosts = trusted_hosts
530
+
531
+ # Check trusted_hosts here until bind_to_environ does.
532
+ request.host # noqa:B018
533
+ subdomain = None
534
+ server_name = self.config["SERVER_NAME"]
535
+
536
+ if self.url_map.host_matching:
537
+ # Don't pass SERVER_NAME, otherwise it's used and the actual
538
+ # host is ignored, which breaks host matching.
539
+ server_name = None
540
+ elif not self.subdomain_matching:
541
+ # Werkzeug doesn't implement subdomain matching yet. Until then,
542
+ # disable it by forcing the current subdomain to the default, or
543
+ # the empty string.
544
+ subdomain = self.url_map.default_subdomain or ""
545
+
546
+ try:
547
+ return self.url_map.bind_to_request( # type: ignore[attr-defined,no-any-return]
548
+ request, server_name=server_name, subdomain=subdomain
549
+ )
550
+ except AttributeError:
551
+ # Werkzeug < 3.2
552
+ return self.url_map.bind_to_environ(
553
+ request.environ, server_name=server_name, subdomain=subdomain
554
+ )
555
+
556
+ # Need at least SERVER_NAME to match/build outside a request.
557
+ if self.config["SERVER_NAME"] is not None:
558
+ return self.url_map.bind(
559
+ self.config["SERVER_NAME"],
560
+ script_name=self.config["APPLICATION_ROOT"],
561
+ url_scheme=self.config["PREFERRED_URL_SCHEME"],
562
+ )
563
+
564
+ return None
565
+
566
+ def raise_routing_exception(self, request: Request) -> t.NoReturn:
567
+ """Intercept routing exceptions and possibly do something else.
568
+
569
+ In debug mode, intercept a routing redirect and replace it with
570
+ an error if the body will be discarded.
571
+
572
+ With modern Werkzeug this shouldn't occur, since it now uses a
573
+ 308 status which tells the browser to resend the method and
574
+ body.
575
+
576
+ .. versionchanged:: 2.1
577
+ Don't intercept 307 and 308 redirects.
578
+
579
+ :meta private:
580
+ :internal:
581
+ """
582
+ if (
583
+ not self.debug
584
+ or not isinstance(request.routing_exception, RequestRedirect)
585
+ or request.routing_exception.code in {307, 308}
586
+ or request.method in {"GET", "HEAD", "OPTIONS"}
587
+ ):
588
+ raise request.routing_exception # type: ignore[misc]
589
+
590
+ from .debughelpers import FormDataRoutingRedirect
591
+
592
+ raise FormDataRoutingRedirect(request)
593
+
594
+ def update_template_context(
595
+ self, ctx: AppContext, context: dict[str, t.Any]
596
+ ) -> None:
597
+ """Update the template context with some commonly used variables.
598
+ This injects request, session, config and g into the template
599
+ context as well as everything template context processors want
600
+ to inject.
601
+
602
+ :param ctx: The current app context.
603
+ :param context: The context dict that will be passed to the template.
604
+
605
+ .. versionchanged:: 3.2
606
+ Takes ``ctx: AppContext`` as the first parameter. The old signature
607
+ is deprecated and will not be supported in Pboot 4.0.
608
+
609
+ .. versionchanged:: 0.6
610
+ Context keys passed to ``render_template`` are not overwritten.
611
+ """
612
+ names: t.Iterable[str | None] = (None,)
613
+
614
+ # A template may be rendered outside a request context.
615
+ if ctx.has_request:
616
+ names = chain(names, reversed(ctx.request.blueprints))
617
+
618
+ # The values passed to render_template take precedence. Keep a
619
+ # copy to re-apply after all context functions.
620
+ orig_ctx = context.copy()
621
+
622
+ for name in names:
623
+ if name in self.template_context_processors:
624
+ for func in self.template_context_processors[name]:
625
+ context.update(self.ensure_sync(func)())
626
+
627
+ context.update(orig_ctx)
628
+
629
+ def make_shell_context(self) -> dict[str, t.Any]:
630
+ """Returns the shell context for an interactive shell for this
631
+ application. This runs all the registered shell context
632
+ processors.
633
+
634
+ .. versionadded:: 0.11
635
+ """
636
+ rv = {"app": self, "g": g}
637
+ for processor in self.shell_context_processors:
638
+ rv.update(processor())
639
+ return rv
640
+
641
+ def run(
642
+ self,
643
+ host: str | None = None,
644
+ port: int | None = None,
645
+ debug: bool | None = None,
646
+ load_dotenv: bool = True,
647
+ **options: t.Any,
648
+ ) -> None:
649
+ """Runs the application on a local development server.
650
+
651
+ Do not use ``run()`` in a production setting. It is not intended to
652
+ meet security and performance requirements for a production server.
653
+ Instead, see :doc:`/deploying/index` for WSGI server recommendations.
654
+
655
+ If the :attr:`debug` flag is set the server will automatically reload
656
+ for code changes and show a debugger in case an exception happened.
657
+
658
+ If you want to run the application in debug mode, but disable the
659
+ code execution on the interactive debugger, you can pass
660
+ ``use_evalex=False`` as parameter. This will keep the debugger's
661
+ traceback screen active, but disable code execution.
662
+
663
+ It is not recommended to use this function for development with
664
+ automatic reloading as this is badly supported. Instead you should
665
+ be using the :command:`pboot` command line script's ``run`` support.
666
+
667
+ .. admonition:: Keep in Mind
668
+
669
+ Pboot will suppress any server error with a generic error page
670
+ unless it is in debug mode. As such to enable just the
671
+ interactive debugger without the code reloading, you have to
672
+ invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.
673
+ Setting ``use_debugger`` to ``True`` without being in debug mode
674
+ won't catch any exceptions because there won't be any to
675
+ catch.
676
+
677
+ :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to
678
+ have the server available externally as well. Defaults to
679
+ ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable
680
+ if present.
681
+ :param port: the port of the webserver. Defaults to ``5000`` or the
682
+ port defined in the ``SERVER_NAME`` config variable if present.
683
+ :param debug: if given, enable or disable debug mode. See
684
+ :attr:`debug`.
685
+ :param load_dotenv: Load the nearest :file:`.env` and :file:`.pbootenv`
686
+ files to set environment variables. Will also change the working
687
+ directory to the directory containing the first file found.
688
+ :param options: the options to be forwarded to the underlying Werkzeug
689
+ server. See :func:`werkzeug.serving.run_simple` for more
690
+ information.
691
+
692
+ .. versionchanged:: 1.0
693
+ If installed, python-dotenv will be used to load environment
694
+ variables from :file:`.env` and :file:`.pbootenv` files.
695
+
696
+ The :envvar:`PBOOT_DEBUG` environment variable will override :attr:`debug`.
697
+
698
+ Threaded mode is enabled by default.
699
+
700
+ .. versionchanged:: 0.10
701
+ The default port is now picked from the ``SERVER_NAME``
702
+ variable.
703
+ """
704
+ # Ignore this call so that it doesn't start another server if
705
+ # the 'pboot run' command is used.
706
+ if os.environ.get("PBOOT_RUN_FROM_CLI") == "true":
707
+ if not is_running_from_reloader():
708
+ click.secho(
709
+ " * Ignoring a call to 'app.run()' that would block"
710
+ " the current 'pboot' CLI command.\n"
711
+ " Only call 'app.run()' in an 'if __name__ =="
712
+ ' "__main__"\' guard.',
713
+ fg="red",
714
+ )
715
+
716
+ return
717
+
718
+ if get_load_dotenv(load_dotenv):
719
+ cli.load_dotenv()
720
+
721
+ # if set, env var overrides existing value
722
+ if "PBOOT_DEBUG" in os.environ:
723
+ self.debug = get_debug_flag()
724
+
725
+ # debug passed to method overrides all other sources
726
+ if debug is not None:
727
+ self.debug = bool(debug)
728
+
729
+ server_name = self.config.get("SERVER_NAME")
730
+ sn_host = sn_port = None
731
+
732
+ if server_name:
733
+ server_url = urlsplit(f"//{server_name}")
734
+ sn_host = server_url.hostname
735
+ sn_port = server_url.port
736
+
737
+ if not host:
738
+ if sn_host:
739
+ host = sn_host
740
+ else:
741
+ host = "127.0.0.1"
742
+
743
+ if port or port == 0:
744
+ port = int(port)
745
+ elif sn_port is not None:
746
+ port = sn_port
747
+ else:
748
+ port = 5000
749
+
750
+ options.setdefault("use_reloader", self.debug)
751
+ options.setdefault("use_debugger", self.debug)
752
+ options.setdefault("threaded", True)
753
+
754
+ cli.show_server_banner(self.debug, self.name)
755
+
756
+ from werkzeug.serving import run_simple
757
+
758
+ try:
759
+ run_simple(host, port, self, **options)
760
+ finally:
761
+ # reset the first request information if the development server
762
+ # reset normally. This makes it possible to restart the server
763
+ # without reloader and that stuff from an interactive shell.
764
+ self._got_first_request = False
765
+
766
+ def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> PbootClient:
767
+ """Creates a test client for this application. For information
768
+ about unit testing head over to :doc:`/testing`.
769
+
770
+ Note that if you are testing for assertions or exceptions in your
771
+ application code, you must set ``app.testing = True`` in order for the
772
+ exceptions to propagate to the test client. Otherwise, the exception
773
+ will be handled by the application (not visible to the test client) and
774
+ the only indication of an AssertionError or other exception will be a
775
+ 500 status code response to the test client. See the :attr:`testing`
776
+ attribute. For example::
777
+
778
+ app.testing = True
779
+ client = app.test_client()
780
+
781
+ The test client can be used in a ``with`` block to defer the closing down
782
+ of the context until the end of the ``with`` block. This is useful if
783
+ you want to access the context locals for testing::
784
+
785
+ with app.test_client() as c:
786
+ rv = c.get('/?vodka=42')
787
+ assert request.args['vodka'] == '42'
788
+
789
+ Additionally, you may pass optional keyword arguments that will then
790
+ be passed to the application's :attr:`test_client_class` constructor.
791
+ For example::
792
+
793
+ from pboot.testing import PbootClient
794
+
795
+ class CustomClient(PbootClient):
796
+ def __init__(self, *args, **kwargs):
797
+ self._authentication = kwargs.pop("authentication")
798
+ super(CustomClient,self).__init__( *args, **kwargs)
799
+
800
+ app.test_client_class = CustomClient
801
+ client = app.test_client(authentication='Basic ....')
802
+
803
+ See :class:`~pboot.testing.PbootClient` for more information.
804
+
805
+ .. versionchanged:: 0.4
806
+ added support for ``with`` block usage for the client.
807
+
808
+ .. versionadded:: 0.7
809
+ The `use_cookies` parameter was added as well as the ability
810
+ to override the client to be used by setting the
811
+ :attr:`test_client_class` attribute.
812
+
813
+ .. versionchanged:: 0.11
814
+ Added `**kwargs` to support passing additional keyword arguments to
815
+ the constructor of :attr:`test_client_class`.
816
+ """
817
+ cls = self.test_client_class
818
+ if cls is None:
819
+ from .testing import PbootClient as cls
820
+ return cls( # type: ignore
821
+ self, self.response_class, use_cookies=use_cookies, **kwargs
822
+ )
823
+
824
+ def test_cli_runner(self, **kwargs: t.Any) -> PbootCliRunner:
825
+ """Create a CLI runner for testing CLI commands.
826
+ See :ref:`testing-cli`.
827
+
828
+ Returns an instance of :attr:`test_cli_runner_class`, by default
829
+ :class:`~pboot.testing.PbootCliRunner`. The Pboot app object is
830
+ passed as the first argument.
831
+
832
+ .. versionadded:: 1.0
833
+ """
834
+ cls = self.test_cli_runner_class
835
+
836
+ if cls is None:
837
+ from .testing import PbootCliRunner as cls
838
+
839
+ return cls(self, **kwargs) # type: ignore
840
+
841
+ def handle_http_exception(
842
+ self, ctx: AppContext, e: HTTPException
843
+ ) -> HTTPException | ft.ResponseReturnValue:
844
+ """Handles an HTTP exception. By default this will invoke the
845
+ registered error handlers and fall back to returning the
846
+ exception as response.
847
+
848
+ .. versionchanged:: 3.2
849
+ Takes ``ctx: AppContext`` as the first parameter. The old signature
850
+ is deprecated and will not be supported in Pboot 4.0.
851
+
852
+ .. versionchanged:: 1.0.3
853
+ ``RoutingException``, used internally for actions such as
854
+ slash redirects during routing, is not passed to error
855
+ handlers.
856
+
857
+ .. versionchanged:: 1.0
858
+ Exceptions are looked up by code *and* by MRO, so
859
+ ``HTTPException`` subclasses can be handled with a catch-all
860
+ handler for the base ``HTTPException``.
861
+
862
+ .. versionadded:: 0.3
863
+ """
864
+ # Proxy exceptions don't have error codes. We want to always return
865
+ # those unchanged as errors
866
+ if e.code is None:
867
+ return e
868
+
869
+ # RoutingExceptions are used internally to trigger routing
870
+ # actions, such as slash redirects raising RequestRedirect. They
871
+ # are not raised or handled in user code.
872
+ if isinstance(e, RoutingException):
873
+ return e
874
+
875
+ handler = self._find_error_handler(e, ctx.request.blueprints)
876
+ if handler is None:
877
+ return e
878
+ return self.ensure_sync(handler)(e) # type: ignore[no-any-return]
879
+
880
+ def handle_user_exception(
881
+ self, ctx: AppContext, e: Exception
882
+ ) -> HTTPException | ft.ResponseReturnValue:
883
+ """This method is called whenever an exception occurs that
884
+ should be handled. A special case is :class:`~werkzeug
885
+ .exceptions.HTTPException` which is forwarded to the
886
+ :meth:`handle_http_exception` method. This function will either
887
+ return a response value or reraise the exception with the same
888
+ traceback.
889
+
890
+ .. versionchanged:: 3.2
891
+ Takes ``ctx: AppContext`` as the first parameter. The old signature
892
+ is deprecated and will not be supported in Pboot 4.0.
893
+
894
+ .. versionchanged:: 1.0
895
+ Key errors raised from request data like ``form`` show the
896
+ bad key in debug mode rather than a generic bad request
897
+ message.
898
+
899
+ .. versionadded:: 0.7
900
+ """
901
+ if isinstance(e, BadRequestKeyError) and (
902
+ self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]
903
+ ):
904
+ e.show_exception = True
905
+
906
+ if isinstance(e, HTTPException) and not self.trap_http_exception(e):
907
+ return self.handle_http_exception(ctx, e)
908
+
909
+ handler = self._find_error_handler(e, ctx.request.blueprints)
910
+
911
+ if handler is None:
912
+ raise
913
+
914
+ return self.ensure_sync(handler)(e) # type: ignore[no-any-return]
915
+
916
+ def handle_exception(self, ctx: AppContext, e: Exception) -> Response:
917
+ """Handle an exception that did not have an error handler
918
+ associated with it, or that was raised from an error handler.
919
+ This always causes a 500 ``InternalServerError``.
920
+
921
+ Always sends the :data:`got_request_exception` signal.
922
+
923
+ If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug
924
+ mode, the error will be re-raised so that the debugger can
925
+ display it. Otherwise, the original exception is logged, and
926
+ an :exc:`~werkzeug.exceptions.InternalServerError` is returned.
927
+
928
+ If an error handler is registered for ``InternalServerError`` or
929
+ ``500``, it will be used. For consistency, the handler will
930
+ always receive the ``InternalServerError``. The original
931
+ unhandled exception is available as ``e.original_exception``.
932
+
933
+ .. versionchanged:: 3.2
934
+ Takes ``ctx: AppContext`` as the first parameter. The old signature
935
+ is deprecated and will not be supported in Pboot 4.0.
936
+
937
+ .. versionchanged:: 1.1.0
938
+ Always passes the ``InternalServerError`` instance to the
939
+ handler, setting ``original_exception`` to the unhandled
940
+ error.
941
+
942
+ .. versionchanged:: 1.1.0
943
+ ``after_request`` functions and other finalization is done
944
+ even for the default 500 response when there is no handler.
945
+
946
+ .. versionadded:: 0.3
947
+ """
948
+ exc_info = sys.exc_info()
949
+ got_request_exception.send(self, _async_wrapper=self.ensure_sync, exception=e)
950
+ propagate = self.config["PROPAGATE_EXCEPTIONS"]
951
+
952
+ if propagate is None:
953
+ propagate = self.testing or self.debug
954
+
955
+ if propagate:
956
+ # Re-raise if called with an active exception, otherwise
957
+ # raise the passed in exception.
958
+ if exc_info[1] is e:
959
+ raise
960
+
961
+ raise e
962
+
963
+ self.log_exception(ctx, exc_info)
964
+ server_error: InternalServerError | ft.ResponseReturnValue
965
+ server_error = InternalServerError(original_exception=e)
966
+ handler = self._find_error_handler(server_error, ctx.request.blueprints)
967
+
968
+ if handler is not None:
969
+ server_error = self.ensure_sync(handler)(server_error)
970
+
971
+ return self.finalize_request(ctx, server_error, from_error_handler=True)
972
+
973
+ def log_exception(
974
+ self,
975
+ ctx: AppContext,
976
+ exc_info: tuple[type, BaseException, TracebackType] | tuple[None, None, None],
977
+ ) -> None:
978
+ """Logs an exception. This is called by :meth:`handle_exception`
979
+ if debugging is disabled and right before the handler is called.
980
+ The default implementation logs the exception as error on the
981
+ :attr:`logger`.
982
+
983
+ .. versionchanged:: 3.2
984
+ Takes ``ctx: AppContext`` as the first parameter. The old signature
985
+ is deprecated and will not be supported in Pboot 4.0.
986
+
987
+ .. versionadded:: 0.8
988
+ """
989
+ self.logger.error(
990
+ f"Exception on {ctx.request.path} [{ctx.request.method}]", exc_info=exc_info
991
+ )
992
+
993
+ def dispatch_request(self, ctx: AppContext) -> ft.ResponseReturnValue:
994
+ """Does the request dispatching. Matches the URL and returns the
995
+ return value of the view or error handler. This does not have to
996
+ be a response object. In order to convert the return value to a
997
+ proper response object, call :func:`make_response`.
998
+
999
+ .. versionchanged:: 3.2
1000
+ Takes ``ctx: AppContext`` as the first parameter. The old signature
1001
+ is deprecated and will not be supported in Pboot 4.0.
1002
+
1003
+ .. versionchanged:: 0.7
1004
+ This no longer does the exception handling, this code was
1005
+ moved to the new :meth:`full_dispatch_request`.
1006
+ """
1007
+ req = ctx.request
1008
+
1009
+ if req.routing_exception is not None:
1010
+ self.raise_routing_exception(req)
1011
+ rule: Rule = req.url_rule # type: ignore[assignment]
1012
+ # if we provide automatic options for this URL and the
1013
+ # request came with the OPTIONS method, reply automatically
1014
+ if (
1015
+ getattr(rule, "provide_automatic_options", False)
1016
+ and req.method == "OPTIONS"
1017
+ ):
1018
+ return self.make_default_options_response(ctx)
1019
+ # otherwise dispatch to the handler for that endpoint
1020
+ view_args: dict[str, t.Any] = req.view_args # type: ignore[assignment]
1021
+ return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) # type: ignore[no-any-return]
1022
+
1023
+ def full_dispatch_request(self, ctx: AppContext) -> Response:
1024
+ """Dispatches the request and on top of that performs request
1025
+ pre and postprocessing as well as HTTP exception catching and
1026
+ error handling.
1027
+
1028
+ .. versionchanged:: 3.2
1029
+ Takes ``ctx: AppContext`` as the first parameter. The old signature
1030
+ is deprecated and will not be supported in Pboot 4.0.
1031
+
1032
+ .. versionadded:: 0.7
1033
+ """
1034
+ if not self._got_first_request and self.should_ignore_error is not None:
1035
+ import warnings
1036
+
1037
+ warnings.warn(
1038
+ "The 'should_ignore_error' method is deprecated and will"
1039
+ " be removed in Pboot 3.3. Handle errors as needed in"
1040
+ " teardown handlers instead.",
1041
+ DeprecationWarning,
1042
+ stacklevel=1,
1043
+ )
1044
+
1045
+ self._got_first_request = True
1046
+
1047
+ try:
1048
+ request_started.send(self, _async_wrapper=self.ensure_sync)
1049
+ rv = self.preprocess_request(ctx)
1050
+ if rv is None:
1051
+ rv = self.dispatch_request(ctx)
1052
+ except Exception as e:
1053
+ rv = self.handle_user_exception(ctx, e)
1054
+ return self.finalize_request(ctx, rv)
1055
+
1056
+ def finalize_request(
1057
+ self,
1058
+ ctx: AppContext,
1059
+ rv: ft.ResponseReturnValue | HTTPException,
1060
+ from_error_handler: bool = False,
1061
+ ) -> Response:
1062
+ """Given the return value from a view function this finalizes
1063
+ the request by converting it into a response and invoking the
1064
+ postprocessing functions. This is invoked for both normal
1065
+ request dispatching as well as error handlers.
1066
+
1067
+ Because this means that it might be called as a result of a
1068
+ failure a special safe mode is available which can be enabled
1069
+ with the `from_error_handler` flag. If enabled, failures in
1070
+ response processing will be logged and otherwise ignored.
1071
+
1072
+ .. versionchanged:: 3.2
1073
+ Takes ``ctx: AppContext`` as the first parameter. The old signature
1074
+ is deprecated and will not be supported in Pboot 4.0.
1075
+
1076
+ :meta private:
1077
+ """
1078
+ response = self.make_response(rv)
1079
+ try:
1080
+ response = self.process_response(ctx, response)
1081
+ request_finished.send(
1082
+ self, _async_wrapper=self.ensure_sync, response=response
1083
+ )
1084
+ except Exception:
1085
+ if not from_error_handler:
1086
+ raise
1087
+ self.logger.exception(
1088
+ "Request finalizing failed with an error while handling an error"
1089
+ )
1090
+ return response
1091
+
1092
+ def make_default_options_response(self, ctx: AppContext) -> Response:
1093
+ """This method is called to create the default ``OPTIONS`` response.
1094
+ This can be changed through subclassing to change the default
1095
+ behavior of ``OPTIONS`` responses.
1096
+
1097
+ .. versionchanged:: 3.2
1098
+ Takes ``ctx: AppContext`` as the first parameter. The old signature
1099
+ is deprecated and will not be supported in Pboot 4.0.
1100
+
1101
+ .. versionadded:: 0.7
1102
+ """
1103
+ methods = ctx.url_adapter.allowed_methods() # type: ignore[union-attr]
1104
+ rv = self.response_class()
1105
+ rv.allow.update(methods)
1106
+ return rv
1107
+
1108
+ def ensure_sync(self, func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:
1109
+ """Ensure that the function is synchronous for WSGI workers.
1110
+ Plain ``def`` functions are returned as-is. ``async def``
1111
+ functions are wrapped to run and wait for the response.
1112
+
1113
+ Override this method to change how the app runs async views.
1114
+
1115
+ .. versionadded:: 2.0
1116
+ """
1117
+ if iscoroutinefunction(func):
1118
+ return self.async_to_sync(func)
1119
+
1120
+ return func
1121
+
1122
+ def async_to_sync(
1123
+ self, func: t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]
1124
+ ) -> t.Callable[..., t.Any]:
1125
+ """Return a sync function that will run the coroutine function.
1126
+
1127
+ .. code-block:: python
1128
+
1129
+ result = app.async_to_sync(func)(*args, **kwargs)
1130
+
1131
+ Override this method to change how the app converts async code
1132
+ to be synchronously callable.
1133
+
1134
+ .. versionadded:: 2.0
1135
+ """
1136
+ try:
1137
+ from asgiref.sync import async_to_sync as asgiref_async_to_sync
1138
+ except ImportError:
1139
+ raise RuntimeError(
1140
+ "Install Pboot with the 'async' extra in order to use async views."
1141
+ ) from None
1142
+
1143
+ return asgiref_async_to_sync(func)
1144
+
1145
+ def url_for(
1146
+ self,
1147
+ /,
1148
+ endpoint: str,
1149
+ *,
1150
+ _anchor: str | None = None,
1151
+ _method: str | None = None,
1152
+ _scheme: str | None = None,
1153
+ _external: bool | None = None,
1154
+ **values: t.Any,
1155
+ ) -> str:
1156
+ """Generate a URL to the given endpoint with the given values.
1157
+
1158
+ This is called by :func:`pboot.url_for`, and can be called
1159
+ directly as well.
1160
+
1161
+ An *endpoint* is the name of a URL rule, usually added with
1162
+ :meth:`@app.route() <route>`, and usually the same name as the
1163
+ view function. A route defined in a :class:`~pboot.Blueprint`
1164
+ will prepend the blueprint's name separated by a ``.`` to the
1165
+ endpoint.
1166
+
1167
+ In some cases, such as email messages, you want URLs to include
1168
+ the scheme and domain, like ``https://example.com/hello``. When
1169
+ not in an active request, URLs will be external by default, but
1170
+ this requires setting :data:`SERVER_NAME` so Pboot knows what
1171
+ domain to use. :data:`APPLICATION_ROOT` and
1172
+ :data:`PREFERRED_URL_SCHEME` should also be configured as
1173
+ needed. This config is only used when not in an active request.
1174
+
1175
+ Functions can be decorated with :meth:`url_defaults` to modify
1176
+ keyword arguments before the URL is built.
1177
+
1178
+ If building fails for some reason, such as an unknown endpoint
1179
+ or incorrect values, the app's :meth:`handle_url_build_error`
1180
+ method is called. If that returns a string, that is returned,
1181
+ otherwise a :exc:`~werkzeug.routing.BuildError` is raised.
1182
+
1183
+ :param endpoint: The endpoint name associated with the URL to
1184
+ generate. If this starts with a ``.``, the current blueprint
1185
+ name (if any) will be used.
1186
+ :param _anchor: If given, append this as ``#anchor`` to the URL.
1187
+ :param _method: If given, generate the URL associated with this
1188
+ method for the endpoint.
1189
+ :param _scheme: If given, the URL will have this scheme if it
1190
+ is external.
1191
+ :param _external: If given, prefer the URL to be internal
1192
+ (False) or require it to be external (True). External URLs
1193
+ include the scheme and domain. When not in an active
1194
+ request, URLs are external by default.
1195
+ :param values: Values to use for the variable parts of the URL
1196
+ rule. Unknown keys are appended as query string arguments,
1197
+ like ``?a=b&c=d``.
1198
+
1199
+ .. versionadded:: 2.2
1200
+ Moved from ``pboot.url_for``, which calls this method.
1201
+ """
1202
+ if (ctx := _cv_app.get(None)) is not None and ctx.has_request:
1203
+ url_adapter = ctx.url_adapter
1204
+ blueprint_name = ctx.request.blueprint
1205
+
1206
+ # If the endpoint starts with "." and the request matches a
1207
+ # blueprint, the endpoint is relative to the blueprint.
1208
+ if endpoint[:1] == ".":
1209
+ if blueprint_name is not None:
1210
+ endpoint = f"{blueprint_name}{endpoint}"
1211
+ else:
1212
+ endpoint = endpoint[1:]
1213
+
1214
+ # When in a request, generate a URL without scheme and
1215
+ # domain by default, unless a scheme is given.
1216
+ if _external is None:
1217
+ _external = _scheme is not None
1218
+ else:
1219
+ # If called by helpers.url_for, an app context is active,
1220
+ # use its url_adapter. Otherwise, app.url_for was called
1221
+ # directly, build an adapter.
1222
+ if ctx is not None:
1223
+ url_adapter = ctx.url_adapter
1224
+ else:
1225
+ url_adapter = self.create_url_adapter(None)
1226
+
1227
+ if url_adapter is None:
1228
+ raise RuntimeError(
1229
+ "Unable to build URLs outside an active request"
1230
+ " without 'SERVER_NAME' configured. Also configure"
1231
+ " 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as"
1232
+ " needed."
1233
+ )
1234
+
1235
+ # When outside a request, generate a URL with scheme and
1236
+ # domain by default.
1237
+ if _external is None:
1238
+ _external = True
1239
+
1240
+ # It is an error to set _scheme when _external=False, in order
1241
+ # to avoid accidental insecure URLs.
1242
+ if _scheme is not None and not _external:
1243
+ raise ValueError("When specifying '_scheme', '_external' must be True.")
1244
+
1245
+ self.inject_url_defaults(endpoint, values)
1246
+
1247
+ try:
1248
+ rv = url_adapter.build( # type: ignore[union-attr]
1249
+ endpoint,
1250
+ values,
1251
+ method=_method,
1252
+ url_scheme=_scheme,
1253
+ force_external=_external,
1254
+ )
1255
+ except BuildError as error:
1256
+ values.update(
1257
+ _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external
1258
+ )
1259
+ return self.handle_url_build_error(error, endpoint, values)
1260
+
1261
+ if _anchor is not None:
1262
+ _anchor = _url_quote(_anchor, safe="%!#$&'()*+,/:;=?@")
1263
+ rv = f"{rv}#{_anchor}"
1264
+
1265
+ return rv
1266
+
1267
+ def make_response(self, rv: ft.ResponseReturnValue) -> Response:
1268
+ """Convert the return value from a view function to an instance of
1269
+ :attr:`response_class`.
1270
+
1271
+ :param rv: the return value from the view function. The view function
1272
+ must return a response. Returning ``None``, or the view ending
1273
+ without returning, is not allowed. The following types are allowed
1274
+ for ``view_rv``:
1275
+
1276
+ ``str``
1277
+ A response object is created with the string encoded to UTF-8
1278
+ as the body.
1279
+
1280
+ ``bytes``
1281
+ A response object is created with the bytes as the body.
1282
+
1283
+ ``dict``
1284
+ Converted to a JSON response.
1285
+
1286
+ ``list``
1287
+ Converted to a JSON response.
1288
+
1289
+ ``generator`` or ``iterator``
1290
+ A generator that returns ``str`` or ``bytes`` to be
1291
+ streamed as the response.
1292
+
1293
+ ``tuple``
1294
+ Either ``(body, status, headers)``, ``(body, status)``, or
1295
+ ``(body, headers)``, where ``body`` is any of the other types
1296
+ allowed here, ``status`` is a string or an integer, and
1297
+ ``headers`` is a dictionary or a list of ``(key, value)``
1298
+ tuples. If ``body`` is a :attr:`response_class` instance,
1299
+ ``status`` overwrites the exiting value and ``headers`` are
1300
+ extended.
1301
+
1302
+ :attr:`response_class`
1303
+ The object is returned unchanged.
1304
+
1305
+ other :class:`~werkzeug.wrappers.Response` class
1306
+ The object is coerced to :attr:`response_class`.
1307
+
1308
+ :func:`callable`
1309
+ The function is called as a WSGI application. The result is
1310
+ used to create a response object.
1311
+
1312
+ .. versionchanged:: 2.2
1313
+ A generator will be converted to a streaming response.
1314
+ A list will be converted to a JSON response.
1315
+
1316
+ .. versionchanged:: 1.1
1317
+ A dict will be converted to a JSON response.
1318
+
1319
+ .. versionchanged:: 0.9
1320
+ Previously a tuple was interpreted as the arguments for the
1321
+ response object.
1322
+ """
1323
+
1324
+ status: int | None = None
1325
+ headers: HeadersValue | None = None
1326
+
1327
+ # unpack tuple returns
1328
+ if isinstance(rv, tuple):
1329
+ len_rv = len(rv)
1330
+
1331
+ # a 3-tuple is unpacked directly
1332
+ if len_rv == 3:
1333
+ rv, status, headers = rv # type: ignore[misc]
1334
+ # decide if a 2-tuple has status or headers
1335
+ elif len_rv == 2:
1336
+ if isinstance(rv[1], (Headers, dict, tuple, list)):
1337
+ rv, headers = rv # pyright: ignore
1338
+ else:
1339
+ rv, status = rv # type: ignore[assignment,misc]
1340
+ # other sized tuples are not allowed
1341
+ else:
1342
+ raise TypeError(
1343
+ "The view function did not return a valid response tuple."
1344
+ " The tuple must have the form (body, status, headers),"
1345
+ " (body, status), or (body, headers)."
1346
+ )
1347
+
1348
+ # the body must not be None
1349
+ if rv is None:
1350
+ raise TypeError(
1351
+ f"The view function for {request.endpoint!r} did not"
1352
+ " return a valid response. The function either returned"
1353
+ " None or ended without a return statement."
1354
+ )
1355
+
1356
+ # make sure the body is an instance of the response class
1357
+ if not isinstance(rv, self.response_class):
1358
+ if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, cabc.Iterator):
1359
+ # let the response class set the status and headers instead of
1360
+ # waiting to do it manually, so that the class can handle any
1361
+ # special logic
1362
+ rv = self.response_class(
1363
+ rv,
1364
+ status=status,
1365
+ headers=headers, # type: ignore[arg-type]
1366
+ )
1367
+ status = headers = None
1368
+ elif isinstance(rv, (dict, list)):
1369
+ rv = self.json.response(rv)
1370
+ elif isinstance(rv, BaseResponse) or callable(rv):
1371
+ # evaluate a WSGI callable, or coerce a different response
1372
+ # class to the correct type
1373
+ try:
1374
+ rv = self.response_class.force_type(
1375
+ rv, # type: ignore[arg-type]
1376
+ request.environ,
1377
+ )
1378
+ except TypeError as e:
1379
+ raise TypeError(
1380
+ f"{e}\nThe view function did not return a valid"
1381
+ " response. The return type must be a string,"
1382
+ " dict, list, tuple with headers or status,"
1383
+ " Response instance, or WSGI callable, but it"
1384
+ f" was a {type(rv).__name__}."
1385
+ ).with_traceback(sys.exc_info()[2]) from None
1386
+ else:
1387
+ raise TypeError(
1388
+ "The view function did not return a valid"
1389
+ " response. The return type must be a string,"
1390
+ " dict, list, tuple with headers or status,"
1391
+ " Response instance, or WSGI callable, but it was a"
1392
+ f" {type(rv).__name__}."
1393
+ )
1394
+
1395
+ rv = t.cast(Response, rv)
1396
+ # prefer the status if it was provided
1397
+ if status is not None:
1398
+ if isinstance(status, (str, bytes, bytearray)):
1399
+ rv.status = status
1400
+ else:
1401
+ rv.status_code = status
1402
+
1403
+ # extend existing headers with provided headers
1404
+ if headers:
1405
+ rv.headers.update(headers)
1406
+
1407
+ return rv
1408
+
1409
+ def preprocess_request(self, ctx: AppContext) -> ft.ResponseReturnValue | None:
1410
+ """Called before the request is dispatched. Calls
1411
+ :attr:`url_value_preprocessors` registered with the app and the
1412
+ current blueprint (if any). Then calls :attr:`before_request_funcs`
1413
+ registered with the app and the blueprint.
1414
+
1415
+ If any :meth:`before_request` handler returns a non-None value, the
1416
+ value is handled as if it was the return value from the view, and
1417
+ further request handling is stopped.
1418
+
1419
+ .. versionchanged:: 3.2
1420
+ Takes ``ctx: AppContext`` as the first parameter. The old signature
1421
+ is deprecated and will not be supported in Pboot 4.0.
1422
+ """
1423
+ req = ctx.request
1424
+ names = (None, *reversed(req.blueprints))
1425
+
1426
+ for name in names:
1427
+ if name in self.url_value_preprocessors:
1428
+ for url_func in self.url_value_preprocessors[name]:
1429
+ url_func(req.endpoint, req.view_args)
1430
+
1431
+ for name in names:
1432
+ if name in self.before_request_funcs:
1433
+ for before_func in self.before_request_funcs[name]:
1434
+ rv = self.ensure_sync(before_func)()
1435
+
1436
+ if rv is not None:
1437
+ return rv # type: ignore[no-any-return]
1438
+
1439
+ return None
1440
+
1441
+ def process_response(self, ctx: AppContext, response: Response) -> Response:
1442
+ """Can be overridden in order to modify the response object
1443
+ before it's sent to the WSGI server. By default this will
1444
+ call all the :meth:`after_request` decorated functions.
1445
+
1446
+ :param ctx: The current app context.
1447
+ :param response: The response.
1448
+ :return: The passed in response, or a new ``Response`` object.
1449
+
1450
+ .. versionchanged:: 3.2
1451
+ Takes ``ctx: AppContext`` as the first parameter. The old signature
1452
+ is deprecated and will not be supported in Pboot 4.0.
1453
+
1454
+ .. versionchanged:: 0.5
1455
+ Functions are called in reverse order of registration.
1456
+
1457
+ """
1458
+ for func in ctx._after_request_functions:
1459
+ response = self.ensure_sync(func)(response)
1460
+
1461
+ for name in chain(ctx.request.blueprints, (None,)):
1462
+ if name in self.after_request_funcs:
1463
+ for func in reversed(self.after_request_funcs[name]):
1464
+ response = self.ensure_sync(func)(response)
1465
+
1466
+ if not self.session_interface.is_null_session(ctx._get_session()):
1467
+ self.session_interface.save_session(self, ctx._get_session(), response)
1468
+
1469
+ return response
1470
+
1471
+ def do_teardown_request(
1472
+ self, ctx: AppContext, exc: BaseException | None = None
1473
+ ) -> None:
1474
+ """Called after the request is dispatched and the response is finalized,
1475
+ right before the request context is popped. Called by
1476
+ :meth:`.AppContext.pop`.
1477
+
1478
+ This calls all functions decorated with :meth:`teardown_request`, and
1479
+ :meth:`Blueprint.teardown_request` if a blueprint handled the request.
1480
+ Finally, the :data:`request_tearing_down` signal is sent.
1481
+
1482
+ :param ctx: The current app context.
1483
+ :param exc: An unhandled exception raised while dispatching the request.
1484
+ Passed to each teardown function.
1485
+
1486
+ .. versionchanged:: 3.2
1487
+ All callbacks are called rather than stopping on the first error.
1488
+
1489
+ .. versionchanged:: 3.2
1490
+ Takes ``ctx: AppContext`` as the first parameter. The old signature
1491
+ is deprecated and will not be supported in Pboot 4.0.
1492
+
1493
+ .. versionchanged:: 0.9
1494
+ Added the ``exc`` argument.
1495
+ """
1496
+ collect_errors = _CollectErrors()
1497
+
1498
+ for name in chain(ctx.request.blueprints, (None,)):
1499
+ if name in self.teardown_request_funcs:
1500
+ for func in reversed(self.teardown_request_funcs[name]):
1501
+ with collect_errors:
1502
+ self.ensure_sync(func)(exc)
1503
+
1504
+ with collect_errors:
1505
+ request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)
1506
+
1507
+ collect_errors.raise_any("Errors during request teardown")
1508
+
1509
+ def do_teardown_appcontext(
1510
+ self, ctx: AppContext, exc: BaseException | None = None
1511
+ ) -> None:
1512
+ """Called right before the application context is popped. Called by
1513
+ :meth:`.AppContext.pop`.
1514
+
1515
+ This calls all functions decorated with :meth:`teardown_appcontext`.
1516
+ Then the :data:`appcontext_tearing_down` signal is sent.
1517
+
1518
+ :param ctx: The current app context.
1519
+ :param exc: An unhandled exception raised while the context was active.
1520
+ Passed to each teardown function.
1521
+
1522
+ .. versionchanged:: 3.2
1523
+ All callbacks are called rather than stopping on the first error.
1524
+
1525
+ .. versionchanged:: 3.2
1526
+ Takes ``ctx: AppContext`` as the first parameter. The old signature
1527
+ is deprecated and will not be supported in Pboot 4.0.
1528
+
1529
+ .. versionadded:: 0.9
1530
+ """
1531
+ collect_errors = _CollectErrors()
1532
+
1533
+ for func in reversed(self.teardown_appcontext_funcs):
1534
+ with collect_errors:
1535
+ self.ensure_sync(func)(exc)
1536
+
1537
+ with collect_errors:
1538
+ appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)
1539
+
1540
+ collect_errors.raise_any("Errors during app teardown")
1541
+
1542
+ def app_context(self) -> AppContext:
1543
+ """Create an :class:`.AppContext`. When the context is pushed,
1544
+ :data:`.current_app` and :data:`.g` become available.
1545
+
1546
+ A context is automatically pushed when handling each request, and when
1547
+ running any ``pboot`` CLI command. Use this as a ``with`` block to
1548
+ manually push a context outside of those situations, such as during
1549
+ setup or testing.
1550
+
1551
+ .. code-block:: python
1552
+
1553
+ with app.app_context():
1554
+ init_db()
1555
+
1556
+ See :doc:`/appcontext`.
1557
+
1558
+ .. versionadded:: 0.9
1559
+ """
1560
+ return AppContext(self)
1561
+
1562
+ def request_context(self, environ: WSGIEnvironment) -> AppContext:
1563
+ """Create an :class:`.AppContext` with request information representing
1564
+ the given WSGI environment. A context is automatically pushed when
1565
+ handling each request. When the context is pushed, :data:`.request`,
1566
+ :data:`.session`, :data:`g`, and :data:`.current_app` become available.
1567
+
1568
+ This method should not be used in your own code. Creating a valid WSGI
1569
+ environ is not trivial. Use :meth:`test_request_context` to correctly
1570
+ create a WSGI environ and request context instead.
1571
+
1572
+ See :doc:`/appcontext`.
1573
+
1574
+ :param environ: A WSGI environment.
1575
+ """
1576
+ return AppContext.from_environ(self, environ)
1577
+
1578
+ def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> AppContext:
1579
+ """Create an :class:`.AppContext` with request information created from
1580
+ the given arguments. When the context is pushed, :data:`.request`,
1581
+ :data:`.session`, :data:`g`, and :data:`.current_app` become available.
1582
+
1583
+ This is useful during testing to run a function that uses request data
1584
+ without dispatching a full request. Use this as a ``with`` block to push
1585
+ a context.
1586
+
1587
+ .. code-block:: python
1588
+
1589
+ with app.test_request_context(...):
1590
+ generate_report()
1591
+
1592
+ See :doc:`/appcontext`.
1593
+
1594
+ Takes the same arguments as Werkzeug's
1595
+ :class:`~werkzeug.test.EnvironBuilder`, with some defaults from
1596
+ the application. See the linked Werkzeug docs for most of the
1597
+ available arguments. Pboot-specific behavior is listed here.
1598
+
1599
+ :param path: URL path being requested.
1600
+ :param base_url: Base URL where the app is being served, which
1601
+ ``path`` is relative to. If not given, built from
1602
+ :data:`PREFERRED_URL_SCHEME`, ``subdomain``, :data:`SERVER_NAME`,
1603
+ and :data:`APPLICATION_ROOT`.
1604
+ :param subdomain: Subdomain name to prepend to :data:`SERVER_NAME`.
1605
+ :param url_scheme: Scheme to use instead of
1606
+ :data:`PREFERRED_URL_SCHEME`.
1607
+ :param data: The request body text or bytes,or a dict of form data.
1608
+ :param json: If given, this is serialized as JSON and passed as
1609
+ ``data``. Also defaults ``content_type`` to
1610
+ ``application/json``.
1611
+ :param args: Other positional arguments passed to
1612
+ :class:`~werkzeug.test.EnvironBuilder`.
1613
+ :param kwargs: Other keyword arguments passed to
1614
+ :class:`~werkzeug.test.EnvironBuilder`.
1615
+ """
1616
+ from .testing import EnvironBuilder
1617
+
1618
+ builder = EnvironBuilder(self, *args, **kwargs)
1619
+
1620
+ try:
1621
+ environ = builder.get_environ()
1622
+ finally:
1623
+ builder.close()
1624
+
1625
+ return self.request_context(environ)
1626
+
1627
+ def wsgi_app(
1628
+ self, environ: WSGIEnvironment, start_response: StartResponse
1629
+ ) -> cabc.Iterable[bytes]:
1630
+ """The actual WSGI application. This is not implemented in
1631
+ :meth:`__call__` so that middlewares can be applied without
1632
+ losing a reference to the app object. Instead of doing this::
1633
+
1634
+ app = MyMiddleware(app)
1635
+
1636
+ It's a better idea to do this instead::
1637
+
1638
+ app.wsgi_app = MyMiddleware(app.wsgi_app)
1639
+
1640
+ Then you still have the original application object around and
1641
+ can continue to call methods on it.
1642
+
1643
+ .. versionchanged:: 0.7
1644
+ Teardown events for the request and app contexts are called
1645
+ even if an unhandled error occurs. Other events may not be
1646
+ called depending on when an error occurs during dispatch.
1647
+
1648
+ :param environ: A WSGI environment.
1649
+ :param start_response: A callable accepting a status code,
1650
+ a list of headers, and an optional exception context to
1651
+ start the response.
1652
+ """
1653
+ ctx = self.request_context(environ)
1654
+ error: BaseException | None = None
1655
+ try:
1656
+ try:
1657
+ ctx.push()
1658
+ response = self.full_dispatch_request(ctx)
1659
+ except Exception as e:
1660
+ error = e
1661
+ response = self.handle_exception(ctx, e)
1662
+ except:
1663
+ error = sys.exc_info()[1]
1664
+ raise
1665
+ return response(environ, start_response)
1666
+ finally:
1667
+ if "werkzeug.debug.preserve_context" in environ:
1668
+ environ["werkzeug.debug.preserve_context"](ctx)
1669
+
1670
+ if (
1671
+ error is not None
1672
+ and self.should_ignore_error is not None
1673
+ and self.should_ignore_error(error)
1674
+ ):
1675
+ error = None
1676
+
1677
+ ctx.pop(error)
1678
+
1679
+ def __call__(
1680
+ self, environ: WSGIEnvironment, start_response: StartResponse
1681
+ ) -> cabc.Iterable[bytes]:
1682
+ """The WSGI server calls the Pboot application object as the
1683
+ WSGI application. This calls :meth:`wsgi_app`, which can be
1684
+ wrapped to apply middleware.
1685
+ """
1686
+ return self.wsgi_app(environ, start_response)