You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

168 lines
5.5KB

  1. import typing as t
  2. from werkzeug.exceptions import BadRequest
  3. from werkzeug.wrappers import Request as RequestBase
  4. from werkzeug.wrappers import Response as ResponseBase
  5. from . import json
  6. from .globals import current_app
  7. from .helpers import _split_blueprint_path
  8. if t.TYPE_CHECKING:
  9. import typing_extensions as te
  10. from werkzeug.routing import Rule
  11. class Request(RequestBase):
  12. """The request object used by default in Flask. Remembers the
  13. matched endpoint and view arguments.
  14. It is what ends up as :class:`~flask.request`. If you want to replace
  15. the request object used you can subclass this and set
  16. :attr:`~flask.Flask.request_class` to your subclass.
  17. The request object is a :class:`~werkzeug.wrappers.Request` subclass and
  18. provides all of the attributes Werkzeug defines plus a few Flask
  19. specific ones.
  20. """
  21. json_module = json
  22. #: The internal URL rule that matched the request. This can be
  23. #: useful to inspect which methods are allowed for the URL from
  24. #: a before/after handler (``request.url_rule.methods``) etc.
  25. #: Though if the request's method was invalid for the URL rule,
  26. #: the valid list is available in ``routing_exception.valid_methods``
  27. #: instead (an attribute of the Werkzeug exception
  28. #: :exc:`~werkzeug.exceptions.MethodNotAllowed`)
  29. #: because the request was never internally bound.
  30. #:
  31. #: .. versionadded:: 0.6
  32. url_rule: t.Optional["Rule"] = None
  33. #: A dict of view arguments that matched the request. If an exception
  34. #: happened when matching, this will be ``None``.
  35. view_args: t.Optional[t.Dict[str, t.Any]] = None
  36. #: If matching the URL failed, this is the exception that will be
  37. #: raised / was raised as part of the request handling. This is
  38. #: usually a :exc:`~werkzeug.exceptions.NotFound` exception or
  39. #: something similar.
  40. routing_exception: t.Optional[Exception] = None
  41. @property
  42. def max_content_length(self) -> t.Optional[int]: # type: ignore
  43. """Read-only view of the ``MAX_CONTENT_LENGTH`` config key."""
  44. if current_app:
  45. return current_app.config["MAX_CONTENT_LENGTH"]
  46. else:
  47. return None
  48. @property
  49. def endpoint(self) -> t.Optional[str]:
  50. """The endpoint that matched the request URL.
  51. This will be ``None`` if matching failed or has not been
  52. performed yet.
  53. This in combination with :attr:`view_args` can be used to
  54. reconstruct the same URL or a modified URL.
  55. """
  56. if self.url_rule is not None:
  57. return self.url_rule.endpoint
  58. return None
  59. @property
  60. def blueprint(self) -> t.Optional[str]:
  61. """The registered name of the current blueprint.
  62. This will be ``None`` if the endpoint is not part of a
  63. blueprint, or if URL matching failed or has not been performed
  64. yet.
  65. This does not necessarily match the name the blueprint was
  66. created with. It may have been nested, or registered with a
  67. different name.
  68. """
  69. endpoint = self.endpoint
  70. if endpoint is not None and "." in endpoint:
  71. return endpoint.rpartition(".")[0]
  72. return None
  73. @property
  74. def blueprints(self) -> t.List[str]:
  75. """The registered names of the current blueprint upwards through
  76. parent blueprints.
  77. This will be an empty list if there is no current blueprint, or
  78. if URL matching failed.
  79. .. versionadded:: 2.0.1
  80. """
  81. name = self.blueprint
  82. if name is None:
  83. return []
  84. return _split_blueprint_path(name)
  85. def _load_form_data(self) -> None:
  86. RequestBase._load_form_data(self)
  87. # In debug mode we're replacing the files multidict with an ad-hoc
  88. # subclass that raises a different error for key errors.
  89. if (
  90. current_app
  91. and current_app.debug
  92. and self.mimetype != "multipart/form-data"
  93. and not self.files
  94. ):
  95. from .debughelpers import attach_enctype_error_multidict
  96. attach_enctype_error_multidict(self)
  97. def on_json_loading_failed(self, e: Exception) -> "te.NoReturn":
  98. if current_app and current_app.debug:
  99. raise BadRequest(f"Failed to decode JSON object: {e}")
  100. raise BadRequest()
  101. class Response(ResponseBase):
  102. """The response object that is used by default in Flask. Works like the
  103. response object from Werkzeug but is set to have an HTML mimetype by
  104. default. Quite often you don't have to create this object yourself because
  105. :meth:`~flask.Flask.make_response` will take care of that for you.
  106. If you want to replace the response object used you can subclass this and
  107. set :attr:`~flask.Flask.response_class` to your subclass.
  108. .. versionchanged:: 1.0
  109. JSON support is added to the response, like the request. This is useful
  110. when testing to get the test client response data as JSON.
  111. .. versionchanged:: 1.0
  112. Added :attr:`max_cookie_size`.
  113. """
  114. default_mimetype = "text/html"
  115. json_module = json
  116. @property
  117. def max_cookie_size(self) -> int: # type: ignore
  118. """Read-only view of the :data:`MAX_COOKIE_SIZE` config key.
  119. See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in
  120. Werkzeug's docs.
  121. """
  122. if current_app:
  123. return current_app.config["MAX_COOKIE_SIZE"]
  124. # return Werkzeug's default when not in an app context
  125. return super().max_cookie_size