helpers.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. import os
  2. import pkgutil
  3. import socket
  4. import sys
  5. import typing as t
  6. import warnings
  7. from datetime import datetime
  8. from datetime import timedelta
  9. from functools import lru_cache
  10. from functools import update_wrapper
  11. from threading import RLock
  12. import werkzeug.utils
  13. from werkzeug.exceptions import NotFound
  14. from werkzeug.routing import BuildError
  15. from werkzeug.urls import url_quote
  16. from .globals import _app_ctx_stack
  17. from .globals import _request_ctx_stack
  18. from .globals import current_app
  19. from .globals import request
  20. from .globals import session
  21. from .signals import message_flashed
  22. if t.TYPE_CHECKING:
  23. from .wrappers import Response
  24. def get_env() -> str:
  25. """Get the environment the app is running in, indicated by the
  26. :envvar:`FLASK_ENV` environment variable. The default is
  27. ``'production'``.
  28. """
  29. return os.environ.get("FLASK_ENV") or "production"
  30. def get_debug_flag() -> bool:
  31. """Get whether debug mode should be enabled for the app, indicated
  32. by the :envvar:`FLASK_DEBUG` environment variable. The default is
  33. ``True`` if :func:`.get_env` returns ``'development'``, or ``False``
  34. otherwise.
  35. """
  36. val = os.environ.get("FLASK_DEBUG")
  37. if not val:
  38. return get_env() == "development"
  39. return val.lower() not in ("0", "false", "no")
  40. def get_load_dotenv(default: bool = True) -> bool:
  41. """Get whether the user has disabled loading dotenv files by setting
  42. :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load the
  43. files.
  44. :param default: What to return if the env var isn't set.
  45. """
  46. val = os.environ.get("FLASK_SKIP_DOTENV")
  47. if not val:
  48. return default
  49. return val.lower() in ("0", "false", "no")
  50. def stream_with_context(
  51. generator_or_function: t.Union[
  52. t.Iterator[t.AnyStr], t.Callable[..., t.Iterator[t.AnyStr]]
  53. ]
  54. ) -> t.Iterator[t.AnyStr]:
  55. """Request contexts disappear when the response is started on the server.
  56. This is done for efficiency reasons and to make it less likely to encounter
  57. memory leaks with badly written WSGI middlewares. The downside is that if
  58. you are using streamed responses, the generator cannot access request bound
  59. information any more.
  60. This function however can help you keep the context around for longer::
  61. from flask import stream_with_context, request, Response
  62. @app.route('/stream')
  63. def streamed_response():
  64. @stream_with_context
  65. def generate():
  66. yield 'Hello '
  67. yield request.args['name']
  68. yield '!'
  69. return Response(generate())
  70. Alternatively it can also be used around a specific generator::
  71. from flask import stream_with_context, request, Response
  72. @app.route('/stream')
  73. def streamed_response():
  74. def generate():
  75. yield 'Hello '
  76. yield request.args['name']
  77. yield '!'
  78. return Response(stream_with_context(generate()))
  79. .. versionadded:: 0.9
  80. """
  81. try:
  82. gen = iter(generator_or_function) # type: ignore
  83. except TypeError:
  84. def decorator(*args: t.Any, **kwargs: t.Any) -> t.Any:
  85. gen = generator_or_function(*args, **kwargs) # type: ignore
  86. return stream_with_context(gen)
  87. return update_wrapper(decorator, generator_or_function) # type: ignore
  88. def generator() -> t.Generator:
  89. ctx = _request_ctx_stack.top
  90. if ctx is None:
  91. raise RuntimeError(
  92. "Attempted to stream with context but "
  93. "there was no context in the first place to keep around."
  94. )
  95. with ctx:
  96. # Dummy sentinel. Has to be inside the context block or we're
  97. # not actually keeping the context around.
  98. yield None
  99. # The try/finally is here so that if someone passes a WSGI level
  100. # iterator in we're still running the cleanup logic. Generators
  101. # don't need that because they are closed on their destruction
  102. # automatically.
  103. try:
  104. yield from gen
  105. finally:
  106. if hasattr(gen, "close"):
  107. gen.close() # type: ignore
  108. # The trick is to start the generator. Then the code execution runs until
  109. # the first dummy None is yielded at which point the context was already
  110. # pushed. This item is discarded. Then when the iteration continues the
  111. # real generator is executed.
  112. wrapped_g = generator()
  113. next(wrapped_g)
  114. return wrapped_g
  115. def make_response(*args: t.Any) -> "Response":
  116. """Sometimes it is necessary to set additional headers in a view. Because
  117. views do not have to return response objects but can return a value that
  118. is converted into a response object by Flask itself, it becomes tricky to
  119. add headers to it. This function can be called instead of using a return
  120. and you will get a response object which you can use to attach headers.
  121. If view looked like this and you want to add a new header::
  122. def index():
  123. return render_template('index.html', foo=42)
  124. You can now do something like this::
  125. def index():
  126. response = make_response(render_template('index.html', foo=42))
  127. response.headers['X-Parachutes'] = 'parachutes are cool'
  128. return response
  129. This function accepts the very same arguments you can return from a
  130. view function. This for example creates a response with a 404 error
  131. code::
  132. response = make_response(render_template('not_found.html'), 404)
  133. The other use case of this function is to force the return value of a
  134. view function into a response which is helpful with view
  135. decorators::
  136. response = make_response(view_function())
  137. response.headers['X-Parachutes'] = 'parachutes are cool'
  138. Internally this function does the following things:
  139. - if no arguments are passed, it creates a new response argument
  140. - if one argument is passed, :meth:`flask.Flask.make_response`
  141. is invoked with it.
  142. - if more than one argument is passed, the arguments are passed
  143. to the :meth:`flask.Flask.make_response` function as tuple.
  144. .. versionadded:: 0.6
  145. """
  146. if not args:
  147. return current_app.response_class()
  148. if len(args) == 1:
  149. args = args[0]
  150. return current_app.make_response(args)
  151. def url_for(endpoint: str, **values: t.Any) -> str:
  152. """Generates a URL to the given endpoint with the method provided.
  153. Variable arguments that are unknown to the target endpoint are appended
  154. to the generated URL as query arguments. If the value of a query argument
  155. is ``None``, the whole pair is skipped. In case blueprints are active
  156. you can shortcut references to the same blueprint by prefixing the
  157. local endpoint with a dot (``.``).
  158. This will reference the index function local to the current blueprint::
  159. url_for('.index')
  160. See :ref:`url-building`.
  161. Configuration values ``APPLICATION_ROOT`` and ``SERVER_NAME`` are only used when
  162. generating URLs outside of a request context.
  163. To integrate applications, :class:`Flask` has a hook to intercept URL build
  164. errors through :attr:`Flask.url_build_error_handlers`. The `url_for`
  165. function results in a :exc:`~werkzeug.routing.BuildError` when the current
  166. app does not have a URL for the given endpoint and values. When it does, the
  167. :data:`~flask.current_app` calls its :attr:`~Flask.url_build_error_handlers` if
  168. it is not ``None``, which can return a string to use as the result of
  169. `url_for` (instead of `url_for`'s default to raise the
  170. :exc:`~werkzeug.routing.BuildError` exception) or re-raise the exception.
  171. An example::
  172. def external_url_handler(error, endpoint, values):
  173. "Looks up an external URL when `url_for` cannot build a URL."
  174. # This is an example of hooking the build_error_handler.
  175. # Here, lookup_url is some utility function you've built
  176. # which looks up the endpoint in some external URL registry.
  177. url = lookup_url(endpoint, **values)
  178. if url is None:
  179. # External lookup did not have a URL.
  180. # Re-raise the BuildError, in context of original traceback.
  181. exc_type, exc_value, tb = sys.exc_info()
  182. if exc_value is error:
  183. raise exc_type(exc_value).with_traceback(tb)
  184. else:
  185. raise error
  186. # url_for will use this result, instead of raising BuildError.
  187. return url
  188. app.url_build_error_handlers.append(external_url_handler)
  189. Here, `error` is the instance of :exc:`~werkzeug.routing.BuildError`, and
  190. `endpoint` and `values` are the arguments passed into `url_for`. Note
  191. that this is for building URLs outside the current application, and not for
  192. handling 404 NotFound errors.
  193. .. versionadded:: 0.10
  194. The `_scheme` parameter was added.
  195. .. versionadded:: 0.9
  196. The `_anchor` and `_method` parameters were added.
  197. .. versionadded:: 0.9
  198. Calls :meth:`Flask.handle_build_error` on
  199. :exc:`~werkzeug.routing.BuildError`.
  200. :param endpoint: the endpoint of the URL (name of the function)
  201. :param values: the variable arguments of the URL rule
  202. :param _external: if set to ``True``, an absolute URL is generated. Server
  203. address can be changed via ``SERVER_NAME`` configuration variable which
  204. falls back to the `Host` header, then to the IP and port of the request.
  205. :param _scheme: a string specifying the desired URL scheme. The `_external`
  206. parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default
  207. behavior uses the same scheme as the current request, or
  208. :data:`PREFERRED_URL_SCHEME` if no request context is available.
  209. This also can be set to an empty string to build protocol-relative
  210. URLs.
  211. :param _anchor: if provided this is added as anchor to the URL.
  212. :param _method: if provided this explicitly specifies an HTTP method.
  213. """
  214. appctx = _app_ctx_stack.top
  215. reqctx = _request_ctx_stack.top
  216. if appctx is None:
  217. raise RuntimeError(
  218. "Attempted to generate a URL without the application context being"
  219. " pushed. This has to be executed when application context is"
  220. " available."
  221. )
  222. # If request specific information is available we have some extra
  223. # features that support "relative" URLs.
  224. if reqctx is not None:
  225. url_adapter = reqctx.url_adapter
  226. blueprint_name = request.blueprint
  227. if endpoint[:1] == ".":
  228. if blueprint_name is not None:
  229. endpoint = f"{blueprint_name}{endpoint}"
  230. else:
  231. endpoint = endpoint[1:]
  232. external = values.pop("_external", False)
  233. # Otherwise go with the url adapter from the appctx and make
  234. # the URLs external by default.
  235. else:
  236. url_adapter = appctx.url_adapter
  237. if url_adapter is None:
  238. raise RuntimeError(
  239. "Application was not able to create a URL adapter for request"
  240. " independent URL generation. You might be able to fix this by"
  241. " setting the SERVER_NAME config variable."
  242. )
  243. external = values.pop("_external", True)
  244. anchor = values.pop("_anchor", None)
  245. method = values.pop("_method", None)
  246. scheme = values.pop("_scheme", None)
  247. appctx.app.inject_url_defaults(endpoint, values)
  248. # This is not the best way to deal with this but currently the
  249. # underlying Werkzeug router does not support overriding the scheme on
  250. # a per build call basis.
  251. old_scheme = None
  252. if scheme is not None:
  253. if not external:
  254. raise ValueError("When specifying _scheme, _external must be True")
  255. old_scheme = url_adapter.url_scheme
  256. url_adapter.url_scheme = scheme
  257. try:
  258. try:
  259. rv = url_adapter.build(
  260. endpoint, values, method=method, force_external=external
  261. )
  262. finally:
  263. if old_scheme is not None:
  264. url_adapter.url_scheme = old_scheme
  265. except BuildError as error:
  266. # We need to inject the values again so that the app callback can
  267. # deal with that sort of stuff.
  268. values["_external"] = external
  269. values["_anchor"] = anchor
  270. values["_method"] = method
  271. values["_scheme"] = scheme
  272. return appctx.app.handle_url_build_error(error, endpoint, values)
  273. if anchor is not None:
  274. rv += f"#{url_quote(anchor)}"
  275. return rv
  276. def get_template_attribute(template_name: str, attribute: str) -> t.Any:
  277. """Loads a macro (or variable) a template exports. This can be used to
  278. invoke a macro from within Python code. If you for example have a
  279. template named :file:`_cider.html` with the following contents:
  280. .. sourcecode:: html+jinja
  281. {% macro hello(name) %}Hello {{ name }}!{% endmacro %}
  282. You can access this from Python code like this::
  283. hello = get_template_attribute('_cider.html', 'hello')
  284. return hello('World')
  285. .. versionadded:: 0.2
  286. :param template_name: the name of the template
  287. :param attribute: the name of the variable of macro to access
  288. """
  289. return getattr(current_app.jinja_env.get_template(template_name).module, attribute)
  290. def flash(message: str, category: str = "message") -> None:
  291. """Flashes a message to the next request. In order to remove the
  292. flashed message from the session and to display it to the user,
  293. the template has to call :func:`get_flashed_messages`.
  294. .. versionchanged:: 0.3
  295. `category` parameter added.
  296. :param message: the message to be flashed.
  297. :param category: the category for the message. The following values
  298. are recommended: ``'message'`` for any kind of message,
  299. ``'error'`` for errors, ``'info'`` for information
  300. messages and ``'warning'`` for warnings. However any
  301. kind of string can be used as category.
  302. """
  303. # Original implementation:
  304. #
  305. # session.setdefault('_flashes', []).append((category, message))
  306. #
  307. # This assumed that changes made to mutable structures in the session are
  308. # always in sync with the session object, which is not true for session
  309. # implementations that use external storage for keeping their keys/values.
  310. flashes = session.get("_flashes", [])
  311. flashes.append((category, message))
  312. session["_flashes"] = flashes
  313. message_flashed.send(
  314. current_app._get_current_object(), # type: ignore
  315. message=message,
  316. category=category,
  317. )
  318. def get_flashed_messages(
  319. with_categories: bool = False, category_filter: t.Iterable[str] = ()
  320. ) -> t.Union[t.List[str], t.List[t.Tuple[str, str]]]:
  321. """Pulls all flashed messages from the session and returns them.
  322. Further calls in the same request to the function will return
  323. the same messages. By default just the messages are returned,
  324. but when `with_categories` is set to ``True``, the return value will
  325. be a list of tuples in the form ``(category, message)`` instead.
  326. Filter the flashed messages to one or more categories by providing those
  327. categories in `category_filter`. This allows rendering categories in
  328. separate html blocks. The `with_categories` and `category_filter`
  329. arguments are distinct:
  330. * `with_categories` controls whether categories are returned with message
  331. text (``True`` gives a tuple, where ``False`` gives just the message text).
  332. * `category_filter` filters the messages down to only those matching the
  333. provided categories.
  334. See :doc:`/patterns/flashing` for examples.
  335. .. versionchanged:: 0.3
  336. `with_categories` parameter added.
  337. .. versionchanged:: 0.9
  338. `category_filter` parameter added.
  339. :param with_categories: set to ``True`` to also receive categories.
  340. :param category_filter: filter of categories to limit return values. Only
  341. categories in the list will be returned.
  342. """
  343. flashes = _request_ctx_stack.top.flashes
  344. if flashes is None:
  345. _request_ctx_stack.top.flashes = flashes = (
  346. session.pop("_flashes") if "_flashes" in session else []
  347. )
  348. if category_filter:
  349. flashes = list(filter(lambda f: f[0] in category_filter, flashes))
  350. if not with_categories:
  351. return [x[1] for x in flashes]
  352. return flashes
  353. def _prepare_send_file_kwargs(
  354. download_name: t.Optional[str] = None,
  355. attachment_filename: t.Optional[str] = None,
  356. etag: t.Optional[t.Union[bool, str]] = None,
  357. add_etags: t.Optional[t.Union[bool]] = None,
  358. max_age: t.Optional[
  359. t.Union[int, t.Callable[[t.Optional[str]], t.Optional[int]]]
  360. ] = None,
  361. cache_timeout: t.Optional[int] = None,
  362. **kwargs: t.Any,
  363. ) -> t.Dict[str, t.Any]:
  364. if attachment_filename is not None:
  365. warnings.warn(
  366. "The 'attachment_filename' parameter has been renamed to"
  367. " 'download_name'. The old name will be removed in Flask"
  368. " 2.1.",
  369. DeprecationWarning,
  370. stacklevel=3,
  371. )
  372. download_name = attachment_filename
  373. if cache_timeout is not None:
  374. warnings.warn(
  375. "The 'cache_timeout' parameter has been renamed to"
  376. " 'max_age'. The old name will be removed in Flask 2.1.",
  377. DeprecationWarning,
  378. stacklevel=3,
  379. )
  380. max_age = cache_timeout
  381. if add_etags is not None:
  382. warnings.warn(
  383. "The 'add_etags' parameter has been renamed to 'etag'. The"
  384. " old name will be removed in Flask 2.1.",
  385. DeprecationWarning,
  386. stacklevel=3,
  387. )
  388. etag = add_etags
  389. if max_age is None:
  390. max_age = current_app.get_send_file_max_age
  391. kwargs.update(
  392. environ=request.environ,
  393. download_name=download_name,
  394. etag=etag,
  395. max_age=max_age,
  396. use_x_sendfile=current_app.use_x_sendfile,
  397. response_class=current_app.response_class,
  398. _root_path=current_app.root_path, # type: ignore
  399. )
  400. return kwargs
  401. def send_file(
  402. path_or_file: t.Union[os.PathLike, str, t.BinaryIO],
  403. mimetype: t.Optional[str] = None,
  404. as_attachment: bool = False,
  405. download_name: t.Optional[str] = None,
  406. attachment_filename: t.Optional[str] = None,
  407. conditional: bool = True,
  408. etag: t.Union[bool, str] = True,
  409. add_etags: t.Optional[bool] = None,
  410. last_modified: t.Optional[t.Union[datetime, int, float]] = None,
  411. max_age: t.Optional[
  412. t.Union[int, t.Callable[[t.Optional[str]], t.Optional[int]]]
  413. ] = None,
  414. cache_timeout: t.Optional[int] = None,
  415. ):
  416. """Send the contents of a file to the client.
  417. The first argument can be a file path or a file-like object. Paths
  418. are preferred in most cases because Werkzeug can manage the file and
  419. get extra information from the path. Passing a file-like object
  420. requires that the file is opened in binary mode, and is mostly
  421. useful when building a file in memory with :class:`io.BytesIO`.
  422. Never pass file paths provided by a user. The path is assumed to be
  423. trusted, so a user could craft a path to access a file you didn't
  424. intend. Use :func:`send_from_directory` to safely serve
  425. user-requested paths from within a directory.
  426. If the WSGI server sets a ``file_wrapper`` in ``environ``, it is
  427. used, otherwise Werkzeug's built-in wrapper is used. Alternatively,
  428. if the HTTP server supports ``X-Sendfile``, configuring Flask with
  429. ``USE_X_SENDFILE = True`` will tell the server to send the given
  430. path, which is much more efficient than reading it in Python.
  431. :param path_or_file: The path to the file to send, relative to the
  432. current working directory if a relative path is given.
  433. Alternatively, a file-like object opened in binary mode. Make
  434. sure the file pointer is seeked to the start of the data.
  435. :param mimetype: The MIME type to send for the file. If not
  436. provided, it will try to detect it from the file name.
  437. :param as_attachment: Indicate to a browser that it should offer to
  438. save the file instead of displaying it.
  439. :param download_name: The default name browsers will use when saving
  440. the file. Defaults to the passed file name.
  441. :param conditional: Enable conditional and range responses based on
  442. request headers. Requires passing a file path and ``environ``.
  443. :param etag: Calculate an ETag for the file, which requires passing
  444. a file path. Can also be a string to use instead.
  445. :param last_modified: The last modified time to send for the file,
  446. in seconds. If not provided, it will try to detect it from the
  447. file path.
  448. :param max_age: How long the client should cache the file, in
  449. seconds. If set, ``Cache-Control`` will be ``public``, otherwise
  450. it will be ``no-cache`` to prefer conditional caching.
  451. .. versionchanged:: 2.0
  452. ``download_name`` replaces the ``attachment_filename``
  453. parameter. If ``as_attachment=False``, it is passed with
  454. ``Content-Disposition: inline`` instead.
  455. .. versionchanged:: 2.0
  456. ``max_age`` replaces the ``cache_timeout`` parameter.
  457. ``conditional`` is enabled and ``max_age`` is not set by
  458. default.
  459. .. versionchanged:: 2.0
  460. ``etag`` replaces the ``add_etags`` parameter. It can be a
  461. string to use instead of generating one.
  462. .. versionchanged:: 2.0
  463. Passing a file-like object that inherits from
  464. :class:`~io.TextIOBase` will raise a :exc:`ValueError` rather
  465. than sending an empty file.
  466. .. versionadded:: 2.0
  467. Moved the implementation to Werkzeug. This is now a wrapper to
  468. pass some Flask-specific arguments.
  469. .. versionchanged:: 1.1
  470. ``filename`` may be a :class:`~os.PathLike` object.
  471. .. versionchanged:: 1.1
  472. Passing a :class:`~io.BytesIO` object supports range requests.
  473. .. versionchanged:: 1.0.3
  474. Filenames are encoded with ASCII instead of Latin-1 for broader
  475. compatibility with WSGI servers.
  476. .. versionchanged:: 1.0
  477. UTF-8 filenames as specified in :rfc:`2231` are supported.
  478. .. versionchanged:: 0.12
  479. The filename is no longer automatically inferred from file
  480. objects. If you want to use automatic MIME and etag support,
  481. pass a filename via ``filename_or_fp`` or
  482. ``attachment_filename``.
  483. .. versionchanged:: 0.12
  484. ``attachment_filename`` is preferred over ``filename`` for MIME
  485. detection.
  486. .. versionchanged:: 0.9
  487. ``cache_timeout`` defaults to
  488. :meth:`Flask.get_send_file_max_age`.
  489. .. versionchanged:: 0.7
  490. MIME guessing and etag support for file-like objects was
  491. deprecated because it was unreliable. Pass a filename if you are
  492. able to, otherwise attach an etag yourself.
  493. .. versionchanged:: 0.5
  494. The ``add_etags``, ``cache_timeout`` and ``conditional``
  495. parameters were added. The default behavior is to add etags.
  496. .. versionadded:: 0.2
  497. """
  498. return werkzeug.utils.send_file(
  499. **_prepare_send_file_kwargs(
  500. path_or_file=path_or_file,
  501. environ=request.environ,
  502. mimetype=mimetype,
  503. as_attachment=as_attachment,
  504. download_name=download_name,
  505. attachment_filename=attachment_filename,
  506. conditional=conditional,
  507. etag=etag,
  508. add_etags=add_etags,
  509. last_modified=last_modified,
  510. max_age=max_age,
  511. cache_timeout=cache_timeout,
  512. )
  513. )
  514. def safe_join(directory: str, *pathnames: str) -> str:
  515. """Safely join zero or more untrusted path components to a base
  516. directory to avoid escaping the base directory.
  517. :param directory: The trusted base directory.
  518. :param pathnames: The untrusted path components relative to the
  519. base directory.
  520. :return: A safe path, otherwise ``None``.
  521. """
  522. warnings.warn(
  523. "'flask.helpers.safe_join' is deprecated and will be removed in"
  524. " Flask 2.1. Use 'werkzeug.utils.safe_join' instead.",
  525. DeprecationWarning,
  526. stacklevel=2,
  527. )
  528. path = werkzeug.utils.safe_join(directory, *pathnames)
  529. if path is None:
  530. raise NotFound()
  531. return path
  532. def send_from_directory(
  533. directory: t.Union[os.PathLike, str],
  534. path: t.Union[os.PathLike, str],
  535. filename: t.Optional[str] = None,
  536. **kwargs: t.Any,
  537. ) -> "Response":
  538. """Send a file from within a directory using :func:`send_file`.
  539. .. code-block:: python
  540. @app.route("/uploads/<path:name>")
  541. def download_file(name):
  542. return send_from_directory(
  543. app.config['UPLOAD_FOLDER'], name, as_attachment=True
  544. )
  545. This is a secure way to serve files from a folder, such as static
  546. files or uploads. Uses :func:`~werkzeug.security.safe_join` to
  547. ensure the path coming from the client is not maliciously crafted to
  548. point outside the specified directory.
  549. If the final path does not point to an existing regular file,
  550. raises a 404 :exc:`~werkzeug.exceptions.NotFound` error.
  551. :param directory: The directory that ``path`` must be located under.
  552. :param path: The path to the file to send, relative to
  553. ``directory``.
  554. :param kwargs: Arguments to pass to :func:`send_file`.
  555. .. versionchanged:: 2.0
  556. ``path`` replaces the ``filename`` parameter.
  557. .. versionadded:: 2.0
  558. Moved the implementation to Werkzeug. This is now a wrapper to
  559. pass some Flask-specific arguments.
  560. .. versionadded:: 0.5
  561. """
  562. if filename is not None:
  563. warnings.warn(
  564. "The 'filename' parameter has been renamed to 'path'. The"
  565. " old name will be removed in Flask 2.1.",
  566. DeprecationWarning,
  567. stacklevel=2,
  568. )
  569. path = filename
  570. return werkzeug.utils.send_from_directory( # type: ignore
  571. directory, path, **_prepare_send_file_kwargs(**kwargs)
  572. )
  573. def get_root_path(import_name: str) -> str:
  574. """Find the root path of a package, or the path that contains a
  575. module. If it cannot be found, returns the current working
  576. directory.
  577. Not to be confused with the value returned by :func:`find_package`.
  578. :meta private:
  579. """
  580. # Module already imported and has a file attribute. Use that first.
  581. mod = sys.modules.get(import_name)
  582. if mod is not None and hasattr(mod, "__file__"):
  583. return os.path.dirname(os.path.abspath(mod.__file__))
  584. # Next attempt: check the loader.
  585. loader = pkgutil.get_loader(import_name)
  586. # Loader does not exist or we're referring to an unloaded main
  587. # module or a main module without path (interactive sessions), go
  588. # with the current working directory.
  589. if loader is None or import_name == "__main__":
  590. return os.getcwd()
  591. if hasattr(loader, "get_filename"):
  592. filepath = loader.get_filename(import_name) # type: ignore
  593. else:
  594. # Fall back to imports.
  595. __import__(import_name)
  596. mod = sys.modules[import_name]
  597. filepath = getattr(mod, "__file__", None)
  598. # If we don't have a file path it might be because it is a
  599. # namespace package. In this case pick the root path from the
  600. # first module that is contained in the package.
  601. if filepath is None:
  602. raise RuntimeError(
  603. "No root path can be found for the provided module"
  604. f" {import_name!r}. This can happen because the module"
  605. " came from an import hook that does not provide file"
  606. " name information or because it's a namespace package."
  607. " In this case the root path needs to be explicitly"
  608. " provided."
  609. )
  610. # filepath is import_name.py for a module, or __init__.py for a package.
  611. return os.path.dirname(os.path.abspath(filepath))
  612. class locked_cached_property(werkzeug.utils.cached_property):
  613. """A :func:`property` that is only evaluated once. Like
  614. :class:`werkzeug.utils.cached_property` except access uses a lock
  615. for thread safety.
  616. .. versionchanged:: 2.0
  617. Inherits from Werkzeug's ``cached_property`` (and ``property``).
  618. """
  619. def __init__(
  620. self,
  621. fget: t.Callable[[t.Any], t.Any],
  622. name: t.Optional[str] = None,
  623. doc: t.Optional[str] = None,
  624. ) -> None:
  625. super().__init__(fget, name=name, doc=doc)
  626. self.lock = RLock()
  627. def __get__(self, obj: object, type: type = None) -> t.Any: # type: ignore
  628. if obj is None:
  629. return self
  630. with self.lock:
  631. return super().__get__(obj, type=type)
  632. def __set__(self, obj: object, value: t.Any) -> None:
  633. with self.lock:
  634. super().__set__(obj, value)
  635. def __delete__(self, obj: object) -> None:
  636. with self.lock:
  637. super().__delete__(obj)
  638. def total_seconds(td: timedelta) -> int:
  639. """Returns the total seconds from a timedelta object.
  640. :param timedelta td: the timedelta to be converted in seconds
  641. :returns: number of seconds
  642. :rtype: int
  643. .. deprecated:: 2.0
  644. Will be removed in Flask 2.1. Use
  645. :meth:`timedelta.total_seconds` instead.
  646. """
  647. warnings.warn(
  648. "'total_seconds' is deprecated and will be removed in Flask"
  649. " 2.1. Use 'timedelta.total_seconds' instead.",
  650. DeprecationWarning,
  651. stacklevel=2,
  652. )
  653. return td.days * 60 * 60 * 24 + td.seconds
  654. def is_ip(value: str) -> bool:
  655. """Determine if the given string is an IP address.
  656. :param value: value to check
  657. :type value: str
  658. :return: True if string is an IP address
  659. :rtype: bool
  660. """
  661. for family in (socket.AF_INET, socket.AF_INET6):
  662. try:
  663. socket.inet_pton(family, value)
  664. except OSError:
  665. pass
  666. else:
  667. return True
  668. return False
  669. @lru_cache(maxsize=None)
  670. def _split_blueprint_path(name: str) -> t.List[str]:
  671. out: t.List[str] = [name]
  672. if "." in name:
  673. out.extend(_split_blueprint_path(name.rpartition(".")[0]))
  674. return out