shared_data.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. """
  2. Serve Shared Static Files
  3. =========================
  4. .. autoclass:: SharedDataMiddleware
  5. :members: is_allowed
  6. :copyright: 2007 Pallets
  7. :license: BSD-3-Clause
  8. """
  9. from __future__ import annotations
  10. import collections.abc as cabc
  11. import importlib.util
  12. import mimetypes
  13. import os
  14. import posixpath
  15. import typing as t
  16. from datetime import datetime
  17. from datetime import timezone
  18. from io import BytesIO
  19. from time import time
  20. from zlib import adler32
  21. from ..http import http_date
  22. from ..http import is_resource_modified
  23. from ..http import quote_etag
  24. from ..security import safe_join
  25. from ..utils import get_content_type
  26. from ..wsgi import get_path_info
  27. from ..wsgi import wrap_file
  28. _TOpener = t.Callable[[], tuple[t.IO[bytes], datetime, int]]
  29. _TLoader = t.Callable[[t.Optional[str]], tuple[t.Optional[str], t.Optional[_TOpener]]]
  30. if t.TYPE_CHECKING:
  31. from _typeshed.wsgi import StartResponse
  32. from _typeshed.wsgi import WSGIApplication
  33. from _typeshed.wsgi import WSGIEnvironment
  34. class SharedDataMiddleware:
  35. """A WSGI middleware which provides static content for development
  36. environments or simple server setups. Its usage is quite simple::
  37. import os
  38. from werkzeug.middleware.shared_data import SharedDataMiddleware
  39. app = SharedDataMiddleware(app, {
  40. '/shared': os.path.join(os.path.dirname(__file__), 'shared')
  41. })
  42. The contents of the folder ``./shared`` will now be available on
  43. ``http://example.com/shared/``. This is pretty useful during development
  44. because a standalone media server is not required. Files can also be
  45. mounted on the root folder and still continue to use the application because
  46. the shared data middleware forwards all unhandled requests to the
  47. application, even if the requests are below one of the shared folders.
  48. If `pkg_resources` is available you can also tell the middleware to serve
  49. files from package data::
  50. app = SharedDataMiddleware(app, {
  51. '/static': ('myapplication', 'static')
  52. })
  53. This will then serve the ``static`` folder in the `myapplication`
  54. Python package.
  55. The optional `disallow` parameter can be a list of :func:`~fnmatch.fnmatch`
  56. rules for files that are not accessible from the web. If `cache` is set to
  57. `False` no caching headers are sent.
  58. Currently the middleware does not support non-ASCII filenames. If the
  59. encoding on the file system happens to match the encoding of the URI it may
  60. work but this could also be by accident. We strongly suggest using ASCII
  61. only file names for static files.
  62. The middleware will guess the mimetype using the Python `mimetype`
  63. module. If it's unable to figure out the charset it will fall back
  64. to `fallback_mimetype`.
  65. :param app: the application to wrap. If you don't want to wrap an
  66. application you can pass it :exc:`NotFound`.
  67. :param exports: a list or dict of exported files and folders.
  68. :param disallow: a list of :func:`~fnmatch.fnmatch` rules.
  69. :param cache: enable or disable caching headers.
  70. :param cache_timeout: the cache timeout in seconds for the headers.
  71. :param fallback_mimetype: The fallback mimetype for unknown files.
  72. .. versionchanged:: 1.0
  73. The default ``fallback_mimetype`` is
  74. ``application/octet-stream``. If a filename looks like a text
  75. mimetype, the ``utf-8`` charset is added to it.
  76. .. versionadded:: 0.6
  77. Added ``fallback_mimetype``.
  78. .. versionchanged:: 0.5
  79. Added ``cache_timeout``.
  80. """
  81. def __init__(
  82. self,
  83. app: WSGIApplication,
  84. exports: (
  85. cabc.Mapping[str, str | tuple[str, str]]
  86. | t.Iterable[tuple[str, str | tuple[str, str]]]
  87. ),
  88. disallow: None = None,
  89. cache: bool = True,
  90. cache_timeout: int = 60 * 60 * 12,
  91. fallback_mimetype: str = "application/octet-stream",
  92. ) -> None:
  93. self.app = app
  94. self.exports: list[tuple[str, _TLoader]] = []
  95. self.cache = cache
  96. self.cache_timeout = cache_timeout
  97. if isinstance(exports, cabc.Mapping):
  98. exports = exports.items()
  99. for key, value in exports:
  100. if isinstance(value, tuple):
  101. loader = self.get_package_loader(*value)
  102. elif isinstance(value, str):
  103. if os.path.isfile(value):
  104. loader = self.get_file_loader(value)
  105. else:
  106. loader = self.get_directory_loader(value)
  107. else:
  108. raise TypeError(f"unknown def {value!r}")
  109. self.exports.append((key, loader))
  110. if disallow is not None:
  111. from fnmatch import fnmatch
  112. self.is_allowed = lambda x: not fnmatch(x, disallow)
  113. self.fallback_mimetype = fallback_mimetype
  114. def is_allowed(self, filename: str) -> bool:
  115. """Subclasses can override this method to disallow the access to
  116. certain files. However by providing `disallow` in the constructor
  117. this method is overwritten.
  118. """
  119. return True
  120. def _opener(self, filename: str) -> _TOpener:
  121. return lambda: (
  122. open(filename, "rb"),
  123. datetime.fromtimestamp(os.path.getmtime(filename), tz=timezone.utc),
  124. int(os.path.getsize(filename)),
  125. )
  126. def get_file_loader(self, filename: str) -> _TLoader:
  127. return lambda x: (os.path.basename(filename), self._opener(filename))
  128. def get_package_loader(self, package: str, package_path: str) -> _TLoader:
  129. load_time = datetime.now(timezone.utc)
  130. spec = importlib.util.find_spec(package)
  131. reader = spec.loader.get_resource_reader(package) # type: ignore[union-attr]
  132. def loader(
  133. path: str | None,
  134. ) -> tuple[str | None, _TOpener | None]:
  135. if path is None:
  136. return None, None
  137. path = safe_join(package_path, path)
  138. if path is None:
  139. return None, None
  140. basename = posixpath.basename(path)
  141. try:
  142. resource = reader.open_resource(path)
  143. except OSError:
  144. return None, None
  145. if isinstance(resource, BytesIO):
  146. return (
  147. basename,
  148. lambda: (resource, load_time, len(resource.getvalue())),
  149. )
  150. return (
  151. basename,
  152. lambda: (
  153. resource,
  154. datetime.fromtimestamp(
  155. os.path.getmtime(resource.name), tz=timezone.utc
  156. ),
  157. os.path.getsize(resource.name),
  158. ),
  159. )
  160. return loader
  161. def get_directory_loader(self, directory: str) -> _TLoader:
  162. def loader(
  163. path: str | None,
  164. ) -> tuple[str | None, _TOpener | None]:
  165. if path is not None:
  166. path = safe_join(directory, path)
  167. if path is None:
  168. return None, None
  169. else:
  170. path = directory
  171. if os.path.isfile(path):
  172. return os.path.basename(path), self._opener(path)
  173. return None, None
  174. return loader
  175. def generate_etag(self, mtime: datetime, file_size: int, real_filename: str) -> str:
  176. fn_str = os.fsencode(real_filename)
  177. timestamp = mtime.timestamp()
  178. checksum = adler32(fn_str) & 0xFFFFFFFF
  179. return f"wzsdm-{timestamp}-{file_size}-{checksum}"
  180. def __call__(
  181. self, environ: WSGIEnvironment, start_response: StartResponse
  182. ) -> t.Iterable[bytes]:
  183. path = get_path_info(environ)
  184. file_loader = None
  185. for search_path, loader in self.exports:
  186. if search_path == path:
  187. real_filename, file_loader = loader(None)
  188. if file_loader is not None:
  189. break
  190. if not search_path.endswith("/"):
  191. search_path += "/"
  192. if path.startswith(search_path):
  193. real_filename, file_loader = loader(path[len(search_path) :])
  194. if file_loader is not None:
  195. break
  196. if file_loader is None or not self.is_allowed(real_filename): # type: ignore
  197. return self.app(environ, start_response)
  198. guessed_type = mimetypes.guess_type(real_filename) # type: ignore
  199. mime_type = get_content_type(guessed_type[0] or self.fallback_mimetype, "utf-8")
  200. f, mtime, file_size = file_loader()
  201. headers = [("Date", http_date())]
  202. if self.cache:
  203. timeout = self.cache_timeout
  204. etag = quote_etag(self.generate_etag(mtime, file_size, real_filename)) # type: ignore
  205. headers += [
  206. ("Etag", etag),
  207. ("Cache-Control", f"max-age={timeout}, public"),
  208. ]
  209. if not is_resource_modified(environ, etag, last_modified=mtime):
  210. f.close()
  211. start_response("304 Not Modified", headers)
  212. return []
  213. headers.append(("Expires", http_date(time() + timeout)))
  214. else:
  215. headers.append(("Cache-Control", "public"))
  216. headers.extend(
  217. (
  218. ("Content-Type", mime_type),
  219. ("Content-Length", str(file_size)),
  220. ("Last-Modified", http_date(mtime)),
  221. )
  222. )
  223. start_response("200 OK", headers)
  224. return wrap_file(environ, f)