debughelpers.py
This file
Path
src/flask/debughelpers.py
158 lines · 5.4 KiB · Python
Last changed by
Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae
History of this fileTake it
1import typing as t23from .app import Flask4from .blueprints import Blueprint5from .globals import request_ctx678class UnexpectedUnicodeError(AssertionError, UnicodeError):9 """Raised in places where we want some better error reporting for10 unexpected unicode or binary data.11 """121314class DebugFilesKeyError(KeyError, AssertionError):15 """Raised from request.files during debugging. The idea is that it can16 provide a better error message than just a generic KeyError/BadRequest.17 """1819 def __init__(self, request, key):20 form_matches = request.form.getlist(key)21 buf = [22 f"You tried to access the file {key!r} in the request.files"23 " dictionary but it does not exist. The mimetype for the"24 f" request is {request.mimetype!r} instead of"25 " 'multipart/form-data' which means that no file contents"26 " were transmitted. To fix this error you should provide"27 ' enctype="multipart/form-data" in your form.'28 ]29 if form_matches:30 names = ", ".join(repr(x) for x in form_matches)31 buf.append(32 "\n\nThe browser instead transmitted some file names. "33 f"This was submitted: {names}"34 )35 self.msg = "".join(buf)3637 def __str__(self):38 return self.msg394041class FormDataRoutingRedirect(AssertionError):42 """This exception is raised in debug mode if a routing redirect43 would cause the browser to drop the method or body. This happens44 when method is not GET, HEAD or OPTIONS and the status code is not45 307 or 308.46 """4748 def __init__(self, request):49 exc = request.routing_exception50 buf = [51 f"A request was sent to '{request.url}', but routing issued"52 f" a redirect to the canonical URL '{exc.new_url}'."53 ]5455 if f"{request.base_url}/" == exc.new_url.partition("?")[0]:56 buf.append(57 " The URL was defined with a trailing slash. Flask"58 " will redirect to the URL with a trailing slash if it"59 " was accessed without one."60 )6162 buf.append(63 " Send requests to the canonical URL, or use 307 or 308 for"64 " routing redirects. Otherwise, browsers will drop form"65 " data.\n\n"66 "This exception is only raised in debug mode."67 )68 super().__init__("".join(buf))697071def attach_enctype_error_multidict(request):72 """Patch ``request.files.__getitem__`` to raise a descriptive error73 about ``enctype=multipart/form-data``.7475 :param request: The request to patch.76 :meta private:77 """78 oldcls = request.files.__class__7980 class newcls(oldcls):81 def __getitem__(self, key):82 try:83 return super().__getitem__(key)84 except KeyError as e:85 if key not in request.form:86 raise8788 raise DebugFilesKeyError(request, key).with_traceback(89 e.__traceback__90 ) from None9192 newcls.__name__ = oldcls.__name__93 newcls.__module__ = oldcls.__module__94 request.files.__class__ = newcls959697def _dump_loader_info(loader) -> t.Generator:98 yield f"class: {type(loader).__module__}.{type(loader).__name__}"99 for key, value in sorted(loader.__dict__.items()):100 if key.startswith("_"):101 continue102 if isinstance(value, (tuple, list)):103 if not all(isinstance(x, str) for x in value):104 continue105 yield f"{key}:"106 for item in value:107 yield f" - {item}"108 continue109 elif not isinstance(value, (str, int, float, bool)):110 continue111 yield f"{key}: {value!r}"112113114def explain_template_loading_attempts(app: Flask, template, attempts) -> None:115 """This should help developers understand what failed"""116 info = [f"Locating template {template!r}:"]117 total_found = 0118 blueprint = None119 if request_ctx and request_ctx.request.blueprint is not None:120 blueprint = request_ctx.request.blueprint121122 for idx, (loader, srcobj, triple) in enumerate(attempts):123 if isinstance(srcobj, Flask):124 src_info = f"application {srcobj.import_name!r}"125 elif isinstance(srcobj, Blueprint):126 src_info = f"blueprint {srcobj.name!r} ({srcobj.import_name})"127 else:128 src_info = repr(srcobj)129130 info.append(f"{idx + 1:5}: trying loader of {src_info}")131132 for line in _dump_loader_info(loader):133 info.append(f" {line}")134135 if triple is None:136 detail = "no match"137 else:138 detail = f"found ({triple[1] or '<string>'!r})"139 total_found += 1140 info.append(f" -> {detail}")141142 seems_fishy = False143 if total_found == 0:144 info.append("Error: the template could not be found.")145 seems_fishy = True146 elif total_found > 1:147 info.append("Warning: multiple loaders returned a match for the template.")148 seems_fishy = True149150 if blueprint is not None and seems_fishy:151 info.append(152 " The template was looked up from an endpoint that belongs"153 f" to the blueprint {blueprint!r}."154 )155 info.append(" Maybe you did not place a template in the right folder?")156 info.append(" See https://flask.palletsprojects.com/blueprints/#templates")157158 app.logger.info("\n".join(info))