helpers.py 22 KB

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