helpers.py 25 KB

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