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. """Validate and modify a filename so that it is safe to use on a regular
  146. filesystem and in :func:`os.path.join`. This may produce an empty string if
  147. nothing in the filename could be safely preserved.
  148. Only the ASCII letters, digits, and ``._-`` characters are allowed, all
  149. others are removed or replaced. Unicode characters are decomposed and
  150. replaced with ASCII equivalents according to NFKD. ``/`` (and ``\\`` on
  151. Windows) and whitespace, are replaced with ``_``. Surrounding ``._``
  152. characters are removed.
  153. On Windows, special device names such as ``CON`` and ``NUL`` will be
  154. prefixed with ``_`` to avoid access.
  155. This only considers the filename, it does not validate if the file does or
  156. does not exist, if it is a symlink, or other properties of the file.
  157. :param filename: The filename to validate and modify.
  158. .. versionadded:: 0.5
  159. """
  160. # decompose combined chars, replace compat chars
  161. filename = unicodedata.normalize("NFKD", filename)
  162. # only keep ASCII chars
  163. filename = filename.encode("ascii", "ignore").decode("ascii")
  164. for sep in os.sep, os.path.altsep:
  165. if sep:
  166. filename = filename.replace(sep, " ")
  167. # replace any whitespace with _
  168. filename = "_".join(filename.split())
  169. # only allow ASCII letters, numbers, and _.-
  170. filename = _filename_ascii_strip_re.sub("", filename)
  171. # remove surrounding ._, left behind after replacing slash in ../
  172. filename = filename.strip("._")
  173. # prefix special device names on Windows
  174. if (
  175. os.name == "nt"
  176. and filename.partition(".")[0].strip().upper() in _windows_device_files
  177. ):
  178. filename = f"_{filename}"
  179. return filename
  180. def redirect(
  181. location: str, code: int = 302, Response: type[Response] | None = None
  182. ) -> Response:
  183. """Returns a response object (a WSGI application) that, if called,
  184. redirects the client to the target location. Supported codes are
  185. 301, 302, 303, 305, 307, and 308. 300 is not supported because
  186. it's not a real redirect and 304 because it's the answer for a
  187. request with a request with defined If-Modified-Since headers.
  188. .. versionadded:: 0.6
  189. The location can now be a unicode string that is encoded using
  190. the :func:`iri_to_uri` function.
  191. .. versionadded:: 0.10
  192. The class used for the Response object can now be passed in.
  193. :param location: the location the response should redirect to.
  194. :param code: the redirect status code. defaults to 302.
  195. :param class Response: a Response class to use when instantiating a
  196. response. The default is :class:`werkzeug.wrappers.Response` if
  197. unspecified.
  198. """
  199. if Response is None:
  200. from .wrappers import Response
  201. html_location = escape(location)
  202. response = Response( # type: ignore[misc]
  203. "<!doctype html>\n"
  204. "<html lang=en>\n"
  205. "<title>Redirecting...</title>\n"
  206. "<h1>Redirecting...</h1>\n"
  207. "<p>You should be redirected automatically to the target URL: "
  208. f'<a href="{html_location}">{html_location}</a>. If not, click the link.\n',
  209. code,
  210. mimetype="text/html",
  211. )
  212. response.headers["Location"] = location
  213. return response
  214. def append_slash_redirect(environ: WSGIEnvironment, code: int = 308) -> Response:
  215. """Redirect to the current URL with a slash appended.
  216. If the current URL is ``/user/42``, the redirect URL will be
  217. ``42/``. When joined to the current URL during response
  218. processing or by the browser, this will produce ``/user/42/``.
  219. The behavior is undefined if the path ends with a slash already. If
  220. called unconditionally on a URL, it may produce a redirect loop.
  221. :param environ: Use the path and query from this WSGI environment
  222. to produce the redirect URL.
  223. :param code: the status code for the redirect.
  224. .. versionchanged:: 2.1
  225. Produce a relative URL that only modifies the last segment.
  226. Relevant when the current path has multiple segments.
  227. .. versionchanged:: 2.1
  228. The default status code is 308 instead of 301. This preserves
  229. the request method and body.
  230. """
  231. tail = environ["PATH_INFO"].rpartition("/")[2]
  232. if not tail:
  233. new_path = "./"
  234. else:
  235. new_path = f"{tail}/"
  236. query_string = environ.get("QUERY_STRING")
  237. if query_string:
  238. new_path = f"{new_path}?{query_string}"
  239. return redirect(new_path, code)
  240. def send_file(
  241. path_or_file: os.PathLike[str] | str | t.IO[bytes],
  242. environ: WSGIEnvironment,
  243. mimetype: str | None = None,
  244. as_attachment: bool = False,
  245. download_name: str | None = None,
  246. conditional: bool = True,
  247. etag: bool | str = True,
  248. last_modified: datetime | int | float | None = None,
  249. max_age: None | (int | t.Callable[[str | None], int | None]) = None,
  250. use_x_sendfile: bool = False,
  251. response_class: type[Response] | None = None,
  252. _root_path: os.PathLike[str] | str | None = None,
  253. ) -> Response:
  254. """Send the contents of a file to the client.
  255. The first argument can be a file path or a file-like object. Paths
  256. are preferred in most cases because Werkzeug can manage the file and
  257. get extra information from the path. Passing a file-like object
  258. requires that the file is opened in binary mode, and is mostly
  259. useful when building a file in memory with :class:`io.BytesIO`.
  260. Never pass file paths provided by a user. The path is assumed to be
  261. trusted, so a user could craft a path to access a file you didn't
  262. intend. Use :func:`send_from_directory` to safely serve user-provided paths.
  263. If the WSGI server sets a ``file_wrapper`` in ``environ``, it is
  264. used, otherwise Werkzeug's built-in wrapper is used. Alternatively,
  265. if the HTTP server supports ``X-Sendfile``, ``use_x_sendfile=True``
  266. will tell the server to send the given path, which is much more
  267. efficient than reading it in Python.
  268. :param path_or_file: The path to the file to send, relative to the
  269. current working directory if a relative path is given.
  270. Alternatively, a file-like object opened in binary mode. Make
  271. sure the file pointer is seeked to the start of the data.
  272. :param environ: The WSGI environ for the current request.
  273. :param mimetype: The MIME type to send for the file. If not
  274. provided, it will try to detect it from the file name.
  275. :param as_attachment: Indicate to a browser that it should offer to
  276. save the file instead of displaying it.
  277. :param download_name: The default name browsers will use when saving
  278. the file. Defaults to the passed file name.
  279. :param conditional: Enable conditional and range responses based on
  280. request headers. Requires passing a file path and ``environ``.
  281. :param etag: Calculate an ETag for the file, which requires passing
  282. a file path. Can also be a string to use instead.
  283. :param last_modified: The last modified time to send for the file,
  284. in seconds. If not provided, it will try to detect it from the
  285. file path.
  286. :param max_age: How long the client should cache the file, in
  287. seconds. If set, ``Cache-Control`` will be ``public``, otherwise
  288. it will be ``no-cache`` to prefer conditional caching.
  289. :param use_x_sendfile: Set the ``X-Sendfile`` header to let the
  290. server to efficiently send the file. Requires support from the
  291. HTTP server. Requires passing a file path.
  292. :param response_class: Build the response using this class. Defaults
  293. to :class:`~werkzeug.wrappers.Response`.
  294. :param _root_path: Do not use. For internal use only. Use
  295. :func:`send_from_directory` to safely send files under a path.
  296. .. versionchanged:: 2.0.2
  297. ``send_file`` only sets a detected ``Content-Encoding`` if
  298. ``as_attachment`` is disabled.
  299. .. versionadded:: 2.0
  300. Adapted from Flask's implementation.
  301. .. versionchanged:: 2.0
  302. ``download_name`` replaces Flask's ``attachment_filename``
  303. parameter. If ``as_attachment=False``, it is passed with
  304. ``Content-Disposition: inline`` instead.
  305. .. versionchanged:: 2.0
  306. ``max_age`` replaces Flask's ``cache_timeout`` parameter.
  307. ``conditional`` is enabled and ``max_age`` is not set by
  308. default.
  309. .. versionchanged:: 2.0
  310. ``etag`` replaces Flask's ``add_etags`` parameter. It can be a
  311. string to use instead of generating one.
  312. .. versionchanged:: 2.0
  313. If an encoding is returned when guessing ``mimetype`` from
  314. ``download_name``, set the ``Content-Encoding`` header.
  315. """
  316. if response_class is None:
  317. from .wrappers import Response
  318. response_class = Response
  319. path: str | None = None
  320. file: t.IO[bytes] | None = None
  321. size: int | None = None
  322. mtime: float | None = None
  323. headers = Headers()
  324. if isinstance(path_or_file, (os.PathLike, str)) or hasattr(
  325. path_or_file, "__fspath__"
  326. ):
  327. path_or_file = t.cast("os.PathLike[str] | str", path_or_file)
  328. # Flask will pass app.root_path, allowing its send_file wrapper
  329. # to not have to deal with paths.
  330. if _root_path is not None:
  331. path = os.path.join(_root_path, path_or_file)
  332. else:
  333. path = os.path.abspath(path_or_file)
  334. stat = os.stat(path)
  335. size = stat.st_size
  336. mtime = stat.st_mtime
  337. else:
  338. file = path_or_file
  339. if download_name is None and path is not None:
  340. download_name = os.path.basename(path)
  341. if mimetype is None:
  342. if download_name is None:
  343. raise TypeError(
  344. "Unable to detect the MIME type because a file name is"
  345. " not available. Either set 'download_name', pass a"
  346. " path instead of a file, or set 'mimetype'."
  347. )
  348. mimetype, encoding = mimetypes.guess_type(download_name)
  349. if mimetype is None:
  350. mimetype = "application/octet-stream"
  351. # Don't send encoding for attachments, it causes browsers to
  352. # save decompress tar.gz files.
  353. if encoding is not None and not as_attachment:
  354. headers.set("Content-Encoding", encoding)
  355. if download_name is not None:
  356. try:
  357. download_name.encode("ascii")
  358. except UnicodeEncodeError:
  359. simple = unicodedata.normalize("NFKD", download_name)
  360. simple = simple.encode("ascii", "ignore").decode("ascii")
  361. # safe = RFC 5987 attr-char
  362. quoted = quote(download_name, safe="!#$&+-.^_`|~")
  363. names = {"filename": simple, "filename*": f"UTF-8''{quoted}"}
  364. else:
  365. names = {"filename": download_name}
  366. value = "attachment" if as_attachment else "inline"
  367. headers.set("Content-Disposition", value, **names)
  368. elif as_attachment:
  369. raise TypeError(
  370. "No name provided for attachment. Either set"
  371. " 'download_name' or pass a path instead of a file."
  372. )
  373. if use_x_sendfile and path is not None:
  374. headers["X-Sendfile"] = path
  375. data = None
  376. else:
  377. if file is None:
  378. file = open(path, "rb") # type: ignore
  379. elif isinstance(file, io.BytesIO):
  380. size = file.getbuffer().nbytes
  381. elif isinstance(file, io.TextIOBase):
  382. raise ValueError("Files must be opened in binary mode or use BytesIO.")
  383. data = wrap_file(environ, file)
  384. rv = response_class(
  385. data, mimetype=mimetype, headers=headers, direct_passthrough=True
  386. )
  387. if size is not None:
  388. rv.content_length = size
  389. if last_modified is not None:
  390. rv.last_modified = last_modified # type: ignore
  391. elif mtime is not None:
  392. rv.last_modified = mtime # type: ignore
  393. rv.cache_control.no_cache = True
  394. # Flask will pass app.get_send_file_max_age, allowing its send_file
  395. # wrapper to not have to deal with paths.
  396. if callable(max_age):
  397. max_age = max_age(path)
  398. if max_age is not None:
  399. if max_age > 0:
  400. rv.cache_control.no_cache = None
  401. rv.cache_control.public = True
  402. rv.cache_control.max_age = max_age
  403. rv.expires = int(time() + max_age) # type: ignore
  404. if isinstance(etag, str):
  405. rv.set_etag(etag)
  406. elif etag and path is not None:
  407. check = adler32(path.encode()) & 0xFFFFFFFF
  408. rv.set_etag(f"{mtime}-{size}-{check}")
  409. if conditional:
  410. try:
  411. rv = rv.make_conditional(environ, accept_ranges=True, complete_length=size)
  412. except RequestedRangeNotSatisfiable:
  413. if file is not None:
  414. file.close()
  415. raise
  416. # Some x-sendfile implementations incorrectly ignore the 304
  417. # status code and send the file anyway.
  418. if rv.status_code == 304:
  419. rv.headers.pop("x-sendfile", None)
  420. return rv
  421. def send_from_directory(
  422. directory: os.PathLike[str] | str,
  423. path: os.PathLike[str] | str,
  424. environ: WSGIEnvironment,
  425. **kwargs: t.Any,
  426. ) -> Response:
  427. """Send a file from within a directory using :func:`send_file`.
  428. This is a secure way to serve files from a folder, such as static
  429. files or uploads. Uses :func:`~werkzeug.security.safe_join` to
  430. ensure the path coming from the client is not maliciously crafted to
  431. point outside the specified directory.
  432. If the final path does not point to an existing regular file,
  433. returns a 404 :exc:`~werkzeug.exceptions.NotFound` error.
  434. :param directory: The directory that ``path`` must be located under. This *must not*
  435. be a value provided by the client, otherwise it becomes insecure.
  436. :param path: The path to the file to send, relative to ``directory``. This is the
  437. part of the path provided by the client, which is checked for security.
  438. :param environ: The WSGI environ for the current request.
  439. :param kwargs: Arguments to pass to :func:`send_file`.
  440. .. versionadded:: 2.0
  441. Adapted from Flask's implementation.
  442. """
  443. path_str = safe_join(os.fspath(directory), os.fspath(path))
  444. if path_str is None:
  445. raise NotFound()
  446. # Flask will pass app.root_path, allowing its send_from_directory
  447. # wrapper to not have to deal with paths.
  448. if "_root_path" in kwargs:
  449. path_str = os.path.join(kwargs["_root_path"], path_str)
  450. if not os.path.isfile(path_str):
  451. raise NotFound()
  452. return send_file(path_str, environ, **kwargs)
  453. def import_string(import_name: str, silent: bool = False) -> t.Any:
  454. """Imports an object based on a string. This is useful if you want to
  455. use import paths as endpoints or something similar. An import path can
  456. be specified either in dotted notation (``xml.sax.saxutils.escape``)
  457. or with a colon as object delimiter (``xml.sax.saxutils:escape``).
  458. If `silent` is True the return value will be `None` if the import fails.
  459. :param import_name: the dotted name for the object to import.
  460. :param silent: if set to `True` import errors are ignored and
  461. `None` is returned instead.
  462. :return: imported object
  463. """
  464. import_name = import_name.replace(":", ".")
  465. try:
  466. try:
  467. __import__(import_name)
  468. except ImportError:
  469. if "." not in import_name:
  470. raise
  471. else:
  472. return sys.modules[import_name]
  473. module_name, obj_name = import_name.rsplit(".", 1)
  474. module = __import__(module_name, globals(), locals(), [obj_name])
  475. try:
  476. return getattr(module, obj_name)
  477. except AttributeError as e:
  478. raise ImportError(e) from None
  479. except ImportError as e:
  480. if not silent:
  481. raise ImportStringError(import_name, e).with_traceback(
  482. sys.exc_info()[2]
  483. ) from None
  484. return None
  485. def find_modules(
  486. import_path: str, include_packages: bool = False, recursive: bool = False
  487. ) -> t.Iterator[str]:
  488. """Finds all the modules below a package. This can be useful to
  489. automatically import all views / controllers so that their metaclasses /
  490. function decorators have a chance to register themselves on the
  491. application.
  492. Packages are not returned unless `include_packages` is `True`. This can
  493. also recursively list modules but in that case it will import all the
  494. packages to get the correct load path of that module.
  495. :param import_path: the dotted name for the package to find child modules.
  496. :param include_packages: set to `True` if packages should be returned, too.
  497. :param recursive: set to `True` if recursion should happen.
  498. :return: generator
  499. """
  500. module = import_string(import_path)
  501. path = getattr(module, "__path__", None)
  502. if path is None:
  503. raise ValueError(f"{import_path!r} is not a package")
  504. basename = f"{module.__name__}."
  505. for _importer, modname, ispkg in pkgutil.iter_modules(path):
  506. modname = basename + modname
  507. if ispkg:
  508. if include_packages:
  509. yield modname
  510. if recursive:
  511. yield from find_modules(modname, include_packages, True)
  512. else:
  513. yield modname
  514. class ImportStringError(ImportError):
  515. """Provides information about a failed :func:`import_string` attempt."""
  516. #: String in dotted notation that failed to be imported.
  517. import_name: str
  518. #: Wrapped exception.
  519. exception: BaseException
  520. def __init__(self, import_name: str, exception: BaseException) -> None:
  521. self.import_name = import_name
  522. self.exception = exception
  523. msg = import_name
  524. name = ""
  525. tracked = []
  526. for part in import_name.replace(":", ".").split("."):
  527. name = f"{name}.{part}" if name else part
  528. imported = import_string(name, silent=True)
  529. if imported:
  530. tracked.append((name, getattr(imported, "__file__", None)))
  531. else:
  532. track = [f"- {n!r} found in {i!r}." for n, i in tracked]
  533. track.append(f"- {name!r} not found.")
  534. track_str = "\n".join(track)
  535. msg = (
  536. f"import_string() failed for {import_name!r}. Possible reasons"
  537. f" are:\n\n"
  538. "- missing __init__.py in a package;\n"
  539. "- package or module path not included in sys.path;\n"
  540. "- duplicated package or module name taking precedence in"
  541. " sys.path;\n"
  542. "- missing module, class, function or variable;\n\n"
  543. f"Debugged import:\n\n{track_str}\n\n"
  544. f"Original exception:\n\n{type(exception).__name__}: {exception}"
  545. )
  546. break
  547. super().__init__(msg)
  548. def __repr__(self) -> str:
  549. return f"<{type(self).__name__}({self.import_name!r}, {self.exception!r})>"