utils.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. import io
  2. import mimetypes
  3. import os
  4. import pkgutil
  5. import re
  6. import sys
  7. import typing as t
  8. import unicodedata
  9. from datetime import datetime
  10. from time import time
  11. from zlib import adler32
  12. from markupsafe import escape
  13. from ._internal import _DictAccessorProperty
  14. from ._internal import _missing
  15. from ._internal import _TAccessorValue
  16. from .datastructures import Headers
  17. from .exceptions import NotFound
  18. from .exceptions import RequestedRangeNotSatisfiable
  19. from .security import safe_join
  20. from .urls import url_quote
  21. from .wsgi import wrap_file
  22. if t.TYPE_CHECKING:
  23. from _typeshed.wsgi import WSGIEnvironment
  24. from .wrappers.request import Request
  25. from .wrappers.response import Response
  26. _T = t.TypeVar("_T")
  27. _entity_re = re.compile(r"&([^;]+);")
  28. _filename_ascii_strip_re = re.compile(r"[^A-Za-z0-9_.-]")
  29. _windows_device_files = (
  30. "CON",
  31. "AUX",
  32. "COM1",
  33. "COM2",
  34. "COM3",
  35. "COM4",
  36. "LPT1",
  37. "LPT2",
  38. "LPT3",
  39. "PRN",
  40. "NUL",
  41. )
  42. class cached_property(property, t.Generic[_T]):
  43. """A :func:`property` that is only evaluated once. Subsequent access
  44. returns the cached value. Setting the property sets the cached
  45. value. Deleting the property clears the cached value, accessing it
  46. again will evaluate it again.
  47. .. code-block:: python
  48. class Example:
  49. @cached_property
  50. def value(self):
  51. # calculate something important here
  52. return 42
  53. e = Example()
  54. e.value # evaluates
  55. e.value # uses cache
  56. e.value = 16 # sets cache
  57. del e.value # clears cache
  58. If the class defines ``__slots__``, it must add ``_cache_{name}`` as
  59. a slot. Alternatively, it can add ``__dict__``, but that's usually
  60. not desirable.
  61. .. versionchanged:: 2.1
  62. Works with ``__slots__``.
  63. .. versionchanged:: 2.0
  64. ``del obj.name`` clears the cached value.
  65. """
  66. def __init__(
  67. self,
  68. fget: t.Callable[[t.Any], _T],
  69. name: t.Optional[str] = None,
  70. doc: t.Optional[str] = None,
  71. ) -> None:
  72. super().__init__(fget, doc=doc)
  73. self.__name__ = name or fget.__name__
  74. self.slot_name = f"_cache_{self.__name__}"
  75. self.__module__ = fget.__module__
  76. def __set__(self, obj: object, value: _T) -> None:
  77. if hasattr(obj, "__dict__"):
  78. obj.__dict__[self.__name__] = value
  79. else:
  80. setattr(obj, self.slot_name, value)
  81. def __get__(self, obj: object, type: type = None) -> _T: # type: ignore
  82. if obj is None:
  83. return self # type: ignore
  84. obj_dict = getattr(obj, "__dict__", None)
  85. if obj_dict is not None:
  86. value: _T = obj_dict.get(self.__name__, _missing)
  87. else:
  88. value = getattr(obj, self.slot_name, _missing) # type: ignore[arg-type]
  89. if value is _missing:
  90. value = self.fget(obj) # type: ignore
  91. if obj_dict is not None:
  92. obj.__dict__[self.__name__] = value
  93. else:
  94. setattr(obj, self.slot_name, value)
  95. return value
  96. def __delete__(self, obj: object) -> None:
  97. if hasattr(obj, "__dict__"):
  98. del obj.__dict__[self.__name__]
  99. else:
  100. setattr(obj, self.slot_name, _missing)
  101. class environ_property(_DictAccessorProperty[_TAccessorValue]):
  102. """Maps request attributes to environment variables. This works not only
  103. for the Werkzeug request object, but also any other class with an
  104. environ attribute:
  105. >>> class Test(object):
  106. ... environ = {'key': 'value'}
  107. ... test = environ_property('key')
  108. >>> var = Test()
  109. >>> var.test
  110. 'value'
  111. If you pass it a second value it's used as default if the key does not
  112. exist, the third one can be a converter that takes a value and converts
  113. it. If it raises :exc:`ValueError` or :exc:`TypeError` the default value
  114. is used. If no default value is provided `None` is used.
  115. Per default the property is read only. You have to explicitly enable it
  116. by passing ``read_only=False`` to the constructor.
  117. """
  118. read_only = True
  119. def lookup(self, obj: "Request") -> "WSGIEnvironment":
  120. return obj.environ
  121. class header_property(_DictAccessorProperty[_TAccessorValue]):
  122. """Like `environ_property` but for headers."""
  123. def lookup(self, obj: t.Union["Request", "Response"]) -> Headers:
  124. return obj.headers
  125. # https://cgit.freedesktop.org/xdg/shared-mime-info/tree/freedesktop.org.xml.in
  126. # https://www.iana.org/assignments/media-types/media-types.xhtml
  127. # Types listed in the XDG mime info that have a charset in the IANA registration.
  128. _charset_mimetypes = {
  129. "application/ecmascript",
  130. "application/javascript",
  131. "application/sql",
  132. "application/xml",
  133. "application/xml-dtd",
  134. "application/xml-external-parsed-entity",
  135. }
  136. def get_content_type(mimetype: str, charset: str) -> str:
  137. """Returns the full content type string with charset for a mimetype.
  138. If the mimetype represents text, the charset parameter will be
  139. appended, otherwise the mimetype is returned unchanged.
  140. :param mimetype: The mimetype to be used as content type.
  141. :param charset: The charset to be appended for text mimetypes.
  142. :return: The content type.
  143. .. versionchanged:: 0.15
  144. Any type that ends with ``+xml`` gets a charset, not just those
  145. that start with ``application/``. Known text types such as
  146. ``application/javascript`` are also given charsets.
  147. """
  148. if (
  149. mimetype.startswith("text/")
  150. or mimetype in _charset_mimetypes
  151. or mimetype.endswith("+xml")
  152. ):
  153. mimetype += f"; charset={charset}"
  154. return mimetype
  155. def secure_filename(filename: str) -> str:
  156. r"""Pass it a filename and it will return a secure version of it. This
  157. filename can then safely be stored on a regular file system and passed
  158. to :func:`os.path.join`. The filename returned is an ASCII only string
  159. for maximum portability.
  160. On windows systems the function also makes sure that the file is not
  161. named after one of the special device files.
  162. >>> secure_filename("My cool movie.mov")
  163. 'My_cool_movie.mov'
  164. >>> secure_filename("../../../etc/passwd")
  165. 'etc_passwd'
  166. >>> secure_filename('i contain cool \xfcml\xe4uts.txt')
  167. 'i_contain_cool_umlauts.txt'
  168. The function might return an empty filename. It's your responsibility
  169. to ensure that the filename is unique and that you abort or
  170. generate a random filename if the function returned an empty one.
  171. .. versionadded:: 0.5
  172. :param filename: the filename to secure
  173. """
  174. filename = unicodedata.normalize("NFKD", filename)
  175. filename = filename.encode("ascii", "ignore").decode("ascii")
  176. for sep in os.path.sep, os.path.altsep:
  177. if sep:
  178. filename = filename.replace(sep, " ")
  179. filename = str(_filename_ascii_strip_re.sub("", "_".join(filename.split()))).strip(
  180. "._"
  181. )
  182. # on nt a couple of special files are present in each folder. We
  183. # have to ensure that the target file is not such a filename. In
  184. # this case we prepend an underline
  185. if (
  186. os.name == "nt"
  187. and filename
  188. and filename.split(".")[0].upper() in _windows_device_files
  189. ):
  190. filename = f"_{filename}"
  191. return filename
  192. def redirect(
  193. location: str, code: int = 302, Response: t.Optional[t.Type["Response"]] = None
  194. ) -> "Response":
  195. """Returns a response object (a WSGI application) that, if called,
  196. redirects the client to the target location. Supported codes are
  197. 301, 302, 303, 305, 307, and 308. 300 is not supported because
  198. it's not a real redirect and 304 because it's the answer for a
  199. request with a request with defined If-Modified-Since headers.
  200. .. versionadded:: 0.6
  201. The location can now be a unicode string that is encoded using
  202. the :func:`iri_to_uri` function.
  203. .. versionadded:: 0.10
  204. The class used for the Response object can now be passed in.
  205. :param location: the location the response should redirect to.
  206. :param code: the redirect status code. defaults to 302.
  207. :param class Response: a Response class to use when instantiating a
  208. response. The default is :class:`werkzeug.wrappers.Response` if
  209. unspecified.
  210. """
  211. if Response is None:
  212. from .wrappers import Response # type: ignore
  213. display_location = escape(location)
  214. if isinstance(location, str):
  215. # Safe conversion is necessary here as we might redirect
  216. # to a broken URI scheme (for instance itms-services).
  217. from .urls import iri_to_uri
  218. location = iri_to_uri(location, safe_conversion=True)
  219. response = Response( # type: ignore
  220. "<!doctype html>\n"
  221. "<html lang=en>\n"
  222. "<title>Redirecting...</title>\n"
  223. "<h1>Redirecting...</h1>\n"
  224. "<p>You should be redirected automatically to the target URL: "
  225. f'<a href="{escape(location)}">{display_location}</a>. If'
  226. " not, click the link.\n",
  227. code,
  228. mimetype="text/html",
  229. )
  230. response.headers["Location"] = location
  231. return response
  232. def append_slash_redirect(environ: "WSGIEnvironment", code: int = 308) -> "Response":
  233. """Redirect to the current URL with a slash appended.
  234. If the current URL is ``/user/42``, the redirect URL will be
  235. ``42/``. When joined to the current URL during response
  236. processing or by the browser, this will produce ``/user/42/``.
  237. The behavior is undefined if the path ends with a slash already. If
  238. called unconditionally on a URL, it may produce a redirect loop.
  239. :param environ: Use the path and query from this WSGI environment
  240. to produce the redirect URL.
  241. :param code: the status code for the redirect.
  242. .. versionchanged:: 2.1
  243. Produce a relative URL that only modifies the last segment.
  244. Relevant when the current path has multiple segments.
  245. .. versionchanged:: 2.1
  246. The default status code is 308 instead of 301. This preserves
  247. the request method and body.
  248. """
  249. tail = environ["PATH_INFO"].rpartition("/")[2]
  250. if not tail:
  251. new_path = "./"
  252. else:
  253. new_path = f"{tail}/"
  254. query_string = environ.get("QUERY_STRING")
  255. if query_string:
  256. new_path = f"{new_path}?{query_string}"
  257. return redirect(new_path, code)
  258. def send_file(
  259. path_or_file: t.Union[os.PathLike, str, t.IO[bytes]],
  260. environ: "WSGIEnvironment",
  261. mimetype: t.Optional[str] = None,
  262. as_attachment: bool = False,
  263. download_name: t.Optional[str] = None,
  264. conditional: bool = True,
  265. etag: t.Union[bool, str] = True,
  266. last_modified: t.Optional[t.Union[datetime, int, float]] = None,
  267. max_age: t.Optional[
  268. t.Union[int, t.Callable[[t.Optional[str]], t.Optional[int]]]
  269. ] = None,
  270. use_x_sendfile: bool = False,
  271. response_class: t.Optional[t.Type["Response"]] = None,
  272. _root_path: t.Optional[t.Union[os.PathLike, str]] = None,
  273. ) -> "Response":
  274. """Send the contents of a file to the client.
  275. The first argument can be a file path or a file-like object. Paths
  276. are preferred in most cases because Werkzeug can manage the file and
  277. get extra information from the path. Passing a file-like object
  278. requires that the file is opened in binary mode, and is mostly
  279. useful when building a file in memory with :class:`io.BytesIO`.
  280. Never pass file paths provided by a user. The path is assumed to be
  281. trusted, so a user could craft a path to access a file you didn't
  282. intend.
  283. If the WSGI server sets a ``file_wrapper`` in ``environ``, it is
  284. used, otherwise Werkzeug's built-in wrapper is used. Alternatively,
  285. if the HTTP server supports ``X-Sendfile``, ``use_x_sendfile=True``
  286. will tell the server to send the given path, which is much more
  287. efficient than reading it in Python.
  288. :param path_or_file: The path to the file to send, relative to the
  289. current working directory if a relative path is given.
  290. Alternatively, a file-like object opened in binary mode. Make
  291. sure the file pointer is seeked to the start of the data.
  292. :param environ: The WSGI environ for the current request.
  293. :param mimetype: The MIME type to send for the file. If not
  294. provided, it will try to detect it from the file name.
  295. :param as_attachment: Indicate to a browser that it should offer to
  296. save the file instead of displaying it.
  297. :param download_name: The default name browsers will use when saving
  298. the file. Defaults to the passed file name.
  299. :param conditional: Enable conditional and range responses based on
  300. request headers. Requires passing a file path and ``environ``.
  301. :param etag: Calculate an ETag for the file, which requires passing
  302. a file path. Can also be a string to use instead.
  303. :param last_modified: The last modified time to send for the file,
  304. in seconds. If not provided, it will try to detect it from the
  305. file path.
  306. :param max_age: How long the client should cache the file, in
  307. seconds. If set, ``Cache-Control`` will be ``public``, otherwise
  308. it will be ``no-cache`` to prefer conditional caching.
  309. :param use_x_sendfile: Set the ``X-Sendfile`` header to let the
  310. server to efficiently send the file. Requires support from the
  311. HTTP server. Requires passing a file path.
  312. :param response_class: Build the response using this class. Defaults
  313. to :class:`~werkzeug.wrappers.Response`.
  314. :param _root_path: Do not use. For internal use only. Use
  315. :func:`send_from_directory` to safely send files under a path.
  316. .. versionchanged:: 2.0.2
  317. ``send_file`` only sets a detected ``Content-Encoding`` if
  318. ``as_attachment`` is disabled.
  319. .. versionadded:: 2.0
  320. Adapted from Flask's implementation.
  321. .. versionchanged:: 2.0
  322. ``download_name`` replaces Flask's ``attachment_filename``
  323. parameter. If ``as_attachment=False``, it is passed with
  324. ``Content-Disposition: inline`` instead.
  325. .. versionchanged:: 2.0
  326. ``max_age`` replaces Flask's ``cache_timeout`` parameter.
  327. ``conditional`` is enabled and ``max_age`` is not set by
  328. default.
  329. .. versionchanged:: 2.0
  330. ``etag`` replaces Flask's ``add_etags`` parameter. It can be a
  331. string to use instead of generating one.
  332. .. versionchanged:: 2.0
  333. If an encoding is returned when guessing ``mimetype`` from
  334. ``download_name``, set the ``Content-Encoding`` header.
  335. """
  336. if response_class is None:
  337. from .wrappers import Response
  338. response_class = Response
  339. path: t.Optional[str] = None
  340. file: t.Optional[t.IO[bytes]] = None
  341. size: t.Optional[int] = None
  342. mtime: t.Optional[float] = None
  343. headers = Headers()
  344. if isinstance(path_or_file, (os.PathLike, str)) or hasattr(
  345. path_or_file, "__fspath__"
  346. ):
  347. path_or_file = t.cast(t.Union[os.PathLike, str], path_or_file)
  348. # Flask will pass app.root_path, allowing its send_file wrapper
  349. # to not have to deal with paths.
  350. if _root_path is not None:
  351. path = os.path.join(_root_path, path_or_file)
  352. else:
  353. path = os.path.abspath(path_or_file)
  354. stat = os.stat(path)
  355. size = stat.st_size
  356. mtime = stat.st_mtime
  357. else:
  358. file = path_or_file
  359. if download_name is None and path is not None:
  360. download_name = os.path.basename(path)
  361. if mimetype is None:
  362. if download_name is None:
  363. raise TypeError(
  364. "Unable to detect the MIME type because a file name is"
  365. " not available. Either set 'download_name', pass a"
  366. " path instead of a file, or set 'mimetype'."
  367. )
  368. mimetype, encoding = mimetypes.guess_type(download_name)
  369. if mimetype is None:
  370. mimetype = "application/octet-stream"
  371. # Don't send encoding for attachments, it causes browsers to
  372. # save decompress tar.gz files.
  373. if encoding is not None and not as_attachment:
  374. headers.set("Content-Encoding", encoding)
  375. if download_name is not None:
  376. try:
  377. download_name.encode("ascii")
  378. except UnicodeEncodeError:
  379. simple = unicodedata.normalize("NFKD", download_name)
  380. simple = simple.encode("ascii", "ignore").decode("ascii")
  381. quoted = url_quote(download_name, safe="")
  382. names = {"filename": simple, "filename*": f"UTF-8''{quoted}"}
  383. else:
  384. names = {"filename": download_name}
  385. value = "attachment" if as_attachment else "inline"
  386. headers.set("Content-Disposition", value, **names)
  387. elif as_attachment:
  388. raise TypeError(
  389. "No name provided for attachment. Either set"
  390. " 'download_name' or pass a path instead of a file."
  391. )
  392. if use_x_sendfile and path is not None:
  393. headers["X-Sendfile"] = path
  394. data = None
  395. else:
  396. if file is None:
  397. file = open(path, "rb") # type: ignore
  398. elif isinstance(file, io.BytesIO):
  399. size = file.getbuffer().nbytes
  400. elif isinstance(file, io.TextIOBase):
  401. raise ValueError("Files must be opened in binary mode or use BytesIO.")
  402. data = wrap_file(environ, file)
  403. rv = response_class(
  404. data, mimetype=mimetype, headers=headers, direct_passthrough=True
  405. )
  406. if size is not None:
  407. rv.content_length = size
  408. if last_modified is not None:
  409. rv.last_modified = last_modified # type: ignore
  410. elif mtime is not None:
  411. rv.last_modified = mtime # type: ignore
  412. rv.cache_control.no_cache = True
  413. # Flask will pass app.get_send_file_max_age, allowing its send_file
  414. # wrapper to not have to deal with paths.
  415. if callable(max_age):
  416. max_age = max_age(path)
  417. if max_age is not None:
  418. if max_age > 0:
  419. rv.cache_control.no_cache = None
  420. rv.cache_control.public = True
  421. rv.cache_control.max_age = max_age
  422. rv.expires = int(time() + max_age) # type: ignore
  423. if isinstance(etag, str):
  424. rv.set_etag(etag)
  425. elif etag and path is not None:
  426. check = adler32(path.encode("utf-8")) & 0xFFFFFFFF
  427. rv.set_etag(f"{mtime}-{size}-{check}")
  428. if conditional:
  429. try:
  430. rv = rv.make_conditional(environ, accept_ranges=True, complete_length=size)
  431. except RequestedRangeNotSatisfiable:
  432. if file is not None:
  433. file.close()
  434. raise
  435. # Some x-sendfile implementations incorrectly ignore the 304
  436. # status code and send the file anyway.
  437. if rv.status_code == 304:
  438. rv.headers.pop("x-sendfile", None)
  439. return rv
  440. def send_from_directory(
  441. directory: t.Union[os.PathLike, str],
  442. path: t.Union[os.PathLike, str],
  443. environ: "WSGIEnvironment",
  444. **kwargs: t.Any,
  445. ) -> "Response":
  446. """Send a file from within a directory using :func:`send_file`.
  447. This is a secure way to serve files from a folder, such as static
  448. files or uploads. Uses :func:`~werkzeug.security.safe_join` to
  449. ensure the path coming from the client is not maliciously crafted to
  450. point outside the specified directory.
  451. If the final path does not point to an existing regular file,
  452. returns a 404 :exc:`~werkzeug.exceptions.NotFound` error.
  453. :param directory: The directory that ``path`` must be located under.
  454. :param path: The path to the file to send, relative to
  455. ``directory``.
  456. :param environ: The WSGI environ for the current request.
  457. :param kwargs: Arguments to pass to :func:`send_file`.
  458. .. versionadded:: 2.0
  459. Adapted from Flask's implementation.
  460. """
  461. path = safe_join(os.fspath(directory), os.fspath(path))
  462. if path is None:
  463. raise NotFound()
  464. # Flask will pass app.root_path, allowing its send_from_directory
  465. # wrapper to not have to deal with paths.
  466. if "_root_path" in kwargs:
  467. path = os.path.join(kwargs["_root_path"], path)
  468. try:
  469. if not os.path.isfile(path):
  470. raise NotFound()
  471. except ValueError:
  472. # path contains null byte on Python < 3.8
  473. raise NotFound() from None
  474. return send_file(path, environ, **kwargs)
  475. def import_string(import_name: str, silent: bool = False) -> t.Any:
  476. """Imports an object based on a string. This is useful if you want to
  477. use import paths as endpoints or something similar. An import path can
  478. be specified either in dotted notation (``xml.sax.saxutils.escape``)
  479. or with a colon as object delimiter (``xml.sax.saxutils:escape``).
  480. If `silent` is True the return value will be `None` if the import fails.
  481. :param import_name: the dotted name for the object to import.
  482. :param silent: if set to `True` import errors are ignored and
  483. `None` is returned instead.
  484. :return: imported object
  485. """
  486. import_name = import_name.replace(":", ".")
  487. try:
  488. try:
  489. __import__(import_name)
  490. except ImportError:
  491. if "." not in import_name:
  492. raise
  493. else:
  494. return sys.modules[import_name]
  495. module_name, obj_name = import_name.rsplit(".", 1)
  496. module = __import__(module_name, globals(), locals(), [obj_name])
  497. try:
  498. return getattr(module, obj_name)
  499. except AttributeError as e:
  500. raise ImportError(e) from None
  501. except ImportError as e:
  502. if not silent:
  503. raise ImportStringError(import_name, e).with_traceback(
  504. sys.exc_info()[2]
  505. ) from None
  506. return None
  507. def find_modules(
  508. import_path: str, include_packages: bool = False, recursive: bool = False
  509. ) -> t.Iterator[str]:
  510. """Finds all the modules below a package. This can be useful to
  511. automatically import all views / controllers so that their metaclasses /
  512. function decorators have a chance to register themselves on the
  513. application.
  514. Packages are not returned unless `include_packages` is `True`. This can
  515. also recursively list modules but in that case it will import all the
  516. packages to get the correct load path of that module.
  517. :param import_path: the dotted name for the package to find child modules.
  518. :param include_packages: set to `True` if packages should be returned, too.
  519. :param recursive: set to `True` if recursion should happen.
  520. :return: generator
  521. """
  522. module = import_string(import_path)
  523. path = getattr(module, "__path__", None)
  524. if path is None:
  525. raise ValueError(f"{import_path!r} is not a package")
  526. basename = f"{module.__name__}."
  527. for _importer, modname, ispkg in pkgutil.iter_modules(path):
  528. modname = basename + modname
  529. if ispkg:
  530. if include_packages:
  531. yield modname
  532. if recursive:
  533. yield from find_modules(modname, include_packages, True)
  534. else:
  535. yield modname
  536. class ImportStringError(ImportError):
  537. """Provides information about a failed :func:`import_string` attempt."""
  538. #: String in dotted notation that failed to be imported.
  539. import_name: str
  540. #: Wrapped exception.
  541. exception: BaseException
  542. def __init__(self, import_name: str, exception: BaseException) -> None:
  543. self.import_name = import_name
  544. self.exception = exception
  545. msg = import_name
  546. name = ""
  547. tracked = []
  548. for part in import_name.replace(":", ".").split("."):
  549. name = f"{name}.{part}" if name else part
  550. imported = import_string(name, silent=True)
  551. if imported:
  552. tracked.append((name, getattr(imported, "__file__", None)))
  553. else:
  554. track = [f"- {n!r} found in {i!r}." for n, i in tracked]
  555. track.append(f"- {name!r} not found.")
  556. track_str = "\n".join(track)
  557. msg = (
  558. f"import_string() failed for {import_name!r}. Possible reasons"
  559. f" are:\n\n"
  560. "- missing __init__.py in a package;\n"
  561. "- package or module path not included in sys.path;\n"
  562. "- duplicated package or module name taking precedence in"
  563. " sys.path;\n"
  564. "- missing module, class, function or variable;\n\n"
  565. f"Debugged import:\n\n{track_str}\n\n"
  566. f"Original exception:\n\n{type(exception).__name__}: {exception}"
  567. )
  568. break
  569. super().__init__(msg)
  570. def __repr__(self) -> str:
  571. return f"<{type(self).__name__}({self.import_name!r}, {self.exception!r})>"