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/sansio/app.py ADDED
@@ -0,0 +1,1014 @@
1
+ from __future__ import annotations
2
+
3
+ import collections.abc as cabc
4
+ import logging
5
+ import os
6
+ import sys
7
+ import typing as t
8
+ from datetime import timedelta
9
+ from itertools import chain
10
+
11
+ from werkzeug.exceptions import Aborter
12
+ from werkzeug.exceptions import BadRequest
13
+ from werkzeug.exceptions import BadRequestKeyError
14
+ from werkzeug.routing import BuildError
15
+ from werkzeug.routing import Map
16
+ from werkzeug.routing import Rule
17
+ from werkzeug.sansio.response import Response
18
+ from werkzeug.utils import cached_property
19
+ from werkzeug.utils import redirect as _wz_redirect
20
+
21
+ from .. import typing as ft
22
+ from ..config import Config
23
+ from ..config import ConfigAttribute
24
+ from ..ctx import _AppCtxGlobals
25
+ from ..helpers import _split_blueprint_path
26
+ from ..helpers import get_debug_flag
27
+ from ..json.provider import DefaultJSONProvider
28
+ from ..json.provider import JSONProvider
29
+ from ..logging import create_logger
30
+ from ..templating import DispatchingJinjaLoader
31
+ from ..templating import Environment
32
+ from .scaffold import _endpoint_from_view_func
33
+ from .scaffold import find_package
34
+ from .scaffold import Scaffold
35
+ from .scaffold import setupmethod
36
+
37
+ if t.TYPE_CHECKING: # pragma: no cover
38
+ from werkzeug.wrappers import Response as BaseResponse
39
+
40
+ from ..testing import PbootClient
41
+ from ..testing import PbootCliRunner
42
+ from .blueprints import Blueprint
43
+
44
+ T_shell_context_processor = t.TypeVar(
45
+ "T_shell_context_processor", bound=ft.ShellContextProcessorCallable
46
+ )
47
+ T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)
48
+ T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable)
49
+ T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable)
50
+ T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable)
51
+
52
+
53
+ def _make_timedelta(value: timedelta | int | None) -> timedelta | None:
54
+ if value is None or isinstance(value, timedelta):
55
+ return value
56
+
57
+ return timedelta(seconds=value)
58
+
59
+
60
+ class App(Scaffold):
61
+ """The pboot object implements a WSGI application and acts as the central
62
+ object. It is passed the name of the module or package of the
63
+ application. Once it is created it will act as a central registry for
64
+ the view functions, the URL rules, template configuration and much more.
65
+
66
+ The name of the package is used to resolve resources from inside the
67
+ package or the folder the module is contained in depending on if the
68
+ package parameter resolves to an actual python package (a folder with
69
+ an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).
70
+
71
+ For more information about resource loading, see :func:`open_resource`.
72
+
73
+ Usually you create a :class:`Pboot` instance in your main module or
74
+ in the :file:`__init__.py` file of your package like this::
75
+
76
+ from pboot import Pboot
77
+ app = Pboot(__name__)
78
+
79
+ .. admonition:: About the First Parameter
80
+
81
+ The idea of the first parameter is to give Pboot an idea of what
82
+ belongs to your application. This name is used to find resources
83
+ on the filesystem, can be used by extensions to improve debugging
84
+ information and a lot more.
85
+
86
+ So it's important what you provide there. If you are using a single
87
+ module, `__name__` is always the correct value. If you however are
88
+ using a package, it's usually recommended to hardcode the name of
89
+ your package there.
90
+
91
+ For example if your application is defined in :file:`yourapplication/app.py`
92
+ you should create it with one of the two versions below::
93
+
94
+ app = Pboot('yourapplication')
95
+ app = Pboot(__name__.split('.')[0])
96
+
97
+ Why is that? The application will work even with `__name__`, thanks
98
+ to how resources are looked up. However it will make debugging more
99
+ painful. Certain extensions can make assumptions based on the
100
+ import name of your application. For example the pboot-pbatis
101
+ extension will look for the code in your application that triggered
102
+ an SQL query in debug mode. If the import name is not properly set
103
+ up, that debugging information is lost. (For example it would only
104
+ pick up SQL queries in `yourapplication.app` and not
105
+ `yourapplication.views.frontend`)
106
+
107
+ .. versionadded:: 0.7
108
+ The `static_url_path`, `static_folder`, and `template_folder`
109
+ parameters were added.
110
+
111
+ .. versionadded:: 0.8
112
+ The `instance_path` and `instance_relative_config` parameters were
113
+ added.
114
+
115
+ .. versionadded:: 0.11
116
+ The `root_path` parameter was added.
117
+
118
+ .. versionadded:: 1.0
119
+ The ``host_matching`` and ``static_host`` parameters were added.
120
+
121
+ .. versionadded:: 1.0
122
+ The ``subdomain_matching`` parameter was added. Subdomain
123
+ matching needs to be enabled manually now. Setting
124
+ :data:`SERVER_NAME` does not implicitly enable it.
125
+
126
+ :param import_name: the name of the application package
127
+ :param static_url_path: can be used to specify a different path for the
128
+ static files on the web. Defaults to the name
129
+ of the `static_folder` folder.
130
+ :param static_folder: The folder with static files that is served at
131
+ ``static_url_path``. Relative to the application ``root_path``
132
+ or an absolute path. Defaults to ``'static'``.
133
+ :param static_host: the host to use when adding the static route.
134
+ Defaults to None. Required when using ``host_matching=True``
135
+ with a ``static_folder`` configured.
136
+ :param host_matching: set ``url_map.host_matching`` attribute.
137
+ Defaults to False.
138
+ :param subdomain_matching: consider the subdomain relative to
139
+ :data:`SERVER_NAME` when matching routes. Defaults to False.
140
+ :param template_folder: the folder that contains the templates that should
141
+ be used by the application. Defaults to
142
+ ``'templates'`` folder in the root path of the
143
+ application.
144
+ :param instance_path: An alternative instance path for the application.
145
+ By default the folder ``'instance'`` next to the
146
+ package or module is assumed to be the instance
147
+ path.
148
+ :param instance_relative_config: if set to ``True`` relative filenames
149
+ for loading the config are assumed to
150
+ be relative to the instance path instead
151
+ of the application root.
152
+ :param root_path: The path to the root of the application files.
153
+ This should only be set manually when it can't be detected
154
+ automatically, such as for namespace packages.
155
+ """
156
+
157
+ #: The class of the object assigned to :attr:`aborter`, created by
158
+ #: :meth:`create_aborter`. That object is called by
159
+ #: :func:`pboot.abort` to raise HTTP errors, and can be
160
+ #: called directly as well.
161
+ #:
162
+ #: Defaults to :class:`werkzeug.exceptions.Aborter`.
163
+ #:
164
+ #: .. versionadded:: 2.2
165
+ aborter_class = Aborter
166
+
167
+ #: The class that is used for the Jinja environment.
168
+ #:
169
+ #: .. versionadded:: 0.11
170
+ jinja_environment = Environment
171
+
172
+ #: The class that is used for the :data:`~pboot.g` instance.
173
+ #:
174
+ #: Example use cases for a custom class:
175
+ #:
176
+ #: 1. Store arbitrary attributes on pboot.g.
177
+ #: 2. Add a property for lazy per-request database connectors.
178
+ #: 3. Return None instead of AttributeError on unexpected attributes.
179
+ #: 4. Raise exception if an unexpected attr is set, a "controlled" pboot.g.
180
+ #:
181
+ #: .. versionadded:: 0.10
182
+ #: Renamed from ``request_globals_class`.
183
+ app_ctx_globals_class = _AppCtxGlobals
184
+
185
+ #: The class that is used for the ``config`` attribute of this app.
186
+ #: Defaults to :class:`~pboot.Config`.
187
+ #:
188
+ #: Example use cases for a custom class:
189
+ #:
190
+ #: 1. Default values for certain config options.
191
+ #: 2. Access to config values through attributes in addition to keys.
192
+ #:
193
+ #: .. versionadded:: 0.11
194
+ config_class = Config
195
+
196
+ #: The testing flag. Set this to ``True`` to enable the test mode of
197
+ #: Pboot extensions (and in the future probably also Pboot itself).
198
+ #: For example this might activate test helpers that have an
199
+ #: additional runtime cost which should not be enabled by default.
200
+ #:
201
+ #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the
202
+ #: default it's implicitly enabled.
203
+ #:
204
+ #: This attribute can also be configured from the config with the
205
+ #: ``TESTING`` configuration key. Defaults to ``False``.
206
+ testing = ConfigAttribute[bool]("TESTING")
207
+
208
+ #: If a secret key is set, cryptographic components can use this to
209
+ #: sign cookies and other things. Set this to a complex random value
210
+ #: when you want to use the secure cookie for instance.
211
+ #:
212
+ #: This attribute can also be configured from the config with the
213
+ #: :data:`SECRET_KEY` configuration key. Defaults to ``None``.
214
+ secret_key = ConfigAttribute[str | bytes | None]("SECRET_KEY")
215
+
216
+ #: A :class:`~datetime.timedelta` which is used to set the expiration
217
+ #: date of a permanent session. The default is 31 days which makes a
218
+ #: permanent session survive for roughly one month.
219
+ #:
220
+ #: This attribute can also be configured from the config with the
221
+ #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to
222
+ #: ``timedelta(days=31)``
223
+ permanent_session_lifetime = ConfigAttribute[timedelta](
224
+ "PERMANENT_SESSION_LIFETIME",
225
+ get_converter=_make_timedelta, # type: ignore[arg-type]
226
+ )
227
+
228
+ json_provider_class: type[JSONProvider] = DefaultJSONProvider
229
+ """A subclass of :class:`~pboot.json.provider.JSONProvider`. An
230
+ instance is created and assigned to :attr:`app.json` when creating
231
+ the app.
232
+
233
+ The default, :class:`~pboot.json.provider.DefaultJSONProvider`, uses
234
+ Python's built-in :mod:`json` library. A different provider can use
235
+ a different JSON library.
236
+
237
+ .. versionadded:: 2.2
238
+ """
239
+
240
+ #: Options that are passed to the Jinja environment in
241
+ #: :meth:`create_jinja_environment`. Changing these options after
242
+ #: the environment is created (accessing :attr:`jinja_env`) will
243
+ #: have no effect.
244
+ #:
245
+ #: .. versionchanged:: 1.1.0
246
+ #: This is a ``dict`` instead of an ``ImmutableDict`` to allow
247
+ #: easier configuration.
248
+ #:
249
+ jinja_options: dict[str, t.Any] = {}
250
+
251
+ #: The rule object to use for URL rules created. This is used by
252
+ #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.
253
+ #:
254
+ #: .. versionadded:: 0.7
255
+ url_rule_class = Rule
256
+
257
+ #: The map object to use for storing the URL rules and routing
258
+ #: configuration parameters. Defaults to :class:`werkzeug.routing.Map`.
259
+ #:
260
+ #: .. versionadded:: 1.1.0
261
+ url_map_class = Map
262
+
263
+ #: The :meth:`test_client` method creates an instance of this test
264
+ #: client class. Defaults to :class:`~pboot.testing.PbootClient`.
265
+ #:
266
+ #: .. versionadded:: 0.7
267
+ test_client_class: type[PbootClient] | None = None
268
+
269
+ #: The :class:`~click.testing.CliRunner` subclass, by default
270
+ #: :class:`~pboot.testing.PbootCliRunner` that is used by
271
+ #: :meth:`test_cli_runner`. Its ``__init__`` method should take a
272
+ #: Pboot app object as the first argument.
273
+ #:
274
+ #: .. versionadded:: 1.0
275
+ test_cli_runner_class: type[PbootCliRunner] | None = None
276
+
277
+ default_config: cabc.Mapping[str, t.Any]
278
+ response_class: type[Response]
279
+
280
+ def __init__(
281
+ self,
282
+ import_name: str,
283
+ static_url_path: str | None = None,
284
+ static_folder: str | os.PathLike[str] | None = "static",
285
+ static_host: str | None = None,
286
+ host_matching: bool = False,
287
+ subdomain_matching: bool = False,
288
+ template_folder: str | os.PathLike[str] | None = "templates",
289
+ instance_path: str | None = None,
290
+ instance_relative_config: bool = False,
291
+ root_path: str | None = None,
292
+ ) -> None:
293
+ super().__init__(
294
+ import_name=import_name,
295
+ static_folder=static_folder,
296
+ static_url_path=static_url_path,
297
+ template_folder=template_folder,
298
+ root_path=root_path,
299
+ )
300
+
301
+ if instance_path is None:
302
+ instance_path = self.auto_find_instance_path()
303
+ elif not os.path.isabs(instance_path):
304
+ raise ValueError(
305
+ "If an instance path is provided it must be absolute."
306
+ " A relative path was given instead."
307
+ )
308
+
309
+ #: Holds the path to the instance folder.
310
+ #:
311
+ #: .. versionadded:: 0.8
312
+ self.instance_path = instance_path
313
+
314
+ #: The configuration dictionary as :class:`Config`. This behaves
315
+ #: exactly like a regular dictionary but supports additional methods
316
+ #: to load a config from files.
317
+ self.config = self.make_config(instance_relative_config)
318
+
319
+ #: An instance of :attr:`aborter_class` created by
320
+ #: :meth:`make_aborter`. This is called by :func:`pboot.abort`
321
+ #: to raise HTTP errors, and can be called directly as well.
322
+ #:
323
+ #: .. versionadded:: 2.2
324
+ #: Moved from ``pboot.abort``, which calls this object.
325
+ self.aborter = self.make_aborter()
326
+
327
+ self.json: JSONProvider = self.json_provider_class(self)
328
+ """Provides access to JSON methods. Functions in ``pboot.json``
329
+ will call methods on this provider when the application context
330
+ is active. Used for handling JSON requests and responses.
331
+
332
+ An instance of :attr:`json_provider_class`. Can be customized by
333
+ changing that attribute on a subclass, or by assigning to this
334
+ attribute afterwards.
335
+
336
+ The default, :class:`~pboot.json.provider.DefaultJSONProvider`,
337
+ uses Python's built-in :mod:`json` library. A different provider
338
+ can use a different JSON library.
339
+
340
+ .. versionadded:: 2.2
341
+ """
342
+
343
+ #: A list of functions that are called by
344
+ #: :meth:`handle_url_build_error` when :meth:`.url_for` raises a
345
+ #: :exc:`~werkzeug.routing.BuildError`. Each function is called
346
+ #: with ``error``, ``endpoint`` and ``values``. If a function
347
+ #: returns ``None`` or raises a ``BuildError``, it is skipped.
348
+ #: Otherwise, its return value is returned by ``url_for``.
349
+ #:
350
+ #: .. versionadded:: 0.9
351
+ self.url_build_error_handlers: list[
352
+ t.Callable[[Exception, str, dict[str, t.Any]], str]
353
+ ] = []
354
+
355
+ #: A list of functions that are called when the application context
356
+ #: is destroyed. Since the application context is also torn down
357
+ #: if the request ends this is the place to store code that disconnects
358
+ #: from databases.
359
+ #:
360
+ #: .. versionadded:: 0.9
361
+ self.teardown_appcontext_funcs: list[ft.TeardownCallable] = []
362
+
363
+ #: A list of shell context processor functions that should be run
364
+ #: when a shell context is created.
365
+ #:
366
+ #: .. versionadded:: 0.11
367
+ self.shell_context_processors: list[ft.ShellContextProcessorCallable] = []
368
+
369
+ #: Maps registered blueprint names to blueprint objects. The
370
+ #: dict retains the order the blueprints were registered in.
371
+ #: Blueprints can be registered multiple times, this dict does
372
+ #: not track how often they were attached.
373
+ #:
374
+ #: .. versionadded:: 0.7
375
+ self.blueprints: dict[str, Blueprint] = {}
376
+
377
+ #: a place where extensions can store application specific state. For
378
+ #: example this is where an extension could store database engines and
379
+ #: similar things.
380
+ #:
381
+ #: The key must match the name of the extension module. For example in
382
+ #: case of a "Pboot-Foo" extension in `pboot_foo`, the key would be
383
+ #: ``'foo'``.
384
+ #:
385
+ #: .. versionadded:: 0.7
386
+ self.extensions: dict[str, t.Any] = {}
387
+
388
+ #: The :class:`~werkzeug.routing.Map` for this instance. You can use
389
+ #: this to change the routing converters after the class was created
390
+ #: but before any routes are connected. Example::
391
+ #:
392
+ #: from werkzeug.routing import BaseConverter
393
+ #:
394
+ #: class ListConverter(BaseConverter):
395
+ #: def to_python(self, value):
396
+ #: return value.split(',')
397
+ #: def to_url(self, values):
398
+ #: return ','.join(super(ListConverter, self).to_url(value)
399
+ #: for value in values)
400
+ #:
401
+ #: app = Pboot(__name__)
402
+ #: app.url_map.converters['list'] = ListConverter
403
+ self.url_map = self.url_map_class(host_matching=host_matching)
404
+
405
+ self.subdomain_matching = subdomain_matching
406
+
407
+ # tracks internally if the application already handled at least one
408
+ # request.
409
+ self._got_first_request = False
410
+
411
+ def _check_setup_finished(self, f_name: str) -> None:
412
+ if self._got_first_request:
413
+ raise AssertionError(
414
+ f"The setup method '{f_name}' can no longer be called"
415
+ " on the application. It has already handled its first"
416
+ " request, any changes will not be applied"
417
+ " consistently.\n"
418
+ "Make sure all imports, decorators, functions, etc."
419
+ " needed to set up the application are done before"
420
+ " running it."
421
+ )
422
+
423
+ @cached_property
424
+ def name(self) -> str:
425
+ """The name of the application. This is usually the import name
426
+ with the difference that it's guessed from the run file if the
427
+ import name is main. This name is used as a display name when
428
+ Pboot needs the name of the application. It can be set and overridden
429
+ to change the value.
430
+
431
+ .. versionadded:: 0.8
432
+ """
433
+ if self.import_name == "__main__":
434
+ fn: str | None = getattr(sys.modules["__main__"], "__file__", None)
435
+ if fn is None:
436
+ return "__main__"
437
+ return os.path.splitext(os.path.basename(fn))[0]
438
+ return self.import_name
439
+
440
+ @cached_property
441
+ def logger(self) -> logging.Logger:
442
+ """A standard Python :class:`~logging.Logger` for the app, with
443
+ the same name as :attr:`name`.
444
+
445
+ In debug mode, the logger's :attr:`~logging.Logger.level` will
446
+ be set to :data:`~logging.DEBUG`.
447
+
448
+ If there are no handlers configured, a default handler will be
449
+ added. See :doc:`/logging` for more information.
450
+
451
+ .. versionchanged:: 1.1.0
452
+ The logger takes the same name as :attr:`name` rather than
453
+ hard-coding ``"pboot.app"``.
454
+
455
+ .. versionchanged:: 1.0.0
456
+ Behavior was simplified. The logger is always named
457
+ ``"pboot.app"``. The level is only set during configuration,
458
+ it doesn't check ``app.debug`` each time. Only one format is
459
+ used, not different ones depending on ``app.debug``. No
460
+ handlers are removed, and a handler is only added if no
461
+ handlers are already configured.
462
+
463
+ .. versionadded:: 0.3
464
+ """
465
+ return create_logger(self)
466
+
467
+ @cached_property
468
+ def jinja_env(self) -> Environment:
469
+ """The Jinja environment used to load templates.
470
+
471
+ The environment is created the first time this property is
472
+ accessed. Changing :attr:`jinja_options` after that will have no
473
+ effect.
474
+ """
475
+ return self.create_jinja_environment()
476
+
477
+ def create_jinja_environment(self) -> Environment:
478
+ raise NotImplementedError()
479
+
480
+ def make_config(self, instance_relative: bool = False) -> Config:
481
+ """Used to create the config attribute by the Pboot constructor.
482
+ The `instance_relative` parameter is passed in from the constructor
483
+ of Pboot (there named `instance_relative_config`) and indicates if
484
+ the config should be relative to the instance path or the root path
485
+ of the application.
486
+
487
+ .. versionadded:: 0.8
488
+ """
489
+ root_path = self.root_path
490
+ if instance_relative:
491
+ root_path = self.instance_path
492
+ defaults = dict(self.default_config)
493
+ defaults["DEBUG"] = get_debug_flag()
494
+ return self.config_class(root_path, defaults)
495
+
496
+ def make_aborter(self) -> Aborter:
497
+ """Create the object to assign to :attr:`aborter`. That object
498
+ is called by :func:`pboot.abort` to raise HTTP errors, and can
499
+ be called directly as well.
500
+
501
+ By default, this creates an instance of :attr:`aborter_class`,
502
+ which defaults to :class:`werkzeug.exceptions.Aborter`.
503
+
504
+ .. versionadded:: 2.2
505
+ """
506
+ return self.aborter_class()
507
+
508
+ def auto_find_instance_path(self) -> str:
509
+ """Tries to locate the instance path if it was not provided to the
510
+ constructor of the application class. It will basically calculate
511
+ the path to a folder named ``instance`` next to your main file or
512
+ the package.
513
+
514
+ .. versionadded:: 0.8
515
+ """
516
+ prefix, package_path = find_package(self.import_name)
517
+ if prefix is None:
518
+ return os.path.join(package_path, "instance")
519
+ return os.path.join(prefix, "var", f"{self.name}-instance")
520
+
521
+ def create_global_jinja_loader(self) -> DispatchingJinjaLoader:
522
+ """Creates the loader for the Jinja environment. Can be used to
523
+ override just the loader and keeping the rest unchanged. It's
524
+ discouraged to override this function. Instead one should override
525
+ the :meth:`jinja_loader` function instead.
526
+
527
+ The global loader dispatches between the loaders of the application
528
+ and the individual blueprints.
529
+
530
+ .. versionadded:: 0.7
531
+ """
532
+ return DispatchingJinjaLoader(self)
533
+
534
+ def select_jinja_autoescape(self, filename: str | None) -> bool:
535
+ """Returns ``True`` if autoescaping should be active for the given
536
+ template name. If no template name is given, returns `True`.
537
+
538
+ .. versionchanged:: 3.2
539
+ Use case-insensitive comparison instead of only lower case.
540
+
541
+ .. versionchanged:: 2.2
542
+ Autoescaping is now enabled by default for ``.svg`` files.
543
+
544
+ .. versionadded:: 0.5
545
+ """
546
+ if filename is None:
547
+ return True
548
+ return filename.lower().endswith((".html", ".htm", ".xml", ".xhtml", ".svg"))
549
+
550
+ @property
551
+ def debug(self) -> bool:
552
+ """Whether debug mode is enabled. When using ``pboot run`` to start the
553
+ development server, an interactive debugger will be shown for unhandled
554
+ exceptions, and the server will be reloaded when code changes. This maps to the
555
+ :data:`DEBUG` config key. It may not behave as expected if set late.
556
+
557
+ **Do not enable debug mode when deploying in production.**
558
+
559
+ Default: ``False``
560
+ """
561
+ return self.config["DEBUG"] # type: ignore[no-any-return]
562
+
563
+ @debug.setter
564
+ def debug(self, value: bool) -> None:
565
+ self.config["DEBUG"] = value
566
+
567
+ if self.config["TEMPLATES_AUTO_RELOAD"] is None:
568
+ self.jinja_env.auto_reload = value
569
+
570
+ @setupmethod
571
+ def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:
572
+ """Register a :class:`~pboot.Blueprint` on the application. Keyword
573
+ arguments passed to this method will override the defaults set on the
574
+ blueprint.
575
+
576
+ Calls the blueprint's :meth:`~pboot.Blueprint.register` method after
577
+ recording the blueprint in the application's :attr:`blueprints`.
578
+
579
+ :param blueprint: The blueprint to register.
580
+ :param url_prefix: Blueprint routes will be prefixed with this.
581
+ :param subdomain: Blueprint routes will match on this subdomain.
582
+ :param url_defaults: Blueprint routes will use these default values for
583
+ view arguments.
584
+ :param options: Additional keyword arguments are passed to
585
+ :class:`~pboot.blueprints.BlueprintSetupState`. They can be
586
+ accessed in :meth:`~pboot.Blueprint.record` callbacks.
587
+
588
+ .. versionchanged:: 2.0.1
589
+ The ``name`` option can be used to change the (pre-dotted)
590
+ name the blueprint is registered with. This allows the same
591
+ blueprint to be registered multiple times with unique names
592
+ for ``url_for``.
593
+
594
+ .. versionadded:: 0.7
595
+ """
596
+ blueprint.register(self, options)
597
+
598
+ def iter_blueprints(self) -> t.ValuesView[Blueprint]:
599
+ """Iterates over all blueprints by the order they were registered.
600
+
601
+ .. versionadded:: 0.11
602
+ """
603
+ return self.blueprints.values()
604
+
605
+ @setupmethod
606
+ def add_url_rule(
607
+ self,
608
+ rule: str,
609
+ endpoint: str | None = None,
610
+ view_func: ft.RouteCallable | None = None,
611
+ provide_automatic_options: bool | None = None,
612
+ **options: t.Any,
613
+ ) -> None:
614
+ if endpoint is None:
615
+ endpoint = _endpoint_from_view_func(view_func) # type: ignore
616
+ options["endpoint"] = endpoint
617
+ methods = options.pop("methods", None)
618
+
619
+ # if the methods are not given and the view_func object knows its
620
+ # methods we can use that instead. If neither exists, we go with
621
+ # a tuple of only ``GET`` as default.
622
+ if methods is None:
623
+ methods = getattr(view_func, "methods", None) or ("GET",)
624
+ if isinstance(methods, str):
625
+ raise TypeError(
626
+ "Allowed methods must be a list of strings, for"
627
+ ' example: @app.route(..., methods=["POST"])'
628
+ )
629
+ methods = {item.upper() for item in methods}
630
+
631
+ # Methods that should always be added
632
+ required_methods: set[str] = set(getattr(view_func, "required_methods", ()))
633
+
634
+ if provide_automatic_options is None:
635
+ provide_automatic_options = getattr(
636
+ view_func, "provide_automatic_options", None
637
+ )
638
+
639
+ if provide_automatic_options is None:
640
+ provide_automatic_options = (
641
+ "OPTIONS" not in methods
642
+ and self.config["PROVIDE_AUTOMATIC_OPTIONS"]
643
+ )
644
+
645
+ if provide_automatic_options:
646
+ required_methods.add("OPTIONS")
647
+
648
+ # Add the required methods now.
649
+ methods |= required_methods
650
+
651
+ rule_obj = self.url_rule_class(rule, methods=methods, **options)
652
+ rule_obj.provide_automatic_options = provide_automatic_options # type: ignore[attr-defined]
653
+
654
+ self.url_map.add(rule_obj)
655
+ if view_func is not None:
656
+ old_func = self.view_functions.get(endpoint)
657
+ if old_func is not None and old_func != view_func:
658
+ raise AssertionError(
659
+ "View function mapping is overwriting an existing"
660
+ f" endpoint function: {endpoint}"
661
+ )
662
+ self.view_functions[endpoint] = view_func
663
+
664
+ @t.overload
665
+ def template_filter(self, name: T_template_filter) -> T_template_filter: ...
666
+ @t.overload
667
+ def template_filter(
668
+ self, name: str | None = None
669
+ ) -> t.Callable[[T_template_filter], T_template_filter]: ...
670
+ @setupmethod
671
+ def template_filter(
672
+ self, name: T_template_filter | str | None = None
673
+ ) -> T_template_filter | t.Callable[[T_template_filter], T_template_filter]:
674
+ """Decorate a function to register it as a custom Jinja filter. The name
675
+ is optional. The decorator may be used without parentheses.
676
+
677
+ .. code-block:: python
678
+
679
+ @app.template_filter("reverse")
680
+ def reverse_filter(s):
681
+ return reversed(s)
682
+
683
+ The :meth:`add_template_filter` method may be used to register a
684
+ function later rather than decorating.
685
+
686
+ :param name: The name to register the filter as. If not given, uses the
687
+ function's name.
688
+ """
689
+ if callable(name):
690
+ self.add_template_filter(name)
691
+ return name
692
+
693
+ def decorator(f: T_template_filter) -> T_template_filter:
694
+ self.add_template_filter(f, name=name)
695
+ return f
696
+
697
+ return decorator
698
+
699
+ @setupmethod
700
+ def add_template_filter(
701
+ self, f: ft.TemplateFilterCallable, name: str | None = None
702
+ ) -> None:
703
+ """Register a function to use as a custom Jinja filter.
704
+
705
+ The :meth:`template_filter` decorator can be used to register a function
706
+ by decorating instead.
707
+
708
+ :param f: The function to register.
709
+ :param name: The name to register the filter as. If not given, uses the
710
+ function's name.
711
+ """
712
+ self.jinja_env.filters[name or f.__name__] = f
713
+
714
+ @t.overload
715
+ def template_test(self, name: T_template_test) -> T_template_test: ...
716
+ @t.overload
717
+ def template_test(
718
+ self, name: str | None = None
719
+ ) -> t.Callable[[T_template_test], T_template_test]: ...
720
+ @setupmethod
721
+ def template_test(
722
+ self, name: T_template_test | str | None = None
723
+ ) -> T_template_test | t.Callable[[T_template_test], T_template_test]:
724
+ """Decorate a function to register it as a custom Jinja test. The name
725
+ is optional. The decorator may be used without parentheses.
726
+
727
+ .. code-block:: python
728
+
729
+ @app.template_test("prime")
730
+ def is_prime_test(n):
731
+ if n == 2:
732
+ return True
733
+ for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
734
+ if n % i == 0:
735
+ return False
736
+ return True
737
+
738
+ The :meth:`add_template_test` method may be used to register a function
739
+ later rather than decorating.
740
+
741
+ :param name: The name to register the filter as. If not given, uses the
742
+ function's name.
743
+
744
+ .. versionadded:: 0.10
745
+ """
746
+ if callable(name):
747
+ self.add_template_test(name)
748
+ return name
749
+
750
+ def decorator(f: T_template_test) -> T_template_test:
751
+ self.add_template_test(f, name=name)
752
+ return f
753
+
754
+ return decorator
755
+
756
+ @setupmethod
757
+ def add_template_test(
758
+ self, f: ft.TemplateTestCallable, name: str | None = None
759
+ ) -> None:
760
+ """Register a function to use as a custom Jinja test.
761
+
762
+ The :meth:`template_test` decorator can be used to register a function
763
+ by decorating instead.
764
+
765
+ :param f: The function to register.
766
+ :param name: The name to register the test as. If not given, uses the
767
+ function's name.
768
+
769
+ .. versionadded:: 0.10
770
+ """
771
+ self.jinja_env.tests[name or f.__name__] = f
772
+
773
+ @t.overload
774
+ def template_global(self, name: T_template_global) -> T_template_global: ...
775
+ @t.overload
776
+ def template_global(
777
+ self, name: str | None = None
778
+ ) -> t.Callable[[T_template_global], T_template_global]: ...
779
+ @setupmethod
780
+ def template_global(
781
+ self, name: T_template_global | str | None = None
782
+ ) -> T_template_global | t.Callable[[T_template_global], T_template_global]:
783
+ """Decorate a function to register it as a custom Jinja global. The name
784
+ is optional. The decorator may be used without parentheses.
785
+
786
+ .. code-block:: python
787
+
788
+ @app.template_global
789
+ def double(n):
790
+ return 2 * n
791
+
792
+ The :meth:`add_template_global` method may be used to register a
793
+ function later rather than decorating.
794
+
795
+ :param name: The name to register the global as. If not given, uses the
796
+ function's name.
797
+
798
+ .. versionadded:: 0.10
799
+ """
800
+ if callable(name):
801
+ self.add_template_global(name)
802
+ return name
803
+
804
+ def decorator(f: T_template_global) -> T_template_global:
805
+ self.add_template_global(f, name=name)
806
+ return f
807
+
808
+ return decorator
809
+
810
+ @setupmethod
811
+ def add_template_global(
812
+ self, f: ft.TemplateGlobalCallable, name: str | None = None
813
+ ) -> None:
814
+ """Register a function to use as a custom Jinja global.
815
+
816
+ The :meth:`template_global` decorator can be used to register a function
817
+ by decorating instead.
818
+
819
+ :param f: The function to register.
820
+ :param name: The name to register the global as. If not given, uses the
821
+ function's name.
822
+
823
+ .. versionadded:: 0.10
824
+ """
825
+ self.jinja_env.globals[name or f.__name__] = f
826
+
827
+ @setupmethod
828
+ def teardown_appcontext(self, f: T_teardown) -> T_teardown:
829
+ """Registers a function to be called when the app context is popped. The
830
+ context is popped at the end of a request, CLI command, or manual ``with``
831
+ block.
832
+
833
+ .. code-block:: python
834
+
835
+ with app.app_context():
836
+ ...
837
+
838
+ When the ``with`` block exits (or ``ctx.pop()`` is called), the
839
+ teardown functions are called just before the app context is
840
+ made inactive.
841
+
842
+ When a teardown function was called because of an unhandled
843
+ exception it will be passed an error object. If an
844
+ :meth:`errorhandler` is registered, it will handle the exception
845
+ and the teardown will not receive it.
846
+
847
+ Teardown functions must avoid raising exceptions. If they
848
+ execute code that might fail they must surround that code with a
849
+ ``try``/``except`` block and log any errors.
850
+
851
+ The return values of teardown functions are ignored.
852
+
853
+ .. versionadded:: 0.9
854
+ """
855
+ self.teardown_appcontext_funcs.append(f)
856
+ return f
857
+
858
+ @setupmethod
859
+ def shell_context_processor(
860
+ self, f: T_shell_context_processor
861
+ ) -> T_shell_context_processor:
862
+ """Registers a shell context processor function.
863
+
864
+ .. versionadded:: 0.11
865
+ """
866
+ self.shell_context_processors.append(f)
867
+ return f
868
+
869
+ def _find_error_handler(
870
+ self, e: Exception, blueprints: list[str]
871
+ ) -> ft.ErrorHandlerCallable | None:
872
+ """Return a registered error handler for an exception in this order:
873
+ blueprint handler for a specific code, app handler for a specific code,
874
+ blueprint handler for an exception class, app handler for an exception
875
+ class, or ``None`` if a suitable handler is not found.
876
+ """
877
+ exc_class, code = self._get_exc_class_and_code(type(e))
878
+ names = (*blueprints, None)
879
+
880
+ for c in (code, None) if code is not None else (None,):
881
+ for name in names:
882
+ handler_map = self.error_handler_spec[name][c]
883
+
884
+ if not handler_map:
885
+ continue
886
+
887
+ for cls in exc_class.__mro__:
888
+ handler = handler_map.get(cls)
889
+
890
+ if handler is not None:
891
+ return handler
892
+ return None
893
+
894
+ def trap_http_exception(self, e: Exception) -> bool:
895
+ """Checks if an HTTP exception should be trapped or not. By default
896
+ this will return ``False`` for all exceptions except for a bad request
897
+ key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It
898
+ also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.
899
+
900
+ This is called for all HTTP exceptions raised by a view function.
901
+ If it returns ``True`` for any exception the error handler for this
902
+ exception is not called and it shows up as regular exception in the
903
+ traceback. This is helpful for debugging implicitly raised HTTP
904
+ exceptions.
905
+
906
+ .. versionchanged:: 1.0
907
+ Bad request errors are not trapped by default in debug mode.
908
+
909
+ .. versionadded:: 0.8
910
+ """
911
+ if self.config["TRAP_HTTP_EXCEPTIONS"]:
912
+ return True
913
+
914
+ trap_bad_request = self.config["TRAP_BAD_REQUEST_ERRORS"]
915
+
916
+ # if unset, trap key errors in debug mode
917
+ if (
918
+ trap_bad_request is None
919
+ and self.debug
920
+ and isinstance(e, BadRequestKeyError)
921
+ ):
922
+ return True
923
+
924
+ if trap_bad_request:
925
+ return isinstance(e, BadRequest)
926
+
927
+ return False
928
+
929
+ should_ignore_error: None = None
930
+ """If this method returns ``True``, the error will not be passed to
931
+ teardown handlers, and the context will not be preserved for
932
+ debugging.
933
+
934
+ .. deprecated:: 3.2
935
+ Handle errors as needed in teardown handlers instead.
936
+
937
+ .. versionadded:: 0.10
938
+ """
939
+
940
+ def redirect(self, location: str, code: int = 303) -> BaseResponse:
941
+ """Create a redirect response object.
942
+
943
+ This is called by :func:`pboot.redirect`, and can be called
944
+ directly as well.
945
+
946
+ :param location: The URL to redirect to.
947
+ :param code: The status code for the redirect.
948
+
949
+ .. versionchanged:: 3.2
950
+ ``code`` defaults to ``303`` instead of ``302``.
951
+
952
+ .. versionadded:: 2.2
953
+ Moved from ``pboot.redirect``, which calls this method.
954
+ """
955
+ return _wz_redirect(
956
+ location,
957
+ code=code,
958
+ Response=self.response_class, # type: ignore[arg-type]
959
+ )
960
+
961
+ def inject_url_defaults(self, endpoint: str, values: dict[str, t.Any]) -> None:
962
+ """Injects the URL defaults for the given endpoint directly into
963
+ the values dictionary passed. This is used internally and
964
+ automatically called on URL building.
965
+
966
+ .. versionadded:: 0.7
967
+ """
968
+ names: t.Iterable[str | None] = (None,)
969
+
970
+ # url_for may be called outside a request context, parse the
971
+ # passed endpoint instead of using request.blueprints.
972
+ if "." in endpoint:
973
+ names = chain(
974
+ names, reversed(_split_blueprint_path(endpoint.rpartition(".")[0]))
975
+ )
976
+
977
+ for name in names:
978
+ if name in self.url_default_functions:
979
+ for func in self.url_default_functions[name]:
980
+ func(endpoint, values)
981
+
982
+ def handle_url_build_error(
983
+ self, error: BuildError, endpoint: str, values: dict[str, t.Any]
984
+ ) -> str:
985
+ """Called by :meth:`.url_for` if a
986
+ :exc:`~werkzeug.routing.BuildError` was raised. If this returns
987
+ a value, it will be returned by ``url_for``, otherwise the error
988
+ will be re-raised.
989
+
990
+ Each function in :attr:`url_build_error_handlers` is called with
991
+ ``error``, ``endpoint`` and ``values``. If a function returns
992
+ ``None`` or raises a ``BuildError``, it is skipped. Otherwise,
993
+ its return value is returned by ``url_for``.
994
+
995
+ :param error: The active ``BuildError`` being handled.
996
+ :param endpoint: The endpoint being built.
997
+ :param values: The keyword arguments passed to ``url_for``.
998
+ """
999
+ for handler in self.url_build_error_handlers:
1000
+ try:
1001
+ rv = handler(error, endpoint, values)
1002
+ except BuildError as e:
1003
+ # make error available outside except block
1004
+ error = e
1005
+ else:
1006
+ if rv is not None:
1007
+ return rv
1008
+
1009
+ # Re-raise if called with an active exception, otherwise raise
1010
+ # the passed in exception.
1011
+ if error is sys.exc_info()[1]:
1012
+ raise
1013
+
1014
+ raise error