You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

837 lines
27KB

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