utils.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  1. # -*- coding: utf-8 -*-
  2. """
  3. werkzeug.utils
  4. ~~~~~~~~~~~~~~
  5. This module implements various utilities for WSGI applications. Most of
  6. them are used by the request and response wrappers but especially for
  7. middleware development it makes sense to use them without the wrappers.
  8. :copyright: 2007 Pallets
  9. :license: BSD-3-Clause
  10. """
  11. import codecs
  12. import os
  13. import pkgutil
  14. import re
  15. import sys
  16. from ._compat import iteritems
  17. from ._compat import PY2
  18. from ._compat import reraise
  19. from ._compat import string_types
  20. from ._compat import text_type
  21. from ._compat import unichr
  22. from ._internal import _DictAccessorProperty
  23. from ._internal import _missing
  24. from ._internal import _parse_signature
  25. try:
  26. from html.entities import name2codepoint
  27. except ImportError:
  28. from htmlentitydefs import name2codepoint
  29. _format_re = re.compile(r"\$(?:(%s)|\{(%s)\})" % (("[a-zA-Z_][a-zA-Z0-9_]*",) * 2))
  30. _entity_re = re.compile(r"&([^;]+);")
  31. _filename_ascii_strip_re = re.compile(r"[^A-Za-z0-9_.-]")
  32. _windows_device_files = (
  33. "CON",
  34. "AUX",
  35. "COM1",
  36. "COM2",
  37. "COM3",
  38. "COM4",
  39. "LPT1",
  40. "LPT2",
  41. "LPT3",
  42. "PRN",
  43. "NUL",
  44. )
  45. class cached_property(property):
  46. """A decorator that converts a function into a lazy property. The
  47. function wrapped is called the first time to retrieve the result
  48. and then that calculated result is used the next time you access
  49. the value::
  50. class Foo(object):
  51. @cached_property
  52. def foo(self):
  53. # calculate something important here
  54. return 42
  55. The class has to have a `__dict__` in order for this property to
  56. work.
  57. """
  58. # implementation detail: A subclass of python's builtin property
  59. # decorator, we override __get__ to check for a cached value. If one
  60. # chooses to invoke __get__ by hand the property will still work as
  61. # expected because the lookup logic is replicated in __get__ for
  62. # manual invocation.
  63. def __init__(self, func, name=None, doc=None):
  64. self.__name__ = name or func.__name__
  65. self.__module__ = func.__module__
  66. self.__doc__ = doc or func.__doc__
  67. self.func = func
  68. def __set__(self, obj, value):
  69. obj.__dict__[self.__name__] = value
  70. def __get__(self, obj, type=None):
  71. if obj is None:
  72. return self
  73. value = obj.__dict__.get(self.__name__, _missing)
  74. if value is _missing:
  75. value = self.func(obj)
  76. obj.__dict__[self.__name__] = value
  77. return value
  78. def invalidate_cached_property(obj, name):
  79. """Invalidates the cache for a :class:`cached_property`:
  80. >>> class Test(object):
  81. ... @cached_property
  82. ... def magic_number(self):
  83. ... print("recalculating...")
  84. ... return 42
  85. ...
  86. >>> var = Test()
  87. >>> var.magic_number
  88. recalculating...
  89. 42
  90. >>> var.magic_number
  91. 42
  92. >>> invalidate_cached_property(var, "magic_number")
  93. >>> var.magic_number
  94. recalculating...
  95. 42
  96. You must pass the name of the cached property as the second argument.
  97. """
  98. if not isinstance(getattr(obj.__class__, name, None), cached_property):
  99. raise TypeError(
  100. "Attribute {} of object {} is not a cached_property, "
  101. "cannot be invalidated".format(name, obj)
  102. )
  103. obj.__dict__[name] = _missing
  104. class environ_property(_DictAccessorProperty):
  105. """Maps request attributes to environment variables. This works not only
  106. for the Werzeug request object, but also any other class with an
  107. environ attribute:
  108. >>> class Test(object):
  109. ... environ = {'key': 'value'}
  110. ... test = environ_property('key')
  111. >>> var = Test()
  112. >>> var.test
  113. 'value'
  114. If you pass it a second value it's used as default if the key does not
  115. exist, the third one can be a converter that takes a value and converts
  116. it. If it raises :exc:`ValueError` or :exc:`TypeError` the default value
  117. is used. If no default value is provided `None` is used.
  118. Per default the property is read only. You have to explicitly enable it
  119. by passing ``read_only=False`` to the constructor.
  120. """
  121. read_only = True
  122. def lookup(self, obj):
  123. return obj.environ
  124. class header_property(_DictAccessorProperty):
  125. """Like `environ_property` but for headers."""
  126. def lookup(self, obj):
  127. return obj.headers
  128. class HTMLBuilder(object):
  129. """Helper object for HTML generation.
  130. Per default there are two instances of that class. The `html` one, and
  131. the `xhtml` one for those two dialects. The class uses keyword parameters
  132. and positional parameters to generate small snippets of HTML.
  133. Keyword parameters are converted to XML/SGML attributes, positional
  134. arguments are used as children. Because Python accepts positional
  135. arguments before keyword arguments it's a good idea to use a list with the
  136. star-syntax for some children:
  137. >>> html.p(class_='foo', *[html.a('foo', href='foo.html'), ' ',
  138. ... html.a('bar', href='bar.html')])
  139. u'<p class="foo"><a href="foo.html">foo</a> <a href="bar.html">bar</a></p>'
  140. This class works around some browser limitations and can not be used for
  141. arbitrary SGML/XML generation. For that purpose lxml and similar
  142. libraries exist.
  143. Calling the builder escapes the string passed:
  144. >>> html.p(html("<foo>"))
  145. u'<p>&lt;foo&gt;</p>'
  146. """
  147. _entity_re = re.compile(r"&([^;]+);")
  148. _entities = name2codepoint.copy()
  149. _entities["apos"] = 39
  150. _empty_elements = {
  151. "area",
  152. "base",
  153. "basefont",
  154. "br",
  155. "col",
  156. "command",
  157. "embed",
  158. "frame",
  159. "hr",
  160. "img",
  161. "input",
  162. "keygen",
  163. "isindex",
  164. "link",
  165. "meta",
  166. "param",
  167. "source",
  168. "wbr",
  169. }
  170. _boolean_attributes = {
  171. "selected",
  172. "checked",
  173. "compact",
  174. "declare",
  175. "defer",
  176. "disabled",
  177. "ismap",
  178. "multiple",
  179. "nohref",
  180. "noresize",
  181. "noshade",
  182. "nowrap",
  183. }
  184. _plaintext_elements = {"textarea"}
  185. _c_like_cdata = {"script", "style"}
  186. def __init__(self, dialect):
  187. self._dialect = dialect
  188. def __call__(self, s):
  189. return escape(s)
  190. def __getattr__(self, tag):
  191. if tag[:2] == "__":
  192. raise AttributeError(tag)
  193. def proxy(*children, **arguments):
  194. buffer = "<" + tag
  195. for key, value in iteritems(arguments):
  196. if value is None:
  197. continue
  198. if key[-1] == "_":
  199. key = key[:-1]
  200. if key in self._boolean_attributes:
  201. if not value:
  202. continue
  203. if self._dialect == "xhtml":
  204. value = '="' + key + '"'
  205. else:
  206. value = ""
  207. else:
  208. value = '="' + escape(value) + '"'
  209. buffer += " " + key + value
  210. if not children and tag in self._empty_elements:
  211. if self._dialect == "xhtml":
  212. buffer += " />"
  213. else:
  214. buffer += ">"
  215. return buffer
  216. buffer += ">"
  217. children_as_string = "".join(
  218. [text_type(x) for x in children if x is not None]
  219. )
  220. if children_as_string:
  221. if tag in self._plaintext_elements:
  222. children_as_string = escape(children_as_string)
  223. elif tag in self._c_like_cdata and self._dialect == "xhtml":
  224. children_as_string = (
  225. "/*<![CDATA[*/" + children_as_string + "/*]]>*/"
  226. )
  227. buffer += children_as_string + "</" + tag + ">"
  228. return buffer
  229. return proxy
  230. def __repr__(self):
  231. return "<%s for %r>" % (self.__class__.__name__, self._dialect)
  232. html = HTMLBuilder("html")
  233. xhtml = HTMLBuilder("xhtml")
  234. # https://cgit.freedesktop.org/xdg/shared-mime-info/tree/freedesktop.org.xml.in
  235. # https://www.iana.org/assignments/media-types/media-types.xhtml
  236. # Types listed in the XDG mime info that have a charset in the IANA registration.
  237. _charset_mimetypes = {
  238. "application/ecmascript",
  239. "application/javascript",
  240. "application/sql",
  241. "application/xml",
  242. "application/xml-dtd",
  243. "application/xml-external-parsed-entity",
  244. }
  245. def get_content_type(mimetype, charset):
  246. """Returns the full content type string with charset for a mimetype.
  247. If the mimetype represents text, the charset parameter will be
  248. appended, otherwise the mimetype is returned unchanged.
  249. :param mimetype: The mimetype to be used as content type.
  250. :param charset: The charset to be appended for text mimetypes.
  251. :return: The content type.
  252. .. versionchanged:: 0.15
  253. Any type that ends with ``+xml`` gets a charset, not just those
  254. that start with ``application/``. Known text types such as
  255. ``application/javascript`` are also given charsets.
  256. """
  257. if (
  258. mimetype.startswith("text/")
  259. or mimetype in _charset_mimetypes
  260. or mimetype.endswith("+xml")
  261. ):
  262. mimetype += "; charset=" + charset
  263. return mimetype
  264. def detect_utf_encoding(data):
  265. """Detect which UTF encoding was used to encode the given bytes.
  266. The latest JSON standard (:rfc:`8259`) suggests that only UTF-8 is
  267. accepted. Older documents allowed 8, 16, or 32. 16 and 32 can be big
  268. or little endian. Some editors or libraries may prepend a BOM.
  269. :internal:
  270. :param data: Bytes in unknown UTF encoding.
  271. :return: UTF encoding name
  272. .. versionadded:: 0.15
  273. """
  274. head = data[:4]
  275. if head[:3] == codecs.BOM_UTF8:
  276. return "utf-8-sig"
  277. if b"\x00" not in head:
  278. return "utf-8"
  279. if head in (codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE):
  280. return "utf-32"
  281. if head[:2] in (codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE):
  282. return "utf-16"
  283. if len(head) == 4:
  284. if head[:3] == b"\x00\x00\x00":
  285. return "utf-32-be"
  286. if head[::2] == b"\x00\x00":
  287. return "utf-16-be"
  288. if head[1:] == b"\x00\x00\x00":
  289. return "utf-32-le"
  290. if head[1::2] == b"\x00\x00":
  291. return "utf-16-le"
  292. if len(head) == 2:
  293. return "utf-16-be" if head.startswith(b"\x00") else "utf-16-le"
  294. return "utf-8"
  295. def format_string(string, context):
  296. """String-template format a string:
  297. >>> format_string('$foo and ${foo}s', dict(foo=42))
  298. '42 and 42s'
  299. This does not do any attribute lookup etc. For more advanced string
  300. formattings have a look at the `werkzeug.template` module.
  301. :param string: the format string.
  302. :param context: a dict with the variables to insert.
  303. """
  304. def lookup_arg(match):
  305. x = context[match.group(1) or match.group(2)]
  306. if not isinstance(x, string_types):
  307. x = type(string)(x)
  308. return x
  309. return _format_re.sub(lookup_arg, string)
  310. def secure_filename(filename):
  311. r"""Pass it a filename and it will return a secure version of it. This
  312. filename can then safely be stored on a regular file system and passed
  313. to :func:`os.path.join`. The filename returned is an ASCII only string
  314. for maximum portability.
  315. On windows systems the function also makes sure that the file is not
  316. named after one of the special device files.
  317. >>> secure_filename("My cool movie.mov")
  318. 'My_cool_movie.mov'
  319. >>> secure_filename("../../../etc/passwd")
  320. 'etc_passwd'
  321. >>> secure_filename(u'i contain cool \xfcml\xe4uts.txt')
  322. 'i_contain_cool_umlauts.txt'
  323. The function might return an empty filename. It's your responsibility
  324. to ensure that the filename is unique and that you abort or
  325. generate a random filename if the function returned an empty one.
  326. .. versionadded:: 0.5
  327. :param filename: the filename to secure
  328. """
  329. if isinstance(filename, text_type):
  330. from unicodedata import normalize
  331. filename = normalize("NFKD", filename).encode("ascii", "ignore")
  332. if not PY2:
  333. filename = filename.decode("ascii")
  334. for sep in os.path.sep, os.path.altsep:
  335. if sep:
  336. filename = filename.replace(sep, " ")
  337. filename = str(_filename_ascii_strip_re.sub("", "_".join(filename.split()))).strip(
  338. "._"
  339. )
  340. # on nt a couple of special files are present in each folder. We
  341. # have to ensure that the target file is not such a filename. In
  342. # this case we prepend an underline
  343. if (
  344. os.name == "nt"
  345. and filename
  346. and filename.split(".")[0].upper() in _windows_device_files
  347. ):
  348. filename = "_" + filename
  349. return filename
  350. def escape(s):
  351. """Replace special characters "&", "<", ">" and (") to HTML-safe sequences.
  352. There is a special handling for `None` which escapes to an empty string.
  353. .. versionchanged:: 0.9
  354. `quote` is now implicitly on.
  355. :param s: the string to escape.
  356. :param quote: ignored.
  357. """
  358. if s is None:
  359. return ""
  360. elif hasattr(s, "__html__"):
  361. return text_type(s.__html__())
  362. if not isinstance(s, string_types):
  363. s = text_type(s)
  364. return (
  365. s.replace("&", "&amp;")
  366. .replace("<", "&lt;")
  367. .replace(">", "&gt;")
  368. .replace('"', "&quot;")
  369. )
  370. def unescape(s):
  371. """The reverse function of `escape`. This unescapes all the HTML
  372. entities, not only the XML entities inserted by `escape`.
  373. :param s: the string to unescape.
  374. """
  375. def handle_match(m):
  376. name = m.group(1)
  377. if name in HTMLBuilder._entities:
  378. return unichr(HTMLBuilder._entities[name])
  379. try:
  380. if name[:2] in ("#x", "#X"):
  381. return unichr(int(name[2:], 16))
  382. elif name.startswith("#"):
  383. return unichr(int(name[1:]))
  384. except ValueError:
  385. pass
  386. return u""
  387. return _entity_re.sub(handle_match, s)
  388. def redirect(location, code=302, Response=None):
  389. """Returns a response object (a WSGI application) that, if called,
  390. redirects the client to the target location. Supported codes are
  391. 301, 302, 303, 305, 307, and 308. 300 is not supported because
  392. it's not a real redirect and 304 because it's the answer for a
  393. request with a request with defined If-Modified-Since headers.
  394. .. versionadded:: 0.6
  395. The location can now be a unicode string that is encoded using
  396. the :func:`iri_to_uri` function.
  397. .. versionadded:: 0.10
  398. The class used for the Response object can now be passed in.
  399. :param location: the location the response should redirect to.
  400. :param code: the redirect status code. defaults to 302.
  401. :param class Response: a Response class to use when instantiating a
  402. response. The default is :class:`werkzeug.wrappers.Response` if
  403. unspecified.
  404. """
  405. if Response is None:
  406. from .wrappers import Response
  407. display_location = escape(location)
  408. if isinstance(location, text_type):
  409. # Safe conversion is necessary here as we might redirect
  410. # to a broken URI scheme (for instance itms-services).
  411. from .urls import iri_to_uri
  412. location = iri_to_uri(location, safe_conversion=True)
  413. response = Response(
  414. '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n'
  415. "<title>Redirecting...</title>\n"
  416. "<h1>Redirecting...</h1>\n"
  417. "<p>You should be redirected automatically to target URL: "
  418. '<a href="%s">%s</a>. If not click the link.'
  419. % (escape(location), display_location),
  420. code,
  421. mimetype="text/html",
  422. )
  423. response.headers["Location"] = location
  424. return response
  425. def append_slash_redirect(environ, code=301):
  426. """Redirects to the same URL but with a slash appended. The behavior
  427. of this function is undefined if the path ends with a slash already.
  428. :param environ: the WSGI environment for the request that triggers
  429. the redirect.
  430. :param code: the status code for the redirect.
  431. """
  432. new_path = environ["PATH_INFO"].strip("/") + "/"
  433. query_string = environ.get("QUERY_STRING")
  434. if query_string:
  435. new_path += "?" + query_string
  436. return redirect(new_path, code)
  437. def import_string(import_name, silent=False):
  438. """Imports an object based on a string. This is useful if you want to
  439. use import paths as endpoints or something similar. An import path can
  440. be specified either in dotted notation (``xml.sax.saxutils.escape``)
  441. or with a colon as object delimiter (``xml.sax.saxutils:escape``).
  442. If `silent` is True the return value will be `None` if the import fails.
  443. :param import_name: the dotted name for the object to import.
  444. :param silent: if set to `True` import errors are ignored and
  445. `None` is returned instead.
  446. :return: imported object
  447. """
  448. # force the import name to automatically convert to strings
  449. # __import__ is not able to handle unicode strings in the fromlist
  450. # if the module is a package
  451. import_name = str(import_name).replace(":", ".")
  452. try:
  453. try:
  454. __import__(import_name)
  455. except ImportError:
  456. if "." not in import_name:
  457. raise
  458. else:
  459. return sys.modules[import_name]
  460. module_name, obj_name = import_name.rsplit(".", 1)
  461. module = __import__(module_name, globals(), locals(), [obj_name])
  462. try:
  463. return getattr(module, obj_name)
  464. except AttributeError as e:
  465. raise ImportError(e)
  466. except ImportError as e:
  467. if not silent:
  468. reraise(
  469. ImportStringError, ImportStringError(import_name, e), sys.exc_info()[2]
  470. )
  471. def find_modules(import_path, include_packages=False, recursive=False):
  472. """Finds all the modules below a package. This can be useful to
  473. automatically import all views / controllers so that their metaclasses /
  474. function decorators have a chance to register themselves on the
  475. application.
  476. Packages are not returned unless `include_packages` is `True`. This can
  477. also recursively list modules but in that case it will import all the
  478. packages to get the correct load path of that module.
  479. :param import_path: the dotted name for the package to find child modules.
  480. :param include_packages: set to `True` if packages should be returned, too.
  481. :param recursive: set to `True` if recursion should happen.
  482. :return: generator
  483. """
  484. module = import_string(import_path)
  485. path = getattr(module, "__path__", None)
  486. if path is None:
  487. raise ValueError("%r is not a package" % import_path)
  488. basename = module.__name__ + "."
  489. for _importer, modname, ispkg in pkgutil.iter_modules(path):
  490. modname = basename + modname
  491. if ispkg:
  492. if include_packages:
  493. yield modname
  494. if recursive:
  495. for item in find_modules(modname, include_packages, True):
  496. yield item
  497. else:
  498. yield modname
  499. def validate_arguments(func, args, kwargs, drop_extra=True):
  500. """Checks if the function accepts the arguments and keyword arguments.
  501. Returns a new ``(args, kwargs)`` tuple that can safely be passed to
  502. the function without causing a `TypeError` because the function signature
  503. is incompatible. If `drop_extra` is set to `True` (which is the default)
  504. any extra positional or keyword arguments are dropped automatically.
  505. The exception raised provides three attributes:
  506. `missing`
  507. A set of argument names that the function expected but where
  508. missing.
  509. `extra`
  510. A dict of keyword arguments that the function can not handle but
  511. where provided.
  512. `extra_positional`
  513. A list of values that where given by positional argument but the
  514. function cannot accept.
  515. This can be useful for decorators that forward user submitted data to
  516. a view function::
  517. from werkzeug.utils import ArgumentValidationError, validate_arguments
  518. def sanitize(f):
  519. def proxy(request):
  520. data = request.values.to_dict()
  521. try:
  522. args, kwargs = validate_arguments(f, (request,), data)
  523. except ArgumentValidationError:
  524. raise BadRequest('The browser failed to transmit all '
  525. 'the data expected.')
  526. return f(*args, **kwargs)
  527. return proxy
  528. :param func: the function the validation is performed against.
  529. :param args: a tuple of positional arguments.
  530. :param kwargs: a dict of keyword arguments.
  531. :param drop_extra: set to `False` if you don't want extra arguments
  532. to be silently dropped.
  533. :return: tuple in the form ``(args, kwargs)``.
  534. """
  535. parser = _parse_signature(func)
  536. args, kwargs, missing, extra, extra_positional = parser(args, kwargs)[:5]
  537. if missing:
  538. raise ArgumentValidationError(tuple(missing))
  539. elif (extra or extra_positional) and not drop_extra:
  540. raise ArgumentValidationError(None, extra, extra_positional)
  541. return tuple(args), kwargs
  542. def bind_arguments(func, args, kwargs):
  543. """Bind the arguments provided into a dict. When passed a function,
  544. a tuple of arguments and a dict of keyword arguments `bind_arguments`
  545. returns a dict of names as the function would see it. This can be useful
  546. to implement a cache decorator that uses the function arguments to build
  547. the cache key based on the values of the arguments.
  548. :param func: the function the arguments should be bound for.
  549. :param args: tuple of positional arguments.
  550. :param kwargs: a dict of keyword arguments.
  551. :return: a :class:`dict` of bound keyword arguments.
  552. """
  553. (
  554. args,
  555. kwargs,
  556. missing,
  557. extra,
  558. extra_positional,
  559. arg_spec,
  560. vararg_var,
  561. kwarg_var,
  562. ) = _parse_signature(func)(args, kwargs)
  563. values = {}
  564. for (name, _has_default, _default), value in zip(arg_spec, args):
  565. values[name] = value
  566. if vararg_var is not None:
  567. values[vararg_var] = tuple(extra_positional)
  568. elif extra_positional:
  569. raise TypeError("too many positional arguments")
  570. if kwarg_var is not None:
  571. multikw = set(extra) & set([x[0] for x in arg_spec])
  572. if multikw:
  573. raise TypeError(
  574. "got multiple values for keyword argument " + repr(next(iter(multikw)))
  575. )
  576. values[kwarg_var] = extra
  577. elif extra:
  578. raise TypeError("got unexpected keyword argument " + repr(next(iter(extra))))
  579. return values
  580. class ArgumentValidationError(ValueError):
  581. """Raised if :func:`validate_arguments` fails to validate"""
  582. def __init__(self, missing=None, extra=None, extra_positional=None):
  583. self.missing = set(missing or ())
  584. self.extra = extra or {}
  585. self.extra_positional = extra_positional or []
  586. ValueError.__init__(
  587. self,
  588. "function arguments invalid. (%d missing, %d additional)"
  589. % (len(self.missing), len(self.extra) + len(self.extra_positional)),
  590. )
  591. class ImportStringError(ImportError):
  592. """Provides information about a failed :func:`import_string` attempt."""
  593. #: String in dotted notation that failed to be imported.
  594. import_name = None
  595. #: Wrapped exception.
  596. exception = None
  597. def __init__(self, import_name, exception):
  598. self.import_name = import_name
  599. self.exception = exception
  600. msg = (
  601. "import_string() failed for %r. Possible reasons are:\n\n"
  602. "- missing __init__.py in a package;\n"
  603. "- package or module path not included in sys.path;\n"
  604. "- duplicated package or module name taking precedence in "
  605. "sys.path;\n"
  606. "- missing module, class, function or variable;\n\n"
  607. "Debugged import:\n\n%s\n\n"
  608. "Original exception:\n\n%s: %s"
  609. )
  610. name = ""
  611. tracked = []
  612. for part in import_name.replace(":", ".").split("."):
  613. name += (name and ".") + part
  614. imported = import_string(name, silent=True)
  615. if imported:
  616. tracked.append((name, getattr(imported, "__file__", None)))
  617. else:
  618. track = ["- %r found in %r." % (n, i) for n, i in tracked]
  619. track.append("- %r not found." % name)
  620. msg = msg % (
  621. import_name,
  622. "\n".join(track),
  623. exception.__class__.__name__,
  624. str(exception),
  625. )
  626. break
  627. ImportError.__init__(self, msg)
  628. def __repr__(self):
  629. return "<%s(%r, %r)>" % (
  630. self.__class__.__name__,
  631. self.import_name,
  632. self.exception,
  633. )