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.

628 lines
22 KiB

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