debughelpers.py 5.4 KB

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