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.
@@ -0,0 +1,800 @@
1
+ from __future__ import annotations
2
+
3
+ import importlib.util
4
+ import os
5
+ import pathlib
6
+ import sys
7
+ import typing as t
8
+ from collections import defaultdict
9
+ from functools import update_wrapper
10
+
11
+ from jinja2 import BaseLoader
12
+ from jinja2 import FileSystemLoader
13
+ from werkzeug.exceptions import default_exceptions
14
+ from werkzeug.exceptions import HTTPException
15
+ from werkzeug.utils import cached_property
16
+
17
+ from .. import typing as ft
18
+ from ..helpers import get_root_path
19
+ from ..templating import _default_template_ctx_processor
20
+
21
+ if t.TYPE_CHECKING: # pragma: no cover
22
+ from click import Group
23
+
24
+ # a singleton sentinel value for parameter defaults
25
+ _sentinel = object()
26
+
27
+ F = t.TypeVar("F", bound=t.Callable[..., t.Any])
28
+ T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable[t.Any])
29
+ T_before_request = t.TypeVar("T_before_request", bound=ft.BeforeRequestCallable)
30
+ T_error_handler = t.TypeVar("T_error_handler", bound=ft.ErrorHandlerCallable)
31
+ T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)
32
+ T_template_context_processor = t.TypeVar(
33
+ "T_template_context_processor", bound=ft.TemplateContextProcessorCallable
34
+ )
35
+ T_url_defaults = t.TypeVar("T_url_defaults", bound=ft.URLDefaultCallable)
36
+ T_url_value_preprocessor = t.TypeVar(
37
+ "T_url_value_preprocessor", bound=ft.URLValuePreprocessorCallable
38
+ )
39
+ T_route = t.TypeVar("T_route", bound=ft.RouteCallable)
40
+
41
+
42
+ def setupmethod(f: F) -> F:
43
+ f_name = f.__name__
44
+
45
+ def wrapper_func(self: Scaffold, *args: t.Any, **kwargs: t.Any) -> t.Any:
46
+ self._check_setup_finished(f_name)
47
+ return f(self, *args, **kwargs)
48
+
49
+ return t.cast(F, update_wrapper(wrapper_func, f))
50
+
51
+
52
+ class Scaffold:
53
+ """Common behavior shared between :class:`~pboot.Pboot` and
54
+ :class:`~pboot.blueprints.Blueprint`.
55
+
56
+ :param import_name: The import name of the module where this object
57
+ is defined. Usually :attr:`__name__` should be used.
58
+ :param static_folder: Path to a folder of static files to serve.
59
+ If this is set, a static route will be added.
60
+ :param static_url_path: URL prefix for the static route.
61
+ :param template_folder: Path to a folder containing template files.
62
+ for rendering. If this is set, a Jinja loader will be added.
63
+ :param root_path: The path that static, template, and resource files
64
+ are relative to. Typically not set, it is discovered based on
65
+ the ``import_name``.
66
+
67
+ .. versionadded:: 2.0
68
+ """
69
+
70
+ cli: Group
71
+ name: str
72
+ _static_folder: str | None = None
73
+ _static_url_path: str | None = None
74
+
75
+ def __init__(
76
+ self,
77
+ import_name: str,
78
+ static_folder: str | os.PathLike[str] | None = None,
79
+ static_url_path: str | None = None,
80
+ template_folder: str | os.PathLike[str] | None = None,
81
+ root_path: str | None = None,
82
+ ):
83
+ #: The name of the package or module that this object belongs
84
+ #: to. Do not change this once it is set by the constructor.
85
+ self.import_name = import_name
86
+
87
+ self.static_folder = static_folder
88
+ self.static_url_path = static_url_path
89
+
90
+ #: The path to the templates folder, relative to
91
+ #: :attr:`root_path`, to add to the template loader. ``None`` if
92
+ #: templates should not be added.
93
+ self.template_folder = template_folder
94
+
95
+ if root_path is None:
96
+ root_path = get_root_path(self.import_name)
97
+
98
+ #: Absolute path to the package on the filesystem. Used to look
99
+ #: up resources contained in the package.
100
+ self.root_path = root_path
101
+
102
+ #: A dictionary mapping endpoint names to view functions.
103
+ #:
104
+ #: To register a view function, use the :meth:`route` decorator.
105
+ #:
106
+ #: This data structure is internal. It should not be modified
107
+ #: directly and its format may change at any time.
108
+ self.view_functions: dict[str, ft.RouteCallable] = {}
109
+
110
+ #: A data structure of registered error handlers, in the format
111
+ #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is
112
+ #: the name of a blueprint the handlers are active for, or
113
+ #: ``None`` for all requests. The ``code`` key is the HTTP
114
+ #: status code for ``HTTPException``, or ``None`` for
115
+ #: other exceptions. The innermost dictionary maps exception
116
+ #: classes to handler functions.
117
+ #:
118
+ #: To register an error handler, use the :meth:`errorhandler`
119
+ #: decorator.
120
+ #:
121
+ #: This data structure is internal. It should not be modified
122
+ #: directly and its format may change at any time.
123
+ self.error_handler_spec: dict[
124
+ ft.AppOrBlueprintKey,
125
+ dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]],
126
+ ] = defaultdict(lambda: defaultdict(dict))
127
+
128
+ #: A data structure of functions to call at the beginning of
129
+ #: each request, in the format ``{scope: [functions]}``. The
130
+ #: ``scope`` key is the name of a blueprint the functions are
131
+ #: active for, or ``None`` for all requests.
132
+ #:
133
+ #: To register a function, use the :meth:`before_request`
134
+ #: decorator.
135
+ #:
136
+ #: This data structure is internal. It should not be modified
137
+ #: directly and its format may change at any time.
138
+ self.before_request_funcs: dict[
139
+ ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]
140
+ ] = defaultdict(list)
141
+
142
+ #: A data structure of functions to call at the end of each
143
+ #: request, in the format ``{scope: [functions]}``. The
144
+ #: ``scope`` key is the name of a blueprint the functions are
145
+ #: active for, or ``None`` for all requests.
146
+ #:
147
+ #: To register a function, use the :meth:`after_request`
148
+ #: decorator.
149
+ #:
150
+ #: This data structure is internal. It should not be modified
151
+ #: directly and its format may change at any time.
152
+ self.after_request_funcs: dict[
153
+ ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]]
154
+ ] = defaultdict(list)
155
+
156
+ #: A data structure of functions to call at the end of each
157
+ #: request even if an exception is raised, in the format
158
+ #: ``{scope: [functions]}``. The ``scope`` key is the name of a
159
+ #: blueprint the functions are active for, or ``None`` for all
160
+ #: requests.
161
+ #:
162
+ #: To register a function, use the :meth:`teardown_request`
163
+ #: decorator.
164
+ #:
165
+ #: This data structure is internal. It should not be modified
166
+ #: directly and its format may change at any time.
167
+ self.teardown_request_funcs: dict[
168
+ ft.AppOrBlueprintKey, list[ft.TeardownCallable]
169
+ ] = defaultdict(list)
170
+
171
+ #: A data structure of functions to call to pass extra context
172
+ #: values when rendering templates, in the format
173
+ #: ``{scope: [functions]}``. The ``scope`` key is the name of a
174
+ #: blueprint the functions are active for, or ``None`` for all
175
+ #: requests.
176
+ #:
177
+ #: To register a function, use the :meth:`context_processor`
178
+ #: decorator.
179
+ #:
180
+ #: This data structure is internal. It should not be modified
181
+ #: directly and its format may change at any time.
182
+ self.template_context_processors: dict[
183
+ ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]
184
+ ] = defaultdict(list, {None: [_default_template_ctx_processor]})
185
+
186
+ #: A data structure of functions to call to modify the keyword
187
+ #: arguments passed to the view function, in the format
188
+ #: ``{scope: [functions]}``. The ``scope`` key is the name of a
189
+ #: blueprint the functions are active for, or ``None`` for all
190
+ #: requests.
191
+ #:
192
+ #: To register a function, use the
193
+ #: :meth:`url_value_preprocessor` decorator.
194
+ #:
195
+ #: This data structure is internal. It should not be modified
196
+ #: directly and its format may change at any time.
197
+ self.url_value_preprocessors: dict[
198
+ ft.AppOrBlueprintKey,
199
+ list[ft.URLValuePreprocessorCallable],
200
+ ] = defaultdict(list)
201
+
202
+ #: A data structure of functions to call to modify the keyword
203
+ #: arguments when generating URLs, in the format
204
+ #: ``{scope: [functions]}``. The ``scope`` key is the name of a
205
+ #: blueprint the functions are active for, or ``None`` for all
206
+ #: requests.
207
+ #:
208
+ #: To register a function, use the :meth:`url_defaults`
209
+ #: decorator.
210
+ #:
211
+ #: This data structure is internal. It should not be modified
212
+ #: directly and its format may change at any time.
213
+ self.url_default_functions: dict[
214
+ ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]
215
+ ] = defaultdict(list)
216
+
217
+ def __repr__(self) -> str:
218
+ return f"<{type(self).__name__} {self.name!r}>"
219
+
220
+ def _check_setup_finished(self, f_name: str) -> None:
221
+ raise NotImplementedError
222
+
223
+ @property
224
+ def static_folder(self) -> str | None:
225
+ """The absolute path to the configured static folder. ``None``
226
+ if no static folder is set.
227
+ """
228
+ if self._static_folder is not None:
229
+ return os.path.join(self.root_path, self._static_folder)
230
+ else:
231
+ return None
232
+
233
+ @static_folder.setter
234
+ def static_folder(self, value: str | os.PathLike[str] | None) -> None:
235
+ if value is not None:
236
+ value = os.fspath(value).rstrip(r"\/")
237
+
238
+ self._static_folder = value
239
+
240
+ @property
241
+ def has_static_folder(self) -> bool:
242
+ """``True`` if :attr:`static_folder` is set.
243
+
244
+ .. versionadded:: 0.5
245
+ """
246
+ return self.static_folder is not None
247
+
248
+ @property
249
+ def static_url_path(self) -> str | None:
250
+ """The URL prefix that the static route will be accessible from.
251
+
252
+ If it was not configured during init, it is derived from
253
+ :attr:`static_folder`.
254
+ """
255
+ if self._static_url_path is not None:
256
+ return self._static_url_path
257
+
258
+ if self.static_folder is not None:
259
+ basename = os.path.basename(self.static_folder)
260
+ return f"/{basename}".rstrip("/")
261
+
262
+ return None
263
+
264
+ @static_url_path.setter
265
+ def static_url_path(self, value: str | None) -> None:
266
+ if value is not None:
267
+ value = value.rstrip("/")
268
+
269
+ self._static_url_path = value
270
+
271
+ @cached_property
272
+ def jinja_loader(self) -> BaseLoader | None:
273
+ """The Jinja loader for this object's templates. By default this
274
+ is a class :class:`jinja2.loaders.FileSystemLoader` to
275
+ :attr:`template_folder` if it is set.
276
+
277
+ .. versionadded:: 0.5
278
+ """
279
+ if self.template_folder is not None:
280
+ return FileSystemLoader(os.path.join(self.root_path, self.template_folder))
281
+ else:
282
+ return None
283
+
284
+ def _method_route(
285
+ self,
286
+ method: str,
287
+ rule: str,
288
+ options: dict[str, t.Any],
289
+ ) -> t.Callable[[T_route], T_route]:
290
+ if "methods" in options:
291
+ raise TypeError("Use the 'route' decorator to use the 'methods' argument.")
292
+
293
+ return self.route(rule, methods=[method], **options)
294
+
295
+ @setupmethod
296
+ def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:
297
+ """Shortcut for :meth:`route` with ``methods=["GET"]``.
298
+
299
+ .. versionadded:: 2.0
300
+ """
301
+ return self._method_route("GET", rule, options)
302
+
303
+ @setupmethod
304
+ def query(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:
305
+ """Shortcut for :meth:`route` with ``methods=["QUERY"]``.
306
+
307
+ .. versionadded:: 3.2
308
+ """
309
+ return self._method_route("QUERY", rule, options)
310
+
311
+ @setupmethod
312
+ def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:
313
+ """Shortcut for :meth:`route` with ``methods=["POST"]``.
314
+
315
+ .. versionadded:: 2.0
316
+ """
317
+ return self._method_route("POST", rule, options)
318
+
319
+ @setupmethod
320
+ def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:
321
+ """Shortcut for :meth:`route` with ``methods=["PUT"]``.
322
+
323
+ .. versionadded:: 2.0
324
+ """
325
+ return self._method_route("PUT", rule, options)
326
+
327
+ @setupmethod
328
+ def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:
329
+ """Shortcut for :meth:`route` with ``methods=["DELETE"]``.
330
+
331
+ .. versionadded:: 2.0
332
+ """
333
+ return self._method_route("DELETE", rule, options)
334
+
335
+ @setupmethod
336
+ def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:
337
+ """Shortcut for :meth:`route` with ``methods=["PATCH"]``.
338
+
339
+ .. versionadded:: 2.0
340
+ """
341
+ return self._method_route("PATCH", rule, options)
342
+
343
+ @setupmethod
344
+ def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:
345
+ """Decorate a view function to register it with the given URL
346
+ rule and options. Calls :meth:`add_url_rule`, which has more
347
+ details about the implementation.
348
+
349
+ .. code-block:: python
350
+
351
+ @app.route("/")
352
+ def index():
353
+ return "Hello, World!"
354
+
355
+ See :ref:`url-route-registrations`.
356
+
357
+ The endpoint name for the route defaults to the name of the view
358
+ function if the ``endpoint`` parameter isn't passed.
359
+
360
+ The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` and
361
+ ``OPTIONS`` are added automatically.
362
+
363
+ :param rule: The URL rule string.
364
+ :param options: Extra options passed to the
365
+ :class:`~werkzeug.routing.Rule` object.
366
+ """
367
+
368
+ def decorator(f: T_route) -> T_route:
369
+ endpoint = options.pop("endpoint", None)
370
+ self.add_url_rule(rule, endpoint, f, **options)
371
+ return f
372
+
373
+ return decorator
374
+
375
+ @setupmethod
376
+ def add_url_rule(
377
+ self,
378
+ rule: str,
379
+ endpoint: str | None = None,
380
+ view_func: ft.RouteCallable | None = None,
381
+ provide_automatic_options: bool | None = None,
382
+ **options: t.Any,
383
+ ) -> None:
384
+ """Register a rule for routing incoming requests and building
385
+ URLs. The :meth:`route` decorator is a shortcut to call this
386
+ with the ``view_func`` argument. These are equivalent:
387
+
388
+ .. code-block:: python
389
+
390
+ @app.route("/")
391
+ def index():
392
+ ...
393
+
394
+ .. code-block:: python
395
+
396
+ def index():
397
+ ...
398
+
399
+ app.add_url_rule("/", view_func=index)
400
+
401
+ See :ref:`url-route-registrations`.
402
+
403
+ The endpoint name for the route defaults to the name of the view
404
+ function if the ``endpoint`` parameter isn't passed. An error
405
+ will be raised if a function has already been registered for the
406
+ endpoint.
407
+
408
+ The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` is
409
+ always added automatically, and ``OPTIONS`` is added
410
+ automatically by default.
411
+
412
+ ``view_func`` does not necessarily need to be passed, but if the
413
+ rule should participate in routing an endpoint name must be
414
+ associated with a view function at some point with the
415
+ :meth:`endpoint` decorator.
416
+
417
+ .. code-block:: python
418
+
419
+ app.add_url_rule("/", endpoint="index")
420
+
421
+ @app.endpoint("index")
422
+ def index():
423
+ ...
424
+
425
+ If ``view_func`` has a ``required_methods`` attribute, those
426
+ methods are added to the passed and automatic methods. If it
427
+ has a ``provide_automatic_methods`` attribute, it is used as the
428
+ default if the parameter is not passed.
429
+
430
+ :param rule: The URL rule string.
431
+ :param endpoint: The endpoint name to associate with the rule
432
+ and view function. Used when routing and building URLs.
433
+ Defaults to ``view_func.__name__``.
434
+ :param view_func: The view function to associate with the
435
+ endpoint name.
436
+ :param provide_automatic_options: Add the ``OPTIONS`` method and
437
+ respond to ``OPTIONS`` requests automatically.
438
+ :param options: Extra options passed to the
439
+ :class:`~werkzeug.routing.Rule` object.
440
+ """
441
+ raise NotImplementedError
442
+
443
+ @setupmethod
444
+ def endpoint(self, endpoint: str) -> t.Callable[[F], F]:
445
+ """Decorate a view function to register it for the given
446
+ endpoint. Used if a rule is added without a ``view_func`` with
447
+ :meth:`add_url_rule`.
448
+
449
+ .. code-block:: python
450
+
451
+ app.add_url_rule("/ex", endpoint="example")
452
+
453
+ @app.endpoint("example")
454
+ def example():
455
+ ...
456
+
457
+ :param endpoint: The endpoint name to associate with the view
458
+ function.
459
+ """
460
+
461
+ def decorator(f: F) -> F:
462
+ self.view_functions[endpoint] = f
463
+ return f
464
+
465
+ return decorator
466
+
467
+ @setupmethod
468
+ def before_request(self, f: T_before_request) -> T_before_request:
469
+ """Register a function to run before each request.
470
+
471
+ For example, this can be used to open a database connection, or
472
+ to load the logged in user from the session.
473
+
474
+ .. code-block:: python
475
+
476
+ @app.before_request
477
+ def load_user():
478
+ if "user_id" in session:
479
+ g.user = db.session.get(session["user_id"])
480
+
481
+ The function will be called without any arguments. If it returns
482
+ a non-``None`` value, the value is handled as if it was the
483
+ return value from the view, and further request handling is
484
+ stopped.
485
+
486
+ This is available on both app and blueprint objects. When used on an app, this
487
+ executes before every request. When used on a blueprint, this executes before
488
+ every request that the blueprint handles. To register with a blueprint and
489
+ execute before every request, use :meth:`.Blueprint.before_app_request`.
490
+ """
491
+ self.before_request_funcs.setdefault(None, []).append(f)
492
+ return f
493
+
494
+ @setupmethod
495
+ def after_request(self, f: T_after_request) -> T_after_request:
496
+ """Register a function to run after each request to this object.
497
+
498
+ The function is called with the response object, and must return
499
+ a response object. This allows the functions to modify or
500
+ replace the response before it is sent.
501
+
502
+ If a function raises an exception, any remaining
503
+ ``after_request`` functions will not be called. Therefore, this
504
+ should not be used for actions that must execute, such as to
505
+ close resources. Use :meth:`teardown_request` for that.
506
+
507
+ This is available on both app and blueprint objects. When used on an app, this
508
+ executes after every request. When used on a blueprint, this executes after
509
+ every request that the blueprint handles. To register with a blueprint and
510
+ execute after every request, use :meth:`.Blueprint.after_app_request`.
511
+ """
512
+ self.after_request_funcs.setdefault(None, []).append(f)
513
+ return f
514
+
515
+ @setupmethod
516
+ def teardown_request(self, f: T_teardown) -> T_teardown:
517
+ """Register a function to be called when the request context is
518
+ popped. Typically, this happens at the end of each request, but
519
+ contexts may be pushed manually during testing.
520
+
521
+ .. code-block:: python
522
+
523
+ with app.test_request_context():
524
+ ...
525
+
526
+ When the ``with`` block exits (or ``ctx.pop()`` is called), the
527
+ teardown functions are called just before the request context is
528
+ made inactive.
529
+
530
+ When a teardown function was called because of an unhandled
531
+ exception it will be passed an error object. If an
532
+ :meth:`errorhandler` is registered, it will handle the exception
533
+ and the teardown will not receive it.
534
+
535
+ Teardown functions must avoid raising exceptions. If they
536
+ execute code that might fail they must surround that code with a
537
+ ``try``/``except`` block and log any errors.
538
+
539
+ The return values of teardown functions are ignored.
540
+
541
+ This is available on both app and blueprint objects. When used on an app, this
542
+ executes after every request. When used on a blueprint, this executes after
543
+ every request that the blueprint handles. To register with a blueprint and
544
+ execute after every request, use :meth:`.Blueprint.teardown_app_request`.
545
+ """
546
+ self.teardown_request_funcs.setdefault(None, []).append(f)
547
+ return f
548
+
549
+ @setupmethod
550
+ def context_processor(
551
+ self,
552
+ f: T_template_context_processor,
553
+ ) -> T_template_context_processor:
554
+ """Registers a template context processor function. These functions run before
555
+ rendering a template. The keys of the returned dict are added as variables
556
+ available in the template.
557
+
558
+ This is available on both app and blueprint objects. When used on an app, this
559
+ is called for every rendered template. When used on a blueprint, this is called
560
+ for templates rendered from the blueprint's views. To register with a blueprint
561
+ and affect every template, use :meth:`.Blueprint.app_context_processor`.
562
+ """
563
+ self.template_context_processors[None].append(f)
564
+ return f
565
+
566
+ @setupmethod
567
+ def url_value_preprocessor(
568
+ self,
569
+ f: T_url_value_preprocessor,
570
+ ) -> T_url_value_preprocessor:
571
+ """Register a URL value preprocessor function for all view
572
+ functions in the application. These functions will be called before the
573
+ :meth:`before_request` functions.
574
+
575
+ The function can modify the values captured from the matched url before
576
+ they are passed to the view. For example, this can be used to pop a
577
+ common language code value and place it in ``g`` rather than pass it to
578
+ every view.
579
+
580
+ The function is passed the endpoint name and values dict. The return
581
+ value is ignored.
582
+
583
+ This is available on both app and blueprint objects. When used on an app, this
584
+ is called for every request. When used on a blueprint, this is called for
585
+ requests that the blueprint handles. To register with a blueprint and affect
586
+ every request, use :meth:`.Blueprint.app_url_value_preprocessor`.
587
+ """
588
+ self.url_value_preprocessors[None].append(f)
589
+ return f
590
+
591
+ @setupmethod
592
+ def url_defaults(self, f: T_url_defaults) -> T_url_defaults:
593
+ """Callback function for URL defaults for all view functions of the
594
+ application. It's called with the endpoint and values and should
595
+ update the values passed in place.
596
+
597
+ This is available on both app and blueprint objects. When used on an app, this
598
+ is called for every request. When used on a blueprint, this is called for
599
+ requests that the blueprint handles. To register with a blueprint and affect
600
+ every request, use :meth:`.Blueprint.app_url_defaults`.
601
+ """
602
+ self.url_default_functions[None].append(f)
603
+ return f
604
+
605
+ @setupmethod
606
+ def errorhandler(
607
+ self, code_or_exception: type[Exception] | int
608
+ ) -> t.Callable[[T_error_handler], T_error_handler]:
609
+ """Register a function to handle errors by code or exception class.
610
+
611
+ A decorator that is used to register a function given an
612
+ error code. Example::
613
+
614
+ @app.errorhandler(404)
615
+ def page_not_found(error):
616
+ return 'This page does not exist', 404
617
+
618
+ You can also register handlers for arbitrary exceptions::
619
+
620
+ @app.errorhandler(DatabaseError)
621
+ def special_exception_handler(error):
622
+ return 'Database connection failed', 500
623
+
624
+ This is available on both app and blueprint objects. When used on an app, this
625
+ can handle errors from every request. When used on a blueprint, this can handle
626
+ errors from requests that the blueprint handles. To register with a blueprint
627
+ and affect every request, use :meth:`.Blueprint.app_errorhandler`.
628
+
629
+ .. versionadded:: 0.7
630
+ Use :meth:`register_error_handler` instead of modifying
631
+ :attr:`error_handler_spec` directly, for application wide error
632
+ handlers.
633
+
634
+ .. versionadded:: 0.7
635
+ One can now additionally also register custom exception types
636
+ that do not necessarily have to be a subclass of the
637
+ :class:`~werkzeug.exceptions.HTTPException` class.
638
+
639
+ :param code_or_exception: the code as integer for the handler, or
640
+ an arbitrary exception
641
+ """
642
+
643
+ def decorator(f: T_error_handler) -> T_error_handler:
644
+ self.register_error_handler(code_or_exception, f)
645
+ return f
646
+
647
+ return decorator
648
+
649
+ @setupmethod
650
+ def register_error_handler(
651
+ self,
652
+ code_or_exception: type[Exception] | int,
653
+ f: ft.ErrorHandlerCallable,
654
+ ) -> None:
655
+ """Alternative error attach function to the :meth:`errorhandler`
656
+ decorator that is more straightforward to use for non decorator
657
+ usage.
658
+
659
+ .. versionadded:: 0.7
660
+ """
661
+ exc_class, code = self._get_exc_class_and_code(code_or_exception)
662
+ self.error_handler_spec[None][code][exc_class] = f
663
+
664
+ @staticmethod
665
+ def _get_exc_class_and_code(
666
+ exc_class_or_code: type[Exception] | int,
667
+ ) -> tuple[type[Exception], int | None]:
668
+ """Get the exception class being handled. For HTTP status codes
669
+ or ``HTTPException`` subclasses, return both the exception and
670
+ status code.
671
+
672
+ :param exc_class_or_code: Any exception class, or an HTTP status
673
+ code as an integer.
674
+ """
675
+ exc_class: type[Exception]
676
+
677
+ if isinstance(exc_class_or_code, int):
678
+ try:
679
+ exc_class = default_exceptions[exc_class_or_code]
680
+ except KeyError:
681
+ raise ValueError(
682
+ f"'{exc_class_or_code}' is not a recognized HTTP"
683
+ " error code. Use a subclass of HTTPException with"
684
+ " that code instead."
685
+ ) from None
686
+ else:
687
+ exc_class = exc_class_or_code
688
+
689
+ if isinstance(exc_class, Exception):
690
+ raise TypeError(
691
+ f"{exc_class!r} is an instance, not a class. Handlers"
692
+ " can only be registered for Exception classes or HTTP"
693
+ " error codes."
694
+ )
695
+
696
+ if not issubclass(exc_class, Exception):
697
+ raise ValueError(
698
+ f"'{exc_class.__name__}' is not a subclass of Exception."
699
+ " Handlers can only be registered for Exception classes"
700
+ " or HTTP error codes."
701
+ )
702
+
703
+ if issubclass(exc_class, HTTPException):
704
+ return exc_class, exc_class.code
705
+ else:
706
+ return exc_class, None
707
+
708
+
709
+ def _endpoint_from_view_func(view_func: ft.RouteCallable) -> str:
710
+ """Internal helper that returns the default endpoint for a given
711
+ function. This always is the function name.
712
+ """
713
+ assert view_func is not None, "expected view func if endpoint is not provided."
714
+ return view_func.__name__
715
+
716
+
717
+ def _find_package_path(import_name: str) -> str:
718
+ """Find the path that contains the package or module."""
719
+ root_mod_name, _, _ = import_name.partition(".")
720
+
721
+ try:
722
+ root_spec = importlib.util.find_spec(root_mod_name)
723
+
724
+ if root_spec is None:
725
+ raise ValueError("not found")
726
+ except (ImportError, ValueError):
727
+ # ImportError: the machinery told us it does not exist
728
+ # ValueError:
729
+ # - the module name was invalid
730
+ # - the module name is __main__
731
+ # - we raised `ValueError` due to `root_spec` being `None`
732
+ return os.getcwd()
733
+
734
+ if root_spec.submodule_search_locations:
735
+ if root_spec.origin is None or root_spec.origin == "namespace":
736
+ # namespace package
737
+ package_spec = importlib.util.find_spec(import_name)
738
+
739
+ if package_spec is not None and package_spec.submodule_search_locations:
740
+ # Pick the path in the namespace that contains the submodule.
741
+ package_path = pathlib.Path(
742
+ os.path.commonpath(package_spec.submodule_search_locations)
743
+ )
744
+ search_location = next(
745
+ location
746
+ for location in root_spec.submodule_search_locations
747
+ if package_path.is_relative_to(location)
748
+ )
749
+ else:
750
+ # Pick the first path.
751
+ search_location = root_spec.submodule_search_locations[0]
752
+
753
+ return os.path.dirname(search_location)
754
+ else:
755
+ # package with __init__.py
756
+ return os.path.dirname(os.path.dirname(root_spec.origin))
757
+ else:
758
+ # module
759
+ return os.path.dirname(root_spec.origin) # type: ignore[type-var, return-value]
760
+
761
+
762
+ def find_package(import_name: str) -> tuple[str | None, str]:
763
+ """Find the prefix that a package is installed under, and the path
764
+ that it would be imported from.
765
+
766
+ The prefix is the directory containing the standard directory
767
+ hierarchy (lib, bin, etc.). If the package is not installed to the
768
+ system (:attr:`sys.prefix`) or a virtualenv (``site-packages``),
769
+ ``None`` is returned.
770
+
771
+ The path is the entry in :attr:`sys.path` that contains the package
772
+ for import. If the package is not installed, it's assumed that the
773
+ package was imported from the current working directory.
774
+ """
775
+ package_path = _find_package_path(import_name)
776
+ py_prefix = os.path.abspath(sys.prefix)
777
+
778
+ # installed to the system
779
+ if pathlib.PurePath(package_path).is_relative_to(py_prefix):
780
+ return py_prefix, package_path
781
+
782
+ site_parent, site_folder = os.path.split(package_path)
783
+
784
+ # installed to a virtualenv
785
+ if site_folder.lower() == "site-packages":
786
+ parent, folder = os.path.split(site_parent)
787
+
788
+ # Windows (prefix/lib/site-packages)
789
+ if folder.lower() == "lib":
790
+ return parent, package_path
791
+
792
+ # Unix (prefix/lib/pythonX.Y/site-packages)
793
+ if os.path.basename(parent).lower() == "lib":
794
+ return os.path.dirname(parent), package_path
795
+
796
+ # something else (prefix/site-packages)
797
+ return site_parent, package_path
798
+
799
+ # not installed
800
+ return None, package_path