1 from __future__
import annotations
8 from collections
import defaultdict
9 from functools
import update_wrapper
11 from jinja2
import FileSystemLoader
12 from werkzeug
.exceptions
import default_exceptions
13 from werkzeug
.exceptions
import HTTPException
14 from werkzeug
.utils
import cached_property
16 from .. import typing
as ft
17 from ..cli
import AppGroup
18 from ..helpers
import get_root_path
19 from ..templating
import _default_template_ctx_processor
21 # a singleton sentinel value for parameter defaults
24 F
= t
.TypeVar("F", bound
=t
.Callable
[..., t
.Any
])
25 T_after_request
= t
.TypeVar("T_after_request", bound
=ft
.AfterRequestCallable
)
26 T_before_request
= t
.TypeVar("T_before_request", bound
=ft
.BeforeRequestCallable
)
27 T_error_handler
= t
.TypeVar("T_error_handler", bound
=ft
.ErrorHandlerCallable
)
28 T_teardown
= t
.TypeVar("T_teardown", bound
=ft
.TeardownCallable
)
29 T_template_context_processor
= t
.TypeVar(
30 "T_template_context_processor", bound
=ft
.TemplateContextProcessorCallable
32 T_url_defaults
= t
.TypeVar("T_url_defaults", bound
=ft
.URLDefaultCallable
)
33 T_url_value_preprocessor
= t
.TypeVar(
34 "T_url_value_preprocessor", bound
=ft
.URLValuePreprocessorCallable
36 T_route
= t
.TypeVar("T_route", bound
=ft
.RouteCallable
)
39 def setupmethod(f
: F
) -> F
:
42 def wrapper_func(self
, *args
: t
.Any
, **kwargs
: t
.Any
) -> t
.Any
:
43 self
._check
_setup
_finished
(f_name
)
44 return f(self
, *args
, **kwargs
)
46 return t
.cast(F
, update_wrapper(wrapper_func
, f
))
50 """Common behavior shared between :class:`~flask.Flask` and
51 :class:`~flask.blueprints.Blueprint`.
53 :param import_name: The import name of the module where this object
54 is defined. Usually :attr:`__name__` should be used.
55 :param static_folder: Path to a folder of static files to serve.
56 If this is set, a static route will be added.
57 :param static_url_path: URL prefix for the static route.
58 :param template_folder: Path to a folder containing template files.
59 for rendering. If this is set, a Jinja loader will be added.
60 :param root_path: The path that static, template, and resource files
61 are relative to. Typically not set, it is discovered based on
68 _static_folder
: str |
None = None
69 _static_url_path
: str |
None = None
74 static_folder
: str | os
.PathLike |
None = None,
75 static_url_path
: str |
None = None,
76 template_folder
: str | os
.PathLike |
None = None,
77 root_path
: str |
None = None,
79 #: The name of the package or module that this object belongs
80 #: to. Do not change this once it is set by the constructor.
81 self
.import_name
= import_name
83 self
.static_folder
= static_folder
# type: ignore
84 self
.static_url_path
= static_url_path
86 #: The path to the templates folder, relative to
87 #: :attr:`root_path`, to add to the template loader. ``None`` if
88 #: templates should not be added.
89 self
.template_folder
= template_folder
92 root_path
= get_root_path(self
.import_name
)
94 #: Absolute path to the package on the filesystem. Used to look
95 #: up resources contained in the package.
96 self
.root_path
= root_path
98 #: The Click command group for registering CLI commands for this
99 #: object. The commands are available from the ``flask`` command
100 #: once the application has been discovered and blueprints have
102 self
.cli
= AppGroup()
104 #: A dictionary mapping endpoint names to view functions.
106 #: To register a view function, use the :meth:`route` decorator.
108 #: This data structure is internal. It should not be modified
109 #: directly and its format may change at any time.
110 self
.view_functions
: dict[str, t
.Callable
] = {}
112 #: A data structure of registered error handlers, in the format
113 #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is
114 #: the name of a blueprint the handlers are active for, or
115 #: ``None`` for all requests. The ``code`` key is the HTTP
116 #: status code for ``HTTPException``, or ``None`` for
117 #: other exceptions. The innermost dictionary maps exception
118 #: classes to handler functions.
120 #: To register an error handler, use the :meth:`errorhandler`
123 #: This data structure is internal. It should not be modified
124 #: directly and its format may change at any time.
125 self
.error_handler_spec
: dict[
126 ft
.AppOrBlueprintKey
,
127 dict[int |
None, dict[type[Exception], ft
.ErrorHandlerCallable
]],
128 ] = defaultdict(lambda: defaultdict(dict))
130 #: A data structure of functions to call at the beginning of
131 #: each request, in the format ``{scope: [functions]}``. The
132 #: ``scope`` key is the name of a blueprint the functions are
133 #: active for, or ``None`` for all requests.
135 #: To register a function, use the :meth:`before_request`
138 #: This data structure is internal. It should not be modified
139 #: directly and its format may change at any time.
140 self
.before_request_funcs
: dict[
141 ft
.AppOrBlueprintKey
, list[ft
.BeforeRequestCallable
]
142 ] = defaultdict(list)
144 #: A data structure of functions to call at the end of each
145 #: request, in the format ``{scope: [functions]}``. The
146 #: ``scope`` key is the name of a blueprint the functions are
147 #: active for, or ``None`` for all requests.
149 #: To register a function, use the :meth:`after_request`
152 #: This data structure is internal. It should not be modified
153 #: directly and its format may change at any time.
154 self
.after_request_funcs
: dict[
155 ft
.AppOrBlueprintKey
, list[ft
.AfterRequestCallable
]
156 ] = defaultdict(list)
158 #: A data structure of functions to call at the end of each
159 #: request even if an exception is raised, in the format
160 #: ``{scope: [functions]}``. The ``scope`` key is the name of a
161 #: blueprint the functions are active for, or ``None`` for all
164 #: To register a function, use the :meth:`teardown_request`
167 #: This data structure is internal. It should not be modified
168 #: directly and its format may change at any time.
169 self
.teardown_request_funcs
: dict[
170 ft
.AppOrBlueprintKey
, list[ft
.TeardownCallable
]
171 ] = defaultdict(list)
173 #: A data structure of functions to call to pass extra context
174 #: values when rendering templates, in the format
175 #: ``{scope: [functions]}``. The ``scope`` key is the name of a
176 #: blueprint the functions are active for, or ``None`` for all
179 #: To register a function, use the :meth:`context_processor`
182 #: This data structure is internal. It should not be modified
183 #: directly and its format may change at any time.
184 self
.template_context_processors
: dict[
185 ft
.AppOrBlueprintKey
, list[ft
.TemplateContextProcessorCallable
]
186 ] = defaultdict(list, {None: [_default_template_ctx_processor]}
)
188 #: A data structure of functions to call to modify the keyword
189 #: arguments passed to the view function, in the format
190 #: ``{scope: [functions]}``. The ``scope`` key is the name of a
191 #: blueprint the functions are active for, or ``None`` for all
194 #: To register a function, use the
195 #: :meth:`url_value_preprocessor` decorator.
197 #: This data structure is internal. It should not be modified
198 #: directly and its format may change at any time.
199 self
.url_value_preprocessors
: dict[
200 ft
.AppOrBlueprintKey
,
201 list[ft
.URLValuePreprocessorCallable
],
202 ] = defaultdict(list)
204 #: A data structure of functions to call to modify the keyword
205 #: arguments when generating URLs, in the format
206 #: ``{scope: [functions]}``. The ``scope`` key is the name of a
207 #: blueprint the functions are active for, or ``None`` for all
210 #: To register a function, use the :meth:`url_defaults`
213 #: This data structure is internal. It should not be modified
214 #: directly and its format may change at any time.
215 self
.url_default_functions
: dict[
216 ft
.AppOrBlueprintKey
, list[ft
.URLDefaultCallable
]
217 ] = defaultdict(list)
219 def __repr__(self
) -> str:
220 return f
"<{type(self).__name__} {self.name!r}>"
222 def _check_setup_finished(self
, f_name
: str) -> None:
223 raise NotImplementedError
226 def static_folder(self
) -> str |
None:
227 """The absolute path to the configured static folder. ``None``
228 if no static folder is set.
230 if self
._static
_folder
is not None:
231 return os
.path
.join(self
.root_path
, self
._static
_folder
)
235 @static_folder.setter
236 def static_folder(self
, value
: str | os
.PathLike |
None) -> None:
237 if value
is not None:
238 value
= os
.fspath(value
).rstrip(r
"\/")
240 self
._static
_folder
= value
243 def has_static_folder(self
) -> bool:
244 """``True`` if :attr:`static_folder` is set.
246 .. versionadded:: 0.5
248 return self
.static_folder
is not None
251 def static_url_path(self
) -> str |
None:
252 """The URL prefix that the static route will be accessible from.
254 If it was not configured during init, it is derived from
255 :attr:`static_folder`.
257 if self
._static
_url
_path
is not None:
258 return self
._static
_url
_path
260 if self
.static_folder
is not None:
261 basename
= os
.path
.basename(self
.static_folder
)
262 return f
"/{basename}".rstrip("/")
266 @static_url_path.setter
267 def static_url_path(self
, value
: str |
None) -> None:
268 if value
is not None:
269 value
= value
.rstrip("/")
271 self
._static
_url
_path
= value
274 def jinja_loader(self
) -> FileSystemLoader |
None:
275 """The Jinja loader for this object's templates. By default this
276 is a class :class:`jinja2.loaders.FileSystemLoader` to
277 :attr:`template_folder` if it is set.
279 .. versionadded:: 0.5
281 if self
.template_folder
is not None:
282 return FileSystemLoader(os
.path
.join(self
.root_path
, self
.template_folder
))
291 ) -> t
.Callable
[[T_route
], T_route
]:
292 if "methods" in options
:
293 raise TypeError("Use the 'route' decorator to use the 'methods' argument.")
295 return self
.route(rule
, methods
=[method
], **options
)
298 def get(self
, rule
: str, **options
: t
.Any
) -> t
.Callable
[[T_route
], T_route
]:
299 """Shortcut for :meth:`route` with ``methods=["GET"]``.
301 .. versionadded:: 2.0
303 return self
._method
_route
("GET", rule
, options
)
306 def post(self
, rule
: str, **options
: t
.Any
) -> t
.Callable
[[T_route
], T_route
]:
307 """Shortcut for :meth:`route` with ``methods=["POST"]``.
309 .. versionadded:: 2.0
311 return self
._method
_route
("POST", rule
, options
)
314 def put(self
, rule
: str, **options
: t
.Any
) -> t
.Callable
[[T_route
], T_route
]:
315 """Shortcut for :meth:`route` with ``methods=["PUT"]``.
317 .. versionadded:: 2.0
319 return self
._method
_route
("PUT", rule
, options
)
322 def delete(self
, rule
: str, **options
: t
.Any
) -> t
.Callable
[[T_route
], T_route
]:
323 """Shortcut for :meth:`route` with ``methods=["DELETE"]``.
325 .. versionadded:: 2.0
327 return self
._method
_route
("DELETE", rule
, options
)
330 def patch(self
, rule
: str, **options
: t
.Any
) -> t
.Callable
[[T_route
], T_route
]:
331 """Shortcut for :meth:`route` with ``methods=["PATCH"]``.
333 .. versionadded:: 2.0
335 return self
._method
_route
("PATCH", rule
, options
)
338 def route(self
, rule
: str, **options
: t
.Any
) -> t
.Callable
[[T_route
], T_route
]:
339 """Decorate a view function to register it with the given URL
340 rule and options. Calls :meth:`add_url_rule`, which has more
341 details about the implementation.
343 .. code-block:: python
347 return "Hello, World!"
349 See :ref:`url-route-registrations`.
351 The endpoint name for the route defaults to the name of the view
352 function if the ``endpoint`` parameter isn't passed.
354 The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` and
355 ``OPTIONS`` are added automatically.
357 :param rule: The URL rule string.
358 :param options: Extra options passed to the
359 :class:`~werkzeug.routing.Rule` object.
362 def decorator(f
: T_route
) -> T_route
:
363 endpoint
= options
.pop("endpoint", None)
364 self
.add_url_rule(rule
, endpoint
, f
, **options
)
373 endpoint
: str |
None = None,
374 view_func
: ft
.RouteCallable |
None = None,
375 provide_automatic_options
: bool |
None = None,
378 """Register a rule for routing incoming requests and building
379 URLs. The :meth:`route` decorator is a shortcut to call this
380 with the ``view_func`` argument. These are equivalent:
382 .. code-block:: python
388 .. code-block:: python
393 app.add_url_rule("/", view_func=index)
395 See :ref:`url-route-registrations`.
397 The endpoint name for the route defaults to the name of the view
398 function if the ``endpoint`` parameter isn't passed. An error
399 will be raised if a function has already been registered for the
402 The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` is
403 always added automatically, and ``OPTIONS`` is added
404 automatically by default.
406 ``view_func`` does not necessarily need to be passed, but if the
407 rule should participate in routing an endpoint name must be
408 associated with a view function at some point with the
409 :meth:`endpoint` decorator.
411 .. code-block:: python
413 app.add_url_rule("/", endpoint="index")
415 @app.endpoint("index")
419 If ``view_func`` has a ``required_methods`` attribute, those
420 methods are added to the passed and automatic methods. If it
421 has a ``provide_automatic_methods`` attribute, it is used as the
422 default if the parameter is not passed.
424 :param rule: The URL rule string.
425 :param endpoint: The endpoint name to associate with the rule
426 and view function. Used when routing and building URLs.
427 Defaults to ``view_func.__name__``.
428 :param view_func: The view function to associate with the
430 :param provide_automatic_options: Add the ``OPTIONS`` method and
431 respond to ``OPTIONS`` requests automatically.
432 :param options: Extra options passed to the
433 :class:`~werkzeug.routing.Rule` object.
435 raise NotImplementedError
438 def endpoint(self
, endpoint
: str) -> t
.Callable
[[F
], F
]:
439 """Decorate a view function to register it for the given
440 endpoint. Used if a rule is added without a ``view_func`` with
441 :meth:`add_url_rule`.
443 .. code-block:: python
445 app.add_url_rule("/ex", endpoint="example")
447 @app.endpoint("example")
451 :param endpoint: The endpoint name to associate with the view
455 def decorator(f
: F
) -> F
:
456 self
.view_functions
[endpoint
] = f
462 def before_request(self
, f
: T_before_request
) -> T_before_request
:
463 """Register a function to run before each request.
465 For example, this can be used to open a database connection, or
466 to load the logged in user from the session.
468 .. code-block:: python
472 if "user_id" in session:
473 g.user = db.session.get(session["user_id"])
475 The function will be called without any arguments. If it returns
476 a non-``None`` value, the value is handled as if it was the
477 return value from the view, and further request handling is
480 This is available on both app and blueprint objects. When used on an app, this
481 executes before every request. When used on a blueprint, this executes before
482 every request that the blueprint handles. To register with a blueprint and
483 execute before every request, use :meth:`.Blueprint.before_app_request`.
485 self
.before_request_funcs
.setdefault(None, []).append(f
)
489 def after_request(self
, f
: T_after_request
) -> T_after_request
:
490 """Register a function to run after each request to this object.
492 The function is called with the response object, and must return
493 a response object. This allows the functions to modify or
494 replace the response before it is sent.
496 If a function raises an exception, any remaining
497 ``after_request`` functions will not be called. Therefore, this
498 should not be used for actions that must execute, such as to
499 close resources. Use :meth:`teardown_request` for that.
501 This is available on both app and blueprint objects. When used on an app, this
502 executes after every request. When used on a blueprint, this executes after
503 every request that the blueprint handles. To register with a blueprint and
504 execute after every request, use :meth:`.Blueprint.after_app_request`.
506 self
.after_request_funcs
.setdefault(None, []).append(f
)
510 def teardown_request(self
, f
: T_teardown
) -> T_teardown
:
511 """Register a function to be called when the request context is
512 popped. Typically this happens at the end of each request, but
513 contexts may be pushed manually as well during testing.
515 .. code-block:: python
517 with app.test_request_context():
520 When the ``with`` block exits (or ``ctx.pop()`` is called), the
521 teardown functions are called just before the request context is
524 When a teardown function was called because of an unhandled
525 exception it will be passed an error object. If an
526 :meth:`errorhandler` is registered, it will handle the exception
527 and the teardown will not receive it.
529 Teardown functions must avoid raising exceptions. If they
530 execute code that might fail they must surround that code with a
531 ``try``/``except`` block and log any errors.
533 The return values of teardown functions are ignored.
535 This is available on both app and blueprint objects. When used on an app, this
536 executes after every request. When used on a blueprint, this executes after
537 every request that the blueprint handles. To register with a blueprint and
538 execute after every request, use :meth:`.Blueprint.teardown_app_request`.
540 self
.teardown_request_funcs
.setdefault(None, []).append(f
)
544 def context_processor(
546 f
: T_template_context_processor
,
547 ) -> T_template_context_processor
:
548 """Registers a template context processor function. These functions run before
549 rendering a template. The keys of the returned dict are added as variables
550 available in the template.
552 This is available on both app and blueprint objects. When used on an app, this
553 is called for every rendered template. When used on a blueprint, this is called
554 for templates rendered from the blueprint's views. To register with a blueprint
555 and affect every template, use :meth:`.Blueprint.app_context_processor`.
557 self
.template_context_processors
[None].append(f
)
561 def url_value_preprocessor(
563 f
: T_url_value_preprocessor
,
564 ) -> T_url_value_preprocessor
:
565 """Register a URL value preprocessor function for all view
566 functions in the application. These functions will be called before the
567 :meth:`before_request` functions.
569 The function can modify the values captured from the matched url before
570 they are passed to the view. For example, this can be used to pop a
571 common language code value and place it in ``g`` rather than pass it to
574 The function is passed the endpoint name and values dict. The return
577 This is available on both app and blueprint objects. When used on an app, this
578 is called for every request. When used on a blueprint, this is called for
579 requests that the blueprint handles. To register with a blueprint and affect
580 every request, use :meth:`.Blueprint.app_url_value_preprocessor`.
582 self
.url_value_preprocessors
[None].append(f
)
586 def url_defaults(self
, f
: T_url_defaults
) -> T_url_defaults
:
587 """Callback function for URL defaults for all view functions of the
588 application. It's called with the endpoint and values and should
589 update the values passed in place.
591 This is available on both app and blueprint objects. When used on an app, this
592 is called for every request. When used on a blueprint, this is called for
593 requests that the blueprint handles. To register with a blueprint and affect
594 every request, use :meth:`.Blueprint.app_url_defaults`.
596 self
.url_default_functions
[None].append(f
)
601 self
, code_or_exception
: type[Exception] |
int
602 ) -> t
.Callable
[[T_error_handler
], T_error_handler
]:
603 """Register a function to handle errors by code or exception class.
605 A decorator that is used to register a function given an
606 error code. Example::
608 @app.errorhandler(404)
609 def page_not_found(error):
610 return 'This page does not exist', 404
612 You can also register handlers for arbitrary exceptions::
614 @app.errorhandler(DatabaseError)
615 def special_exception_handler(error):
616 return 'Database connection failed', 500
618 This is available on both app and blueprint objects. When used on an app, this
619 can handle errors from every request. When used on a blueprint, this can handle
620 errors from requests that the blueprint handles. To register with a blueprint
621 and affect every request, use :meth:`.Blueprint.app_errorhandler`.
623 .. versionadded:: 0.7
624 Use :meth:`register_error_handler` instead of modifying
625 :attr:`error_handler_spec` directly, for application wide error
628 .. versionadded:: 0.7
629 One can now additionally also register custom exception types
630 that do not necessarily have to be a subclass of the
631 :class:`~werkzeug.exceptions.HTTPException` class.
633 :param code_or_exception: the code as integer for the handler, or
634 an arbitrary exception
637 def decorator(f
: T_error_handler
) -> T_error_handler
:
638 self
.register_error_handler(code_or_exception
, f
)
644 def register_error_handler(
646 code_or_exception
: type[Exception] |
int,
647 f
: ft
.ErrorHandlerCallable
,
649 """Alternative error attach function to the :meth:`errorhandler`
650 decorator that is more straightforward to use for non decorator
653 .. versionadded:: 0.7
655 exc_class
, code
= self
._get
_exc
_class
_and
_code
(code_or_exception
)
656 self
.error_handler_spec
[None][code
][exc_class
] = f
659 def _get_exc_class_and_code(
660 exc_class_or_code
: type[Exception] |
int,
661 ) -> tuple[type[Exception], int |
None]:
662 """Get the exception class being handled. For HTTP status codes
663 or ``HTTPException`` subclasses, return both the exception and
666 :param exc_class_or_code: Any exception class, or an HTTP status
669 exc_class
: type[Exception]
671 if isinstance(exc_class_or_code
, int):
673 exc_class
= default_exceptions
[exc_class_or_code
]
676 f
"'{exc_class_or_code}' is not a recognized HTTP"
677 " error code. Use a subclass of HTTPException with"
678 " that code instead."
681 exc_class
= exc_class_or_code
683 if isinstance(exc_class
, Exception):
685 f
"{exc_class!r} is an instance, not a class. Handlers"
686 " can only be registered for Exception classes or HTTP"
690 if not issubclass(exc_class
, Exception):
692 f
"'{exc_class.__name__}' is not a subclass of Exception."
693 " Handlers can only be registered for Exception classes"
694 " or HTTP error codes."
697 if issubclass(exc_class
, HTTPException
):
698 return exc_class
, exc_class
.code
700 return exc_class
, None
703 def _endpoint_from_view_func(view_func
: t
.Callable
) -> str:
704 """Internal helper that returns the default endpoint for a given
705 function. This always is the function name.
707 assert view_func
is not None, "expected view func if endpoint is not provided."
708 return view_func
.__name
__
711 def _path_is_relative_to(path
: pathlib
.PurePath
, base
: str) -> bool:
712 # Path.is_relative_to doesn't exist until Python 3.9
714 path
.relative_to(base
)
720 def _find_package_path(import_name
):
721 """Find the path that contains the package or module."""
722 root_mod_name
, _
, _
= import_name
.partition(".")
725 root_spec
= importlib
.util
.find_spec(root_mod_name
)
727 if root_spec
is None:
728 raise ValueError("not found")
729 except (ImportError, ValueError):
730 # ImportError: the machinery told us it does not exist
732 # - the module name was invalid
733 # - the module name is __main__
734 # - we raised `ValueError` due to `root_spec` being `None`
737 if root_spec
.origin
in {"namespace", None}
:
739 package_spec
= importlib
.util
.find_spec(import_name
)
741 if package_spec
is not None and package_spec
.submodule_search_locations
:
742 # Pick the path in the namespace that contains the submodule.
743 package_path
= pathlib
.Path(
744 os
.path
.commonpath(package_spec
.submodule_search_locations
)
746 search_location
= next(
748 for location
in root_spec
.submodule_search_locations
749 if _path_is_relative_to(package_path
, location
)
752 # Pick the first path.
753 search_location
= root_spec
.submodule_search_locations
[0]
755 return os
.path
.dirname(search_location
)
756 elif root_spec
.submodule_search_locations
:
757 # package with __init__.py
758 return os
.path
.dirname(os
.path
.dirname(root_spec
.origin
))
761 return os
.path
.dirname(root_spec
.origin
)
764 def find_package(import_name
: str):
765 """Find the prefix that a package is installed under, and the path
766 that it would be imported from.
768 The prefix is the directory containing the standard directory
769 hierarchy (lib, bin, etc.). If the package is not installed to the
770 system (:attr:`sys.prefix`) or a virtualenv (``site-packages``),
771 ``None`` is returned.
773 The path is the entry in :attr:`sys.path` that contains the package
774 for import. If the package is not installed, it's assumed that the
775 package was imported from the current working directory.
777 package_path
= _find_package_path(import_name
)
778 py_prefix
= os
.path
.abspath(sys
.prefix
)
780 # installed to the system
781 if _path_is_relative_to(pathlib
.PurePath(package_path
), py_prefix
):
782 return py_prefix
, package_path
784 site_parent
, site_folder
= os
.path
.split(package_path
)
786 # installed to a virtualenv
787 if site_folder
.lower() == "site-packages":
788 parent
, folder
= os
.path
.split(site_parent
)
790 # Windows (prefix/lib/site-packages)
791 if folder
.lower() == "lib":
792 return parent
, package_path
794 # Unix (prefix/lib/pythonX.Y/site-packages)
795 if os
.path
.basename(parent
).lower() == "lib":
796 return os
.path
.dirname(parent
), package_path
798 # something else (prefix/site-packages)
799 return site_parent
, package_path
802 return None, package_path