debughelpers.py 6.3 KB

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