utils.py 24 KB

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