PageRenderTime 29ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/test/rql_test/connections/http_support/werkzeug/http.py

https://gitlab.com/Mashamba/rethinkdb
Python | 980 lines | 946 code | 12 blank | 22 comment | 9 complexity | bc72ebeabf4247c54c609aed17676450 MD5 | raw file
  1. # -*- coding: utf-8 -*-
  2. """
  3. werkzeug.http
  4. ~~~~~~~~~~~~~
  5. Werkzeug comes with a bunch of utilities that help Werkzeug to deal with
  6. HTTP data. Most of the classes and functions provided by this module are
  7. used by the wrappers, but they are useful on their own, too, especially if
  8. the response and request objects are not used.
  9. This covers some of the more HTTP centric features of WSGI, some other
  10. utilities such as cookie handling are documented in the `werkzeug.utils`
  11. module.
  12. :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
  13. :license: BSD, see LICENSE for more details.
  14. """
  15. import re
  16. from time import time, gmtime
  17. try:
  18. from email.utils import parsedate_tz
  19. except ImportError: # pragma: no cover
  20. from email.Utils import parsedate_tz
  21. try:
  22. from urllib2 import parse_http_list as _parse_list_header
  23. except ImportError: # pragma: no cover
  24. from urllib.request import parse_http_list as _parse_list_header
  25. from datetime import datetime, timedelta
  26. from hashlib import md5
  27. import base64
  28. from werkzeug._internal import _cookie_quote, _make_cookie_domain, \
  29. _cookie_parse_impl
  30. from werkzeug._compat import to_unicode, iteritems, text_type, \
  31. string_types, try_coerce_native, to_bytes, PY2, \
  32. integer_types
  33. # incorrect
  34. _cookie_charset = 'latin1'
  35. _accept_re = re.compile(r'([^\s;,]+)(?:[^,]*?;\s*q=(\d*(?:\.\d+)?))?')
  36. _token_chars = frozenset("!#$%&'*+-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  37. '^_`abcdefghijklmnopqrstuvwxyz|~')
  38. _etag_re = re.compile(r'([Ww]/)?(?:"(.*?)"|(.*?))(?:\s*,\s*|$)')
  39. _unsafe_header_chars = set('()<>@,;:\"/[]?={} \t')
  40. _quoted_string_re = r'"[^"\\]*(?:\\.[^"\\]*)*"'
  41. _option_header_piece_re = re.compile(r';\s*(%s|[^\s;=]+)\s*(?:=\s*(%s|[^;]+))?\s*' %
  42. (_quoted_string_re, _quoted_string_re))
  43. _entity_headers = frozenset([
  44. 'allow', 'content-encoding', 'content-language', 'content-length',
  45. 'content-location', 'content-md5', 'content-range', 'content-type',
  46. 'expires', 'last-modified'
  47. ])
  48. _hop_by_hop_headers = frozenset([
  49. 'connection', 'keep-alive', 'proxy-authenticate',
  50. 'proxy-authorization', 'te', 'trailer', 'transfer-encoding',
  51. 'upgrade'
  52. ])
  53. HTTP_STATUS_CODES = {
  54. 100: 'Continue',
  55. 101: 'Switching Protocols',
  56. 102: 'Processing',
  57. 200: 'OK',
  58. 201: 'Created',
  59. 202: 'Accepted',
  60. 203: 'Non Authoritative Information',
  61. 204: 'No Content',
  62. 205: 'Reset Content',
  63. 206: 'Partial Content',
  64. 207: 'Multi Status',
  65. 226: 'IM Used', # see RFC 3229
  66. 300: 'Multiple Choices',
  67. 301: 'Moved Permanently',
  68. 302: 'Found',
  69. 303: 'See Other',
  70. 304: 'Not Modified',
  71. 305: 'Use Proxy',
  72. 307: 'Temporary Redirect',
  73. 400: 'Bad Request',
  74. 401: 'Unauthorized',
  75. 402: 'Payment Required', # unused
  76. 403: 'Forbidden',
  77. 404: 'Not Found',
  78. 405: 'Method Not Allowed',
  79. 406: 'Not Acceptable',
  80. 407: 'Proxy Authentication Required',
  81. 408: 'Request Timeout',
  82. 409: 'Conflict',
  83. 410: 'Gone',
  84. 411: 'Length Required',
  85. 412: 'Precondition Failed',
  86. 413: 'Request Entity Too Large',
  87. 414: 'Request URI Too Long',
  88. 415: 'Unsupported Media Type',
  89. 416: 'Requested Range Not Satisfiable',
  90. 417: 'Expectation Failed',
  91. 418: 'I\'m a teapot', # see RFC 2324
  92. 422: 'Unprocessable Entity',
  93. 423: 'Locked',
  94. 424: 'Failed Dependency',
  95. 426: 'Upgrade Required',
  96. 428: 'Precondition Required', # see RFC 6585
  97. 429: 'Too Many Requests',
  98. 431: 'Request Header Fields Too Large',
  99. 449: 'Retry With', # proprietary MS extension
  100. 500: 'Internal Server Error',
  101. 501: 'Not Implemented',
  102. 502: 'Bad Gateway',
  103. 503: 'Service Unavailable',
  104. 504: 'Gateway Timeout',
  105. 505: 'HTTP Version Not Supported',
  106. 507: 'Insufficient Storage',
  107. 510: 'Not Extended'
  108. }
  109. def wsgi_to_bytes(data):
  110. """coerce wsgi unicode represented bytes to real ones
  111. """
  112. if isinstance(data, bytes):
  113. return data
  114. return data.encode('latin1') #XXX: utf8 fallback?
  115. def bytes_to_wsgi(data):
  116. assert isinstance(data, bytes), 'data must be bytes'
  117. if isinstance(data, str):
  118. return data
  119. else:
  120. return data.decode('latin1')
  121. def quote_header_value(value, extra_chars='', allow_token=True):
  122. """Quote a header value if necessary.
  123. .. versionadded:: 0.5
  124. :param value: the value to quote.
  125. :param extra_chars: a list of extra characters to skip quoting.
  126. :param allow_token: if this is enabled token values are returned
  127. unchanged.
  128. """
  129. if isinstance(value, bytes):
  130. value = bytes_to_wsgi(value)
  131. value = str(value)
  132. if allow_token:
  133. token_chars = _token_chars | set(extra_chars)
  134. if set(value).issubset(token_chars):
  135. return value
  136. return '"%s"' % value.replace('\\', '\\\\').replace('"', '\\"')
  137. def unquote_header_value(value, is_filename=False):
  138. r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).
  139. This does not use the real unquoting but what browsers are actually
  140. using for quoting.
  141. .. versionadded:: 0.5
  142. :param value: the header value to unquote.
  143. """
  144. if value and value[0] == value[-1] == '"':
  145. # this is not the real unquoting, but fixing this so that the
  146. # RFC is met will result in bugs with internet explorer and
  147. # probably some other browsers as well. IE for example is
  148. # uploading files with "C:\foo\bar.txt" as filename
  149. value = value[1:-1]
  150. # if this is a filename and the starting characters look like
  151. # a UNC path, then just return the value without quotes. Using the
  152. # replace sequence below on a UNC path has the effect of turning
  153. # the leading double slash into a single slash and then
  154. # _fix_ie_filename() doesn't work correctly. See #458.
  155. if not is_filename or value[:2] != '\\\\':
  156. return value.replace('\\\\', '\\').replace('\\"', '"')
  157. return value
  158. def dump_options_header(header, options):
  159. """The reverse function to :func:`parse_options_header`.
  160. :param header: the header to dump
  161. :param options: a dict of options to append.
  162. """
  163. segments = []
  164. if header is not None:
  165. segments.append(header)
  166. for key, value in iteritems(options):
  167. if value is None:
  168. segments.append(key)
  169. else:
  170. segments.append('%s=%s' % (key, quote_header_value(value)))
  171. return '; '.join(segments)
  172. def dump_header(iterable, allow_token=True):
  173. """Dump an HTTP header again. This is the reversal of
  174. :func:`parse_list_header`, :func:`parse_set_header` and
  175. :func:`parse_dict_header`. This also quotes strings that include an
  176. equals sign unless you pass it as dict of key, value pairs.
  177. >>> dump_header({'foo': 'bar baz'})
  178. 'foo="bar baz"'
  179. >>> dump_header(('foo', 'bar baz'))
  180. 'foo, "bar baz"'
  181. :param iterable: the iterable or dict of values to quote.
  182. :param allow_token: if set to `False` tokens as values are disallowed.
  183. See :func:`quote_header_value` for more details.
  184. """
  185. if isinstance(iterable, dict):
  186. items = []
  187. for key, value in iteritems(iterable):
  188. if value is None:
  189. items.append(key)
  190. else:
  191. items.append('%s=%s' % (
  192. key,
  193. quote_header_value(value, allow_token=allow_token)
  194. ))
  195. else:
  196. items = [quote_header_value(x, allow_token=allow_token)
  197. for x in iterable]
  198. return ', '.join(items)
  199. def parse_list_header(value):
  200. """Parse lists as described by RFC 2068 Section 2.
  201. In particular, parse comma-separated lists where the elements of
  202. the list may include quoted-strings. A quoted-string could
  203. contain a comma. A non-quoted string could have quotes in the
  204. middle. Quotes are removed automatically after parsing.
  205. It basically works like :func:`parse_set_header` just that items
  206. may appear multiple times and case sensitivity is preserved.
  207. The return value is a standard :class:`list`:
  208. >>> parse_list_header('token, "quoted value"')
  209. ['token', 'quoted value']
  210. To create a header from the :class:`list` again, use the
  211. :func:`dump_header` function.
  212. :param value: a string with a list header.
  213. :return: :class:`list`
  214. """
  215. result = []
  216. for item in _parse_list_header(value):
  217. if item[:1] == item[-1:] == '"':
  218. item = unquote_header_value(item[1:-1])
  219. result.append(item)
  220. return result
  221. def parse_dict_header(value, cls=dict):
  222. """Parse lists of key, value pairs as described by RFC 2068 Section 2 and
  223. convert them into a python dict (or any other mapping object created from
  224. the type with a dict like interface provided by the `cls` arugment):
  225. >>> d = parse_dict_header('foo="is a fish", bar="as well"')
  226. >>> type(d) is dict
  227. True
  228. >>> sorted(d.items())
  229. [('bar', 'as well'), ('foo', 'is a fish')]
  230. If there is no value for a key it will be `None`:
  231. >>> parse_dict_header('key_without_value')
  232. {'key_without_value': None}
  233. To create a header from the :class:`dict` again, use the
  234. :func:`dump_header` function.
  235. .. versionchanged:: 0.9
  236. Added support for `cls` argument.
  237. :param value: a string with a dict header.
  238. :param cls: callable to use for storage of parsed results.
  239. :return: an instance of `cls`
  240. """
  241. result = cls()
  242. if not isinstance(value, text_type):
  243. #XXX: validate
  244. value = bytes_to_wsgi(value)
  245. for item in _parse_list_header(value):
  246. if '=' not in item:
  247. result[item] = None
  248. continue
  249. name, value = item.split('=', 1)
  250. if value[:1] == value[-1:] == '"':
  251. value = unquote_header_value(value[1:-1])
  252. result[name] = value
  253. return result
  254. def parse_options_header(value):
  255. """Parse a ``Content-Type`` like header into a tuple with the content
  256. type and the options:
  257. >>> parse_options_header('text/html; charset=utf8')
  258. ('text/html', {'charset': 'utf8'})
  259. This should not be used to parse ``Cache-Control`` like headers that use
  260. a slightly different format. For these headers use the
  261. :func:`parse_dict_header` function.
  262. .. versionadded:: 0.5
  263. :param value: the header to parse.
  264. :return: (str, options)
  265. """
  266. def _tokenize(string):
  267. for match in _option_header_piece_re.finditer(string):
  268. key, value = match.groups()
  269. key = unquote_header_value(key)
  270. if value is not None:
  271. value = unquote_header_value(value, key == 'filename')
  272. yield key, value
  273. if not value:
  274. return '', {}
  275. parts = _tokenize(';' + value)
  276. name = next(parts)[0]
  277. extra = dict(parts)
  278. return name, extra
  279. def parse_accept_header(value, cls=None):
  280. """Parses an HTTP Accept-* header. This does not implement a complete
  281. valid algorithm but one that supports at least value and quality
  282. extraction.
  283. Returns a new :class:`Accept` object (basically a list of ``(value, quality)``
  284. tuples sorted by the quality with some additional accessor methods).
  285. The second parameter can be a subclass of :class:`Accept` that is created
  286. with the parsed values and returned.
  287. :param value: the accept header string to be parsed.
  288. :param cls: the wrapper class for the return value (can be
  289. :class:`Accept` or a subclass thereof)
  290. :return: an instance of `cls`.
  291. """
  292. if cls is None:
  293. cls = Accept
  294. if not value:
  295. return cls(None)
  296. result = []
  297. for match in _accept_re.finditer(value):
  298. quality = match.group(2)
  299. if not quality:
  300. quality = 1
  301. else:
  302. quality = max(min(float(quality), 1), 0)
  303. result.append((match.group(1), quality))
  304. return cls(result)
  305. def parse_cache_control_header(value, on_update=None, cls=None):
  306. """Parse a cache control header. The RFC differs between response and
  307. request cache control, this method does not. It's your responsibility
  308. to not use the wrong control statements.
  309. .. versionadded:: 0.5
  310. The `cls` was added. If not specified an immutable
  311. :class:`~werkzeug.datastructures.RequestCacheControl` is returned.
  312. :param value: a cache control header to be parsed.
  313. :param on_update: an optional callable that is called every time a value
  314. on the :class:`~werkzeug.datastructures.CacheControl`
  315. object is changed.
  316. :param cls: the class for the returned object. By default
  317. :class:`~werkzeug.datastructures.RequestCacheControl` is used.
  318. :return: a `cls` object.
  319. """
  320. if cls is None:
  321. cls = RequestCacheControl
  322. if not value:
  323. return cls(None, on_update)
  324. return cls(parse_dict_header(value), on_update)
  325. def parse_set_header(value, on_update=None):
  326. """Parse a set-like header and return a
  327. :class:`~werkzeug.datastructures.HeaderSet` object:
  328. >>> hs = parse_set_header('token, "quoted value"')
  329. The return value is an object that treats the items case-insensitively
  330. and keeps the order of the items:
  331. >>> 'TOKEN' in hs
  332. True
  333. >>> hs.index('quoted value')
  334. 1
  335. >>> hs
  336. HeaderSet(['token', 'quoted value'])
  337. To create a header from the :class:`HeaderSet` again, use the
  338. :func:`dump_header` function.
  339. :param value: a set header to be parsed.
  340. :param on_update: an optional callable that is called every time a
  341. value on the :class:`~werkzeug.datastructures.HeaderSet`
  342. object is changed.
  343. :return: a :class:`~werkzeug.datastructures.HeaderSet`
  344. """
  345. if not value:
  346. return HeaderSet(None, on_update)
  347. return HeaderSet(parse_list_header(value), on_update)
  348. def parse_authorization_header(value):
  349. """Parse an HTTP basic/digest authorization header transmitted by the web
  350. browser. The return value is either `None` if the header was invalid or
  351. not given, otherwise an :class:`~werkzeug.datastructures.Authorization`
  352. object.
  353. :param value: the authorization header to parse.
  354. :return: a :class:`~werkzeug.datastructures.Authorization` object or `None`.
  355. """
  356. if not value:
  357. return
  358. value = wsgi_to_bytes(value)
  359. try:
  360. auth_type, auth_info = value.split(None, 1)
  361. auth_type = auth_type.lower()
  362. except ValueError:
  363. return
  364. if auth_type == b'basic':
  365. try:
  366. username, password = base64.b64decode(auth_info).split(b':', 1)
  367. except Exception as e:
  368. return
  369. return Authorization('basic', {'username': bytes_to_wsgi(username),
  370. 'password': bytes_to_wsgi(password)})
  371. elif auth_type == b'digest':
  372. auth_map = parse_dict_header(auth_info)
  373. for key in 'username', 'realm', 'nonce', 'uri', 'response':
  374. if not key in auth_map:
  375. return
  376. if 'qop' in auth_map:
  377. if not auth_map.get('nc') or not auth_map.get('cnonce'):
  378. return
  379. return Authorization('digest', auth_map)
  380. def parse_www_authenticate_header(value, on_update=None):
  381. """Parse an HTTP WWW-Authenticate header into a
  382. :class:`~werkzeug.datastructures.WWWAuthenticate` object.
  383. :param value: a WWW-Authenticate header to parse.
  384. :param on_update: an optional callable that is called every time a value
  385. on the :class:`~werkzeug.datastructures.WWWAuthenticate`
  386. object is changed.
  387. :return: a :class:`~werkzeug.datastructures.WWWAuthenticate` object.
  388. """
  389. if not value:
  390. return WWWAuthenticate(on_update=on_update)
  391. try:
  392. auth_type, auth_info = value.split(None, 1)
  393. auth_type = auth_type.lower()
  394. except (ValueError, AttributeError):
  395. return WWWAuthenticate(value.strip().lower(), on_update=on_update)
  396. return WWWAuthenticate(auth_type, parse_dict_header(auth_info),
  397. on_update)
  398. def parse_if_range_header(value):
  399. """Parses an if-range header which can be an etag or a date. Returns
  400. a :class:`~werkzeug.datastructures.IfRange` object.
  401. .. versionadded:: 0.7
  402. """
  403. if not value:
  404. return IfRange()
  405. date = parse_date(value)
  406. if date is not None:
  407. return IfRange(date=date)
  408. # drop weakness information
  409. return IfRange(unquote_etag(value)[0])
  410. def parse_range_header(value, make_inclusive=True):
  411. """Parses a range header into a :class:`~werkzeug.datastructures.Range`
  412. object. If the header is missing or malformed `None` is returned.
  413. `ranges` is a list of ``(start, stop)`` tuples where the ranges are
  414. non-inclusive.
  415. .. versionadded:: 0.7
  416. """
  417. if not value or '=' not in value:
  418. return None
  419. ranges = []
  420. last_end = 0
  421. units, rng = value.split('=', 1)
  422. units = units.strip().lower()
  423. for item in rng.split(','):
  424. item = item.strip()
  425. if '-' not in item:
  426. return None
  427. if item.startswith('-'):
  428. if last_end < 0:
  429. return None
  430. begin = int(item)
  431. end = None
  432. last_end = -1
  433. elif '-' in item:
  434. begin, end = item.split('-', 1)
  435. begin = int(begin)
  436. if begin < last_end or last_end < 0:
  437. return None
  438. if end:
  439. end = int(end) + 1
  440. if begin >= end:
  441. return None
  442. else:
  443. end = None
  444. last_end = end
  445. ranges.append((begin, end))
  446. return Range(units, ranges)
  447. def parse_content_range_header(value, on_update=None):
  448. """Parses a range header into a
  449. :class:`~werkzeug.datastructures.ContentRange` object or `None` if
  450. parsing is not possible.
  451. .. versionadded:: 0.7
  452. :param value: a content range header to be parsed.
  453. :param on_update: an optional callable that is called every time a value
  454. on the :class:`~werkzeug.datastructures.ContentRange`
  455. object is changed.
  456. """
  457. if value is None:
  458. return None
  459. try:
  460. units, rangedef = (value or '').strip().split(None, 1)
  461. except ValueError:
  462. return None
  463. if '/' not in rangedef:
  464. return None
  465. rng, length = rangedef.split('/', 1)
  466. if length == '*':
  467. length = None
  468. elif length.isdigit():
  469. length = int(length)
  470. else:
  471. return None
  472. if rng == '*':
  473. return ContentRange(units, None, None, length, on_update=on_update)
  474. elif '-' not in rng:
  475. return None
  476. start, stop = rng.split('-', 1)
  477. try:
  478. start = int(start)
  479. stop = int(stop) + 1
  480. except ValueError:
  481. return None
  482. if is_byte_range_valid(start, stop, length):
  483. return ContentRange(units, start, stop, length, on_update=on_update)
  484. def quote_etag(etag, weak=False):
  485. """Quote an etag.
  486. :param etag: the etag to quote.
  487. :param weak: set to `True` to tag it "weak".
  488. """
  489. if '"' in etag:
  490. raise ValueError('invalid etag')
  491. etag = '"%s"' % etag
  492. if weak:
  493. etag = 'w/' + etag
  494. return etag
  495. def unquote_etag(etag):
  496. """Unquote a single etag:
  497. >>> unquote_etag('w/"bar"')
  498. ('bar', True)
  499. >>> unquote_etag('"bar"')
  500. ('bar', False)
  501. :param etag: the etag identifier to unquote.
  502. :return: a ``(etag, weak)`` tuple.
  503. """
  504. if not etag:
  505. return None, None
  506. etag = etag.strip()
  507. weak = False
  508. if etag[:2] in ('w/', 'W/'):
  509. weak = True
  510. etag = etag[2:]
  511. if etag[:1] == etag[-1:] == '"':
  512. etag = etag[1:-1]
  513. return etag, weak
  514. def parse_etags(value):
  515. """Parse an etag header.
  516. :param value: the tag header to parse
  517. :return: an :class:`~werkzeug.datastructures.ETags` object.
  518. """
  519. if not value:
  520. return ETags()
  521. strong = []
  522. weak = []
  523. end = len(value)
  524. pos = 0
  525. while pos < end:
  526. match = _etag_re.match(value, pos)
  527. if match is None:
  528. break
  529. is_weak, quoted, raw = match.groups()
  530. if raw == '*':
  531. return ETags(star_tag=True)
  532. elif quoted:
  533. raw = quoted
  534. if is_weak:
  535. weak.append(raw)
  536. else:
  537. strong.append(raw)
  538. pos = match.end()
  539. return ETags(strong, weak)
  540. def generate_etag(data):
  541. """Generate an etag for some data."""
  542. return md5(data).hexdigest()
  543. def parse_date(value):
  544. """Parse one of the following date formats into a datetime object:
  545. .. sourcecode:: text
  546. Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
  547. Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
  548. Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
  549. If parsing fails the return value is `None`.
  550. :param value: a string with a supported date format.
  551. :return: a :class:`datetime.datetime` object.
  552. """
  553. if value:
  554. t = parsedate_tz(value.strip())
  555. if t is not None:
  556. try:
  557. year = t[0]
  558. # unfortunately that function does not tell us if two digit
  559. # years were part of the string, or if they were prefixed
  560. # with two zeroes. So what we do is to assume that 69-99
  561. # refer to 1900, and everything below to 2000
  562. if year >= 0 and year <= 68:
  563. year += 2000
  564. elif year >= 69 and year <= 99:
  565. year += 1900
  566. return datetime(*((year,) + t[1:7])) - \
  567. timedelta(seconds=t[-1] or 0)
  568. except (ValueError, OverflowError):
  569. return None
  570. def _dump_date(d, delim):
  571. """Used for `http_date` and `cookie_date`."""
  572. if d is None:
  573. d = gmtime()
  574. elif isinstance(d, datetime):
  575. d = d.utctimetuple()
  576. elif isinstance(d, (integer_types, float)):
  577. d = gmtime(d)
  578. return '%s, %02d%s%s%s%s %02d:%02d:%02d GMT' % (
  579. ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')[d.tm_wday],
  580. d.tm_mday, delim,
  581. ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  582. 'Oct', 'Nov', 'Dec')[d.tm_mon - 1],
  583. delim, str(d.tm_year), d.tm_hour, d.tm_min, d.tm_sec
  584. )
  585. def cookie_date(expires=None):
  586. """Formats the time to ensure compatibility with Netscape's cookie
  587. standard.
  588. Accepts a floating point number expressed in seconds since the epoch in, a
  589. datetime object or a timetuple. All times in UTC. The :func:`parse_date`
  590. function can be used to parse such a date.
  591. Outputs a string in the format ``Wdy, DD-Mon-YYYY HH:MM:SS GMT``.
  592. :param expires: If provided that date is used, otherwise the current.
  593. """
  594. return _dump_date(expires, '-')
  595. def http_date(timestamp=None):
  596. """Formats the time to match the RFC1123 date format.
  597. Accepts a floating point number expressed in seconds since the epoch in, a
  598. datetime object or a timetuple. All times in UTC. The :func:`parse_date`
  599. function can be used to parse such a date.
  600. Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``.
  601. :param timestamp: If provided that date is used, otherwise the current.
  602. """
  603. return _dump_date(timestamp, ' ')
  604. def is_resource_modified(environ, etag=None, data=None, last_modified=None):
  605. """Convenience method for conditional requests.
  606. :param environ: the WSGI environment of the request to be checked.
  607. :param etag: the etag for the response for comparison.
  608. :param data: or alternatively the data of the response to automatically
  609. generate an etag using :func:`generate_etag`.
  610. :param last_modified: an optional date of the last modification.
  611. :return: `True` if the resource was modified, otherwise `False`.
  612. """
  613. if etag is None and data is not None:
  614. etag = generate_etag(data)
  615. elif data is not None:
  616. raise TypeError('both data and etag given')
  617. if environ['REQUEST_METHOD'] not in ('GET', 'HEAD'):
  618. return False
  619. unmodified = False
  620. if isinstance(last_modified, string_types):
  621. last_modified = parse_date(last_modified)
  622. # ensure that microsecond is zero because the HTTP spec does not transmit
  623. # that either and we might have some false positives. See issue #39
  624. if last_modified is not None:
  625. last_modified = last_modified.replace(microsecond=0)
  626. modified_since = parse_date(environ.get('HTTP_IF_MODIFIED_SINCE'))
  627. if modified_since and last_modified and last_modified <= modified_since:
  628. unmodified = True
  629. if etag:
  630. if_none_match = parse_etags(environ.get('HTTP_IF_NONE_MATCH'))
  631. if if_none_match:
  632. unmodified = if_none_match.contains_raw(etag)
  633. return not unmodified
  634. def remove_entity_headers(headers, allowed=('expires', 'content-location')):
  635. """Remove all entity headers from a list or :class:`Headers` object. This
  636. operation works in-place. `Expires` and `Content-Location` headers are
  637. by default not removed. The reason for this is :rfc:`2616` section
  638. 10.3.5 which specifies some entity headers that should be sent.
  639. .. versionchanged:: 0.5
  640. added `allowed` parameter.
  641. :param headers: a list or :class:`Headers` object.
  642. :param allowed: a list of headers that should still be allowed even though
  643. they are entity headers.
  644. """
  645. allowed = set(x.lower() for x in allowed)
  646. headers[:] = [(key, value) for key, value in headers if
  647. not is_entity_header(key) or key.lower() in allowed]
  648. def remove_hop_by_hop_headers(headers):
  649. """Remove all HTTP/1.1 "Hop-by-Hop" headers from a list or
  650. :class:`Headers` object. This operation works in-place.
  651. .. versionadded:: 0.5
  652. :param headers: a list or :class:`Headers` object.
  653. """
  654. headers[:] = [(key, value) for key, value in headers if
  655. not is_hop_by_hop_header(key)]
  656. def is_entity_header(header):
  657. """Check if a header is an entity header.
  658. .. versionadded:: 0.5
  659. :param header: the header to test.
  660. :return: `True` if it's an entity header, `False` otherwise.
  661. """
  662. return header.lower() in _entity_headers
  663. def is_hop_by_hop_header(header):
  664. """Check if a header is an HTTP/1.1 "Hop-by-Hop" header.
  665. .. versionadded:: 0.5
  666. :param header: the header to test.
  667. :return: `True` if it's an entity header, `False` otherwise.
  668. """
  669. return header.lower() in _hop_by_hop_headers
  670. def parse_cookie(header, charset='utf-8', errors='replace', cls=None):
  671. """Parse a cookie. Either from a string or WSGI environ.
  672. Per default encoding errors are ignored. If you want a different behavior
  673. you can set `errors` to ``'replace'`` or ``'strict'``. In strict mode a
  674. :exc:`HTTPUnicodeError` is raised.
  675. .. versionchanged:: 0.5
  676. This function now returns a :class:`TypeConversionDict` instead of a
  677. regular dict. The `cls` parameter was added.
  678. :param header: the header to be used to parse the cookie. Alternatively
  679. this can be a WSGI environment.
  680. :param charset: the charset for the cookie values.
  681. :param errors: the error behavior for the charset decoding.
  682. :param cls: an optional dict class to use. If this is not specified
  683. or `None` the default :class:`TypeConversionDict` is
  684. used.
  685. """
  686. if isinstance(header, dict):
  687. header = header.get('HTTP_COOKIE', '')
  688. elif header is None:
  689. header = ''
  690. # If the value is an unicode string it's mangled through latin1. This
  691. # is done because on PEP 3333 on Python 3 all headers are assumed latin1
  692. # which however is incorrect for cookies, which are sent in page encoding.
  693. # As a result we
  694. if isinstance(header, text_type):
  695. header = header.encode('latin1', 'replace')
  696. if cls is None:
  697. cls = TypeConversionDict
  698. def _parse_pairs():
  699. for key, val in _cookie_parse_impl(header):
  700. key = to_unicode(key, charset, errors, allow_none_charset=True)
  701. val = to_unicode(val, charset, errors, allow_none_charset=True)
  702. yield try_coerce_native(key), val
  703. return cls(_parse_pairs())
  704. def dump_cookie(key, value='', max_age=None, expires=None, path='/',
  705. domain=None, secure=False, httponly=False,
  706. charset='utf-8', sync_expires=True):
  707. """Creates a new Set-Cookie header without the ``Set-Cookie`` prefix
  708. The parameters are the same as in the cookie Morsel object in the
  709. Python standard library but it accepts unicode data, too.
  710. On Python 3 the return value of this function will be a unicode
  711. string, on Python 2 it will be a native string. In both cases the
  712. return value is usually restricted to ascii as the vast majority of
  713. values are properly escaped, but that is no guarantee. If a unicode
  714. string is returned it's tunneled through latin1 as required by
  715. PEP 3333.
  716. The return value is not ASCII safe if the key contains unicode
  717. characters. This is technically against the specification but
  718. happens in the wild. It's strongly recommended to not use
  719. non-ASCII values for the keys.
  720. :param max_age: should be a number of seconds, or `None` (default) if
  721. the cookie should last only as long as the client's
  722. browser session. Additionally `timedelta` objects
  723. are accepted, too.
  724. :param expires: should be a `datetime` object or unix timestamp.
  725. :param path: limits the cookie to a given path, per default it will
  726. span the whole domain.
  727. :param domain: Use this if you want to set a cross-domain cookie. For
  728. example, ``domain=".example.com"`` will set a cookie
  729. that is readable by the domain ``www.example.com``,
  730. ``foo.example.com`` etc. Otherwise, a cookie will only
  731. be readable by the domain that set it.
  732. :param secure: The cookie will only be available via HTTPS
  733. :param httponly: disallow JavaScript to access the cookie. This is an
  734. extension to the cookie standard and probably not
  735. supported by all browsers.
  736. :param charset: the encoding for unicode values.
  737. :param sync_expires: automatically set expires if max_age is defined
  738. but expires not.
  739. """
  740. key = to_bytes(key, charset)
  741. value = to_bytes(value, charset)
  742. if path is not None:
  743. path = iri_to_uri(path, charset)
  744. domain = _make_cookie_domain(domain)
  745. if isinstance(max_age, timedelta):
  746. max_age = (max_age.days * 60 * 60 * 24) + max_age.seconds
  747. if expires is not None:
  748. if not isinstance(expires, string_types):
  749. expires = cookie_date(expires)
  750. elif max_age is not None and sync_expires:
  751. expires = to_bytes(cookie_date(time() + max_age))
  752. buf = [key + b'=' + _cookie_quote(value)]
  753. # XXX: In theory all of these parameters that are not marked with `None`
  754. # should be quoted. Because stdlib did not quote it before I did not
  755. # want to introduce quoting there now.
  756. for k, v, q in ((b'Domain', domain, True),
  757. (b'Expires', expires, False,),
  758. (b'Max-Age', max_age, False),
  759. (b'Secure', secure, None),
  760. (b'HttpOnly', httponly, None),
  761. (b'Path', path, False)):
  762. if q is None:
  763. if v:
  764. buf.append(k)
  765. continue
  766. if v is None:
  767. continue
  768. tmp = bytearray(k)
  769. if not isinstance(v, (bytes, bytearray)):
  770. v = to_bytes(text_type(v), charset)
  771. if q:
  772. v = _cookie_quote(v)
  773. tmp += b'=' + v
  774. buf.append(bytes(tmp))
  775. # The return value will be an incorrectly encoded latin1 header on
  776. # Python 3 for consistency with the headers object and a bytestring
  777. # on Python 2 because that's how the API makes more sense.
  778. rv = b'; '.join(buf)
  779. if not PY2:
  780. rv = rv.decode('latin1')
  781. return rv
  782. def is_byte_range_valid(start, stop, length):
  783. """Checks if a given byte content range is valid for the given length.
  784. .. versionadded:: 0.7
  785. """
  786. if (start is None) != (stop is None):
  787. return False
  788. elif start is None:
  789. return length is None or length >= 0
  790. elif length is None:
  791. return 0 <= start < stop
  792. elif start >= stop:
  793. return False
  794. return 0 <= start < length
  795. # circular dependency fun
  796. from werkzeug.datastructures import Accept, HeaderSet, ETags, Authorization, \
  797. WWWAuthenticate, TypeConversionDict, IfRange, Range, ContentRange, \
  798. RequestCacheControl
  799. # DEPRECATED
  800. # backwards compatible imports
  801. from werkzeug.datastructures import MIMEAccept, CharsetAccept, \
  802. LanguageAccept, Headers
  803. from werkzeug.urls import iri_to_uri