utils.py 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  1. import codecs
  2. import io
  3. import mimetypes
  4. import os
  5. import pkgutil
  6. import re
  7. import sys
  8. import typing as t
  9. import unicodedata
  10. import warnings
  11. from datetime import datetime
  12. from html.entities import name2codepoint
  13. from time import time
  14. from zlib import adler32
  15. from ._internal import _DictAccessorProperty
  16. from ._internal import _missing
  17. from ._internal import _parse_signature
  18. from ._internal import _TAccessorValue
  19. from .datastructures import Headers
  20. from .exceptions import NotFound
  21. from .exceptions import RequestedRangeNotSatisfiable
  22. from .security import safe_join
  23. from .urls import url_quote
  24. from .wsgi import wrap_file
  25. if t.TYPE_CHECKING:
  26. from _typeshed.wsgi import WSGIEnvironment
  27. from .wrappers.request import Request
  28. from .wrappers.response import Response
  29. _T = t.TypeVar("_T")
  30. _entity_re = re.compile(r"&([^;]+);")
  31. _filename_ascii_strip_re = re.compile(r"[^A-Za-z0-9_.-]")
  32. _windows_device_files = (
  33. "CON",
  34. "AUX",
  35. "COM1",
  36. "COM2",
  37. "COM3",
  38. "COM4",
  39. "LPT1",
  40. "LPT2",
  41. "LPT3",
  42. "PRN",
  43. "NUL",
  44. )
  45. class cached_property(property, t.Generic[_T]):
  46. """A :func:`property` that is only evaluated once. Subsequent access
  47. returns the cached value. Setting the property sets the cached
  48. value. Deleting the property clears the cached value, accessing it
  49. again will evaluate it again.
  50. .. code-block:: python
  51. class Example:
  52. @cached_property
  53. def value(self):
  54. # calculate something important here
  55. return 42
  56. e = Example()
  57. e.value # evaluates
  58. e.value # uses cache
  59. e.value = 16 # sets cache
  60. del e.value # clears cache
  61. The class must have a ``__dict__`` for this to work.
  62. .. versionchanged:: 2.0
  63. ``del obj.name`` clears the cached value.
  64. """
  65. def __init__(
  66. self,
  67. fget: t.Callable[[t.Any], _T],
  68. name: t.Optional[str] = None,
  69. doc: t.Optional[str] = None,
  70. ) -> None:
  71. super().__init__(fget, doc=doc)
  72. self.__name__ = name or fget.__name__
  73. self.__module__ = fget.__module__
  74. def __set__(self, obj: object, value: _T) -> None:
  75. obj.__dict__[self.__name__] = value
  76. def __get__(self, obj: object, type: type = None) -> _T: # type: ignore
  77. if obj is None:
  78. return self # type: ignore
  79. value: _T = obj.__dict__.get(self.__name__, _missing)
  80. if value is _missing:
  81. value = self.fget(obj) # type: ignore
  82. obj.__dict__[self.__name__] = value
  83. return value
  84. def __delete__(self, obj: object) -> None:
  85. del obj.__dict__[self.__name__]
  86. def invalidate_cached_property(obj: object, name: str) -> None:
  87. """Invalidates the cache for a :class:`cached_property`:
  88. >>> class Test(object):
  89. ... @cached_property
  90. ... def magic_number(self):
  91. ... print("recalculating...")
  92. ... return 42
  93. ...
  94. >>> var = Test()
  95. >>> var.magic_number
  96. recalculating...
  97. 42
  98. >>> var.magic_number
  99. 42
  100. >>> invalidate_cached_property(var, "magic_number")
  101. >>> var.magic_number
  102. recalculating...
  103. 42
  104. You must pass the name of the cached property as the second argument.
  105. .. deprecated:: 2.0
  106. Will be removed in Werkzeug 2.1. Use ``del obj.name`` instead.
  107. """
  108. warnings.warn(
  109. "'invalidate_cached_property' is deprecated and will be removed"
  110. " in Werkzeug 2.1. Use 'del obj.name' instead.",
  111. DeprecationWarning,
  112. stacklevel=2,
  113. )
  114. delattr(obj, name)
  115. class environ_property(_DictAccessorProperty[_TAccessorValue]):
  116. """Maps request attributes to environment variables. This works not only
  117. for the Werkzeug request object, but also any other class with an
  118. environ attribute:
  119. >>> class Test(object):
  120. ... environ = {'key': 'value'}
  121. ... test = environ_property('key')
  122. >>> var = Test()
  123. >>> var.test
  124. 'value'
  125. If you pass it a second value it's used as default if the key does not
  126. exist, the third one can be a converter that takes a value and converts
  127. it. If it raises :exc:`ValueError` or :exc:`TypeError` the default value
  128. is used. If no default value is provided `None` is used.
  129. Per default the property is read only. You have to explicitly enable it
  130. by passing ``read_only=False`` to the constructor.
  131. """
  132. read_only = True
  133. def lookup(self, obj: "Request") -> "WSGIEnvironment":
  134. return obj.environ
  135. class header_property(_DictAccessorProperty[_TAccessorValue]):
  136. """Like `environ_property` but for headers."""
  137. def lookup(self, obj: t.Union["Request", "Response"]) -> Headers:
  138. return obj.headers
  139. class HTMLBuilder:
  140. """Helper object for HTML generation.
  141. Per default there are two instances of that class. The `html` one, and
  142. the `xhtml` one for those two dialects. The class uses keyword parameters
  143. and positional parameters to generate small snippets of HTML.
  144. Keyword parameters are converted to XML/SGML attributes, positional
  145. arguments are used as children. Because Python accepts positional
  146. arguments before keyword arguments it's a good idea to use a list with the
  147. star-syntax for some children:
  148. >>> html.p(class_='foo', *[html.a('foo', href='foo.html'), ' ',
  149. ... html.a('bar', href='bar.html')])
  150. '<p class="foo"><a href="foo.html">foo</a> <a href="bar.html">bar</a></p>'
  151. This class works around some browser limitations and can not be used for
  152. arbitrary SGML/XML generation. For that purpose lxml and similar
  153. libraries exist.
  154. Calling the builder escapes the string passed:
  155. >>> html.p(html("<foo>"))
  156. '<p>&lt;foo&gt;</p>'
  157. .. deprecated:: 2.0
  158. Will be removed in Werkzeug 2.1.
  159. """
  160. _entity_re = re.compile(r"&([^;]+);")
  161. _entities = name2codepoint.copy()
  162. _entities["apos"] = 39
  163. _empty_elements = {
  164. "area",
  165. "base",
  166. "basefont",
  167. "br",
  168. "col",
  169. "command",
  170. "embed",
  171. "frame",
  172. "hr",
  173. "img",
  174. "input",
  175. "keygen",
  176. "isindex",
  177. "link",
  178. "meta",
  179. "param",
  180. "source",
  181. "wbr",
  182. }
  183. _boolean_attributes = {
  184. "selected",
  185. "checked",
  186. "compact",
  187. "declare",
  188. "defer",
  189. "disabled",
  190. "ismap",
  191. "multiple",
  192. "nohref",
  193. "noresize",
  194. "noshade",
  195. "nowrap",
  196. }
  197. _plaintext_elements = {"textarea"}
  198. _c_like_cdata = {"script", "style"}
  199. def __init__(self, dialect): # type: ignore
  200. self._dialect = dialect
  201. def __call__(self, s): # type: ignore
  202. import html
  203. warnings.warn(
  204. "'utils.HTMLBuilder' is deprecated and will be removed in Werkzeug 2.1.",
  205. DeprecationWarning,
  206. stacklevel=2,
  207. )
  208. return html.escape(s)
  209. def __getattr__(self, tag): # type: ignore
  210. import html
  211. warnings.warn(
  212. "'utils.HTMLBuilder' is deprecated and will be removed in Werkzeug 2.1.",
  213. DeprecationWarning,
  214. stacklevel=2,
  215. )
  216. if tag[:2] == "__":
  217. raise AttributeError(tag)
  218. def proxy(*children, **arguments): # type: ignore
  219. buffer = f"<{tag}"
  220. for key, value in arguments.items():
  221. if value is None:
  222. continue
  223. if key[-1] == "_":
  224. key = key[:-1]
  225. if key in self._boolean_attributes:
  226. if not value:
  227. continue
  228. if self._dialect == "xhtml":
  229. value = f'="{key}"'
  230. else:
  231. value = ""
  232. else:
  233. value = f'="{html.escape(value)}"'
  234. buffer += f" {key}{value}"
  235. if not children and tag in self._empty_elements:
  236. if self._dialect == "xhtml":
  237. buffer += " />"
  238. else:
  239. buffer += ">"
  240. return buffer
  241. buffer += ">"
  242. children_as_string = "".join([str(x) for x in children if x is not None])
  243. if children_as_string:
  244. if tag in self._plaintext_elements:
  245. children_as_string = html.escape(children_as_string)
  246. elif tag in self._c_like_cdata and self._dialect == "xhtml":
  247. children_as_string = f"/*<![CDATA[*/{children_as_string}/*]]>*/"
  248. buffer += children_as_string + f"</{tag}>"
  249. return buffer
  250. return proxy
  251. def __repr__(self) -> str:
  252. return f"<{type(self).__name__} for {self._dialect!r}>"
  253. html = HTMLBuilder("html")
  254. xhtml = HTMLBuilder("xhtml")
  255. # https://cgit.freedesktop.org/xdg/shared-mime-info/tree/freedesktop.org.xml.in
  256. # https://www.iana.org/assignments/media-types/media-types.xhtml
  257. # Types listed in the XDG mime info that have a charset in the IANA registration.
  258. _charset_mimetypes = {
  259. "application/ecmascript",
  260. "application/javascript",
  261. "application/sql",
  262. "application/xml",
  263. "application/xml-dtd",
  264. "application/xml-external-parsed-entity",
  265. }
  266. def get_content_type(mimetype: str, charset: str) -> str:
  267. """Returns the full content type string with charset for a mimetype.
  268. If the mimetype represents text, the charset parameter will be
  269. appended, otherwise the mimetype is returned unchanged.
  270. :param mimetype: The mimetype to be used as content type.
  271. :param charset: The charset to be appended for text mimetypes.
  272. :return: The content type.
  273. .. versionchanged:: 0.15
  274. Any type that ends with ``+xml`` gets a charset, not just those
  275. that start with ``application/``. Known text types such as
  276. ``application/javascript`` are also given charsets.
  277. """
  278. if (
  279. mimetype.startswith("text/")
  280. or mimetype in _charset_mimetypes
  281. or mimetype.endswith("+xml")
  282. ):
  283. mimetype += f"; charset={charset}"
  284. return mimetype
  285. def detect_utf_encoding(data: bytes) -> str:
  286. """Detect which UTF encoding was used to encode the given bytes.
  287. The latest JSON standard (:rfc:`8259`) suggests that only UTF-8 is
  288. accepted. Older documents allowed 8, 16, or 32. 16 and 32 can be big
  289. or little endian. Some editors or libraries may prepend a BOM.
  290. :internal:
  291. :param data: Bytes in unknown UTF encoding.
  292. :return: UTF encoding name
  293. .. deprecated:: 2.0
  294. Will be removed in Werkzeug 2.1. This is built in to
  295. :func:`json.loads`.
  296. .. versionadded:: 0.15
  297. """
  298. warnings.warn(
  299. "'detect_utf_encoding' is deprecated and will be removed in"
  300. " Werkzeug 2.1. This is built in to 'json.loads'.",
  301. DeprecationWarning,
  302. stacklevel=2,
  303. )
  304. head = data[:4]
  305. if head[:3] == codecs.BOM_UTF8:
  306. return "utf-8-sig"
  307. if b"\x00" not in head:
  308. return "utf-8"
  309. if head in (codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE):
  310. return "utf-32"
  311. if head[:2] in (codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE):
  312. return "utf-16"
  313. if len(head) == 4:
  314. if head[:3] == b"\x00\x00\x00":
  315. return "utf-32-be"
  316. if head[::2] == b"\x00\x00":
  317. return "utf-16-be"
  318. if head[1:] == b"\x00\x00\x00":
  319. return "utf-32-le"
  320. if head[1::2] == b"\x00\x00":
  321. return "utf-16-le"
  322. if len(head) == 2:
  323. return "utf-16-be" if head.startswith(b"\x00") else "utf-16-le"
  324. return "utf-8"
  325. def format_string(string: str, context: t.Mapping[str, t.Any]) -> str:
  326. """String-template format a string:
  327. >>> format_string('$foo and ${foo}s', dict(foo=42))
  328. '42 and 42s'
  329. This does not do any attribute lookup.
  330. :param string: the format string.
  331. :param context: a dict with the variables to insert.
  332. .. deprecated:: 2.0
  333. Will be removed in Werkzeug 2.1. Use :class:`string.Template`
  334. instead.
  335. """
  336. from string import Template
  337. warnings.warn(
  338. "'utils.format_string' is deprecated and will be removed in"
  339. " Werkzeug 2.1. Use 'string.Template' instead.",
  340. DeprecationWarning,
  341. stacklevel=2,
  342. )
  343. return Template(string).substitute(context)
  344. def secure_filename(filename: str) -> str:
  345. r"""Pass it a filename and it will return a secure version of it. This
  346. filename can then safely be stored on a regular file system and passed
  347. to :func:`os.path.join`. The filename returned is an ASCII only string
  348. for maximum portability.
  349. On windows systems the function also makes sure that the file is not
  350. named after one of the special device files.
  351. >>> secure_filename("My cool movie.mov")
  352. 'My_cool_movie.mov'
  353. >>> secure_filename("../../../etc/passwd")
  354. 'etc_passwd'
  355. >>> secure_filename('i contain cool \xfcml\xe4uts.txt')
  356. 'i_contain_cool_umlauts.txt'
  357. The function might return an empty filename. It's your responsibility
  358. to ensure that the filename is unique and that you abort or
  359. generate a random filename if the function returned an empty one.
  360. .. versionadded:: 0.5
  361. :param filename: the filename to secure
  362. """
  363. filename = unicodedata.normalize("NFKD", filename)
  364. filename = filename.encode("ascii", "ignore").decode("ascii")
  365. for sep in os.path.sep, os.path.altsep:
  366. if sep:
  367. filename = filename.replace(sep, " ")
  368. filename = str(_filename_ascii_strip_re.sub("", "_".join(filename.split()))).strip(
  369. "._"
  370. )
  371. # on nt a couple of special files are present in each folder. We
  372. # have to ensure that the target file is not such a filename. In
  373. # this case we prepend an underline
  374. if (
  375. os.name == "nt"
  376. and filename
  377. and filename.split(".")[0].upper() in _windows_device_files
  378. ):
  379. filename = f"_{filename}"
  380. return filename
  381. def escape(s: t.Any) -> str:
  382. """Replace ``&``, ``<``, ``>``, ``"``, and ``'`` with HTML-safe
  383. sequences.
  384. ``None`` is escaped to an empty string.
  385. .. deprecated:: 2.0
  386. Will be removed in Werkzeug 2.1. Use MarkupSafe instead.
  387. """
  388. import html
  389. warnings.warn(
  390. "'utils.escape' is deprecated and will be removed in Werkzeug"
  391. " 2.1. Use MarkupSafe instead.",
  392. DeprecationWarning,
  393. stacklevel=2,
  394. )
  395. if s is None:
  396. return ""
  397. if hasattr(s, "__html__"):
  398. return s.__html__() # type: ignore
  399. if not isinstance(s, str):
  400. s = str(s)
  401. return html.escape(s, quote=True) # type: ignore
  402. def unescape(s: str) -> str:
  403. """The reverse of :func:`escape`. This unescapes all the HTML
  404. entities, not only those inserted by ``escape``.
  405. .. deprecated:: 2.0
  406. Will be removed in Werkzeug 2.1. Use MarkupSafe instead.
  407. """
  408. import html
  409. warnings.warn(
  410. "'utils.unescape' is deprecated and will be removed in Werkzueg"
  411. " 2.1. Use MarkupSafe instead.",
  412. DeprecationWarning,
  413. stacklevel=2,
  414. )
  415. return html.unescape(s)
  416. def redirect(
  417. location: str, code: int = 302, Response: t.Optional[t.Type["Response"]] = None
  418. ) -> "Response":
  419. """Returns a response object (a WSGI application) that, if called,
  420. redirects the client to the target location. Supported codes are
  421. 301, 302, 303, 305, 307, and 308. 300 is not supported because
  422. it's not a real redirect and 304 because it's the answer for a
  423. request with a request with defined If-Modified-Since headers.
  424. .. versionadded:: 0.6
  425. The location can now be a unicode string that is encoded using
  426. the :func:`iri_to_uri` function.
  427. .. versionadded:: 0.10
  428. The class used for the Response object can now be passed in.
  429. :param location: the location the response should redirect to.
  430. :param code: the redirect status code. defaults to 302.
  431. :param class Response: a Response class to use when instantiating a
  432. response. The default is :class:`werkzeug.wrappers.Response` if
  433. unspecified.
  434. """
  435. import html
  436. if Response is None:
  437. from .wrappers import Response # type: ignore
  438. display_location = html.escape(location)
  439. if isinstance(location, str):
  440. # Safe conversion is necessary here as we might redirect
  441. # to a broken URI scheme (for instance itms-services).
  442. from .urls import iri_to_uri
  443. location = iri_to_uri(location, safe_conversion=True)
  444. response = Response( # type: ignore
  445. '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n'
  446. "<title>Redirecting...</title>\n"
  447. "<h1>Redirecting...</h1>\n"
  448. "<p>You should be redirected automatically to target URL: "
  449. f'<a href="{html.escape(location)}">{display_location}</a>. If'
  450. " not click the link.",
  451. code,
  452. mimetype="text/html",
  453. )
  454. response.headers["Location"] = location
  455. return response
  456. def append_slash_redirect(environ: "WSGIEnvironment", code: int = 301) -> "Response":
  457. """Redirects to the same URL but with a slash appended. The behavior
  458. of this function is undefined if the path ends with a slash already.
  459. :param environ: the WSGI environment for the request that triggers
  460. the redirect.
  461. :param code: the status code for the redirect.
  462. """
  463. new_path = environ["PATH_INFO"].strip("/") + "/"
  464. query_string = environ.get("QUERY_STRING")
  465. if query_string:
  466. new_path += f"?{query_string}"
  467. return redirect(new_path, code)
  468. def send_file(
  469. path_or_file: t.Union[os.PathLike, str, t.IO[bytes]],
  470. environ: "WSGIEnvironment",
  471. mimetype: t.Optional[str] = None,
  472. as_attachment: bool = False,
  473. download_name: t.Optional[str] = None,
  474. conditional: bool = True,
  475. etag: t.Union[bool, str] = True,
  476. last_modified: t.Optional[t.Union[datetime, int, float]] = None,
  477. max_age: t.Optional[
  478. t.Union[int, t.Callable[[t.Optional[str]], t.Optional[int]]]
  479. ] = None,
  480. use_x_sendfile: bool = False,
  481. response_class: t.Optional[t.Type["Response"]] = None,
  482. _root_path: t.Optional[t.Union[os.PathLike, str]] = None,
  483. ) -> "Response":
  484. """Send the contents of a file to the client.
  485. The first argument can be a file path or a file-like object. Paths
  486. are preferred in most cases because Werkzeug can manage the file and
  487. get extra information from the path. Passing a file-like object
  488. requires that the file is opened in binary mode, and is mostly
  489. useful when building a file in memory with :class:`io.BytesIO`.
  490. Never pass file paths provided by a user. The path is assumed to be
  491. trusted, so a user could craft a path to access a file you didn't
  492. intend.
  493. If the WSGI server sets a ``file_wrapper`` in ``environ``, it is
  494. used, otherwise Werkzeug's built-in wrapper is used. Alternatively,
  495. if the HTTP server supports ``X-Sendfile``, ``use_x_sendfile=True``
  496. will tell the server to send the given path, which is much more
  497. efficient than reading it in Python.
  498. :param path_or_file: The path to the file to send, relative to the
  499. current working directory if a relative path is given.
  500. Alternatively, a file-like object opened in binary mode. Make
  501. sure the file pointer is seeked to the start of the data.
  502. :param environ: The WSGI environ for the current request.
  503. :param mimetype: The MIME type to send for the file. If not
  504. provided, it will try to detect it from the file name.
  505. :param as_attachment: Indicate to a browser that it should offer to
  506. save the file instead of displaying it.
  507. :param download_name: The default name browsers will use when saving
  508. the file. Defaults to the passed file name.
  509. :param conditional: Enable conditional and range responses based on
  510. request headers. Requires passing a file path and ``environ``.
  511. :param etag: Calculate an ETag for the file, which requires passing
  512. a file path. Can also be a string to use instead.
  513. :param last_modified: The last modified time to send for the file,
  514. in seconds. If not provided, it will try to detect it from the
  515. file path.
  516. :param max_age: How long the client should cache the file, in
  517. seconds. If set, ``Cache-Control`` will be ``public``, otherwise
  518. it will be ``no-cache`` to prefer conditional caching.
  519. :param use_x_sendfile: Set the ``X-Sendfile`` header to let the
  520. server to efficiently send the file. Requires support from the
  521. HTTP server. Requires passing a file path.
  522. :param response_class: Build the response using this class. Defaults
  523. to :class:`~werkzeug.wrappers.Response`.
  524. :param _root_path: Do not use. For internal use only. Use
  525. :func:`send_from_directory` to safely send files under a path.
  526. .. versionchanged:: 2.0.2
  527. ``send_file`` only sets a detected ``Content-Encoding`` if
  528. ``as_attachment`` is disabled.
  529. .. versionadded:: 2.0
  530. Adapted from Flask's implementation.
  531. .. versionchanged:: 2.0
  532. ``download_name`` replaces Flask's ``attachment_filename``
  533. parameter. If ``as_attachment=False``, it is passed with
  534. ``Content-Disposition: inline`` instead.
  535. .. versionchanged:: 2.0
  536. ``max_age`` replaces Flask's ``cache_timeout`` parameter.
  537. ``conditional`` is enabled and ``max_age`` is not set by
  538. default.
  539. .. versionchanged:: 2.0
  540. ``etag`` replaces Flask's ``add_etags`` parameter. It can be a
  541. string to use instead of generating one.
  542. .. versionchanged:: 2.0
  543. If an encoding is returned when guessing ``mimetype`` from
  544. ``download_name``, set the ``Content-Encoding`` header.
  545. """
  546. if response_class is None:
  547. from .wrappers import Response
  548. response_class = Response
  549. path: t.Optional[str] = None
  550. file: t.Optional[t.IO[bytes]] = None
  551. size: t.Optional[int] = None
  552. mtime: t.Optional[float] = None
  553. headers = Headers()
  554. if isinstance(path_or_file, (os.PathLike, str)) or hasattr(
  555. path_or_file, "__fspath__"
  556. ):
  557. path_or_file = t.cast(t.Union[os.PathLike, str], path_or_file)
  558. # Flask will pass app.root_path, allowing its send_file wrapper
  559. # to not have to deal with paths.
  560. if _root_path is not None:
  561. path = os.path.join(_root_path, path_or_file)
  562. else:
  563. path = os.path.abspath(path_or_file)
  564. stat = os.stat(path)
  565. size = stat.st_size
  566. mtime = stat.st_mtime
  567. else:
  568. file = path_or_file
  569. if download_name is None and path is not None:
  570. download_name = os.path.basename(path)
  571. if mimetype is None:
  572. if download_name is None:
  573. raise TypeError(
  574. "Unable to detect the MIME type because a file name is"
  575. " not available. Either set 'download_name', pass a"
  576. " path instead of a file, or set 'mimetype'."
  577. )
  578. mimetype, encoding = mimetypes.guess_type(download_name)
  579. if mimetype is None:
  580. mimetype = "application/octet-stream"
  581. # Don't send encoding for attachments, it causes browsers to
  582. # save decompress tar.gz files.
  583. if encoding is not None and not as_attachment:
  584. headers.set("Content-Encoding", encoding)
  585. if download_name is not None:
  586. try:
  587. download_name.encode("ascii")
  588. except UnicodeEncodeError:
  589. simple = unicodedata.normalize("NFKD", download_name)
  590. simple = simple.encode("ascii", "ignore").decode("ascii")
  591. quoted = url_quote(download_name, safe="")
  592. names = {"filename": simple, "filename*": f"UTF-8''{quoted}"}
  593. else:
  594. names = {"filename": download_name}
  595. value = "attachment" if as_attachment else "inline"
  596. headers.set("Content-Disposition", value, **names)
  597. elif as_attachment:
  598. raise TypeError(
  599. "No name provided for attachment. Either set"
  600. " 'download_name' or pass a path instead of a file."
  601. )
  602. if use_x_sendfile and path is not None:
  603. headers["X-Sendfile"] = path
  604. data = None
  605. else:
  606. if file is None:
  607. file = open(path, "rb") # type: ignore
  608. elif isinstance(file, io.BytesIO):
  609. size = file.getbuffer().nbytes
  610. elif isinstance(file, io.TextIOBase):
  611. raise ValueError("Files must be opened in binary mode or use BytesIO.")
  612. data = wrap_file(environ, file)
  613. rv = response_class(
  614. data, mimetype=mimetype, headers=headers, direct_passthrough=True
  615. )
  616. if size is not None:
  617. rv.content_length = size
  618. if last_modified is not None:
  619. rv.last_modified = last_modified # type: ignore
  620. elif mtime is not None:
  621. rv.last_modified = mtime # type: ignore
  622. rv.cache_control.no_cache = True
  623. # Flask will pass app.get_send_file_max_age, allowing its send_file
  624. # wrapper to not have to deal with paths.
  625. if callable(max_age):
  626. max_age = max_age(path)
  627. if max_age is not None:
  628. if max_age > 0:
  629. rv.cache_control.no_cache = None
  630. rv.cache_control.public = True
  631. rv.cache_control.max_age = max_age
  632. rv.expires = int(time() + max_age) # type: ignore
  633. if isinstance(etag, str):
  634. rv.set_etag(etag)
  635. elif etag and path is not None:
  636. check = adler32(path.encode("utf-8")) & 0xFFFFFFFF
  637. rv.set_etag(f"{mtime}-{size}-{check}")
  638. if conditional:
  639. try:
  640. rv = rv.make_conditional(environ, accept_ranges=True, complete_length=size)
  641. except RequestedRangeNotSatisfiable:
  642. if file is not None:
  643. file.close()
  644. raise
  645. # Some x-sendfile implementations incorrectly ignore the 304
  646. # status code and send the file anyway.
  647. if rv.status_code == 304:
  648. rv.headers.pop("x-sendfile", None)
  649. return rv
  650. def send_from_directory(
  651. directory: t.Union[os.PathLike, str],
  652. path: t.Union[os.PathLike, str],
  653. environ: "WSGIEnvironment",
  654. **kwargs: t.Any,
  655. ) -> "Response":
  656. """Send a file from within a directory using :func:`send_file`.
  657. This is a secure way to serve files from a folder, such as static
  658. files or uploads. Uses :func:`~werkzeug.security.safe_join` to
  659. ensure the path coming from the client is not maliciously crafted to
  660. point outside the specified directory.
  661. If the final path does not point to an existing regular file,
  662. returns a 404 :exc:`~werkzeug.exceptions.NotFound` error.
  663. :param directory: The directory that ``path`` must be located under.
  664. :param path: The path to the file to send, relative to
  665. ``directory``.
  666. :param environ: The WSGI environ for the current request.
  667. :param kwargs: Arguments to pass to :func:`send_file`.
  668. .. versionadded:: 2.0
  669. Adapted from Flask's implementation.
  670. """
  671. path = safe_join(os.fspath(directory), os.fspath(path))
  672. if path is None:
  673. raise NotFound()
  674. # Flask will pass app.root_path, allowing its send_from_directory
  675. # wrapper to not have to deal with paths.
  676. if "_root_path" in kwargs:
  677. path = os.path.join(kwargs["_root_path"], path)
  678. try:
  679. if not os.path.isfile(path):
  680. raise NotFound()
  681. except ValueError:
  682. # path contains null byte on Python < 3.8
  683. raise NotFound() from None
  684. return send_file(path, environ, **kwargs)
  685. def import_string(import_name: str, silent: bool = False) -> t.Any:
  686. """Imports an object based on a string. This is useful if you want to
  687. use import paths as endpoints or something similar. An import path can
  688. be specified either in dotted notation (``xml.sax.saxutils.escape``)
  689. or with a colon as object delimiter (``xml.sax.saxutils:escape``).
  690. If `silent` is True the return value will be `None` if the import fails.
  691. :param import_name: the dotted name for the object to import.
  692. :param silent: if set to `True` import errors are ignored and
  693. `None` is returned instead.
  694. :return: imported object
  695. """
  696. import_name = import_name.replace(":", ".")
  697. try:
  698. try:
  699. __import__(import_name)
  700. except ImportError:
  701. if "." not in import_name:
  702. raise
  703. else:
  704. return sys.modules[import_name]
  705. module_name, obj_name = import_name.rsplit(".", 1)
  706. module = __import__(module_name, globals(), locals(), [obj_name])
  707. try:
  708. return getattr(module, obj_name)
  709. except AttributeError as e:
  710. raise ImportError(e) from None
  711. except ImportError as e:
  712. if not silent:
  713. raise ImportStringError(import_name, e).with_traceback(
  714. sys.exc_info()[2]
  715. ) from None
  716. return None
  717. def find_modules(
  718. import_path: str, include_packages: bool = False, recursive: bool = False
  719. ) -> t.Iterator[str]:
  720. """Finds all the modules below a package. This can be useful to
  721. automatically import all views / controllers so that their metaclasses /
  722. function decorators have a chance to register themselves on the
  723. application.
  724. Packages are not returned unless `include_packages` is `True`. This can
  725. also recursively list modules but in that case it will import all the
  726. packages to get the correct load path of that module.
  727. :param import_path: the dotted name for the package to find child modules.
  728. :param include_packages: set to `True` if packages should be returned, too.
  729. :param recursive: set to `True` if recursion should happen.
  730. :return: generator
  731. """
  732. module = import_string(import_path)
  733. path = getattr(module, "__path__", None)
  734. if path is None:
  735. raise ValueError(f"{import_path!r} is not a package")
  736. basename = f"{module.__name__}."
  737. for _importer, modname, ispkg in pkgutil.iter_modules(path):
  738. modname = basename + modname
  739. if ispkg:
  740. if include_packages:
  741. yield modname
  742. if recursive:
  743. yield from find_modules(modname, include_packages, True)
  744. else:
  745. yield modname
  746. def validate_arguments(func, args, kwargs, drop_extra=True): # type: ignore
  747. """Checks if the function accepts the arguments and keyword arguments.
  748. Returns a new ``(args, kwargs)`` tuple that can safely be passed to
  749. the function without causing a `TypeError` because the function signature
  750. is incompatible. If `drop_extra` is set to `True` (which is the default)
  751. any extra positional or keyword arguments are dropped automatically.
  752. The exception raised provides three attributes:
  753. `missing`
  754. A set of argument names that the function expected but where
  755. missing.
  756. `extra`
  757. A dict of keyword arguments that the function can not handle but
  758. where provided.
  759. `extra_positional`
  760. A list of values that where given by positional argument but the
  761. function cannot accept.
  762. This can be useful for decorators that forward user submitted data to
  763. a view function::
  764. from werkzeug.utils import ArgumentValidationError, validate_arguments
  765. def sanitize(f):
  766. def proxy(request):
  767. data = request.values.to_dict()
  768. try:
  769. args, kwargs = validate_arguments(f, (request,), data)
  770. except ArgumentValidationError:
  771. raise BadRequest('The browser failed to transmit all '
  772. 'the data expected.')
  773. return f(*args, **kwargs)
  774. return proxy
  775. :param func: the function the validation is performed against.
  776. :param args: a tuple of positional arguments.
  777. :param kwargs: a dict of keyword arguments.
  778. :param drop_extra: set to `False` if you don't want extra arguments
  779. to be silently dropped.
  780. :return: tuple in the form ``(args, kwargs)``.
  781. .. deprecated:: 2.0
  782. Will be removed in Werkzeug 2.1. Use :func:`inspect.signature`
  783. instead.
  784. """
  785. warnings.warn(
  786. "'utils.validate_arguments' is deprecated and will be removed"
  787. " in Werkzeug 2.1. Use 'inspect.signature' instead.",
  788. DeprecationWarning,
  789. stacklevel=2,
  790. )
  791. parser = _parse_signature(func)
  792. args, kwargs, missing, extra, extra_positional = parser(args, kwargs)[:5]
  793. if missing:
  794. raise ArgumentValidationError(tuple(missing))
  795. elif (extra or extra_positional) and not drop_extra:
  796. raise ArgumentValidationError(None, extra, extra_positional)
  797. return tuple(args), kwargs
  798. def bind_arguments(func, args, kwargs): # type: ignore
  799. """Bind the arguments provided into a dict. When passed a function,
  800. a tuple of arguments and a dict of keyword arguments `bind_arguments`
  801. returns a dict of names as the function would see it. This can be useful
  802. to implement a cache decorator that uses the function arguments to build
  803. the cache key based on the values of the arguments.
  804. :param func: the function the arguments should be bound for.
  805. :param args: tuple of positional arguments.
  806. :param kwargs: a dict of keyword arguments.
  807. :return: a :class:`dict` of bound keyword arguments.
  808. .. deprecated:: 2.0
  809. Will be removed in Werkzeug 2.1. Use :meth:`Signature.bind`
  810. instead.
  811. """
  812. warnings.warn(
  813. "'utils.bind_arguments' is deprecated and will be removed in"
  814. " Werkzeug 2.1. Use 'Signature.bind' instead.",
  815. DeprecationWarning,
  816. stacklevel=2,
  817. )
  818. (
  819. args,
  820. kwargs,
  821. missing,
  822. extra,
  823. extra_positional,
  824. arg_spec,
  825. vararg_var,
  826. kwarg_var,
  827. ) = _parse_signature(func)(args, kwargs)
  828. values = {}
  829. for (name, _has_default, _default), value in zip(arg_spec, args):
  830. values[name] = value
  831. if vararg_var is not None:
  832. values[vararg_var] = tuple(extra_positional)
  833. elif extra_positional:
  834. raise TypeError("too many positional arguments")
  835. if kwarg_var is not None:
  836. multikw = set(extra) & {x[0] for x in arg_spec}
  837. if multikw:
  838. raise TypeError(
  839. f"got multiple values for keyword argument {next(iter(multikw))!r}"
  840. )
  841. values[kwarg_var] = extra
  842. elif extra:
  843. raise TypeError(f"got unexpected keyword argument {next(iter(extra))!r}")
  844. return values
  845. class ArgumentValidationError(ValueError):
  846. """Raised if :func:`validate_arguments` fails to validate
  847. .. deprecated:: 2.0
  848. Will be removed in Werkzeug 2.1 along with ``utils.bind`` and
  849. ``validate_arguments``.
  850. """
  851. def __init__(self, missing=None, extra=None, extra_positional=None): # type: ignore
  852. self.missing = set(missing or ())
  853. self.extra = extra or {}
  854. self.extra_positional = extra_positional or []
  855. super().__init__(
  856. "function arguments invalid."
  857. f" ({len(self.missing)} missing,"
  858. f" {len(self.extra) + len(self.extra_positional)} additional)"
  859. )
  860. class ImportStringError(ImportError):
  861. """Provides information about a failed :func:`import_string` attempt."""
  862. #: String in dotted notation that failed to be imported.
  863. import_name: str
  864. #: Wrapped exception.
  865. exception: BaseException
  866. def __init__(self, import_name: str, exception: BaseException) -> None:
  867. self.import_name = import_name
  868. self.exception = exception
  869. msg = import_name
  870. name = ""
  871. tracked = []
  872. for part in import_name.replace(":", ".").split("."):
  873. name = f"{name}.{part}" if name else part
  874. imported = import_string(name, silent=True)
  875. if imported:
  876. tracked.append((name, getattr(imported, "__file__", None)))
  877. else:
  878. track = [f"- {n!r} found in {i!r}." for n, i in tracked]
  879. track.append(f"- {name!r} not found.")
  880. track_str = "\n".join(track)
  881. msg = (
  882. f"import_string() failed for {import_name!r}. Possible reasons"
  883. f" are:\n\n"
  884. "- missing __init__.py in a package;\n"
  885. "- package or module path not included in sys.path;\n"
  886. "- duplicated package or module name taking precedence in"
  887. " sys.path;\n"
  888. "- missing module, class, function or variable;\n\n"
  889. f"Debugged import:\n\n{track_str}\n\n"
  890. f"Original exception:\n\n{type(exception).__name__}: {exception}"
  891. )
  892. break
  893. super().__init__(msg)
  894. def __repr__(self) -> str:
  895. return f"<{type(self).__name__}({self.import_name!r}, {self.exception!r})>"