utils.py 24 KB

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