debughelpers.py 6.0 KB

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