helpers.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. from __future__ import annotations
  2. import importlib.util
  3. import os
  4. import sys
  5. import typing as t
  6. from datetime import datetime
  7. from functools import cache
  8. from functools import update_wrapper
  9. import werkzeug.utils
  10. from werkzeug.exceptions import abort as _wz_abort
  11. from werkzeug.utils import redirect as _wz_redirect
  12. from werkzeug.wrappers import Response as BaseResponse
  13. from .globals import _cv_request
  14. from .globals import current_app
  15. from .globals import request
  16. from .globals import request_ctx
  17. from .globals import session
  18. from .signals import message_flashed
  19. if t.TYPE_CHECKING: # pragma: no cover
  20. from .wrappers import Response
  21. def get_debug_flag() -> bool:
  22. """Get whether debug mode should be enabled for the app, indicated by the
  23. :envvar:`FLASK_DEBUG` environment variable. The default is ``False``.
  24. """
  25. val = os.environ.get("FLASK_DEBUG")
  26. return bool(val and val.lower() not in {"0", "false", "no"})
  27. def get_load_dotenv(default: bool = True) -> bool:
  28. """Get whether the user has disabled loading default dotenv files by
  29. setting :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load
  30. the files.
  31. :param default: What to return if the env var isn't set.
  32. """
  33. val = os.environ.get("FLASK_SKIP_DOTENV")
  34. if not val:
  35. return default
  36. return val.lower() in ("0", "false", "no")
  37. @t.overload
  38. def stream_with_context(
  39. generator_or_function: t.Iterator[t.AnyStr],
  40. ) -> t.Iterator[t.AnyStr]: ...
  41. @t.overload
  42. def stream_with_context(
  43. generator_or_function: t.Callable[..., t.Iterator[t.AnyStr]],
  44. ) -> t.Callable[[t.Iterator[t.AnyStr]], t.Iterator[t.AnyStr]]: ...
  45. def stream_with_context(
  46. generator_or_function: t.Iterator[t.AnyStr] | t.Callable[..., t.Iterator[t.AnyStr]],
  47. ) -> t.Iterator[t.AnyStr] | t.Callable[[t.Iterator[t.AnyStr]], t.Iterator[t.AnyStr]]:
  48. """Request contexts disappear when the response is started on the server.
  49. This is done for efficiency reasons and to make it less likely to encounter
  50. memory leaks with badly written WSGI middlewares. The downside is that if
  51. you are using streamed responses, the generator cannot access request bound
  52. information any more.
  53. This function however can help you keep the context around for longer::
  54. from flask import stream_with_context, request, Response
  55. @app.route('/stream')
  56. def streamed_response():
  57. @stream_with_context
  58. def generate():
  59. yield 'Hello '
  60. yield request.args['name']
  61. yield '!'
  62. return Response(generate())
  63. Alternatively it can also be used around a specific generator::
  64. from flask import stream_with_context, request, Response
  65. @app.route('/stream')
  66. def streamed_response():
  67. def generate():
  68. yield 'Hello '
  69. yield request.args['name']
  70. yield '!'
  71. return Response(stream_with_context(generate()))
  72. .. versionadded:: 0.9
  73. """
  74. try:
  75. gen = iter(generator_or_function) # type: ignore[arg-type]
  76. except TypeError:
  77. def decorator(*args: t.Any, **kwargs: t.Any) -> t.Any:
  78. gen = generator_or_function(*args, **kwargs) # type: ignore[operator]
  79. return stream_with_context(gen)
  80. return update_wrapper(decorator, generator_or_function) # type: ignore[arg-type]
  81. def generator() -> t.Iterator[t.AnyStr | None]:
  82. ctx = _cv_request.get(None)
  83. if ctx is None:
  84. raise RuntimeError(
  85. "'stream_with_context' can only be used when a request"
  86. " context is active, such as in a view function."
  87. )
  88. with ctx:
  89. # Dummy sentinel. Has to be inside the context block or we're
  90. # not actually keeping the context around.
  91. yield None
  92. # The try/finally is here so that if someone passes a WSGI level
  93. # iterator in we're still running the cleanup logic. Generators
  94. # don't need that because they are closed on their destruction
  95. # automatically.
  96. try:
  97. yield from gen
  98. finally:
  99. if hasattr(gen, "close"):
  100. gen.close()
  101. # The trick is to start the generator. Then the code execution runs until
  102. # the first dummy None is yielded at which point the context was already
  103. # pushed. This item is discarded. Then when the iteration continues the
  104. # real generator is executed.
  105. wrapped_g = generator()
  106. next(wrapped_g)
  107. return wrapped_g # type: ignore[return-value]
  108. def make_response(*args: t.Any) -> Response:
  109. """Sometimes it is necessary to set additional headers in a view. Because
  110. views do not have to return response objects but can return a value that
  111. is converted into a response object by Flask itself, it becomes tricky to
  112. add headers to it. This function can be called instead of using a return
  113. and you will get a response object which you can use to attach headers.
  114. If view looked like this and you want to add a new header::
  115. def index():
  116. return render_template('index.html', foo=42)
  117. You can now do something like this::
  118. def index():
  119. response = make_response(render_template('index.html', foo=42))
  120. response.headers['X-Parachutes'] = 'parachutes are cool'
  121. return response
  122. This function accepts the very same arguments you can return from a
  123. view function. This for example creates a response with a 404 error
  124. code::
  125. response = make_response(render_template('not_found.html'), 404)
  126. The other use case of this function is to force the return value of a
  127. view function into a response which is helpful with view
  128. decorators::
  129. response = make_response(view_function())
  130. response.headers['X-Parachutes'] = 'parachutes are cool'
  131. Internally this function does the following things:
  132. - if no arguments are passed, it creates a new response argument
  133. - if one argument is passed, :meth:`flask.Flask.make_response`
  134. is invoked with it.
  135. - if more than one argument is passed, the arguments are passed
  136. to the :meth:`flask.Flask.make_response` function as tuple.
  137. .. versionadded:: 0.6
  138. """
  139. if not args:
  140. return current_app.response_class()
  141. if len(args) == 1:
  142. args = args[0]
  143. return current_app.make_response(args)
  144. def url_for(
  145. endpoint: str,
  146. *,
  147. _anchor: str | None = None,
  148. _method: str | None = None,
  149. _scheme: str | None = None,
  150. _external: bool | None = None,
  151. **values: t.Any,
  152. ) -> str:
  153. """Generate a URL to the given endpoint with the given values.
  154. This requires an active request or application context, and calls
  155. :meth:`current_app.url_for() <flask.Flask.url_for>`. See that method
  156. for full documentation.
  157. :param endpoint: The endpoint name associated with the URL to
  158. generate. If this starts with a ``.``, the current blueprint
  159. name (if any) will be used.
  160. :param _anchor: If given, append this as ``#anchor`` to the URL.
  161. :param _method: If given, generate the URL associated with this
  162. method for the endpoint.
  163. :param _scheme: If given, the URL will have this scheme if it is
  164. external.
  165. :param _external: If given, prefer the URL to be internal (False) or
  166. require it to be external (True). External URLs include the
  167. scheme and domain. When not in an active request, URLs are
  168. external by default.
  169. :param values: Values to use for the variable parts of the URL rule.
  170. Unknown keys are appended as query string arguments, like
  171. ``?a=b&c=d``.
  172. .. versionchanged:: 2.2
  173. Calls ``current_app.url_for``, allowing an app to override the
  174. behavior.
  175. .. versionchanged:: 0.10
  176. The ``_scheme`` parameter was added.
  177. .. versionchanged:: 0.9
  178. The ``_anchor`` and ``_method`` parameters were added.
  179. .. versionchanged:: 0.9
  180. Calls ``app.handle_url_build_error`` on build errors.
  181. """
  182. return current_app.url_for(
  183. endpoint,
  184. _anchor=_anchor,
  185. _method=_method,
  186. _scheme=_scheme,
  187. _external=_external,
  188. **values,
  189. )
  190. def redirect(
  191. location: str, code: int = 302, Response: type[BaseResponse] | None = None
  192. ) -> BaseResponse:
  193. """Create a redirect response object.
  194. If :data:`~flask.current_app` is available, it will use its
  195. :meth:`~flask.Flask.redirect` method, otherwise it will use
  196. :func:`werkzeug.utils.redirect`.
  197. :param location: The URL to redirect to.
  198. :param code: The status code for the redirect.
  199. :param Response: The response class to use. Not used when
  200. ``current_app`` is active, which uses ``app.response_class``.
  201. .. versionadded:: 2.2
  202. Calls ``current_app.redirect`` if available instead of always
  203. using Werkzeug's default ``redirect``.
  204. """
  205. if current_app:
  206. return current_app.redirect(location, code=code)
  207. return _wz_redirect(location, code=code, Response=Response)
  208. def abort(code: int | BaseResponse, *args: t.Any, **kwargs: t.Any) -> t.NoReturn:
  209. """Raise an :exc:`~werkzeug.exceptions.HTTPException` for the given
  210. status code.
  211. If :data:`~flask.current_app` is available, it will call its
  212. :attr:`~flask.Flask.aborter` object, otherwise it will use
  213. :func:`werkzeug.exceptions.abort`.
  214. :param code: The status code for the exception, which must be
  215. registered in ``app.aborter``.
  216. :param args: Passed to the exception.
  217. :param kwargs: Passed to the exception.
  218. .. versionadded:: 2.2
  219. Calls ``current_app.aborter`` if available instead of always
  220. using Werkzeug's default ``abort``.
  221. """
  222. if current_app:
  223. current_app.aborter(code, *args, **kwargs)
  224. _wz_abort(code, *args, **kwargs)
  225. def get_template_attribute(template_name: str, attribute: str) -> t.Any:
  226. """Loads a macro (or variable) a template exports. This can be used to
  227. invoke a macro from within Python code. If you for example have a
  228. template named :file:`_cider.html` with the following contents:
  229. .. sourcecode:: html+jinja
  230. {% macro hello(name) %}Hello {{ name }}!{% endmacro %}
  231. You can access this from Python code like this::
  232. hello = get_template_attribute('_cider.html', 'hello')
  233. return hello('World')
  234. .. versionadded:: 0.2
  235. :param template_name: the name of the template
  236. :param attribute: the name of the variable of macro to access
  237. """
  238. return getattr(current_app.jinja_env.get_template(template_name).module, attribute)
  239. def flash(message: str, category: str = "message") -> None:
  240. """Flashes a message to the next request. In order to remove the
  241. flashed message from the session and to display it to the user,
  242. the template has to call :func:`get_flashed_messages`.
  243. .. versionchanged:: 0.3
  244. `category` parameter added.
  245. :param message: the message to be flashed.
  246. :param category: the category for the message. The following values
  247. are recommended: ``'message'`` for any kind of message,
  248. ``'error'`` for errors, ``'info'`` for information
  249. messages and ``'warning'`` for warnings. However any
  250. kind of string can be used as category.
  251. """
  252. # Original implementation:
  253. #
  254. # session.setdefault('_flashes', []).append((category, message))
  255. #
  256. # This assumed that changes made to mutable structures in the session are
  257. # always in sync with the session object, which is not true for session
  258. # implementations that use external storage for keeping their keys/values.
  259. flashes = session.get("_flashes", [])
  260. flashes.append((category, message))
  261. session["_flashes"] = flashes
  262. app = current_app._get_current_object() # type: ignore
  263. message_flashed.send(
  264. app,
  265. _async_wrapper=app.ensure_sync,
  266. message=message,
  267. category=category,
  268. )
  269. def get_flashed_messages(
  270. with_categories: bool = False, category_filter: t.Iterable[str] = ()
  271. ) -> list[str] | list[tuple[str, str]]:
  272. """Pulls all flashed messages from the session and returns them.
  273. Further calls in the same request to the function will return
  274. the same messages. By default just the messages are returned,
  275. but when `with_categories` is set to ``True``, the return value will
  276. be a list of tuples in the form ``(category, message)`` instead.
  277. Filter the flashed messages to one or more categories by providing those
  278. categories in `category_filter`. This allows rendering categories in
  279. separate html blocks. The `with_categories` and `category_filter`
  280. arguments are distinct:
  281. * `with_categories` controls whether categories are returned with message
  282. text (``True`` gives a tuple, where ``False`` gives just the message text).
  283. * `category_filter` filters the messages down to only those matching the
  284. provided categories.
  285. See :doc:`/patterns/flashing` for examples.
  286. .. versionchanged:: 0.3
  287. `with_categories` parameter added.
  288. .. versionchanged:: 0.9
  289. `category_filter` parameter added.
  290. :param with_categories: set to ``True`` to also receive categories.
  291. :param category_filter: filter of categories to limit return values. Only
  292. categories in the list will be returned.
  293. """
  294. flashes = request_ctx.flashes
  295. if flashes is None:
  296. flashes = session.pop("_flashes") if "_flashes" in session else []
  297. request_ctx.flashes = flashes
  298. if category_filter:
  299. flashes = list(filter(lambda f: f[0] in category_filter, flashes))
  300. if not with_categories:
  301. return [x[1] for x in flashes]
  302. return flashes
  303. def _prepare_send_file_kwargs(**kwargs: t.Any) -> dict[str, t.Any]:
  304. if kwargs.get("max_age") is None:
  305. kwargs["max_age"] = current_app.get_send_file_max_age
  306. kwargs.update(
  307. environ=request.environ,
  308. use_x_sendfile=current_app.config["USE_X_SENDFILE"],
  309. response_class=current_app.response_class,
  310. _root_path=current_app.root_path, # type: ignore
  311. )
  312. return kwargs
  313. def send_file(
  314. path_or_file: os.PathLike[t.AnyStr] | str | t.BinaryIO,
  315. mimetype: str | None = None,
  316. as_attachment: bool = False,
  317. download_name: str | None = None,
  318. conditional: bool = True,
  319. etag: bool | str = True,
  320. last_modified: datetime | int | float | None = None,
  321. max_age: None | (int | t.Callable[[str | None], int | None]) = None,
  322. ) -> Response:
  323. """Send the contents of a file to the client.
  324. The first argument can be a file path or a file-like object. Paths
  325. are preferred in most cases because Werkzeug can manage the file and
  326. get extra information from the path. Passing a file-like object
  327. requires that the file is opened in binary mode, and is mostly
  328. useful when building a file in memory with :class:`io.BytesIO`.
  329. Never pass file paths provided by a user. The path is assumed to be
  330. trusted, so a user could craft a path to access a file you didn't
  331. intend. Use :func:`send_from_directory` to safely serve
  332. user-requested paths from within a directory.
  333. If the WSGI server sets a ``file_wrapper`` in ``environ``, it is
  334. used, otherwise Werkzeug's built-in wrapper is used. Alternatively,
  335. if the HTTP server supports ``X-Sendfile``, configuring Flask with
  336. ``USE_X_SENDFILE = True`` will tell the server to send the given
  337. path, which is much more efficient than reading it in Python.
  338. :param path_or_file: The path to the file to send, relative to the
  339. current working directory if a relative path is given.
  340. Alternatively, a file-like object opened in binary mode. Make
  341. sure the file pointer is seeked to the start of the data.
  342. :param mimetype: The MIME type to send for the file. If not
  343. provided, it will try to detect it from the file name.
  344. :param as_attachment: Indicate to a browser that it should offer to
  345. save the file instead of displaying it.
  346. :param download_name: The default name browsers will use when saving
  347. the file. Defaults to the passed file name.
  348. :param conditional: Enable conditional and range responses based on
  349. request headers. Requires passing a file path and ``environ``.
  350. :param etag: Calculate an ETag for the file, which requires passing
  351. a file path. Can also be a string to use instead.
  352. :param last_modified: The last modified time to send for the file,
  353. in seconds. If not provided, it will try to detect it from the
  354. file path.
  355. :param max_age: How long the client should cache the file, in
  356. seconds. If set, ``Cache-Control`` will be ``public``, otherwise
  357. it will be ``no-cache`` to prefer conditional caching.
  358. .. versionchanged:: 2.0
  359. ``download_name`` replaces the ``attachment_filename``
  360. parameter. If ``as_attachment=False``, it is passed with
  361. ``Content-Disposition: inline`` instead.
  362. .. versionchanged:: 2.0
  363. ``max_age`` replaces the ``cache_timeout`` parameter.
  364. ``conditional`` is enabled and ``max_age`` is not set by
  365. default.
  366. .. versionchanged:: 2.0
  367. ``etag`` replaces the ``add_etags`` parameter. It can be a
  368. string to use instead of generating one.
  369. .. versionchanged:: 2.0
  370. Passing a file-like object that inherits from
  371. :class:`~io.TextIOBase` will raise a :exc:`ValueError` rather
  372. than sending an empty file.
  373. .. versionadded:: 2.0
  374. Moved the implementation to Werkzeug. This is now a wrapper to
  375. pass some Flask-specific arguments.
  376. .. versionchanged:: 1.1
  377. ``filename`` may be a :class:`~os.PathLike` object.
  378. .. versionchanged:: 1.1
  379. Passing a :class:`~io.BytesIO` object supports range requests.
  380. .. versionchanged:: 1.0.3
  381. Filenames are encoded with ASCII instead of Latin-1 for broader
  382. compatibility with WSGI servers.
  383. .. versionchanged:: 1.0
  384. UTF-8 filenames as specified in :rfc:`2231` are supported.
  385. .. versionchanged:: 0.12
  386. The filename is no longer automatically inferred from file
  387. objects. If you want to use automatic MIME and etag support,
  388. pass a filename via ``filename_or_fp`` or
  389. ``attachment_filename``.
  390. .. versionchanged:: 0.12
  391. ``attachment_filename`` is preferred over ``filename`` for MIME
  392. detection.
  393. .. versionchanged:: 0.9
  394. ``cache_timeout`` defaults to
  395. :meth:`Flask.get_send_file_max_age`.
  396. .. versionchanged:: 0.7
  397. MIME guessing and etag support for file-like objects was
  398. removed because it was unreliable. Pass a filename if you are
  399. able to, otherwise attach an etag yourself.
  400. .. versionchanged:: 0.5
  401. The ``add_etags``, ``cache_timeout`` and ``conditional``
  402. parameters were added. The default behavior is to add etags.
  403. .. versionadded:: 0.2
  404. """
  405. return werkzeug.utils.send_file( # type: ignore[return-value]
  406. **_prepare_send_file_kwargs(
  407. path_or_file=path_or_file,
  408. environ=request.environ,
  409. mimetype=mimetype,
  410. as_attachment=as_attachment,
  411. download_name=download_name,
  412. conditional=conditional,
  413. etag=etag,
  414. last_modified=last_modified,
  415. max_age=max_age,
  416. )
  417. )
  418. def send_from_directory(
  419. directory: os.PathLike[str] | str,
  420. path: os.PathLike[str] | str,
  421. **kwargs: t.Any,
  422. ) -> Response:
  423. """Send a file from within a directory using :func:`send_file`.
  424. .. code-block:: python
  425. @app.route("/uploads/<path:name>")
  426. def download_file(name):
  427. return send_from_directory(
  428. app.config['UPLOAD_FOLDER'], name, as_attachment=True
  429. )
  430. This is a secure way to serve files from a folder, such as static
  431. files or uploads. Uses :func:`~werkzeug.security.safe_join` to
  432. ensure the path coming from the client is not maliciously crafted to
  433. point outside the specified directory.
  434. If the final path does not point to an existing regular file,
  435. raises a 404 :exc:`~werkzeug.exceptions.NotFound` error.
  436. :param directory: The directory that ``path`` must be located under,
  437. relative to the current application's root path. This *must not*
  438. be a value provided by the client, otherwise it becomes insecure.
  439. :param path: The path to the file to send, relative to
  440. ``directory``.
  441. :param kwargs: Arguments to pass to :func:`send_file`.
  442. .. versionchanged:: 2.0
  443. ``path`` replaces the ``filename`` parameter.
  444. .. versionadded:: 2.0
  445. Moved the implementation to Werkzeug. This is now a wrapper to
  446. pass some Flask-specific arguments.
  447. .. versionadded:: 0.5
  448. """
  449. return werkzeug.utils.send_from_directory( # type: ignore[return-value]
  450. directory, path, **_prepare_send_file_kwargs(**kwargs)
  451. )
  452. def get_root_path(import_name: str) -> str:
  453. """Find the root path of a package, or the path that contains a
  454. module. If it cannot be found, returns the current working
  455. directory.
  456. Not to be confused with the value returned by :func:`find_package`.
  457. :meta private:
  458. """
  459. # Module already imported and has a file attribute. Use that first.
  460. mod = sys.modules.get(import_name)
  461. if mod is not None and hasattr(mod, "__file__") and mod.__file__ is not None:
  462. return os.path.dirname(os.path.abspath(mod.__file__))
  463. # Next attempt: check the loader.
  464. try:
  465. spec = importlib.util.find_spec(import_name)
  466. if spec is None:
  467. raise ValueError
  468. except (ImportError, ValueError):
  469. loader = None
  470. else:
  471. loader = spec.loader
  472. # Loader does not exist or we're referring to an unloaded main
  473. # module or a main module without path (interactive sessions), go
  474. # with the current working directory.
  475. if loader is None:
  476. return os.getcwd()
  477. if hasattr(loader, "get_filename"):
  478. filepath = loader.get_filename(import_name) # pyright: ignore
  479. else:
  480. # Fall back to imports.
  481. __import__(import_name)
  482. mod = sys.modules[import_name]
  483. filepath = getattr(mod, "__file__", None)
  484. # If we don't have a file path it might be because it is a
  485. # namespace package. In this case pick the root path from the
  486. # first module that is contained in the package.
  487. if filepath is None:
  488. raise RuntimeError(
  489. "No root path can be found for the provided module"
  490. f" {import_name!r}. This can happen because the module"
  491. " came from an import hook that does not provide file"
  492. " name information or because it's a namespace package."
  493. " In this case the root path needs to be explicitly"
  494. " provided."
  495. )
  496. # filepath is import_name.py for a module, or __init__.py for a package.
  497. return os.path.dirname(os.path.abspath(filepath)) # type: ignore[no-any-return]
  498. @cache
  499. def _split_blueprint_path(name: str) -> list[str]:
  500. out: list[str] = [name]
  501. if "." in name:
  502. out.extend(_split_blueprint_path(name.rpartition(".")[0]))
  503. return out