helpers.py 23 KB

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