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 ._internal import _DictAccessorProperty
  13. from ._internal import _missing
  14. from ._internal import _TAccessorValue
  15. from .datastructures import Headers
  16. from .exceptions import NotFound
  17. from .exceptions import RequestedRangeNotSatisfiable
  18. from .security import safe_join
  19. from .urls import url_quote
  20. from .wsgi import wrap_file
  21. if t.TYPE_CHECKING:
  22. from _typeshed.wsgi import WSGIEnvironment
  23. from .wrappers.request import Request
  24. from .wrappers.response import Response
  25. _T = t.TypeVar("_T")
  26. _entity_re = re.compile(r"&([^;]+);")
  27. _filename_ascii_strip_re = re.compile(r"[^A-Za-z0-9_.-]")
  28. _windows_device_files = (
  29. "CON",
  30. "AUX",
  31. "COM1",
  32. "COM2",
  33. "COM3",
  34. "COM4",
  35. "LPT1",
  36. "LPT2",
  37. "LPT3",
  38. "PRN",
  39. "NUL",
  40. )
  41. class cached_property(property, t.Generic[_T]):
  42. """A :func:`property` that is only evaluated once. Subsequent access
  43. returns the cached value. Setting the property sets the cached
  44. value. Deleting the property clears the cached value, accessing it
  45. again will evaluate it again.
  46. .. code-block:: python
  47. class Example:
  48. @cached_property
  49. def value(self):
  50. # calculate something important here
  51. return 42
  52. e = Example()
  53. e.value # evaluates
  54. e.value # uses cache
  55. e.value = 16 # sets cache
  56. del e.value # clears cache
  57. If the class defines ``__slots__``, it must add ``_cache_{name}`` as
  58. a slot. Alternatively, it can add ``__dict__``, but that's usually
  59. not desirable.
  60. .. versionchanged:: 2.1
  61. Works with ``__slots__``.
  62. .. versionchanged:: 2.0
  63. ``del obj.name`` clears the cached value.
  64. """
  65. def __init__(
  66. self,
  67. fget: t.Callable[[t.Any], _T],
  68. name: t.Optional[str] = None,
  69. doc: t.Optional[str] = None,
  70. ) -> None:
  71. super().__init__(fget, doc=doc)
  72. self.__name__ = name or fget.__name__
  73. self.slot_name = f"_cache_{self.__name__}"
  74. self.__module__ = fget.__module__
  75. def __set__(self, obj: object, value: _T) -> None:
  76. if hasattr(obj, "__dict__"):
  77. obj.__dict__[self.__name__] = value
  78. else:
  79. setattr(obj, self.slot_name, value)
  80. def __get__(self, obj: object, type: type = None) -> _T: # type: ignore
  81. if obj is None:
  82. return self # type: ignore
  83. obj_dict = getattr(obj, "__dict__", None)
  84. if obj_dict is not None:
  85. value: _T = obj_dict.get(self.__name__, _missing)
  86. else:
  87. value = getattr(obj, self.slot_name, _missing) # type: ignore[arg-type]
  88. if value is _missing:
  89. value = self.fget(obj) # type: ignore
  90. if obj_dict is not None:
  91. obj.__dict__[self.__name__] = value
  92. else:
  93. setattr(obj, self.slot_name, value)
  94. return value
  95. def __delete__(self, obj: object) -> None:
  96. if hasattr(obj, "__dict__"):
  97. del obj.__dict__[self.__name__]
  98. else:
  99. setattr(obj, self.slot_name, _missing)
  100. class environ_property(_DictAccessorProperty[_TAccessorValue]):
  101. """Maps request attributes to environment variables. This works not only
  102. for the Werkzeug request object, but also any other class with an
  103. environ attribute:
  104. >>> class Test(object):
  105. ... environ = {'key': 'value'}
  106. ... test = environ_property('key')
  107. >>> var = Test()
  108. >>> var.test
  109. 'value'
  110. If you pass it a second value it's used as default if the key does not
  111. exist, the third one can be a converter that takes a value and converts
  112. it. If it raises :exc:`ValueError` or :exc:`TypeError` the default value
  113. is used. If no default value is provided `None` is used.
  114. Per default the property is read only. You have to explicitly enable it
  115. by passing ``read_only=False`` to the constructor.
  116. """
  117. read_only = True
  118. def lookup(self, obj: "Request") -> "WSGIEnvironment":
  119. return obj.environ
  120. class header_property(_DictAccessorProperty[_TAccessorValue]):
  121. """Like `environ_property` but for headers."""
  122. def lookup(self, obj: t.Union["Request", "Response"]) -> Headers:
  123. return obj.headers
  124. # https://cgit.freedesktop.org/xdg/shared-mime-info/tree/freedesktop.org.xml.in
  125. # https://www.iana.org/assignments/media-types/media-types.xhtml
  126. # Types listed in the XDG mime info that have a charset in the IANA registration.
  127. _charset_mimetypes = {
  128. "application/ecmascript",
  129. "application/javascript",
  130. "application/sql",
  131. "application/xml",
  132. "application/xml-dtd",
  133. "application/xml-external-parsed-entity",
  134. }
  135. def get_content_type(mimetype: str, charset: str) -> str:
  136. """Returns the full content type string with charset for a mimetype.
  137. If the mimetype represents text, the charset parameter will be
  138. appended, otherwise the mimetype is returned unchanged.
  139. :param mimetype: The mimetype to be used as content type.
  140. :param charset: The charset to be appended for text mimetypes.
  141. :return: The content type.
  142. .. versionchanged:: 0.15
  143. Any type that ends with ``+xml`` gets a charset, not just those
  144. that start with ``application/``. Known text types such as
  145. ``application/javascript`` are also given charsets.
  146. """
  147. if (
  148. mimetype.startswith("text/")
  149. or mimetype in _charset_mimetypes
  150. or mimetype.endswith("+xml")
  151. ):
  152. mimetype += f"; charset={charset}"
  153. return mimetype
  154. def secure_filename(filename: str) -> str:
  155. r"""Pass it a filename and it will return a secure version of it. This
  156. filename can then safely be stored on a regular file system and passed
  157. to :func:`os.path.join`. The filename returned is an ASCII only string
  158. for maximum portability.
  159. On windows systems the function also makes sure that the file is not
  160. named after one of the special device files.
  161. >>> secure_filename("My cool movie.mov")
  162. 'My_cool_movie.mov'
  163. >>> secure_filename("../../../etc/passwd")
  164. 'etc_passwd'
  165. >>> secure_filename('i contain cool \xfcml\xe4uts.txt')
  166. 'i_contain_cool_umlauts.txt'
  167. The function might return an empty filename. It's your responsibility
  168. to ensure that the filename is unique and that you abort or
  169. generate a random filename if the function returned an empty one.
  170. .. versionadded:: 0.5
  171. :param filename: the filename to secure
  172. """
  173. filename = unicodedata.normalize("NFKD", filename)
  174. filename = filename.encode("ascii", "ignore").decode("ascii")
  175. for sep in os.path.sep, os.path.altsep:
  176. if sep:
  177. filename = filename.replace(sep, " ")
  178. filename = str(_filename_ascii_strip_re.sub("", "_".join(filename.split()))).strip(
  179. "._"
  180. )
  181. # on nt a couple of special files are present in each folder. We
  182. # have to ensure that the target file is not such a filename. In
  183. # this case we prepend an underline
  184. if (
  185. os.name == "nt"
  186. and filename
  187. and filename.split(".")[0].upper() in _windows_device_files
  188. ):
  189. filename = f"_{filename}"
  190. return filename
  191. def redirect(
  192. location: str, code: int = 302, Response: t.Optional[t.Type["Response"]] = None
  193. ) -> "Response":
  194. """Returns a response object (a WSGI application) that, if called,
  195. redirects the client to the target location. Supported codes are
  196. 301, 302, 303, 305, 307, and 308. 300 is not supported because
  197. it's not a real redirect and 304 because it's the answer for a
  198. request with a request with defined If-Modified-Since headers.
  199. .. versionadded:: 0.6
  200. The location can now be a unicode string that is encoded using
  201. the :func:`iri_to_uri` function.
  202. .. versionadded:: 0.10
  203. The class used for the Response object can now be passed in.
  204. :param location: the location the response should redirect to.
  205. :param code: the redirect status code. defaults to 302.
  206. :param class Response: a Response class to use when instantiating a
  207. response. The default is :class:`werkzeug.wrappers.Response` if
  208. unspecified.
  209. """
  210. import html
  211. if Response is None:
  212. from .wrappers import Response # type: ignore
  213. display_location = html.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="{html.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})>"