1
0

debughelpers.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. # -*- coding: utf-8 -*-
  2. """
  3. flask.debughelpers
  4. ~~~~~~~~~~~~~~~~~~
  5. Various helpers to make the development experience better.
  6. :copyright: 2010 Pallets
  7. :license: BSD-3-Clause
  8. """
  9. import os
  10. from warnings import warn
  11. from ._compat import implements_to_string
  12. from ._compat import text_type
  13. from .app import Flask
  14. from .blueprints import Blueprint
  15. from .globals import _request_ctx_stack
  16. class UnexpectedUnicodeError(AssertionError, UnicodeError):
  17. """Raised in places where we want some better error reporting for
  18. unexpected unicode or binary data.
  19. """
  20. @implements_to_string
  21. class DebugFilesKeyError(KeyError, AssertionError):
  22. """Raised from request.files during debugging. The idea is that it can
  23. provide a better error message than just a generic KeyError/BadRequest.
  24. """
  25. def __init__(self, request, key):
  26. form_matches = request.form.getlist(key)
  27. buf = [
  28. 'You tried to access the file "%s" in the request.files '
  29. "dictionary but it does not exist. The mimetype for the request "
  30. 'is "%s" instead of "multipart/form-data" which means that no '
  31. "file contents were transmitted. To fix this error you should "
  32. 'provide enctype="multipart/form-data" in your form.'
  33. % (key, request.mimetype)
  34. ]
  35. if form_matches:
  36. buf.append(
  37. "\n\nThe browser instead transmitted some file names. "
  38. "This was submitted: %s" % ", ".join('"%s"' % x for x in form_matches)
  39. )
  40. self.msg = "".join(buf)
  41. def __str__(self):
  42. return self.msg
  43. class FormDataRoutingRedirect(AssertionError):
  44. """This exception is raised by Flask in debug mode if it detects a
  45. redirect caused by the routing system when the request method is not
  46. GET, HEAD or OPTIONS. Reasoning: form data will be dropped.
  47. """
  48. def __init__(self, request):
  49. exc = request.routing_exception
  50. buf = [
  51. "A request was sent to this URL (%s) but a redirect was "
  52. 'issued automatically by the routing system to "%s".'
  53. % (request.url, exc.new_url)
  54. ]
  55. # In case just a slash was appended we can be extra helpful
  56. if request.base_url + "/" == exc.new_url.split("?")[0]:
  57. buf.append(
  58. " The URL was defined with a trailing slash so "
  59. "Flask will automatically redirect to the URL "
  60. "with the trailing slash if it was accessed "
  61. "without one."
  62. )
  63. buf.append(
  64. " Make sure to directly send your %s-request to this URL "
  65. "since we can't make browsers or HTTP clients redirect "
  66. "with form data reliably or without user interaction." % request.method
  67. )
  68. buf.append("\n\nNote: this exception is only raised in debug mode")
  69. AssertionError.__init__(self, "".join(buf).encode("utf-8"))
  70. def attach_enctype_error_multidict(request):
  71. """Since Flask 0.8 we're monkeypatching the files object in case a
  72. request is detected that does not use multipart form data but the files
  73. object is accessed.
  74. """
  75. oldcls = request.files.__class__
  76. class newcls(oldcls):
  77. def __getitem__(self, key):
  78. try:
  79. return oldcls.__getitem__(self, key)
  80. except KeyError:
  81. if key not in request.form:
  82. raise
  83. raise DebugFilesKeyError(request, key)
  84. newcls.__name__ = oldcls.__name__
  85. newcls.__module__ = oldcls.__module__
  86. request.files.__class__ = newcls
  87. def _dump_loader_info(loader):
  88. yield "class: %s.%s" % (type(loader).__module__, type(loader).__name__)
  89. for key, value in sorted(loader.__dict__.items()):
  90. if key.startswith("_"):
  91. continue
  92. if isinstance(value, (tuple, list)):
  93. if not all(isinstance(x, (str, text_type)) for x in value):
  94. continue
  95. yield "%s:" % key
  96. for item in value:
  97. yield " - %s" % item
  98. continue
  99. elif not isinstance(value, (str, text_type, int, float, bool)):
  100. continue
  101. yield "%s: %r" % (key, value)
  102. def explain_template_loading_attempts(app, template, attempts):
  103. """This should help developers understand what failed"""
  104. info = ['Locating template "%s":' % template]
  105. total_found = 0
  106. blueprint = None
  107. reqctx = _request_ctx_stack.top
  108. if reqctx is not None and reqctx.request.blueprint is not None:
  109. blueprint = reqctx.request.blueprint
  110. for idx, (loader, srcobj, triple) in enumerate(attempts):
  111. if isinstance(srcobj, Flask):
  112. src_info = 'application "%s"' % srcobj.import_name
  113. elif isinstance(srcobj, Blueprint):
  114. src_info = 'blueprint "%s" (%s)' % (srcobj.name, srcobj.import_name)
  115. else:
  116. src_info = repr(srcobj)
  117. info.append("% 5d: trying loader of %s" % (idx + 1, src_info))
  118. for line in _dump_loader_info(loader):
  119. info.append(" %s" % line)
  120. if triple is None:
  121. detail = "no match"
  122. else:
  123. detail = "found (%r)" % (triple[1] or "<string>")
  124. total_found += 1
  125. info.append(" -> %s" % detail)
  126. seems_fishy = False
  127. if total_found == 0:
  128. info.append("Error: the template could not be found.")
  129. seems_fishy = True
  130. elif total_found > 1:
  131. info.append("Warning: multiple loaders returned a match for the template.")
  132. seems_fishy = True
  133. if blueprint is not None and seems_fishy:
  134. info.append(
  135. " The template was looked up from an endpoint that "
  136. 'belongs to the blueprint "%s".' % blueprint
  137. )
  138. info.append(" Maybe you did not place a template in the right folder?")
  139. info.append(" See http://flask.pocoo.org/docs/blueprints/#templates")
  140. app.logger.info("\n".join(info))
  141. def explain_ignored_app_run():
  142. if os.environ.get("WERKZEUG_RUN_MAIN") != "true":
  143. warn(
  144. Warning(
  145. "Silently ignoring app.run() because the "
  146. "application is run from the flask command line "
  147. "executable. Consider putting app.run() behind an "
  148. 'if __name__ == "__main__" guard to silence this '
  149. "warning."
  150. ),
  151. stacklevel=3,
  152. )