utils.py 24 KB

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