wsgi.py 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  1. # -*- coding: utf-8 -*-
  2. """
  3. werkzeug.wsgi
  4. ~~~~~~~~~~~~~
  5. This module implements WSGI related helpers.
  6. :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. import re
  10. import os
  11. import posixpath
  12. import mimetypes
  13. from itertools import chain
  14. from zlib import adler32
  15. from time import time, mktime
  16. from datetime import datetime
  17. from functools import partial, update_wrapper
  18. from werkzeug._compat import iteritems, text_type, string_types, \
  19. implements_iterator, make_literal_wrapper, to_unicode, to_bytes, \
  20. wsgi_get_bytes, try_coerce_native, PY2
  21. from werkzeug._internal import _empty_stream, _encode_idna
  22. from werkzeug.http import is_resource_modified, http_date
  23. from werkzeug.urls import uri_to_iri, url_quote, url_parse, url_join
  24. from werkzeug.filesystem import get_filesystem_encoding
  25. def responder(f):
  26. """Marks a function as responder. Decorate a function with it and it
  27. will automatically call the return value as WSGI application.
  28. Example::
  29. @responder
  30. def application(environ, start_response):
  31. return Response('Hello World!')
  32. """
  33. return update_wrapper(lambda *a: f(*a)(*a[-2:]), f)
  34. def get_current_url(environ, root_only=False, strip_querystring=False,
  35. host_only=False, trusted_hosts=None):
  36. """A handy helper function that recreates the full URL as IRI for the
  37. current request or parts of it. Here an example:
  38. >>> from werkzeug.test import create_environ
  39. >>> env = create_environ("/?param=foo", "http://localhost/script")
  40. >>> get_current_url(env)
  41. 'http://localhost/script/?param=foo'
  42. >>> get_current_url(env, root_only=True)
  43. 'http://localhost/script/'
  44. >>> get_current_url(env, host_only=True)
  45. 'http://localhost/'
  46. >>> get_current_url(env, strip_querystring=True)
  47. 'http://localhost/script/'
  48. This optionally it verifies that the host is in a list of trusted hosts.
  49. If the host is not in there it will raise a
  50. :exc:`~werkzeug.exceptions.SecurityError`.
  51. Note that the string returned might contain unicode characters as the
  52. representation is an IRI not an URI. If you need an ASCII only
  53. representation you can use the :func:`~werkzeug.urls.iri_to_uri`
  54. function:
  55. >>> from werkzeug.urls import iri_to_uri
  56. >>> iri_to_uri(get_current_url(env))
  57. 'http://localhost/script/?param=foo'
  58. :param environ: the WSGI environment to get the current URL from.
  59. :param root_only: set `True` if you only want the root URL.
  60. :param strip_querystring: set to `True` if you don't want the querystring.
  61. :param host_only: set to `True` if the host URL should be returned.
  62. :param trusted_hosts: a list of trusted hosts, see :func:`host_is_trusted`
  63. for more information.
  64. """
  65. tmp = [environ['wsgi.url_scheme'], '://', get_host(environ, trusted_hosts)]
  66. cat = tmp.append
  67. if host_only:
  68. return uri_to_iri(''.join(tmp) + '/')
  69. cat(url_quote(wsgi_get_bytes(environ.get('SCRIPT_NAME', ''))).rstrip('/'))
  70. cat('/')
  71. if not root_only:
  72. cat(url_quote(wsgi_get_bytes(environ.get('PATH_INFO', '')).lstrip(b'/')))
  73. if not strip_querystring:
  74. qs = get_query_string(environ)
  75. if qs:
  76. cat('?' + qs)
  77. return uri_to_iri(''.join(tmp))
  78. def host_is_trusted(hostname, trusted_list):
  79. """Checks if a host is trusted against a list. This also takes care
  80. of port normalization.
  81. .. versionadded:: 0.9
  82. :param hostname: the hostname to check
  83. :param trusted_list: a list of hostnames to check against. If a
  84. hostname starts with a dot it will match against
  85. all subdomains as well.
  86. """
  87. if not hostname:
  88. return False
  89. if isinstance(trusted_list, string_types):
  90. trusted_list = [trusted_list]
  91. def _normalize(hostname):
  92. if ':' in hostname:
  93. hostname = hostname.rsplit(':', 1)[0]
  94. return _encode_idna(hostname)
  95. try:
  96. hostname = _normalize(hostname)
  97. except UnicodeError:
  98. return False
  99. for ref in trusted_list:
  100. if ref.startswith('.'):
  101. ref = ref[1:]
  102. suffix_match = True
  103. else:
  104. suffix_match = False
  105. try:
  106. ref = _normalize(ref)
  107. except UnicodeError:
  108. return False
  109. if ref == hostname:
  110. return True
  111. if suffix_match and hostname.endswith('.' + ref):
  112. return True
  113. return False
  114. def get_host(environ, trusted_hosts=None):
  115. """Return the real host for the given WSGI environment. This first checks
  116. the `X-Forwarded-Host` header, then the normal `Host` header, and finally
  117. the `SERVER_NAME` environment variable (using the first one it finds).
  118. Optionally it verifies that the host is in a list of trusted hosts.
  119. If the host is not in there it will raise a
  120. :exc:`~werkzeug.exceptions.SecurityError`.
  121. :param environ: the WSGI environment to get the host of.
  122. :param trusted_hosts: a list of trusted hosts, see :func:`host_is_trusted`
  123. for more information.
  124. """
  125. if 'HTTP_X_FORWARDED_HOST' in environ:
  126. rv = environ['HTTP_X_FORWARDED_HOST'].split(',', 1)[0].strip()
  127. elif 'HTTP_HOST' in environ:
  128. rv = environ['HTTP_HOST']
  129. else:
  130. rv = environ['SERVER_NAME']
  131. if (environ['wsgi.url_scheme'], environ['SERVER_PORT']) not \
  132. in (('https', '443'), ('http', '80')):
  133. rv += ':' + environ['SERVER_PORT']
  134. if trusted_hosts is not None:
  135. if not host_is_trusted(rv, trusted_hosts):
  136. from werkzeug.exceptions import SecurityError
  137. raise SecurityError('Host "%s" is not trusted' % rv)
  138. return rv
  139. def get_content_length(environ):
  140. """Returns the content length from the WSGI environment as
  141. integer. If it's not available `None` is returned.
  142. .. versionadded:: 0.9
  143. :param environ: the WSGI environ to fetch the content length from.
  144. """
  145. content_length = environ.get('CONTENT_LENGTH')
  146. if content_length is not None:
  147. try:
  148. return max(0, int(content_length))
  149. except (ValueError, TypeError):
  150. pass
  151. def get_input_stream(environ, safe_fallback=True):
  152. """Returns the input stream from the WSGI environment and wraps it
  153. in the most sensible way possible. The stream returned is not the
  154. raw WSGI stream in most cases but one that is safe to read from
  155. without taking into account the content length.
  156. .. versionadded:: 0.9
  157. :param environ: the WSGI environ to fetch the stream from.
  158. :param safe: indicates whether the function should use an empty
  159. stream as safe fallback or just return the original
  160. WSGI input stream if it can't wrap it safely. The
  161. default is to return an empty string in those cases.
  162. """
  163. stream = environ['wsgi.input']
  164. content_length = get_content_length(environ)
  165. # A wsgi extension that tells us if the input is terminated. In
  166. # that case we return the stream unchanged as we know we can safely
  167. # read it until the end.
  168. if environ.get('wsgi.input_terminated'):
  169. return stream
  170. # If we don't have a content length we fall back to an empty stream
  171. # in case of a safe fallback, otherwise we return the stream unchanged.
  172. # The non-safe fallback is not recommended but might be useful in
  173. # some situations.
  174. if content_length is None:
  175. return safe_fallback and _empty_stream or stream
  176. # Otherwise limit the stream to the content length
  177. return LimitedStream(stream, content_length)
  178. def get_query_string(environ):
  179. """Returns the `QUERY_STRING` from the WSGI environment. This also takes
  180. care about the WSGI decoding dance on Python 3 environments as a
  181. native string. The string returned will be restricted to ASCII
  182. characters.
  183. .. versionadded:: 0.9
  184. :param environ: the WSGI environment object to get the query string from.
  185. """
  186. qs = wsgi_get_bytes(environ.get('QUERY_STRING', ''))
  187. # QUERY_STRING really should be ascii safe but some browsers
  188. # will send us some unicode stuff (I am looking at you IE).
  189. # In that case we want to urllib quote it badly.
  190. return try_coerce_native(url_quote(qs, safe=':&%=+$!*\'(),'))
  191. def get_path_info(environ, charset='utf-8', errors='replace'):
  192. """Returns the `PATH_INFO` from the WSGI environment and properly
  193. decodes it. This also takes care about the WSGI decoding dance
  194. on Python 3 environments. if the `charset` is set to `None` a
  195. bytestring is returned.
  196. .. versionadded:: 0.9
  197. :param environ: the WSGI environment object to get the path from.
  198. :param charset: the charset for the path info, or `None` if no
  199. decoding should be performed.
  200. :param errors: the decoding error handling.
  201. """
  202. path = wsgi_get_bytes(environ.get('PATH_INFO', ''))
  203. return to_unicode(path, charset, errors, allow_none_charset=True)
  204. def get_script_name(environ, charset='utf-8', errors='replace'):
  205. """Returns the `SCRIPT_NAME` from the WSGI environment and properly
  206. decodes it. This also takes care about the WSGI decoding dance
  207. on Python 3 environments. if the `charset` is set to `None` a
  208. bytestring is returned.
  209. .. versionadded:: 0.9
  210. :param environ: the WSGI environment object to get the path from.
  211. :param charset: the charset for the path, or `None` if no
  212. decoding should be performed.
  213. :param errors: the decoding error handling.
  214. """
  215. path = wsgi_get_bytes(environ.get('SCRIPT_NAME', ''))
  216. return to_unicode(path, charset, errors, allow_none_charset=True)
  217. def pop_path_info(environ, charset='utf-8', errors='replace'):
  218. """Removes and returns the next segment of `PATH_INFO`, pushing it onto
  219. `SCRIPT_NAME`. Returns `None` if there is nothing left on `PATH_INFO`.
  220. If the `charset` is set to `None` a bytestring is returned.
  221. If there are empty segments (``'/foo//bar``) these are ignored but
  222. properly pushed to the `SCRIPT_NAME`:
  223. >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'}
  224. >>> pop_path_info(env)
  225. 'a'
  226. >>> env['SCRIPT_NAME']
  227. '/foo/a'
  228. >>> pop_path_info(env)
  229. 'b'
  230. >>> env['SCRIPT_NAME']
  231. '/foo/a/b'
  232. .. versionadded:: 0.5
  233. .. versionchanged:: 0.9
  234. The path is now decoded and a charset and encoding
  235. parameter can be provided.
  236. :param environ: the WSGI environment that is modified.
  237. """
  238. path = environ.get('PATH_INFO')
  239. if not path:
  240. return None
  241. script_name = environ.get('SCRIPT_NAME', '')
  242. # shift multiple leading slashes over
  243. old_path = path
  244. path = path.lstrip('/')
  245. if path != old_path:
  246. script_name += '/' * (len(old_path) - len(path))
  247. if '/' not in path:
  248. environ['PATH_INFO'] = ''
  249. environ['SCRIPT_NAME'] = script_name + path
  250. rv = wsgi_get_bytes(path)
  251. else:
  252. segment, path = path.split('/', 1)
  253. environ['PATH_INFO'] = '/' + path
  254. environ['SCRIPT_NAME'] = script_name + segment
  255. rv = wsgi_get_bytes(segment)
  256. return to_unicode(rv, charset, errors, allow_none_charset=True)
  257. def peek_path_info(environ, charset='utf-8', errors='replace'):
  258. """Returns the next segment on the `PATH_INFO` or `None` if there
  259. is none. Works like :func:`pop_path_info` without modifying the
  260. environment:
  261. >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'}
  262. >>> peek_path_info(env)
  263. 'a'
  264. >>> peek_path_info(env)
  265. 'a'
  266. If the `charset` is set to `None` a bytestring is returned.
  267. .. versionadded:: 0.5
  268. .. versionchanged:: 0.9
  269. The path is now decoded and a charset and encoding
  270. parameter can be provided.
  271. :param environ: the WSGI environment that is checked.
  272. """
  273. segments = environ.get('PATH_INFO', '').lstrip('/').split('/', 1)
  274. if segments:
  275. return to_unicode(wsgi_get_bytes(segments[0]),
  276. charset, errors, allow_none_charset=True)
  277. def extract_path_info(environ_or_baseurl, path_or_url, charset='utf-8',
  278. errors='replace', collapse_http_schemes=True):
  279. """Extracts the path info from the given URL (or WSGI environment) and
  280. path. The path info returned is a unicode string, not a bytestring
  281. suitable for a WSGI environment. The URLs might also be IRIs.
  282. If the path info could not be determined, `None` is returned.
  283. Some examples:
  284. >>> extract_path_info('http://example.com/app', '/app/hello')
  285. u'/hello'
  286. >>> extract_path_info('http://example.com/app',
  287. ... 'https://example.com/app/hello')
  288. u'/hello'
  289. >>> extract_path_info('http://example.com/app',
  290. ... 'https://example.com/app/hello',
  291. ... collapse_http_schemes=False) is None
  292. True
  293. Instead of providing a base URL you can also pass a WSGI environment.
  294. .. versionadded:: 0.6
  295. :param environ_or_baseurl: a WSGI environment dict, a base URL or
  296. base IRI. This is the root of the
  297. application.
  298. :param path_or_url: an absolute path from the server root, a
  299. relative path (in which case it's the path info)
  300. or a full URL. Also accepts IRIs and unicode
  301. parameters.
  302. :param charset: the charset for byte data in URLs
  303. :param errors: the error handling on decode
  304. :param collapse_http_schemes: if set to `False` the algorithm does
  305. not assume that http and https on the
  306. same server point to the same
  307. resource.
  308. """
  309. def _normalize_netloc(scheme, netloc):
  310. parts = netloc.split(u'@', 1)[-1].split(u':', 1)
  311. if len(parts) == 2:
  312. netloc, port = parts
  313. if (scheme == u'http' and port == u'80') or \
  314. (scheme == u'https' and port == u'443'):
  315. port = None
  316. else:
  317. netloc = parts[0]
  318. port = None
  319. if port is not None:
  320. netloc += u':' + port
  321. return netloc
  322. # make sure whatever we are working on is a IRI and parse it
  323. path = uri_to_iri(path_or_url, charset, errors)
  324. if isinstance(environ_or_baseurl, dict):
  325. environ_or_baseurl = get_current_url(environ_or_baseurl,
  326. root_only=True)
  327. base_iri = uri_to_iri(environ_or_baseurl, charset, errors)
  328. base_scheme, base_netloc, base_path = url_parse(base_iri)[:3]
  329. cur_scheme, cur_netloc, cur_path, = \
  330. url_parse(url_join(base_iri, path))[:3]
  331. # normalize the network location
  332. base_netloc = _normalize_netloc(base_scheme, base_netloc)
  333. cur_netloc = _normalize_netloc(cur_scheme, cur_netloc)
  334. # is that IRI even on a known HTTP scheme?
  335. if collapse_http_schemes:
  336. for scheme in base_scheme, cur_scheme:
  337. if scheme not in (u'http', u'https'):
  338. return None
  339. else:
  340. if not (base_scheme in (u'http', u'https') and
  341. base_scheme == cur_scheme):
  342. return None
  343. # are the netlocs compatible?
  344. if base_netloc != cur_netloc:
  345. return None
  346. # are we below the application path?
  347. base_path = base_path.rstrip(u'/')
  348. if not cur_path.startswith(base_path):
  349. return None
  350. return u'/' + cur_path[len(base_path):].lstrip(u'/')
  351. class SharedDataMiddleware(object):
  352. """A WSGI middleware that provides static content for development
  353. environments or simple server setups. Usage is quite simple::
  354. import os
  355. from werkzeug.wsgi import SharedDataMiddleware
  356. app = SharedDataMiddleware(app, {
  357. '/shared': os.path.join(os.path.dirname(__file__), 'shared')
  358. })
  359. The contents of the folder ``./shared`` will now be available on
  360. ``http://example.com/shared/``. This is pretty useful during development
  361. because a standalone media server is not required. One can also mount
  362. files on the root folder and still continue to use the application because
  363. the shared data middleware forwards all unhandled requests to the
  364. application, even if the requests are below one of the shared folders.
  365. If `pkg_resources` is available you can also tell the middleware to serve
  366. files from package data::
  367. app = SharedDataMiddleware(app, {
  368. '/shared': ('myapplication', 'shared_files')
  369. })
  370. This will then serve the ``shared_files`` folder in the `myapplication`
  371. Python package.
  372. The optional `disallow` parameter can be a list of :func:`~fnmatch.fnmatch`
  373. rules for files that are not accessible from the web. If `cache` is set to
  374. `False` no caching headers are sent.
  375. Currently the middleware does not support non ASCII filenames. If the
  376. encoding on the file system happens to be the encoding of the URI it may
  377. work but this could also be by accident. We strongly suggest using ASCII
  378. only file names for static files.
  379. The middleware will guess the mimetype using the Python `mimetype`
  380. module. If it's unable to figure out the charset it will fall back
  381. to `fallback_mimetype`.
  382. .. versionchanged:: 0.5
  383. The cache timeout is configurable now.
  384. .. versionadded:: 0.6
  385. The `fallback_mimetype` parameter was added.
  386. :param app: the application to wrap. If you don't want to wrap an
  387. application you can pass it :exc:`NotFound`.
  388. :param exports: a dict of exported files and folders.
  389. :param disallow: a list of :func:`~fnmatch.fnmatch` rules.
  390. :param fallback_mimetype: the fallback mimetype for unknown files.
  391. :param cache: enable or disable caching headers.
  392. :param cache_timeout: the cache timeout in seconds for the headers.
  393. """
  394. def __init__(self, app, exports, disallow=None, cache=True,
  395. cache_timeout=60 * 60 * 12, fallback_mimetype='text/plain'):
  396. self.app = app
  397. self.exports = {}
  398. self.cache = cache
  399. self.cache_timeout = cache_timeout
  400. for key, value in iteritems(exports):
  401. if isinstance(value, tuple):
  402. loader = self.get_package_loader(*value)
  403. elif isinstance(value, string_types):
  404. if os.path.isfile(value):
  405. loader = self.get_file_loader(value)
  406. else:
  407. loader = self.get_directory_loader(value)
  408. else:
  409. raise TypeError('unknown def %r' % value)
  410. self.exports[key] = loader
  411. if disallow is not None:
  412. from fnmatch import fnmatch
  413. self.is_allowed = lambda x: not fnmatch(x, disallow)
  414. self.fallback_mimetype = fallback_mimetype
  415. def is_allowed(self, filename):
  416. """Subclasses can override this method to disallow the access to
  417. certain files. However by providing `disallow` in the constructor
  418. this method is overwritten.
  419. """
  420. return True
  421. def _opener(self, filename):
  422. return lambda: (
  423. open(filename, 'rb'),
  424. datetime.utcfromtimestamp(os.path.getmtime(filename)),
  425. int(os.path.getsize(filename))
  426. )
  427. def get_file_loader(self, filename):
  428. return lambda x: (os.path.basename(filename), self._opener(filename))
  429. def get_package_loader(self, package, package_path):
  430. from pkg_resources import DefaultProvider, ResourceManager, \
  431. get_provider
  432. loadtime = datetime.utcnow()
  433. provider = get_provider(package)
  434. manager = ResourceManager()
  435. filesystem_bound = isinstance(provider, DefaultProvider)
  436. def loader(path):
  437. if path is None:
  438. return None, None
  439. path = posixpath.join(package_path, path)
  440. if not provider.has_resource(path):
  441. return None, None
  442. basename = posixpath.basename(path)
  443. if filesystem_bound:
  444. return basename, self._opener(
  445. provider.get_resource_filename(manager, path))
  446. return basename, lambda: (
  447. provider.get_resource_stream(manager, path),
  448. loadtime,
  449. 0
  450. )
  451. return loader
  452. def get_directory_loader(self, directory):
  453. def loader(path):
  454. if path is not None:
  455. path = os.path.join(directory, path)
  456. else:
  457. path = directory
  458. if os.path.isfile(path):
  459. return os.path.basename(path), self._opener(path)
  460. return None, None
  461. return loader
  462. def generate_etag(self, mtime, file_size, real_filename):
  463. if not isinstance(real_filename, bytes):
  464. real_filename = real_filename.encode(get_filesystem_encoding())
  465. return 'wzsdm-%d-%s-%s' % (
  466. mktime(mtime.timetuple()),
  467. file_size,
  468. adler32(real_filename) & 0xffffffff
  469. )
  470. def __call__(self, environ, start_response):
  471. cleaned_path = get_path_info(environ)
  472. if PY2:
  473. cleaned_path = cleaned_path.encode(get_filesystem_encoding())
  474. # sanitize the path for non unix systems
  475. cleaned_path = cleaned_path.strip('/')
  476. for sep in os.sep, os.altsep:
  477. if sep and sep != '/':
  478. cleaned_path = cleaned_path.replace(sep, '/')
  479. path = '/' + '/'.join(x for x in cleaned_path.split('/')
  480. if x and x != '..')
  481. file_loader = None
  482. for search_path, loader in iteritems(self.exports):
  483. if search_path == path:
  484. real_filename, file_loader = loader(None)
  485. if file_loader is not None:
  486. break
  487. if not search_path.endswith('/'):
  488. search_path += '/'
  489. if path.startswith(search_path):
  490. real_filename, file_loader = loader(path[len(search_path):])
  491. if file_loader is not None:
  492. break
  493. if file_loader is None or not self.is_allowed(real_filename):
  494. return self.app(environ, start_response)
  495. guessed_type = mimetypes.guess_type(real_filename)
  496. mime_type = guessed_type[0] or self.fallback_mimetype
  497. f, mtime, file_size = file_loader()
  498. headers = [('Date', http_date())]
  499. if self.cache:
  500. timeout = self.cache_timeout
  501. etag = self.generate_etag(mtime, file_size, real_filename)
  502. headers += [
  503. ('Etag', '"%s"' % etag),
  504. ('Cache-Control', 'max-age=%d, public' % timeout)
  505. ]
  506. if not is_resource_modified(environ, etag, last_modified=mtime):
  507. f.close()
  508. start_response('304 Not Modified', headers)
  509. return []
  510. headers.append(('Expires', http_date(time() + timeout)))
  511. else:
  512. headers.append(('Cache-Control', 'public'))
  513. headers.extend((
  514. ('Content-Type', mime_type),
  515. ('Content-Length', str(file_size)),
  516. ('Last-Modified', http_date(mtime))
  517. ))
  518. start_response('200 OK', headers)
  519. return wrap_file(environ, f)
  520. class DispatcherMiddleware(object):
  521. """Allows one to mount middlewares or applications in a WSGI application.
  522. This is useful if you want to combine multiple WSGI applications::
  523. app = DispatcherMiddleware(app, {
  524. '/app2': app2,
  525. '/app3': app3
  526. })
  527. """
  528. def __init__(self, app, mounts=None):
  529. self.app = app
  530. self.mounts = mounts or {}
  531. def __call__(self, environ, start_response):
  532. script = environ.get('PATH_INFO', '')
  533. path_info = ''
  534. while '/' in script:
  535. if script in self.mounts:
  536. app = self.mounts[script]
  537. break
  538. script, last_item = script.rsplit('/', 1)
  539. path_info = '/%s%s' % (last_item, path_info)
  540. else:
  541. app = self.mounts.get(script, self.app)
  542. original_script_name = environ.get('SCRIPT_NAME', '')
  543. environ['SCRIPT_NAME'] = original_script_name + script
  544. environ['PATH_INFO'] = path_info
  545. return app(environ, start_response)
  546. @implements_iterator
  547. class ClosingIterator(object):
  548. """The WSGI specification requires that all middlewares and gateways
  549. respect the `close` callback of an iterator. Because it is useful to add
  550. another close action to a returned iterator and adding a custom iterator
  551. is a boring task this class can be used for that::
  552. return ClosingIterator(app(environ, start_response), [cleanup_session,
  553. cleanup_locals])
  554. If there is just one close function it can be passed instead of the list.
  555. A closing iterator is not needed if the application uses response objects
  556. and finishes the processing if the response is started::
  557. try:
  558. return response(environ, start_response)
  559. finally:
  560. cleanup_session()
  561. cleanup_locals()
  562. """
  563. def __init__(self, iterable, callbacks=None):
  564. iterator = iter(iterable)
  565. self._next = partial(next, iterator)
  566. if callbacks is None:
  567. callbacks = []
  568. elif callable(callbacks):
  569. callbacks = [callbacks]
  570. else:
  571. callbacks = list(callbacks)
  572. iterable_close = getattr(iterator, 'close', None)
  573. if iterable_close:
  574. callbacks.insert(0, iterable_close)
  575. self._callbacks = callbacks
  576. def __iter__(self):
  577. return self
  578. def __next__(self):
  579. return self._next()
  580. def close(self):
  581. for callback in self._callbacks:
  582. callback()
  583. def wrap_file(environ, file, buffer_size=8192):
  584. """Wraps a file. This uses the WSGI server's file wrapper if available
  585. or otherwise the generic :class:`FileWrapper`.
  586. .. versionadded:: 0.5
  587. If the file wrapper from the WSGI server is used it's important to not
  588. iterate over it from inside the application but to pass it through
  589. unchanged. If you want to pass out a file wrapper inside a response
  590. object you have to set :attr:`~BaseResponse.direct_passthrough` to `True`.
  591. More information about file wrappers are available in :pep:`333`.
  592. :param file: a :class:`file`-like object with a :meth:`~file.read` method.
  593. :param buffer_size: number of bytes for one iteration.
  594. """
  595. return environ.get('wsgi.file_wrapper', FileWrapper)(file, buffer_size)
  596. @implements_iterator
  597. class FileWrapper(object):
  598. """This class can be used to convert a :class:`file`-like object into
  599. an iterable. It yields `buffer_size` blocks until the file is fully
  600. read.
  601. You should not use this class directly but rather use the
  602. :func:`wrap_file` function that uses the WSGI server's file wrapper
  603. support if it's available.
  604. .. versionadded:: 0.5
  605. If you're using this object together with a :class:`BaseResponse` you have
  606. to use the `direct_passthrough` mode.
  607. :param file: a :class:`file`-like object with a :meth:`~file.read` method.
  608. :param buffer_size: number of bytes for one iteration.
  609. """
  610. def __init__(self, file, buffer_size=8192):
  611. self.file = file
  612. self.buffer_size = buffer_size
  613. def close(self):
  614. if hasattr(self.file, 'close'):
  615. self.file.close()
  616. def __iter__(self):
  617. return self
  618. def __next__(self):
  619. data = self.file.read(self.buffer_size)
  620. if data:
  621. return data
  622. raise StopIteration()
  623. def _make_chunk_iter(stream, limit, buffer_size):
  624. """Helper for the line and chunk iter functions."""
  625. if isinstance(stream, (bytes, bytearray, text_type)):
  626. raise TypeError('Passed a string or byte object instead of '
  627. 'true iterator or stream.')
  628. if not hasattr(stream, 'read'):
  629. for item in stream:
  630. if item:
  631. yield item
  632. return
  633. if not isinstance(stream, LimitedStream) and limit is not None:
  634. stream = LimitedStream(stream, limit)
  635. _read = stream.read
  636. while 1:
  637. item = _read(buffer_size)
  638. if not item:
  639. break
  640. yield item
  641. def make_line_iter(stream, limit=None, buffer_size=10 * 1024,
  642. cap_at_buffer=False):
  643. """Safely iterates line-based over an input stream. If the input stream
  644. is not a :class:`LimitedStream` the `limit` parameter is mandatory.
  645. This uses the stream's :meth:`~file.read` method internally as opposite
  646. to the :meth:`~file.readline` method that is unsafe and can only be used
  647. in violation of the WSGI specification. The same problem applies to the
  648. `__iter__` function of the input stream which calls :meth:`~file.readline`
  649. without arguments.
  650. If you need line-by-line processing it's strongly recommended to iterate
  651. over the input stream using this helper function.
  652. .. versionchanged:: 0.8
  653. This function now ensures that the limit was reached.
  654. .. versionadded:: 0.9
  655. added support for iterators as input stream.
  656. :param stream: the stream or iterate to iterate over.
  657. :param limit: the limit in bytes for the stream. (Usually
  658. content length. Not necessary if the `stream`
  659. is a :class:`LimitedStream`.
  660. :param buffer_size: The optional buffer size.
  661. :param cap_at_buffer: if this is set chunks are split if they are longer
  662. than the buffer size. Internally this is implemented
  663. that the buffer size might be exhausted by a factor
  664. of two however.
  665. .. versionadded:: 0.11.10
  666. added support for the `cap_at_buffer` parameter.
  667. """
  668. _iter = _make_chunk_iter(stream, limit, buffer_size)
  669. first_item = next(_iter, '')
  670. if not first_item:
  671. return
  672. s = make_literal_wrapper(first_item)
  673. empty = s('')
  674. cr = s('\r')
  675. lf = s('\n')
  676. crlf = s('\r\n')
  677. _iter = chain((first_item,), _iter)
  678. def _iter_basic_lines():
  679. _join = empty.join
  680. buffer = []
  681. while 1:
  682. new_data = next(_iter, '')
  683. if not new_data:
  684. break
  685. new_buf = []
  686. buf_size = 0
  687. for item in chain(buffer, new_data.splitlines(True)):
  688. new_buf.append(item)
  689. buf_size += len(item)
  690. if item and item[-1:] in crlf:
  691. yield _join(new_buf)
  692. new_buf = []
  693. elif cap_at_buffer and buf_size >= buffer_size:
  694. rv = _join(new_buf)
  695. while len(rv) >= buffer_size:
  696. yield rv[:buffer_size]
  697. rv = rv[buffer_size:]
  698. new_buf = [rv]
  699. buffer = new_buf
  700. if buffer:
  701. yield _join(buffer)
  702. # This hackery is necessary to merge 'foo\r' and '\n' into one item
  703. # of 'foo\r\n' if we were unlucky and we hit a chunk boundary.
  704. previous = empty
  705. for item in _iter_basic_lines():
  706. if item == lf and previous[-1:] == cr:
  707. previous += item
  708. item = empty
  709. if previous:
  710. yield previous
  711. previous = item
  712. if previous:
  713. yield previous
  714. def make_chunk_iter(stream, separator, limit=None, buffer_size=10 * 1024,
  715. cap_at_buffer=False):
  716. """Works like :func:`make_line_iter` but accepts a separator
  717. which divides chunks. If you want newline based processing
  718. you should use :func:`make_line_iter` instead as it
  719. supports arbitrary newline markers.
  720. .. versionadded:: 0.8
  721. .. versionadded:: 0.9
  722. added support for iterators as input stream.
  723. .. versionadded:: 0.11.10
  724. added support for the `cap_at_buffer` parameter.
  725. :param stream: the stream or iterate to iterate over.
  726. :param separator: the separator that divides chunks.
  727. :param limit: the limit in bytes for the stream. (Usually
  728. content length. Not necessary if the `stream`
  729. is otherwise already limited).
  730. :param buffer_size: The optional buffer size.
  731. :param cap_at_buffer: if this is set chunks are split if they are longer
  732. than the buffer size. Internally this is implemented
  733. that the buffer size might be exhausted by a factor
  734. of two however.
  735. """
  736. _iter = _make_chunk_iter(stream, limit, buffer_size)
  737. first_item = next(_iter, '')
  738. if not first_item:
  739. return
  740. _iter = chain((first_item,), _iter)
  741. if isinstance(first_item, text_type):
  742. separator = to_unicode(separator)
  743. _split = re.compile(r'(%s)' % re.escape(separator)).split
  744. _join = u''.join
  745. else:
  746. separator = to_bytes(separator)
  747. _split = re.compile(b'(' + re.escape(separator) + b')').split
  748. _join = b''.join
  749. buffer = []
  750. while 1:
  751. new_data = next(_iter, '')
  752. if not new_data:
  753. break
  754. chunks = _split(new_data)
  755. new_buf = []
  756. buf_size = 0
  757. for item in chain(buffer, chunks):
  758. if item == separator:
  759. yield _join(new_buf)
  760. new_buf = []
  761. buf_size = 0
  762. else:
  763. buf_size += len(item)
  764. new_buf.append(item)
  765. if cap_at_buffer and buf_size >= buffer_size:
  766. rv = _join(new_buf)
  767. while len(rv) >= buffer_size:
  768. yield rv[:buffer_size]
  769. rv = rv[buffer_size:]
  770. new_buf = [rv]
  771. buf_size = len(rv)
  772. buffer = new_buf
  773. if buffer:
  774. yield _join(buffer)
  775. @implements_iterator
  776. class LimitedStream(object):
  777. """Wraps a stream so that it doesn't read more than n bytes. If the
  778. stream is exhausted and the caller tries to get more bytes from it
  779. :func:`on_exhausted` is called which by default returns an empty
  780. string. The return value of that function is forwarded
  781. to the reader function. So if it returns an empty string
  782. :meth:`read` will return an empty string as well.
  783. The limit however must never be higher than what the stream can
  784. output. Otherwise :meth:`readlines` will try to read past the
  785. limit.
  786. .. admonition:: Note on WSGI compliance
  787. calls to :meth:`readline` and :meth:`readlines` are not
  788. WSGI compliant because it passes a size argument to the
  789. readline methods. Unfortunately the WSGI PEP is not safely
  790. implementable without a size argument to :meth:`readline`
  791. because there is no EOF marker in the stream. As a result
  792. of that the use of :meth:`readline` is discouraged.
  793. For the same reason iterating over the :class:`LimitedStream`
  794. is not portable. It internally calls :meth:`readline`.
  795. We strongly suggest using :meth:`read` only or using the
  796. :func:`make_line_iter` which safely iterates line-based
  797. over a WSGI input stream.
  798. :param stream: the stream to wrap.
  799. :param limit: the limit for the stream, must not be longer than
  800. what the string can provide if the stream does not
  801. end with `EOF` (like `wsgi.input`)
  802. """
  803. def __init__(self, stream, limit):
  804. self._read = stream.read
  805. self._readline = stream.readline
  806. self._pos = 0
  807. self.limit = limit
  808. def __iter__(self):
  809. return self
  810. @property
  811. def is_exhausted(self):
  812. """If the stream is exhausted this attribute is `True`."""
  813. return self._pos >= self.limit
  814. def on_exhausted(self):
  815. """This is called when the stream tries to read past the limit.
  816. The return value of this function is returned from the reading
  817. function.
  818. """
  819. # Read null bytes from the stream so that we get the
  820. # correct end of stream marker.
  821. return self._read(0)
  822. def on_disconnect(self):
  823. """What should happen if a disconnect is detected? The return
  824. value of this function is returned from read functions in case
  825. the client went away. By default a
  826. :exc:`~werkzeug.exceptions.ClientDisconnected` exception is raised.
  827. """
  828. from werkzeug.exceptions import ClientDisconnected
  829. raise ClientDisconnected()
  830. def exhaust(self, chunk_size=1024 * 64):
  831. """Exhaust the stream. This consumes all the data left until the
  832. limit is reached.
  833. :param chunk_size: the size for a chunk. It will read the chunk
  834. until the stream is exhausted and throw away
  835. the results.
  836. """
  837. to_read = self.limit - self._pos
  838. chunk = chunk_size
  839. while to_read > 0:
  840. chunk = min(to_read, chunk)
  841. self.read(chunk)
  842. to_read -= chunk
  843. def read(self, size=None):
  844. """Read `size` bytes or if size is not provided everything is read.
  845. :param size: the number of bytes read.
  846. """
  847. if self._pos >= self.limit:
  848. return self.on_exhausted()
  849. if size is None or size == -1: # -1 is for consistence with file
  850. size = self.limit
  851. to_read = min(self.limit - self._pos, size)
  852. try:
  853. read = self._read(to_read)
  854. except (IOError, ValueError):
  855. return self.on_disconnect()
  856. if to_read and len(read) != to_read:
  857. return self.on_disconnect()
  858. self._pos += len(read)
  859. return read
  860. def readline(self, size=None):
  861. """Reads one line from the stream."""
  862. if self._pos >= self.limit:
  863. return self.on_exhausted()
  864. if size is None:
  865. size = self.limit - self._pos
  866. else:
  867. size = min(size, self.limit - self._pos)
  868. try:
  869. line = self._readline(size)
  870. except (ValueError, IOError):
  871. return self.on_disconnect()
  872. if size and not line:
  873. return self.on_disconnect()
  874. self._pos += len(line)
  875. return line
  876. def readlines(self, size=None):
  877. """Reads a file into a list of strings. It calls :meth:`readline`
  878. until the file is read to the end. It does support the optional
  879. `size` argument if the underlaying stream supports it for
  880. `readline`.
  881. """
  882. last_pos = self._pos
  883. result = []
  884. if size is not None:
  885. end = min(self.limit, last_pos + size)
  886. else:
  887. end = self.limit
  888. while 1:
  889. if size is not None:
  890. size -= last_pos - self._pos
  891. if self._pos >= end:
  892. break
  893. result.append(self.readline(size))
  894. if size is not None:
  895. last_pos = self._pos
  896. return result
  897. def tell(self):
  898. """Returns the position of the stream.
  899. .. versionadded:: 0.9
  900. """
  901. return self._pos
  902. def __next__(self):
  903. line = self.readline()
  904. if not line:
  905. raise StopIteration()
  906. return line