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.

172 lines
6.0KB

  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 by Flask in debug mode if it detects a
  36. redirect caused by the routing system when the request method is not
  37. GET, HEAD or OPTIONS. Reasoning: form data will be dropped.
  38. """
  39. def __init__(self, request):
  40. exc = request.routing_exception
  41. buf = [
  42. f"A request was sent to this URL ({request.url}) but a"
  43. " redirect was issued automatically by the routing system"
  44. f" to {exc.new_url!r}."
  45. ]
  46. # In case just a slash was appended we can be extra helpful
  47. if f"{request.base_url}/" == exc.new_url.split("?")[0]:
  48. buf.append(
  49. " The URL was defined with a trailing slash so Flask"
  50. " will automatically redirect to the URL with the"
  51. " trailing slash if it was accessed without one."
  52. )
  53. buf.append(
  54. " Make sure to directly send your"
  55. f" {request.method}-request to this URL since we can't make"
  56. " browsers or HTTP clients redirect with form data reliably"
  57. " or without user interaction."
  58. )
  59. buf.append("\n\nNote: this exception is only raised in debug mode")
  60. AssertionError.__init__(self, "".join(buf).encode("utf-8"))
  61. def attach_enctype_error_multidict(request):
  62. """Since Flask 0.8 we're monkeypatching the files object in case a
  63. request is detected that does not use multipart form data but the files
  64. object is accessed.
  65. """
  66. oldcls = request.files.__class__
  67. class newcls(oldcls):
  68. def __getitem__(self, key):
  69. try:
  70. return oldcls.__getitem__(self, key)
  71. except KeyError:
  72. if key not in request.form:
  73. raise
  74. raise DebugFilesKeyError(request, key)
  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: Flask, 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. reqctx = _request_ctx_stack.top
  99. if reqctx is not None and reqctx.request.blueprint is not None:
  100. blueprint = reqctx.request.blueprint
  101. for idx, (loader, srcobj, triple) in enumerate(attempts):
  102. if isinstance(srcobj, Flask):
  103. src_info = f"application {srcobj.import_name!r}"
  104. elif isinstance(srcobj, Blueprint):
  105. src_info = f"blueprint {srcobj.name!r} ({srcobj.import_name})"
  106. else:
  107. src_info = repr(srcobj)
  108. info.append(f"{idx + 1:5}: trying loader of {src_info}")
  109. for line in _dump_loader_info(loader):
  110. info.append(f" {line}")
  111. if triple is None:
  112. detail = "no match"
  113. else:
  114. detail = f"found ({triple[1] or '<string>'!r})"
  115. total_found += 1
  116. info.append(f" -> {detail}")
  117. seems_fishy = False
  118. if total_found == 0:
  119. info.append("Error: the template could not be found.")
  120. seems_fishy = True
  121. elif total_found > 1:
  122. info.append("Warning: multiple loaders returned a match for the template.")
  123. seems_fishy = True
  124. if blueprint is not None and seems_fishy:
  125. info.append(
  126. " The template was looked up from an endpoint that belongs"
  127. f" to the blueprint {blueprint!r}."
  128. )
  129. info.append(" Maybe you did not place a template in the right folder?")
  130. info.append(" See https://flask.palletsprojects.com/blueprints/#templates")
  131. app.logger.info("\n".join(info))
  132. def explain_ignored_app_run() -> None:
  133. if os.environ.get("WERKZEUG_RUN_MAIN") != "true":
  134. warn(
  135. Warning(
  136. "Silently ignoring app.run() because the application is"
  137. " run from the flask command line executable. Consider"
  138. ' putting app.run() behind an if __name__ == "__main__"'
  139. " guard to silence this warning."
  140. ),
  141. stacklevel=3,
  142. )