debughelpers.py 5.9 KB

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