debughelpers.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. from __future__ import annotations
  2. import typing as t
  3. from .blueprints import Blueprint
  4. from .globals import request_ctx
  5. from .sansio.app import App
  6. class UnexpectedUnicodeError(AssertionError, UnicodeError):
  7. """Raised in places where we want some better error reporting for
  8. unexpected unicode or binary data.
  9. """
  10. class DebugFilesKeyError(KeyError, AssertionError):
  11. """Raised from request.files during debugging. The idea is that it can
  12. provide a better error message than just a generic KeyError/BadRequest.
  13. """
  14. def __init__(self, request, key):
  15. form_matches = request.form.getlist(key)
  16. buf = [
  17. f"You tried to access the file {key!r} in the request.files"
  18. " dictionary but it does not exist. The mimetype for the"
  19. f" request is {request.mimetype!r} instead of"
  20. " 'multipart/form-data' which means that no file contents"
  21. " were transmitted. To fix this error you should provide"
  22. ' enctype="multipart/form-data" in your form.'
  23. ]
  24. if form_matches:
  25. names = ", ".join(repr(x) for x in form_matches)
  26. buf.append(
  27. "\n\nThe browser instead transmitted some file names. "
  28. f"This was submitted: {names}"
  29. )
  30. self.msg = "".join(buf)
  31. def __str__(self):
  32. return self.msg
  33. class FormDataRoutingRedirect(AssertionError):
  34. """This exception is raised in debug mode if a routing redirect
  35. would cause the browser to drop the method or body. This happens
  36. when method is not GET, HEAD or OPTIONS and the status code is not
  37. 307 or 308.
  38. """
  39. def __init__(self, request):
  40. exc = request.routing_exception
  41. buf = [
  42. f"A request was sent to '{request.url}', but routing issued"
  43. f" a redirect to the canonical URL '{exc.new_url}'."
  44. ]
  45. if f"{request.base_url}/" == exc.new_url.partition("?")[0]:
  46. buf.append(
  47. " The URL was defined with a trailing slash. Flask"
  48. " will redirect to the URL with a trailing slash if it"
  49. " was accessed without one."
  50. )
  51. buf.append(
  52. " Send requests to the canonical URL, or use 307 or 308 for"
  53. " routing redirects. Otherwise, browsers will drop form"
  54. " data.\n\n"
  55. "This exception is only raised in debug mode."
  56. )
  57. super().__init__("".join(buf))
  58. def attach_enctype_error_multidict(request):
  59. """Patch ``request.files.__getitem__`` to raise a descriptive error
  60. about ``enctype=multipart/form-data``.
  61. :param request: The request to patch.
  62. :meta private:
  63. """
  64. oldcls = request.files.__class__
  65. class newcls(oldcls):
  66. def __getitem__(self, key):
  67. try:
  68. return super().__getitem__(key)
  69. except KeyError as e:
  70. if key not in request.form:
  71. raise
  72. raise DebugFilesKeyError(request, key).with_traceback(
  73. e.__traceback__
  74. ) from None
  75. newcls.__name__ = oldcls.__name__
  76. newcls.__module__ = oldcls.__module__
  77. request.files.__class__ = newcls
  78. def _dump_loader_info(loader) -> t.Generator:
  79. yield f"class: {type(loader).__module__}.{type(loader).__name__}"
  80. for key, value in sorted(loader.__dict__.items()):
  81. if key.startswith("_"):
  82. continue
  83. if isinstance(value, (tuple, list)):
  84. if not all(isinstance(x, str) for x in value):
  85. continue
  86. yield f"{key}:"
  87. for item in value:
  88. yield f" - {item}"
  89. continue
  90. elif not isinstance(value, (str, int, float, bool)):
  91. continue
  92. yield f"{key}: {value!r}"
  93. def explain_template_loading_attempts(app: App, template, attempts) -> None:
  94. """This should help developers understand what failed"""
  95. info = [f"Locating template {template!r}:"]
  96. total_found = 0
  97. blueprint = None
  98. if request_ctx and request_ctx.request.blueprint is not None:
  99. blueprint = request_ctx.request.blueprint
  100. for idx, (loader, srcobj, triple) in enumerate(attempts):
  101. if isinstance(srcobj, App):
  102. src_info = f"application {srcobj.import_name!r}"
  103. elif isinstance(srcobj, Blueprint):
  104. src_info = f"blueprint {srcobj.name!r} ({srcobj.import_name})"
  105. else:
  106. src_info = repr(srcobj)
  107. info.append(f"{idx + 1:5}: trying loader of {src_info}")
  108. for line in _dump_loader_info(loader):
  109. info.append(f" {line}")
  110. if triple is None:
  111. detail = "no match"
  112. else:
  113. detail = f"found ({triple[1] or '<string>'!r})"
  114. total_found += 1
  115. info.append(f" -> {detail}")
  116. seems_fishy = False
  117. if total_found == 0:
  118. info.append("Error: the template could not be found.")
  119. seems_fishy = True
  120. elif total_found > 1:
  121. info.append("Warning: multiple loaders returned a match for the template.")
  122. seems_fishy = True
  123. if blueprint is not None and seems_fishy:
  124. info.append(
  125. " The template was looked up from an endpoint that belongs"
  126. f" to the blueprint {blueprint!r}."
  127. )
  128. info.append(" Maybe you did not place a template in the right folder?")
  129. info.append(" See https://flask.palletsprojects.com/blueprints/#templates")
  130. app.logger.info("\n".join(info))