id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
174,809
from __future__ import annotations import ast import inspect import os import platform import re import sys import traceback import typing as t from functools import update_wrapper from operator import attrgetter import click from click.core import ParameterSource from werkzeug import run_simple from werkzeug.serving import is_running_from_reloader from werkzeug.utils import import_string from .globals import current_app from .helpers import get_debug_flag from .helpers import get_load_dotenv The provided code snippet includes necessary dependencies for implementing the `prepare_import` function. Write a Python function `def prepare_import(path)` to solve the following problem: Given a filename this will try to calculate the python path, add it to the search path and return the actual module name that is expected. Here is the function: def prepare_import(path): """Given a filename this will try to calculate the python path, add it to the search path and return the actual module name that is expected. """ path = os.path.realpath(path) fname, ext = os.path.splitext(path) if ext == ".py": path = fname if os.path.basename(path) == "__init__": path = os.path.dirname(path) module_name = [] # move up until outside package structure (no __init__.py) while True: path, name = os.path.split(path) module_name.append(name) if not os.path.exists(os.path.join(path, "__init__.py")): break if sys.path[0] != path: sys.path.insert(0, path) return ".".join(module_name[::-1])
Given a filename this will try to calculate the python path, add it to the search path and return the actual module name that is expected.
174,810
from __future__ import annotations import ast import inspect import os import platform import re import sys import traceback import typing as t from functools import update_wrapper from operator import attrgetter import click from click.core import ParameterSource from werkzeug import run_simple from werkzeug.serving import is_running_from_reloader from werkzeug.utils import import_string from .globals import current_app from .helpers import get_debug_flag from .helpers import get_load_dotenv class NoAppException(click.UsageError): """Raised if an application cannot be found or loaded.""" def find_best_app(module): """Given a module instance this tries to find the best possible application in the module or raises an exception. """ from . import Flask # Search for the most common names first. for attr_name in ("app", "application"): app = getattr(module, attr_name, None) if isinstance(app, Flask): return app # Otherwise find the only object that is a Flask instance. matches = [v for v in module.__dict__.values() if isinstance(v, Flask)] if len(matches) == 1: return matches[0] elif len(matches) > 1: raise NoAppException( "Detected multiple Flask applications in module" f" '{module.__name__}'. Use '{module.__name__}:name'" " to specify the correct one." ) # Search for app factory functions. for attr_name in ("create_app", "make_app"): app_factory = getattr(module, attr_name, None) if inspect.isfunction(app_factory): try: app = app_factory() if isinstance(app, Flask): return app except TypeError as e: if not _called_with_wrong_args(app_factory): raise raise NoAppException( f"Detected factory '{attr_name}' in module '{module.__name__}'," " but could not call it without arguments. Use" f" '{module.__name__}:{attr_name}(args)'" " to specify arguments." ) from e raise NoAppException( "Failed to find Flask application or factory in module" f" '{module.__name__}'. Use '{module.__name__}:name'" " to specify one." ) def find_app_by_string(module, app_name): """Check if the given string is a variable name or a function. Call a function to get the app instance, or return the variable directly. """ from . import Flask # Parse app_name as a single expression to determine if it's a valid # attribute name or function call. try: expr = ast.parse(app_name.strip(), mode="eval").body except SyntaxError: raise NoAppException( f"Failed to parse {app_name!r} as an attribute name or function call." ) from None if isinstance(expr, ast.Name): name = expr.id args = [] kwargs = {} elif isinstance(expr, ast.Call): # Ensure the function name is an attribute name only. if not isinstance(expr.func, ast.Name): raise NoAppException( f"Function reference must be a simple name: {app_name!r}." ) name = expr.func.id # Parse the positional and keyword arguments as literals. try: args = [ast.literal_eval(arg) for arg in expr.args] kwargs = {kw.arg: ast.literal_eval(kw.value) for kw in expr.keywords} except ValueError: # literal_eval gives cryptic error messages, show a generic # message with the full expression instead. raise NoAppException( f"Failed to parse arguments as literal values: {app_name!r}." ) from None else: raise NoAppException( f"Failed to parse {app_name!r} as an attribute name or function call." ) try: attr = getattr(module, name) except AttributeError as e: raise NoAppException( f"Failed to find attribute {name!r} in {module.__name__!r}." ) from e # If the attribute is a function, call it with any args and kwargs # to get the real application. if inspect.isfunction(attr): try: app = attr(*args, **kwargs) except TypeError as e: if not _called_with_wrong_args(attr): raise raise NoAppException( f"The factory {app_name!r} in module" f" {module.__name__!r} could not be called with the" " specified arguments." ) from e else: app = attr if isinstance(app, Flask): return app raise NoAppException( "A valid Flask application was not obtained from" f" '{module.__name__}:{app_name}'." ) def locate_app(module_name, app_name, raise_if_not_found=True): try: __import__(module_name) except ImportError: # Reraise the ImportError if it occurred within the imported module. # Determine this by checking whether the trace has a depth > 1. if sys.exc_info()[2].tb_next: raise NoAppException( f"While importing {module_name!r}, an ImportError was" f" raised:\n\n{traceback.format_exc()}" ) from None elif raise_if_not_found: raise NoAppException(f"Could not import {module_name!r}.") from None else: return module = sys.modules[module_name] if app_name is None: return find_best_app(module) else: return find_app_by_string(module, app_name)
null
174,811
from __future__ import annotations import ast import inspect import os import platform import re import sys import traceback import typing as t from functools import update_wrapper from operator import attrgetter import click from click.core import ParameterSource from werkzeug import run_simple from werkzeug.serving import is_running_from_reloader from werkzeug.utils import import_string from .globals import current_app from .helpers import get_debug_flag from .helpers import get_load_dotenv def get_version(ctx, param, value): if not value or ctx.resilient_parsing: return import werkzeug from . import __version__ click.echo( f"Python {platform.python_version()}\n" f"Flask {__version__}\n" f"Werkzeug {werkzeug.__version__}", color=ctx.color, ) ctx.exit()
null
174,812
from __future__ import annotations import ast import inspect import os import platform import re import sys import traceback import typing as t from functools import update_wrapper from operator import attrgetter import click from click.core import ParameterSource from werkzeug import run_simple from werkzeug.serving import is_running_from_reloader from werkzeug.utils import import_string from .globals import current_app from .helpers import get_debug_flag from .helpers import get_load_dotenv class ScriptInfo: """Helper object to deal with Flask applications. This is usually not necessary to interface with as it's used internally in the dispatching to click. In future versions of Flask this object will most likely play a bigger role. Typically it's created automatically by the :class:`FlaskGroup` but you can also manually create it and pass it onwards as click object. """ def __init__( self, app_import_path: str | None = None, create_app: t.Callable[..., Flask] | None = None, set_debug_flag: bool = True, ) -> None: #: Optionally the import path for the Flask application. self.app_import_path = app_import_path #: Optionally a function that is passed the script info to create #: the instance of the application. self.create_app = create_app #: A dictionary with arbitrary data that can be associated with #: this script info. self.data: t.Dict[t.Any, t.Any] = {} self.set_debug_flag = set_debug_flag self._loaded_app: Flask | None = None def load_app(self) -> Flask: """Loads the Flask app (if not yet loaded) and returns it. Calling this multiple times will just result in the already loaded app to be returned. """ if self._loaded_app is not None: return self._loaded_app if self.create_app is not None: app = self.create_app() else: if self.app_import_path: path, name = ( re.split(r":(?![\\/])", self.app_import_path, 1) + [None] )[:2] import_name = prepare_import(path) app = locate_app(import_name, name) else: for path in ("wsgi.py", "app.py"): import_name = prepare_import(path) app = locate_app(import_name, None, raise_if_not_found=False) if app: break if not app: raise NoAppException( "Could not locate a Flask application. Use the" " 'flask --app' option, 'FLASK_APP' environment" " variable, or a 'wsgi.py' or 'app.py' file in the" " current directory." ) if self.set_debug_flag: # Update the app's debug flag through the descriptor so that # other values repopulate as well. app.debug = get_debug_flag() self._loaded_app = app return app def update_wrapper(wrapper: _T, wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> _T: ... current_app: "Flask" = LocalProxy( # type: ignore[assignment] _cv_app, "app", unbound_message=_no_app_msg ) The provided code snippet includes necessary dependencies for implementing the `with_appcontext` function. Write a Python function `def with_appcontext(f)` to solve the following problem: Wraps a callback so that it's guaranteed to be executed with the script's application context. Custom commands (and their options) registered under ``app.cli`` or ``blueprint.cli`` will always have an app context available, this decorator is not required in that case. .. versionchanged:: 2.2 The app context is active for subcommands as well as the decorated callback. The app context is always available to ``app.cli`` command and parameter callbacks. Here is the function: def with_appcontext(f): """Wraps a callback so that it's guaranteed to be executed with the script's application context. Custom commands (and their options) registered under ``app.cli`` or ``blueprint.cli`` will always have an app context available, this decorator is not required in that case. .. versionchanged:: 2.2 The app context is active for subcommands as well as the decorated callback. The app context is always available to ``app.cli`` command and parameter callbacks. """ @click.pass_context def decorator(__ctx, *args, **kwargs): if not current_app: app = __ctx.ensure_object(ScriptInfo).load_app() __ctx.with_resource(app.app_context()) return __ctx.invoke(f, *args, **kwargs) return update_wrapper(decorator, f)
Wraps a callback so that it's guaranteed to be executed with the script's application context. Custom commands (and their options) registered under ``app.cli`` or ``blueprint.cli`` will always have an app context available, this decorator is not required in that case. .. versionchanged:: 2.2 The app context is active for subcommands as well as the decorated callback. The app context is always available to ``app.cli`` command and parameter callbacks.
174,813
from __future__ import annotations import ast import inspect import os import platform import re import sys import traceback import typing as t from functools import update_wrapper from operator import attrgetter import click from click.core import ParameterSource from werkzeug import run_simple from werkzeug.serving import is_running_from_reloader from werkzeug.utils import import_string from .globals import current_app from .helpers import get_debug_flag from .helpers import get_load_dotenv class ScriptInfo: def __init__( self, app_import_path: str | None = None, create_app: t.Callable[..., Flask] | None = None, set_debug_flag: bool = True, ) -> None: def load_app(self) -> Flask: def _set_app(ctx: click.Context, param: click.Option, value: str | None) -> str | None: if value is None: return None info = ctx.ensure_object(ScriptInfo) info.app_import_path = value return value
null
174,814
from __future__ import annotations import ast import inspect import os import platform import re import sys import traceback import typing as t from functools import update_wrapper from operator import attrgetter import click from click.core import ParameterSource from werkzeug import run_simple from werkzeug.serving import is_running_from_reloader from werkzeug.utils import import_string from .globals import current_app from .helpers import get_debug_flag from .helpers import get_load_dotenv class ParameterSource(enum.Enum): def _set_debug(ctx: click.Context, param: click.Option, value: bool) -> bool | None: # If the flag isn't provided, it will default to False. Don't use # that, let debug be set by env in that case. source = ctx.get_parameter_source(param.name) # type: ignore[arg-type] if source is not None and source in ( ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP, ): return None # Set with env var instead of ScriptInfo.load so that it can be # accessed early during a factory function. os.environ["FLASK_DEBUG"] = "1" if value else "0" return value
null
174,815
from __future__ import annotations import ast import inspect import os import platform import re import sys import traceback import typing as t from functools import update_wrapper from operator import attrgetter import click from click.core import ParameterSource from werkzeug import run_simple from werkzeug.serving import is_running_from_reloader from werkzeug.utils import import_string from .globals import current_app from .helpers import get_debug_flag from .helpers import get_load_dotenv def load_dotenv(path: str | os.PathLike | None = None) -> bool: """Load "dotenv" files in order of precedence to set environment variables. If an env var is already set it is not overwritten, so earlier files in the list are preferred over later files. This is a no-op if `python-dotenv`_ is not installed. .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme :param path: Load the file at this location instead of searching. :return: ``True`` if a file was loaded. .. versionchanged:: 2.0 The current directory is not changed to the location of the loaded file. .. versionchanged:: 2.0 When loading the env files, set the default encoding to UTF-8. .. versionchanged:: 1.1.0 Returns ``False`` when python-dotenv is not installed, or when the given path isn't a file. .. versionadded:: 1.0 """ try: import dotenv except ImportError: if path or os.path.isfile(".env") or os.path.isfile(".flaskenv"): click.secho( " * Tip: There are .env or .flaskenv files present." ' Do "pip install python-dotenv" to use them.', fg="yellow", err=True, ) return False # Always return after attempting to load a given path, don't load # the default files. if path is not None: if os.path.isfile(path): return dotenv.load_dotenv(path, encoding="utf-8") return False loaded = False for name in (".env", ".flaskenv"): path = dotenv.find_dotenv(name, usecwd=True) if not path: continue dotenv.load_dotenv(path, encoding="utf-8") loaded = True return loaded # True if at least one file was located and loaded. def _env_file_callback( ctx: click.Context, param: click.Option, value: str | None ) -> str | None: if value is None: return None import importlib try: importlib.import_module("dotenv") except ImportError: raise click.BadParameter( "python-dotenv must be installed to load an env file.", ctx=ctx, param=param, ) from None # Don't check FLASK_SKIP_DOTENV, that only disables automatically # loading .env and .flaskenv files. load_dotenv(value) return value
null
174,816
from __future__ import annotations import ast import inspect import os import platform import re import sys import traceback import typing as t from functools import update_wrapper from operator import attrgetter import click from click.core import ParameterSource from werkzeug import run_simple from werkzeug.serving import is_running_from_reloader from werkzeug.utils import import_string from .globals import current_app from .helpers import get_debug_flag from .helpers import get_load_dotenv The provided code snippet includes necessary dependencies for implementing the `_path_is_ancestor` function. Write a Python function `def _path_is_ancestor(path, other)` to solve the following problem: Take ``other`` and remove the length of ``path`` from it. Then join it to ``path``. If it is the original value, ``path`` is an ancestor of ``other``. Here is the function: def _path_is_ancestor(path, other): """Take ``other`` and remove the length of ``path`` from it. Then join it to ``path``. If it is the original value, ``path`` is an ancestor of ``other``.""" return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other
Take ``other`` and remove the length of ``path`` from it. Then join it to ``path``. If it is the original value, ``path`` is an ancestor of ``other``.
174,817
from __future__ import annotations import ast import inspect import os import platform import re import sys import traceback import typing as t from functools import update_wrapper from operator import attrgetter import click from click.core import ParameterSource from werkzeug import run_simple from werkzeug.serving import is_running_from_reloader from werkzeug.utils import import_string from .globals import current_app from .helpers import get_debug_flag from .helpers import get_load_dotenv The provided code snippet includes necessary dependencies for implementing the `_validate_key` function. Write a Python function `def _validate_key(ctx, param, value)` to solve the following problem: The ``--key`` option must be specified when ``--cert`` is a file. Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed. Here is the function: def _validate_key(ctx, param, value): """The ``--key`` option must be specified when ``--cert`` is a file. Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed. """ cert = ctx.params.get("cert") is_adhoc = cert == "adhoc" try: import ssl except ImportError: is_context = False else: is_context = isinstance(cert, ssl.SSLContext) if value is not None: if is_adhoc: raise click.BadParameter( 'When "--cert" is "adhoc", "--key" is not used.', ctx, param ) if is_context: raise click.BadParameter( 'When "--cert" is an SSLContext object, "--key is not used.', ctx, param ) if not cert: raise click.BadParameter('"--cert" must also be specified.', ctx, param) ctx.params["cert"] = cert, value else: if cert and not (is_adhoc or is_context): raise click.BadParameter('Required when using "--cert".', ctx, param) return value
The ``--key`` option must be specified when ``--cert`` is a file. Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.
174,818
from __future__ import annotations import ast import inspect import os import platform import re import sys import traceback import typing as t from functools import update_wrapper from operator import attrgetter import click from click.core import ParameterSource from werkzeug import run_simple from werkzeug.serving import is_running_from_reloader from werkzeug.utils import import_string from .globals import current_app from .helpers import get_debug_flag from .helpers import get_load_dotenv def show_server_banner(debug, app_import_path): """Show extra startup messages the first time the server is run, ignoring the reloader. """ if is_running_from_reloader(): return if app_import_path is not None: click.echo(f" * Serving Flask app '{app_import_path}'") if debug is not None: click.echo(f" * Debug mode: {'on' if debug else 'off'}") def is_running_from_reloader() -> bool: """Check if the server is running as a subprocess within the Werkzeug reloader. .. versionadded:: 0.10 """ return os.environ.get("WERKZEUG_RUN_MAIN") == "true" def get_debug_flag() -> bool: """Get whether debug mode should be enabled for the app, indicated by the :envvar:`FLASK_DEBUG` environment variable. The default is ``False``. """ val = os.environ.get("FLASK_DEBUG") if not val: env = os.environ.get("FLASK_ENV") if env is not None: print( "'FLASK_ENV' is deprecated and will not be used in" " Flask 2.3. Use 'FLASK_DEBUG' instead.", file=sys.stderr, ) return env == "development" return False return val.lower() not in {"0", "false", "no"} The provided code snippet includes necessary dependencies for implementing the `run_command` function. Write a Python function `def run_command( info, host, port, reload, debugger, with_threads, cert, extra_files, exclude_patterns, )` to solve the following problem: Run a local development server. This server is for development purposes only. It does not provide the stability, security, or performance of production WSGI servers. The reloader and debugger are enabled by default with the '--debug' option. Here is the function: def run_command( info, host, port, reload, debugger, with_threads, cert, extra_files, exclude_patterns, ): """Run a local development server. This server is for development purposes only. It does not provide the stability, security, or performance of production WSGI servers. The reloader and debugger are enabled by default with the '--debug' option. """ try: app = info.load_app() except Exception as e: if is_running_from_reloader(): # When reloading, print out the error immediately, but raise # it later so the debugger or server can handle it. traceback.print_exc() err = e def app(environ, start_response): raise err from None else: # When not reloading, raise the error immediately so the # command fails. raise e from None debug = get_debug_flag() if reload is None: reload = debug if debugger is None: debugger = debug show_server_banner(debug, info.app_import_path) run_simple( host, port, app, use_reloader=reload, use_debugger=debugger, threaded=with_threads, ssl_context=cert, extra_files=extra_files, exclude_patterns=exclude_patterns, )
Run a local development server. This server is for development purposes only. It does not provide the stability, security, or performance of production WSGI servers. The reloader and debugger are enabled by default with the '--debug' option.
174,819
from __future__ import annotations import ast import inspect import os import platform import re import sys import traceback import typing as t from functools import update_wrapper from operator import attrgetter import click from click.core import ParameterSource from werkzeug import run_simple from werkzeug.serving import is_running_from_reloader from werkzeug.utils import import_string from .globals import current_app from .helpers import get_debug_flag from .helpers import get_load_dotenv current_app: "Flask" = LocalProxy( # type: ignore[assignment] _cv_app, "app", unbound_message=_no_app_msg ) class Completer: def __init__(self, namespace: Optional[Dict[str, Any]] = ...) -> None: ... def complete(self, text: _Text, state: int) -> Optional[str]: ... The provided code snippet includes necessary dependencies for implementing the `shell_command` function. Write a Python function `def shell_command() -> None` to solve the following problem: Run an interactive Python shell in the context of a given Flask application. The application will populate the default namespace of this shell according to its configuration. This is useful for executing small snippets of management code without having to manually configure the application. Here is the function: def shell_command() -> None: """Run an interactive Python shell in the context of a given Flask application. The application will populate the default namespace of this shell according to its configuration. This is useful for executing small snippets of management code without having to manually configure the application. """ import code banner = ( f"Python {sys.version} on {sys.platform}\n" f"App: {current_app.import_name}\n" f"Instance: {current_app.instance_path}" ) ctx: dict = {} # Support the regular Python interpreter startup script if someone # is using it. startup = os.environ.get("PYTHONSTARTUP") if startup and os.path.isfile(startup): with open(startup) as f: eval(compile(f.read(), startup, "exec"), ctx) ctx.update(current_app.make_shell_context()) # Site, customize, or startup script can set a hook to call when # entering interactive mode. The default one sets up readline with # tab and history completion. interactive_hook = getattr(sys, "__interactivehook__", None) if interactive_hook is not None: try: import readline from rlcompleter import Completer except ImportError: pass else: # rlcompleter uses __main__.__dict__ by default, which is # flask.__main__. Use the shell context instead. readline.set_completer(Completer(ctx).complete) interactive_hook() code.interact(banner=banner, local=ctx)
Run an interactive Python shell in the context of a given Flask application. The application will populate the default namespace of this shell according to its configuration. This is useful for executing small snippets of management code without having to manually configure the application.
174,820
from __future__ import annotations import ast import inspect import os import platform import re import sys import traceback import typing as t from functools import update_wrapper from operator import attrgetter import click from click.core import ParameterSource from werkzeug import run_simple from werkzeug.serving import is_running_from_reloader from werkzeug.utils import import_string from .globals import current_app from .helpers import get_debug_flag from .helpers import get_load_dotenv def attrgetter(attr: str) -> Callable[[Any], Any]: ... def attrgetter(*attrs: str) -> Callable[[Any], Tuple[Any, ...]]: ... current_app: "Flask" = LocalProxy( # type: ignore[assignment] _cv_app, "app", unbound_message=_no_app_msg ) The provided code snippet includes necessary dependencies for implementing the `routes_command` function. Write a Python function `def routes_command(sort: str, all_methods: bool) -> None` to solve the following problem: Show all registered routes with endpoints and methods. Here is the function: def routes_command(sort: str, all_methods: bool) -> None: """Show all registered routes with endpoints and methods.""" rules = list(current_app.url_map.iter_rules()) if not rules: click.echo("No routes were registered.") return ignored_methods = set(() if all_methods else ("HEAD", "OPTIONS")) if sort in ("endpoint", "rule"): rules = sorted(rules, key=attrgetter(sort)) elif sort == "methods": rules = sorted(rules, key=lambda rule: sorted(rule.methods)) # type: ignore rule_methods = [ ", ".join(sorted(rule.methods - ignored_methods)) # type: ignore for rule in rules ] headers = ("Endpoint", "Methods", "Rule") widths = ( max(len(rule.endpoint) for rule in rules), max(len(methods) for methods in rule_methods), max(len(rule.rule) for rule in rules), ) widths = [max(len(h), w) for h, w in zip(headers, widths)] row = "{{0:<{0}}} {{1:<{1}}} {{2:<{2}}}".format(*widths) click.echo(row.format(*headers).strip()) click.echo(row.format(*("-" * width for width in widths))) for rule, methods in zip(rules, rule_methods): click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())
Show all registered routes with endpoints and methods.
174,821
import typing as t from .app import Flask from .blueprints import Blueprint from .globals import request_ctx class DebugFilesKeyError(KeyError, AssertionError): """Raised from request.files during debugging. The idea is that it can provide a better error message than just a generic KeyError/BadRequest. """ def __init__(self, request, key): form_matches = request.form.getlist(key) buf = [ f"You tried to access the file {key!r} in the request.files" " dictionary but it does not exist. The mimetype for the" f" request is {request.mimetype!r} instead of" " 'multipart/form-data' which means that no file contents" " were transmitted. To fix this error you should provide" ' enctype="multipart/form-data" in your form.' ] if form_matches: names = ", ".join(repr(x) for x in form_matches) buf.append( "\n\nThe browser instead transmitted some file names. " f"This was submitted: {names}" ) self.msg = "".join(buf) def __str__(self): return self.msg The provided code snippet includes necessary dependencies for implementing the `attach_enctype_error_multidict` function. Write a Python function `def attach_enctype_error_multidict(request)` to solve the following problem: Patch ``request.files.__getitem__`` to raise a descriptive error about ``enctype=multipart/form-data``. :param request: The request to patch. :meta private: Here is the function: def attach_enctype_error_multidict(request): """Patch ``request.files.__getitem__`` to raise a descriptive error about ``enctype=multipart/form-data``. :param request: The request to patch. :meta private: """ oldcls = request.files.__class__ class newcls(oldcls): def __getitem__(self, key): try: return super().__getitem__(key) except KeyError as e: if key not in request.form: raise raise DebugFilesKeyError(request, key).with_traceback( e.__traceback__ ) from None newcls.__name__ = oldcls.__name__ newcls.__module__ = oldcls.__module__ request.files.__class__ = newcls
Patch ``request.files.__getitem__`` to raise a descriptive error about ``enctype=multipart/form-data``. :param request: The request to patch. :meta private:
174,822
import typing as t from .app import Flask from .blueprints import Blueprint from .globals import request_ctx def _dump_loader_info(loader) -> t.Generator: yield f"class: {type(loader).__module__}.{type(loader).__name__}" for key, value in sorted(loader.__dict__.items()): if key.startswith("_"): continue if isinstance(value, (tuple, list)): if not all(isinstance(x, str) for x in value): continue yield f"{key}:" for item in value: yield f" - {item}" continue elif not isinstance(value, (str, int, float, bool)): continue yield f"{key}: {value!r}" class Flask(Scaffold): """The flask object implements a WSGI application and acts as the central object. It is passed the name of the module or package of the application. Once it is created it will act as a central registry for the view functions, the URL rules, template configuration and much more. The name of the package is used to resolve resources from inside the package or the folder the module is contained in depending on if the package parameter resolves to an actual python package (a folder with an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file). For more information about resource loading, see :func:`open_resource`. Usually you create a :class:`Flask` instance in your main module or in the :file:`__init__.py` file of your package like this:: from flask import Flask app = Flask(__name__) .. admonition:: About the First Parameter The idea of the first parameter is to give Flask an idea of what belongs to your application. This name is used to find resources on the filesystem, can be used by extensions to improve debugging information and a lot more. So it's important what you provide there. If you are using a single module, `__name__` is always the correct value. If you however are using a package, it's usually recommended to hardcode the name of your package there. For example if your application is defined in :file:`yourapplication/app.py` you should create it with one of the two versions below:: app = Flask('yourapplication') app = Flask(__name__.split('.')[0]) Why is that? The application will work even with `__name__`, thanks to how resources are looked up. However it will make debugging more painful. Certain extensions can make assumptions based on the import name of your application. For example the Flask-SQLAlchemy extension will look for the code in your application that triggered an SQL query in debug mode. If the import name is not properly set up, that debugging information is lost. (For example it would only pick up SQL queries in `yourapplication.app` and not `yourapplication.views.frontend`) .. versionadded:: 0.7 The `static_url_path`, `static_folder`, and `template_folder` parameters were added. .. versionadded:: 0.8 The `instance_path` and `instance_relative_config` parameters were added. .. versionadded:: 0.11 The `root_path` parameter was added. .. versionadded:: 1.0 The ``host_matching`` and ``static_host`` parameters were added. .. versionadded:: 1.0 The ``subdomain_matching`` parameter was added. Subdomain matching needs to be enabled manually now. Setting :data:`SERVER_NAME` does not implicitly enable it. :param import_name: the name of the application package :param static_url_path: can be used to specify a different path for the static files on the web. Defaults to the name of the `static_folder` folder. :param static_folder: The folder with static files that is served at ``static_url_path``. Relative to the application ``root_path`` or an absolute path. Defaults to ``'static'``. :param static_host: the host to use when adding the static route. Defaults to None. Required when using ``host_matching=True`` with a ``static_folder`` configured. :param host_matching: set ``url_map.host_matching`` attribute. Defaults to False. :param subdomain_matching: consider the subdomain relative to :data:`SERVER_NAME` when matching routes. Defaults to False. :param template_folder: the folder that contains the templates that should be used by the application. Defaults to ``'templates'`` folder in the root path of the application. :param instance_path: An alternative instance path for the application. By default the folder ``'instance'`` next to the package or module is assumed to be the instance path. :param instance_relative_config: if set to ``True`` relative filenames for loading the config are assumed to be relative to the instance path instead of the application root. :param root_path: The path to the root of the application files. This should only be set manually when it can't be detected automatically, such as for namespace packages. """ #: The class that is used for request objects. See :class:`~flask.Request` #: for more information. request_class = Request #: The class that is used for response objects. See #: :class:`~flask.Response` for more information. response_class = Response #: The class of the object assigned to :attr:`aborter`, created by #: :meth:`create_aborter`. That object is called by #: :func:`flask.abort` to raise HTTP errors, and can be #: called directly as well. #: #: Defaults to :class:`werkzeug.exceptions.Aborter`. #: #: .. versionadded:: 2.2 aborter_class = Aborter #: The class that is used for the Jinja environment. #: #: .. versionadded:: 0.11 jinja_environment = Environment #: The class that is used for the :data:`~flask.g` instance. #: #: Example use cases for a custom class: #: #: 1. Store arbitrary attributes on flask.g. #: 2. Add a property for lazy per-request database connectors. #: 3. Return None instead of AttributeError on unexpected attributes. #: 4. Raise exception if an unexpected attr is set, a "controlled" flask.g. #: #: In Flask 0.9 this property was called `request_globals_class` but it #: was changed in 0.10 to :attr:`app_ctx_globals_class` because the #: flask.g object is now application context scoped. #: #: .. versionadded:: 0.10 app_ctx_globals_class = _AppCtxGlobals #: The class that is used for the ``config`` attribute of this app. #: Defaults to :class:`~flask.Config`. #: #: Example use cases for a custom class: #: #: 1. Default values for certain config options. #: 2. Access to config values through attributes in addition to keys. #: #: .. versionadded:: 0.11 config_class = Config #: The testing flag. Set this to ``True`` to enable the test mode of #: Flask extensions (and in the future probably also Flask itself). #: For example this might activate test helpers that have an #: additional runtime cost which should not be enabled by default. #: #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the #: default it's implicitly enabled. #: #: This attribute can also be configured from the config with the #: ``TESTING`` configuration key. Defaults to ``False``. testing = ConfigAttribute("TESTING") #: If a secret key is set, cryptographic components can use this to #: sign cookies and other things. Set this to a complex random value #: when you want to use the secure cookie for instance. #: #: This attribute can also be configured from the config with the #: :data:`SECRET_KEY` configuration key. Defaults to ``None``. secret_key = ConfigAttribute("SECRET_KEY") def session_cookie_name(self) -> str: """The name of the cookie set by the session interface. .. deprecated:: 2.2 Will be removed in Flask 2.3. Use ``app.config["SESSION_COOKIE_NAME"]`` instead. """ import warnings warnings.warn( "'session_cookie_name' is deprecated and will be removed in Flask 2.3. Use" " 'SESSION_COOKIE_NAME' in 'app.config' instead.", DeprecationWarning, stacklevel=2, ) return self.config["SESSION_COOKIE_NAME"] def session_cookie_name(self, value: str) -> None: import warnings warnings.warn( "'session_cookie_name' is deprecated and will be removed in Flask 2.3. Use" " 'SESSION_COOKIE_NAME' in 'app.config' instead.", DeprecationWarning, stacklevel=2, ) self.config["SESSION_COOKIE_NAME"] = value #: A :class:`~datetime.timedelta` which is used to set the expiration #: date of a permanent session. The default is 31 days which makes a #: permanent session survive for roughly one month. #: #: This attribute can also be configured from the config with the #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to #: ``timedelta(days=31)`` permanent_session_lifetime = ConfigAttribute( "PERMANENT_SESSION_LIFETIME", get_converter=_make_timedelta ) def send_file_max_age_default(self) -> t.Optional[timedelta]: """The default value for ``max_age`` for :func:`~flask.send_file`. The default is ``None``, which tells the browser to use conditional requests instead of a timed cache. .. deprecated:: 2.2 Will be removed in Flask 2.3. Use ``app.config["SEND_FILE_MAX_AGE_DEFAULT"]`` instead. .. versionchanged:: 2.0 Defaults to ``None`` instead of 12 hours. """ import warnings warnings.warn( "'send_file_max_age_default' is deprecated and will be removed in Flask" " 2.3. Use 'SEND_FILE_MAX_AGE_DEFAULT' in 'app.config' instead.", DeprecationWarning, stacklevel=2, ) return _make_timedelta(self.config["SEND_FILE_MAX_AGE_DEFAULT"]) def send_file_max_age_default(self, value: t.Union[int, timedelta, None]) -> None: import warnings warnings.warn( "'send_file_max_age_default' is deprecated and will be removed in Flask" " 2.3. Use 'SEND_FILE_MAX_AGE_DEFAULT' in 'app.config' instead.", DeprecationWarning, stacklevel=2, ) self.config["SEND_FILE_MAX_AGE_DEFAULT"] = _make_timedelta(value) def use_x_sendfile(self) -> bool: """Enable this to use the ``X-Sendfile`` feature, assuming the server supports it, from :func:`~flask.send_file`. .. deprecated:: 2.2 Will be removed in Flask 2.3. Use ``app.config["USE_X_SENDFILE"]`` instead. """ import warnings warnings.warn( "'use_x_sendfile' is deprecated and will be removed in Flask 2.3. Use" " 'USE_X_SENDFILE' in 'app.config' instead.", DeprecationWarning, stacklevel=2, ) return self.config["USE_X_SENDFILE"] def use_x_sendfile(self, value: bool) -> None: import warnings warnings.warn( "'use_x_sendfile' is deprecated and will be removed in Flask 2.3. Use" " 'USE_X_SENDFILE' in 'app.config' instead.", DeprecationWarning, stacklevel=2, ) self.config["USE_X_SENDFILE"] = value _json_encoder: t.Union[t.Type[json.JSONEncoder], None] = None _json_decoder: t.Union[t.Type[json.JSONDecoder], None] = None def json_encoder(self) -> t.Type[json.JSONEncoder]: """The JSON encoder class to use. Defaults to :class:`~flask.json.JSONEncoder`. .. deprecated:: 2.2 Will be removed in Flask 2.3. Customize :attr:`json_provider_class` instead. .. versionadded:: 0.10 """ import warnings warnings.warn( "'app.json_encoder' is deprecated and will be removed in Flask 2.3." " Customize 'app.json_provider_class' or 'app.json' instead.", DeprecationWarning, stacklevel=2, ) if self._json_encoder is None: from . import json return json.JSONEncoder return self._json_encoder def json_encoder(self, value: t.Type[json.JSONEncoder]) -> None: import warnings warnings.warn( "'app.json_encoder' is deprecated and will be removed in Flask 2.3." " Customize 'app.json_provider_class' or 'app.json' instead.", DeprecationWarning, stacklevel=2, ) self._json_encoder = value def json_decoder(self) -> t.Type[json.JSONDecoder]: """The JSON decoder class to use. Defaults to :class:`~flask.json.JSONDecoder`. .. deprecated:: 2.2 Will be removed in Flask 2.3. Customize :attr:`json_provider_class` instead. .. versionadded:: 0.10 """ import warnings warnings.warn( "'app.json_decoder' is deprecated and will be removed in Flask 2.3." " Customize 'app.json_provider_class' or 'app.json' instead.", DeprecationWarning, stacklevel=2, ) if self._json_decoder is None: from . import json return json.JSONDecoder return self._json_decoder def json_decoder(self, value: t.Type[json.JSONDecoder]) -> None: import warnings warnings.warn( "'app.json_decoder' is deprecated and will be removed in Flask 2.3." " Customize 'app.json_provider_class' or 'app.json' instead.", DeprecationWarning, stacklevel=2, ) self._json_decoder = value json_provider_class: t.Type[JSONProvider] = DefaultJSONProvider """A subclass of :class:`~flask.json.provider.JSONProvider`. An instance is created and assigned to :attr:`app.json` when creating the app. The default, :class:`~flask.json.provider.DefaultJSONProvider`, uses Python's built-in :mod:`json` library. A different provider can use a different JSON library. .. versionadded:: 2.2 """ #: Options that are passed to the Jinja environment in #: :meth:`create_jinja_environment`. Changing these options after #: the environment is created (accessing :attr:`jinja_env`) will #: have no effect. #: #: .. versionchanged:: 1.1.0 #: This is a ``dict`` instead of an ``ImmutableDict`` to allow #: easier configuration. #: jinja_options: dict = {} #: Default configuration parameters. default_config = ImmutableDict( { "ENV": None, "DEBUG": None, "TESTING": False, "PROPAGATE_EXCEPTIONS": None, "SECRET_KEY": None, "PERMANENT_SESSION_LIFETIME": timedelta(days=31), "USE_X_SENDFILE": False, "SERVER_NAME": None, "APPLICATION_ROOT": "/", "SESSION_COOKIE_NAME": "session", "SESSION_COOKIE_DOMAIN": None, "SESSION_COOKIE_PATH": None, "SESSION_COOKIE_HTTPONLY": True, "SESSION_COOKIE_SECURE": False, "SESSION_COOKIE_SAMESITE": None, "SESSION_REFRESH_EACH_REQUEST": True, "MAX_CONTENT_LENGTH": None, "SEND_FILE_MAX_AGE_DEFAULT": None, "TRAP_BAD_REQUEST_ERRORS": None, "TRAP_HTTP_EXCEPTIONS": False, "EXPLAIN_TEMPLATE_LOADING": False, "PREFERRED_URL_SCHEME": "http", "JSON_AS_ASCII": None, "JSON_SORT_KEYS": None, "JSONIFY_PRETTYPRINT_REGULAR": None, "JSONIFY_MIMETYPE": None, "TEMPLATES_AUTO_RELOAD": None, "MAX_COOKIE_SIZE": 4093, } ) #: The rule object to use for URL rules created. This is used by #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`. #: #: .. versionadded:: 0.7 url_rule_class = Rule #: The map object to use for storing the URL rules and routing #: configuration parameters. Defaults to :class:`werkzeug.routing.Map`. #: #: .. versionadded:: 1.1.0 url_map_class = Map #: The :meth:`test_client` method creates an instance of this test #: client class. Defaults to :class:`~flask.testing.FlaskClient`. #: #: .. versionadded:: 0.7 test_client_class: t.Optional[t.Type["FlaskClient"]] = None #: The :class:`~click.testing.CliRunner` subclass, by default #: :class:`~flask.testing.FlaskCliRunner` that is used by #: :meth:`test_cli_runner`. Its ``__init__`` method should take a #: Flask app object as the first argument. #: #: .. versionadded:: 1.0 test_cli_runner_class: t.Optional[t.Type["FlaskCliRunner"]] = None #: the session interface to use. By default an instance of #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here. #: #: .. versionadded:: 0.8 session_interface: SessionInterface = SecureCookieSessionInterface() def __init__( self, import_name: str, static_url_path: t.Optional[str] = None, static_folder: t.Optional[t.Union[str, os.PathLike]] = "static", static_host: t.Optional[str] = None, host_matching: bool = False, subdomain_matching: bool = False, template_folder: t.Optional[t.Union[str, os.PathLike]] = "templates", instance_path: t.Optional[str] = None, instance_relative_config: bool = False, root_path: t.Optional[str] = None, ): super().__init__( import_name=import_name, static_folder=static_folder, static_url_path=static_url_path, template_folder=template_folder, root_path=root_path, ) if instance_path is None: instance_path = self.auto_find_instance_path() elif not os.path.isabs(instance_path): raise ValueError( "If an instance path is provided it must be absolute." " A relative path was given instead." ) #: Holds the path to the instance folder. #: #: .. versionadded:: 0.8 self.instance_path = instance_path #: The configuration dictionary as :class:`Config`. This behaves #: exactly like a regular dictionary but supports additional methods #: to load a config from files. self.config = self.make_config(instance_relative_config) #: An instance of :attr:`aborter_class` created by #: :meth:`make_aborter`. This is called by :func:`flask.abort` #: to raise HTTP errors, and can be called directly as well. #: #: .. versionadded:: 2.2 #: Moved from ``flask.abort``, which calls this object. self.aborter = self.make_aborter() self.json: JSONProvider = self.json_provider_class(self) """Provides access to JSON methods. Functions in ``flask.json`` will call methods on this provider when the application context is active. Used for handling JSON requests and responses. An instance of :attr:`json_provider_class`. Can be customized by changing that attribute on a subclass, or by assigning to this attribute afterwards. The default, :class:`~flask.json.provider.DefaultJSONProvider`, uses Python's built-in :mod:`json` library. A different provider can use a different JSON library. .. versionadded:: 2.2 """ #: A list of functions that are called by #: :meth:`handle_url_build_error` when :meth:`.url_for` raises a #: :exc:`~werkzeug.routing.BuildError`. Each function is called #: with ``error``, ``endpoint`` and ``values``. If a function #: returns ``None`` or raises a ``BuildError``, it is skipped. #: Otherwise, its return value is returned by ``url_for``. #: #: .. versionadded:: 0.9 self.url_build_error_handlers: t.List[ t.Callable[[Exception, str, t.Dict[str, t.Any]], str] ] = [] #: A list of functions that will be called at the beginning of the #: first request to this instance. To register a function, use the #: :meth:`before_first_request` decorator. #: #: .. deprecated:: 2.2 #: Will be removed in Flask 2.3. Run setup code when #: creating the application instead. #: #: .. versionadded:: 0.8 self.before_first_request_funcs: t.List[ft.BeforeFirstRequestCallable] = [] #: A list of functions that are called when the application context #: is destroyed. Since the application context is also torn down #: if the request ends this is the place to store code that disconnects #: from databases. #: #: .. versionadded:: 0.9 self.teardown_appcontext_funcs: t.List[ft.TeardownCallable] = [] #: A list of shell context processor functions that should be run #: when a shell context is created. #: #: .. versionadded:: 0.11 self.shell_context_processors: t.List[ft.ShellContextProcessorCallable] = [] #: Maps registered blueprint names to blueprint objects. The #: dict retains the order the blueprints were registered in. #: Blueprints can be registered multiple times, this dict does #: not track how often they were attached. #: #: .. versionadded:: 0.7 self.blueprints: t.Dict[str, "Blueprint"] = {} #: a place where extensions can store application specific state. For #: example this is where an extension could store database engines and #: similar things. #: #: The key must match the name of the extension module. For example in #: case of a "Flask-Foo" extension in `flask_foo`, the key would be #: ``'foo'``. #: #: .. versionadded:: 0.7 self.extensions: dict = {} #: The :class:`~werkzeug.routing.Map` for this instance. You can use #: this to change the routing converters after the class was created #: but before any routes are connected. Example:: #: #: from werkzeug.routing import BaseConverter #: #: class ListConverter(BaseConverter): #: def to_python(self, value): #: return value.split(',') #: def to_url(self, values): #: return ','.join(super(ListConverter, self).to_url(value) #: for value in values) #: #: app = Flask(__name__) #: app.url_map.converters['list'] = ListConverter self.url_map = self.url_map_class() self.url_map.host_matching = host_matching self.subdomain_matching = subdomain_matching # tracks internally if the application already handled at least one # request. self._got_first_request = False self._before_request_lock = Lock() # Add a static route using the provided static_url_path, static_host, # and static_folder if there is a configured static_folder. # Note we do this without checking if static_folder exists. # For one, it might be created while the server is running (e.g. during # development). Also, Google App Engine stores static files somewhere if self.has_static_folder: assert ( bool(static_host) == host_matching ), "Invalid static_host/host_matching combination" # Use a weakref to avoid creating a reference cycle between the app # and the view function (see #3761). self_ref = weakref.ref(self) self.add_url_rule( f"{self.static_url_path}/<path:filename>", endpoint="static", host=static_host, view_func=lambda **kw: self_ref().send_static_file(**kw), # type: ignore # noqa: B950 ) # Set the name of the Click group in case someone wants to add # the app's commands to another CLI tool. self.cli.name = self.name def _check_setup_finished(self, f_name: str) -> None: if self._got_first_request: raise AssertionError( f"The setup method '{f_name}' can no longer be called" " on the application. It has already handled its first" " request, any changes will not be applied" " consistently.\n" "Make sure all imports, decorators, functions, etc." " needed to set up the application are done before" " running it." ) def name(self) -> str: # type: ignore """The name of the application. This is usually the import name with the difference that it's guessed from the run file if the import name is main. This name is used as a display name when Flask needs the name of the application. It can be set and overridden to change the value. .. versionadded:: 0.8 """ if self.import_name == "__main__": fn = getattr(sys.modules["__main__"], "__file__", None) if fn is None: return "__main__" return os.path.splitext(os.path.basename(fn))[0] return self.import_name def propagate_exceptions(self) -> bool: """Returns the value of the ``PROPAGATE_EXCEPTIONS`` configuration value in case it's set, otherwise a sensible default is returned. .. deprecated:: 2.2 Will be removed in Flask 2.3. .. versionadded:: 0.7 """ import warnings warnings.warn( "'propagate_exceptions' is deprecated and will be removed in Flask 2.3.", DeprecationWarning, stacklevel=2, ) rv = self.config["PROPAGATE_EXCEPTIONS"] if rv is not None: return rv return self.testing or self.debug def logger(self) -> logging.Logger: """A standard Python :class:`~logging.Logger` for the app, with the same name as :attr:`name`. In debug mode, the logger's :attr:`~logging.Logger.level` will be set to :data:`~logging.DEBUG`. If there are no handlers configured, a default handler will be added. See :doc:`/logging` for more information. .. versionchanged:: 1.1.0 The logger takes the same name as :attr:`name` rather than hard-coding ``"flask.app"``. .. versionchanged:: 1.0.0 Behavior was simplified. The logger is always named ``"flask.app"``. The level is only set during configuration, it doesn't check ``app.debug`` each time. Only one format is used, not different ones depending on ``app.debug``. No handlers are removed, and a handler is only added if no handlers are already configured. .. versionadded:: 0.3 """ return create_logger(self) def jinja_env(self) -> Environment: """The Jinja environment used to load templates. The environment is created the first time this property is accessed. Changing :attr:`jinja_options` after that will have no effect. """ return self.create_jinja_environment() def got_first_request(self) -> bool: """This attribute is set to ``True`` if the application started handling the first request. .. versionadded:: 0.8 """ return self._got_first_request def make_config(self, instance_relative: bool = False) -> Config: """Used to create the config attribute by the Flask constructor. The `instance_relative` parameter is passed in from the constructor of Flask (there named `instance_relative_config`) and indicates if the config should be relative to the instance path or the root path of the application. .. versionadded:: 0.8 """ root_path = self.root_path if instance_relative: root_path = self.instance_path defaults = dict(self.default_config) defaults["ENV"] = os.environ.get("FLASK_ENV") or "production" defaults["DEBUG"] = get_debug_flag() return self.config_class(root_path, defaults) def make_aborter(self) -> Aborter: """Create the object to assign to :attr:`aborter`. That object is called by :func:`flask.abort` to raise HTTP errors, and can be called directly as well. By default, this creates an instance of :attr:`aborter_class`, which defaults to :class:`werkzeug.exceptions.Aborter`. .. versionadded:: 2.2 """ return self.aborter_class() def auto_find_instance_path(self) -> str: """Tries to locate the instance path if it was not provided to the constructor of the application class. It will basically calculate the path to a folder named ``instance`` next to your main file or the package. .. versionadded:: 0.8 """ prefix, package_path = find_package(self.import_name) if prefix is None: return os.path.join(package_path, "instance") return os.path.join(prefix, "var", f"{self.name}-instance") def open_instance_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]: """Opens a resource from the application's instance folder (:attr:`instance_path`). Otherwise works like :meth:`open_resource`. Instance resources can also be opened for writing. :param resource: the name of the resource. To access resources within subfolders use forward slashes as separator. :param mode: resource file opening mode, default is 'rb'. """ return open(os.path.join(self.instance_path, resource), mode) def templates_auto_reload(self) -> bool: """Reload templates when they are changed. Used by :meth:`create_jinja_environment`. It is enabled by default in debug mode. .. deprecated:: 2.2 Will be removed in Flask 2.3. Use ``app.config["TEMPLATES_AUTO_RELOAD"]`` instead. .. versionadded:: 1.0 This property was added but the underlying config and behavior already existed. """ import warnings warnings.warn( "'templates_auto_reload' is deprecated and will be removed in Flask 2.3." " Use 'TEMPLATES_AUTO_RELOAD' in 'app.config' instead.", DeprecationWarning, stacklevel=2, ) rv = self.config["TEMPLATES_AUTO_RELOAD"] return rv if rv is not None else self.debug def templates_auto_reload(self, value: bool) -> None: import warnings warnings.warn( "'templates_auto_reload' is deprecated and will be removed in Flask 2.3." " Use 'TEMPLATES_AUTO_RELOAD' in 'app.config' instead.", DeprecationWarning, stacklevel=2, ) self.config["TEMPLATES_AUTO_RELOAD"] = value def create_jinja_environment(self) -> Environment: """Create the Jinja environment based on :attr:`jinja_options` and the various Jinja-related methods of the app. Changing :attr:`jinja_options` after this will have no effect. Also adds Flask-related globals and filters to the environment. .. versionchanged:: 0.11 ``Environment.auto_reload`` set in accordance with ``TEMPLATES_AUTO_RELOAD`` configuration option. .. versionadded:: 0.5 """ options = dict(self.jinja_options) if "autoescape" not in options: options["autoescape"] = self.select_jinja_autoescape if "auto_reload" not in options: auto_reload = self.config["TEMPLATES_AUTO_RELOAD"] if auto_reload is None: auto_reload = self.debug options["auto_reload"] = auto_reload rv = self.jinja_environment(self, **options) rv.globals.update( url_for=self.url_for, get_flashed_messages=get_flashed_messages, config=self.config, # request, session and g are normally added with the # context processor for efficiency reasons but for imported # templates we also want the proxies in there. request=request, session=session, g=g, ) rv.policies["json.dumps_function"] = self.json.dumps return rv def create_global_jinja_loader(self) -> DispatchingJinjaLoader: """Creates the loader for the Jinja2 environment. Can be used to override just the loader and keeping the rest unchanged. It's discouraged to override this function. Instead one should override the :meth:`jinja_loader` function instead. The global loader dispatches between the loaders of the application and the individual blueprints. .. versionadded:: 0.7 """ return DispatchingJinjaLoader(self) def select_jinja_autoescape(self, filename: str) -> bool: """Returns ``True`` if autoescaping should be active for the given template name. If no template name is given, returns `True`. .. versionchanged:: 2.2 Autoescaping is now enabled by default for ``.svg`` files. .. versionadded:: 0.5 """ if filename is None: return True return filename.endswith((".html", ".htm", ".xml", ".xhtml", ".svg")) def update_template_context(self, context: dict) -> None: """Update the template context with some commonly used variables. This injects request, session, config and g into the template context as well as everything template context processors want to inject. Note that the as of Flask 0.6, the original values in the context will not be overridden if a context processor decides to return a value with the same key. :param context: the context as a dictionary that is updated in place to add extra variables. """ names: t.Iterable[t.Optional[str]] = (None,) # A template may be rendered outside a request context. if request: names = chain(names, reversed(request.blueprints)) # The values passed to render_template take precedence. Keep a # copy to re-apply after all context functions. orig_ctx = context.copy() for name in names: if name in self.template_context_processors: for func in self.template_context_processors[name]: context.update(func()) context.update(orig_ctx) def make_shell_context(self) -> dict: """Returns the shell context for an interactive shell for this application. This runs all the registered shell context processors. .. versionadded:: 0.11 """ rv = {"app": self, "g": g} for processor in self.shell_context_processors: rv.update(processor()) return rv def env(self) -> str: """What environment the app is running in. This maps to the :data:`ENV` config key. **Do not enable development when deploying in production.** Default: ``'production'`` .. deprecated:: 2.2 Will be removed in Flask 2.3. """ import warnings warnings.warn( "'app.env' is deprecated and will be removed in Flask 2.3." " Use 'app.debug' instead.", DeprecationWarning, stacklevel=2, ) return self.config["ENV"] def env(self, value: str) -> None: import warnings warnings.warn( "'app.env' is deprecated and will be removed in Flask 2.3." " Use 'app.debug' instead.", DeprecationWarning, stacklevel=2, ) self.config["ENV"] = value def debug(self) -> bool: """Whether debug mode is enabled. When using ``flask run`` to start the development server, an interactive debugger will be shown for unhandled exceptions, and the server will be reloaded when code changes. This maps to the :data:`DEBUG` config key. It may not behave as expected if set late. **Do not enable debug mode when deploying in production.** Default: ``False`` """ return self.config["DEBUG"] def debug(self, value: bool) -> None: self.config["DEBUG"] = value if self.config["TEMPLATES_AUTO_RELOAD"] is None: self.jinja_env.auto_reload = value def run( self, host: t.Optional[str] = None, port: t.Optional[int] = None, debug: t.Optional[bool] = None, load_dotenv: bool = True, **options: t.Any, ) -> None: """Runs the application on a local development server. Do not use ``run()`` in a production setting. It is not intended to meet security and performance requirements for a production server. Instead, see :doc:`/deploying/index` for WSGI server recommendations. If the :attr:`debug` flag is set the server will automatically reload for code changes and show a debugger in case an exception happened. If you want to run the application in debug mode, but disable the code execution on the interactive debugger, you can pass ``use_evalex=False`` as parameter. This will keep the debugger's traceback screen active, but disable code execution. It is not recommended to use this function for development with automatic reloading as this is badly supported. Instead you should be using the :command:`flask` command line script's ``run`` support. .. admonition:: Keep in Mind Flask will suppress any server error with a generic error page unless it is in debug mode. As such to enable just the interactive debugger without the code reloading, you have to invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``. Setting ``use_debugger`` to ``True`` without being in debug mode won't catch any exceptions because there won't be any to catch. :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to have the server available externally as well. Defaults to ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable if present. :param port: the port of the webserver. Defaults to ``5000`` or the port defined in the ``SERVER_NAME`` config variable if present. :param debug: if given, enable or disable debug mode. See :attr:`debug`. :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv` files to set environment variables. Will also change the working directory to the directory containing the first file found. :param options: the options to be forwarded to the underlying Werkzeug server. See :func:`werkzeug.serving.run_simple` for more information. .. versionchanged:: 1.0 If installed, python-dotenv will be used to load environment variables from :file:`.env` and :file:`.flaskenv` files. The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`. Threaded mode is enabled by default. .. versionchanged:: 0.10 The default port is now picked from the ``SERVER_NAME`` variable. """ # Ignore this call so that it doesn't start another server if # the 'flask run' command is used. if os.environ.get("FLASK_RUN_FROM_CLI") == "true": if not is_running_from_reloader(): click.secho( " * Ignoring a call to 'app.run()' that would block" " the current 'flask' CLI command.\n" " Only call 'app.run()' in an 'if __name__ ==" ' "__main__"\' guard.', fg="red", ) return if get_load_dotenv(load_dotenv): cli.load_dotenv() # if set, let env vars override previous values if "FLASK_ENV" in os.environ: print( "'FLASK_ENV' is deprecated and will not be used in" " Flask 2.3. Use 'FLASK_DEBUG' instead.", file=sys.stderr, ) self.config["ENV"] = os.environ.get("FLASK_ENV") or "production" self.debug = get_debug_flag() elif "FLASK_DEBUG" in os.environ: self.debug = get_debug_flag() # debug passed to method overrides all other sources if debug is not None: self.debug = bool(debug) server_name = self.config.get("SERVER_NAME") sn_host = sn_port = None if server_name: sn_host, _, sn_port = server_name.partition(":") if not host: if sn_host: host = sn_host else: host = "127.0.0.1" if port or port == 0: port = int(port) elif sn_port: port = int(sn_port) else: port = 5000 options.setdefault("use_reloader", self.debug) options.setdefault("use_debugger", self.debug) options.setdefault("threaded", True) cli.show_server_banner(self.debug, self.name) from werkzeug.serving import run_simple try: run_simple(t.cast(str, host), port, self, **options) finally: # reset the first request information if the development server # reset normally. This makes it possible to restart the server # without reloader and that stuff from an interactive shell. self._got_first_request = False def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> "FlaskClient": """Creates a test client for this application. For information about unit testing head over to :doc:`/testing`. Note that if you are testing for assertions or exceptions in your application code, you must set ``app.testing = True`` in order for the exceptions to propagate to the test client. Otherwise, the exception will be handled by the application (not visible to the test client) and the only indication of an AssertionError or other exception will be a 500 status code response to the test client. See the :attr:`testing` attribute. For example:: app.testing = True client = app.test_client() The test client can be used in a ``with`` block to defer the closing down of the context until the end of the ``with`` block. This is useful if you want to access the context locals for testing:: with app.test_client() as c: rv = c.get('/?vodka=42') assert request.args['vodka'] == '42' Additionally, you may pass optional keyword arguments that will then be passed to the application's :attr:`test_client_class` constructor. For example:: from flask.testing import FlaskClient class CustomClient(FlaskClient): def __init__(self, *args, **kwargs): self._authentication = kwargs.pop("authentication") super(CustomClient,self).__init__( *args, **kwargs) app.test_client_class = CustomClient client = app.test_client(authentication='Basic ....') See :class:`~flask.testing.FlaskClient` for more information. .. versionchanged:: 0.4 added support for ``with`` block usage for the client. .. versionadded:: 0.7 The `use_cookies` parameter was added as well as the ability to override the client to be used by setting the :attr:`test_client_class` attribute. .. versionchanged:: 0.11 Added `**kwargs` to support passing additional keyword arguments to the constructor of :attr:`test_client_class`. """ cls = self.test_client_class if cls is None: from .testing import FlaskClient as cls # type: ignore return cls( # type: ignore self, self.response_class, use_cookies=use_cookies, **kwargs ) def test_cli_runner(self, **kwargs: t.Any) -> "FlaskCliRunner": """Create a CLI runner for testing CLI commands. See :ref:`testing-cli`. Returns an instance of :attr:`test_cli_runner_class`, by default :class:`~flask.testing.FlaskCliRunner`. The Flask app object is passed as the first argument. .. versionadded:: 1.0 """ cls = self.test_cli_runner_class if cls is None: from .testing import FlaskCliRunner as cls # type: ignore return cls(self, **kwargs) # type: ignore def register_blueprint(self, blueprint: "Blueprint", **options: t.Any) -> None: """Register a :class:`~flask.Blueprint` on the application. Keyword arguments passed to this method will override the defaults set on the blueprint. Calls the blueprint's :meth:`~flask.Blueprint.register` method after recording the blueprint in the application's :attr:`blueprints`. :param blueprint: The blueprint to register. :param url_prefix: Blueprint routes will be prefixed with this. :param subdomain: Blueprint routes will match on this subdomain. :param url_defaults: Blueprint routes will use these default values for view arguments. :param options: Additional keyword arguments are passed to :class:`~flask.blueprints.BlueprintSetupState`. They can be accessed in :meth:`~flask.Blueprint.record` callbacks. .. versionchanged:: 2.0.1 The ``name`` option can be used to change the (pre-dotted) name the blueprint is registered with. This allows the same blueprint to be registered multiple times with unique names for ``url_for``. .. versionadded:: 0.7 """ blueprint.register(self, options) def iter_blueprints(self) -> t.ValuesView["Blueprint"]: """Iterates over all blueprints by the order they were registered. .. versionadded:: 0.11 """ return self.blueprints.values() def add_url_rule( self, rule: str, endpoint: t.Optional[str] = None, view_func: t.Optional[ft.RouteCallable] = None, provide_automatic_options: t.Optional[bool] = None, **options: t.Any, ) -> None: if endpoint is None: endpoint = _endpoint_from_view_func(view_func) # type: ignore options["endpoint"] = endpoint methods = options.pop("methods", None) # if the methods are not given and the view_func object knows its # methods we can use that instead. If neither exists, we go with # a tuple of only ``GET`` as default. if methods is None: methods = getattr(view_func, "methods", None) or ("GET",) if isinstance(methods, str): raise TypeError( "Allowed methods must be a list of strings, for" ' example: @app.route(..., methods=["POST"])' ) methods = {item.upper() for item in methods} # Methods that should always be added required_methods = set(getattr(view_func, "required_methods", ())) # starting with Flask 0.8 the view_func object can disable and # force-enable the automatic options handling. if provide_automatic_options is None: provide_automatic_options = getattr( view_func, "provide_automatic_options", None ) if provide_automatic_options is None: if "OPTIONS" not in methods: provide_automatic_options = True required_methods.add("OPTIONS") else: provide_automatic_options = False # Add the required methods now. methods |= required_methods rule = self.url_rule_class(rule, methods=methods, **options) rule.provide_automatic_options = provide_automatic_options # type: ignore self.url_map.add(rule) if view_func is not None: old_func = self.view_functions.get(endpoint) if old_func is not None and old_func != view_func: raise AssertionError( "View function mapping is overwriting an existing" f" endpoint function: {endpoint}" ) self.view_functions[endpoint] = view_func def template_filter( self, name: t.Optional[str] = None ) -> t.Callable[[T_template_filter], T_template_filter]: """A decorator that is used to register custom template filter. You can specify a name for the filter, otherwise the function name will be used. Example:: def reverse(s): return s[::-1] :param name: the optional name of the filter, otherwise the function name will be used. """ def decorator(f: T_template_filter) -> T_template_filter: self.add_template_filter(f, name=name) return f return decorator def add_template_filter( self, f: ft.TemplateFilterCallable, name: t.Optional[str] = None ) -> None: """Register a custom template filter. Works exactly like the :meth:`template_filter` decorator. :param name: the optional name of the filter, otherwise the function name will be used. """ self.jinja_env.filters[name or f.__name__] = f def template_test( self, name: t.Optional[str] = None ) -> t.Callable[[T_template_test], T_template_test]: """A decorator that is used to register custom template test. You can specify a name for the test, otherwise the function name will be used. Example:: def is_prime(n): if n == 2: return True for i in range(2, int(math.ceil(math.sqrt(n))) + 1): if n % i == 0: return False return True .. versionadded:: 0.10 :param name: the optional name of the test, otherwise the function name will be used. """ def decorator(f: T_template_test) -> T_template_test: self.add_template_test(f, name=name) return f return decorator def add_template_test( self, f: ft.TemplateTestCallable, name: t.Optional[str] = None ) -> None: """Register a custom template test. Works exactly like the :meth:`template_test` decorator. .. versionadded:: 0.10 :param name: the optional name of the test, otherwise the function name will be used. """ self.jinja_env.tests[name or f.__name__] = f def template_global( self, name: t.Optional[str] = None ) -> t.Callable[[T_template_global], T_template_global]: """A decorator that is used to register a custom template global function. You can specify a name for the global function, otherwise the function name will be used. Example:: def double(n): return 2 * n .. versionadded:: 0.10 :param name: the optional name of the global function, otherwise the function name will be used. """ def decorator(f: T_template_global) -> T_template_global: self.add_template_global(f, name=name) return f return decorator def add_template_global( self, f: ft.TemplateGlobalCallable, name: t.Optional[str] = None ) -> None: """Register a custom template global function. Works exactly like the :meth:`template_global` decorator. .. versionadded:: 0.10 :param name: the optional name of the global function, otherwise the function name will be used. """ self.jinja_env.globals[name or f.__name__] = f def before_first_request(self, f: T_before_first_request) -> T_before_first_request: """Registers a function to be run before the first request to this instance of the application. The function will be called without any arguments and its return value is ignored. .. deprecated:: 2.2 Will be removed in Flask 2.3. Run setup code when creating the application instead. .. versionadded:: 0.8 """ import warnings warnings.warn( "'before_first_request' is deprecated and will be removed" " in Flask 2.3. Run setup code while creating the" " application instead.", DeprecationWarning, stacklevel=2, ) self.before_first_request_funcs.append(f) return f def teardown_appcontext(self, f: T_teardown) -> T_teardown: """Registers a function to be called when the application context is popped. The application context is typically popped after the request context for each request, at the end of CLI commands, or after a manually pushed context ends. .. code-block:: python with app.app_context(): ... When the ``with`` block exits (or ``ctx.pop()`` is called), the teardown functions are called just before the app context is made inactive. Since a request context typically also manages an application context it would also be called when you pop a request context. When a teardown function was called because of an unhandled exception it will be passed an error object. If an :meth:`errorhandler` is registered, it will handle the exception and the teardown will not receive it. Teardown functions must avoid raising exceptions. If they execute code that might fail they must surround that code with a ``try``/``except`` block and log any errors. The return values of teardown functions are ignored. .. versionadded:: 0.9 """ self.teardown_appcontext_funcs.append(f) return f def shell_context_processor( self, f: T_shell_context_processor ) -> T_shell_context_processor: """Registers a shell context processor function. .. versionadded:: 0.11 """ self.shell_context_processors.append(f) return f def _find_error_handler(self, e: Exception) -> t.Optional[ft.ErrorHandlerCallable]: """Return a registered error handler for an exception in this order: blueprint handler for a specific code, app handler for a specific code, blueprint handler for an exception class, app handler for an exception class, or ``None`` if a suitable handler is not found. """ exc_class, code = self._get_exc_class_and_code(type(e)) names = (*request.blueprints, None) for c in (code, None) if code is not None else (None,): for name in names: handler_map = self.error_handler_spec[name][c] if not handler_map: continue for cls in exc_class.__mro__: handler = handler_map.get(cls) if handler is not None: return handler return None def handle_http_exception( self, e: HTTPException ) -> t.Union[HTTPException, ft.ResponseReturnValue]: """Handles an HTTP exception. By default this will invoke the registered error handlers and fall back to returning the exception as response. .. versionchanged:: 1.0.3 ``RoutingException``, used internally for actions such as slash redirects during routing, is not passed to error handlers. .. versionchanged:: 1.0 Exceptions are looked up by code *and* by MRO, so ``HTTPException`` subclasses can be handled with a catch-all handler for the base ``HTTPException``. .. versionadded:: 0.3 """ # Proxy exceptions don't have error codes. We want to always return # those unchanged as errors if e.code is None: return e # RoutingExceptions are used internally to trigger routing # actions, such as slash redirects raising RequestRedirect. They # are not raised or handled in user code. if isinstance(e, RoutingException): return e handler = self._find_error_handler(e) if handler is None: return e return self.ensure_sync(handler)(e) def trap_http_exception(self, e: Exception) -> bool: """Checks if an HTTP exception should be trapped or not. By default this will return ``False`` for all exceptions except for a bad request key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``. This is called for all HTTP exceptions raised by a view function. If it returns ``True`` for any exception the error handler for this exception is not called and it shows up as regular exception in the traceback. This is helpful for debugging implicitly raised HTTP exceptions. .. versionchanged:: 1.0 Bad request errors are not trapped by default in debug mode. .. versionadded:: 0.8 """ if self.config["TRAP_HTTP_EXCEPTIONS"]: return True trap_bad_request = self.config["TRAP_BAD_REQUEST_ERRORS"] # if unset, trap key errors in debug mode if ( trap_bad_request is None and self.debug and isinstance(e, BadRequestKeyError) ): return True if trap_bad_request: return isinstance(e, BadRequest) return False def handle_user_exception( self, e: Exception ) -> t.Union[HTTPException, ft.ResponseReturnValue]: """This method is called whenever an exception occurs that should be handled. A special case is :class:`~werkzeug .exceptions.HTTPException` which is forwarded to the :meth:`handle_http_exception` method. This function will either return a response value or reraise the exception with the same traceback. .. versionchanged:: 1.0 Key errors raised from request data like ``form`` show the bad key in debug mode rather than a generic bad request message. .. versionadded:: 0.7 """ if isinstance(e, BadRequestKeyError) and ( self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"] ): e.show_exception = True if isinstance(e, HTTPException) and not self.trap_http_exception(e): return self.handle_http_exception(e) handler = self._find_error_handler(e) if handler is None: raise return self.ensure_sync(handler)(e) def handle_exception(self, e: Exception) -> Response: """Handle an exception that did not have an error handler associated with it, or that was raised from an error handler. This always causes a 500 ``InternalServerError``. Always sends the :data:`got_request_exception` signal. If :attr:`propagate_exceptions` is ``True``, such as in debug mode, the error will be re-raised so that the debugger can display it. Otherwise, the original exception is logged, and an :exc:`~werkzeug.exceptions.InternalServerError` is returned. If an error handler is registered for ``InternalServerError`` or ``500``, it will be used. For consistency, the handler will always receive the ``InternalServerError``. The original unhandled exception is available as ``e.original_exception``. .. versionchanged:: 1.1.0 Always passes the ``InternalServerError`` instance to the handler, setting ``original_exception`` to the unhandled error. .. versionchanged:: 1.1.0 ``after_request`` functions and other finalization is done even for the default 500 response when there is no handler. .. versionadded:: 0.3 """ exc_info = sys.exc_info() got_request_exception.send(self, exception=e) propagate = self.config["PROPAGATE_EXCEPTIONS"] if propagate is None: propagate = self.testing or self.debug if propagate: # Re-raise if called with an active exception, otherwise # raise the passed in exception. if exc_info[1] is e: raise raise e self.log_exception(exc_info) server_error: t.Union[InternalServerError, ft.ResponseReturnValue] server_error = InternalServerError(original_exception=e) handler = self._find_error_handler(server_error) if handler is not None: server_error = self.ensure_sync(handler)(server_error) return self.finalize_request(server_error, from_error_handler=True) def log_exception( self, exc_info: t.Union[ t.Tuple[type, BaseException, TracebackType], t.Tuple[None, None, None] ], ) -> None: """Logs an exception. This is called by :meth:`handle_exception` if debugging is disabled and right before the handler is called. The default implementation logs the exception as error on the :attr:`logger`. .. versionadded:: 0.8 """ self.logger.error( f"Exception on {request.path} [{request.method}]", exc_info=exc_info ) def raise_routing_exception(self, request: Request) -> "te.NoReturn": """Intercept routing exceptions and possibly do something else. In debug mode, intercept a routing redirect and replace it with an error if the body will be discarded. With modern Werkzeug this shouldn't occur, since it now uses a 308 status which tells the browser to resend the method and body. .. versionchanged:: 2.1 Don't intercept 307 and 308 redirects. :meta private: :internal: """ if ( not self.debug or not isinstance(request.routing_exception, RequestRedirect) or request.routing_exception.code in {307, 308} or request.method in {"GET", "HEAD", "OPTIONS"} ): raise request.routing_exception # type: ignore from .debughelpers import FormDataRoutingRedirect raise FormDataRoutingRedirect(request) def dispatch_request(self) -> ft.ResponseReturnValue: """Does the request dispatching. Matches the URL and returns the return value of the view or error handler. This does not have to be a response object. In order to convert the return value to a proper response object, call :func:`make_response`. .. versionchanged:: 0.7 This no longer does the exception handling, this code was moved to the new :meth:`full_dispatch_request`. """ req = request_ctx.request if req.routing_exception is not None: self.raise_routing_exception(req) rule: Rule = req.url_rule # type: ignore[assignment] # if we provide automatic options for this URL and the # request came with the OPTIONS method, reply automatically if ( getattr(rule, "provide_automatic_options", False) and req.method == "OPTIONS" ): return self.make_default_options_response() # otherwise dispatch to the handler for that endpoint view_args: t.Dict[str, t.Any] = req.view_args # type: ignore[assignment] return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) def full_dispatch_request(self) -> Response: """Dispatches the request and on top of that performs request pre and postprocessing as well as HTTP exception catching and error handling. .. versionadded:: 0.7 """ # Run before_first_request functions if this is the thread's first request. # Inlined to avoid a method call on subsequent requests. # This is deprecated, will be removed in Flask 2.3. if not self._got_first_request: with self._before_request_lock: if not self._got_first_request: for func in self.before_first_request_funcs: self.ensure_sync(func)() self._got_first_request = True try: request_started.send(self) rv = self.preprocess_request() if rv is None: rv = self.dispatch_request() except Exception as e: rv = self.handle_user_exception(e) return self.finalize_request(rv) def finalize_request( self, rv: t.Union[ft.ResponseReturnValue, HTTPException], from_error_handler: bool = False, ) -> Response: """Given the return value from a view function this finalizes the request by converting it into a response and invoking the postprocessing functions. This is invoked for both normal request dispatching as well as error handlers. Because this means that it might be called as a result of a failure a special safe mode is available which can be enabled with the `from_error_handler` flag. If enabled, failures in response processing will be logged and otherwise ignored. :internal: """ response = self.make_response(rv) try: response = self.process_response(response) request_finished.send(self, response=response) except Exception: if not from_error_handler: raise self.logger.exception( "Request finalizing failed with an error while handling an error" ) return response def make_default_options_response(self) -> Response: """This method is called to create the default ``OPTIONS`` response. This can be changed through subclassing to change the default behavior of ``OPTIONS`` responses. .. versionadded:: 0.7 """ adapter = request_ctx.url_adapter methods = adapter.allowed_methods() # type: ignore[union-attr] rv = self.response_class() rv.allow.update(methods) return rv def should_ignore_error(self, error: t.Optional[BaseException]) -> bool: """This is called to figure out if an error should be ignored or not as far as the teardown system is concerned. If this function returns ``True`` then the teardown handlers will not be passed the error. .. versionadded:: 0.10 """ return False def ensure_sync(self, func: t.Callable) -> t.Callable: """Ensure that the function is synchronous for WSGI workers. Plain ``def`` functions are returned as-is. ``async def`` functions are wrapped to run and wait for the response. Override this method to change how the app runs async views. .. versionadded:: 2.0 """ if iscoroutinefunction(func): return self.async_to_sync(func) return func def async_to_sync( self, func: t.Callable[..., t.Coroutine] ) -> t.Callable[..., t.Any]: """Return a sync function that will run the coroutine function. .. code-block:: python result = app.async_to_sync(func)(*args, **kwargs) Override this method to change how the app converts async code to be synchronously callable. .. versionadded:: 2.0 """ try: from asgiref.sync import async_to_sync as asgiref_async_to_sync except ImportError: raise RuntimeError( "Install Flask with the 'async' extra in order to use async views." ) from None return asgiref_async_to_sync(func) def url_for( self, endpoint: str, *, _anchor: t.Optional[str] = None, _method: t.Optional[str] = None, _scheme: t.Optional[str] = None, _external: t.Optional[bool] = None, **values: t.Any, ) -> str: """Generate a URL to the given endpoint with the given values. This is called by :func:`flask.url_for`, and can be called directly as well. An *endpoint* is the name of a URL rule, usually added with :meth:`@app.route() <route>`, and usually the same name as the view function. A route defined in a :class:`~flask.Blueprint` will prepend the blueprint's name separated by a ``.`` to the endpoint. In some cases, such as email messages, you want URLs to include the scheme and domain, like ``https://example.com/hello``. When not in an active request, URLs will be external by default, but this requires setting :data:`SERVER_NAME` so Flask knows what domain to use. :data:`APPLICATION_ROOT` and :data:`PREFERRED_URL_SCHEME` should also be configured as needed. This config is only used when not in an active request. Functions can be decorated with :meth:`url_defaults` to modify keyword arguments before the URL is built. If building fails for some reason, such as an unknown endpoint or incorrect values, the app's :meth:`handle_url_build_error` method is called. If that returns a string, that is returned, otherwise a :exc:`~werkzeug.routing.BuildError` is raised. :param endpoint: The endpoint name associated with the URL to generate. If this starts with a ``.``, the current blueprint name (if any) will be used. :param _anchor: If given, append this as ``#anchor`` to the URL. :param _method: If given, generate the URL associated with this method for the endpoint. :param _scheme: If given, the URL will have this scheme if it is external. :param _external: If given, prefer the URL to be internal (False) or require it to be external (True). External URLs include the scheme and domain. When not in an active request, URLs are external by default. :param values: Values to use for the variable parts of the URL rule. Unknown keys are appended as query string arguments, like ``?a=b&c=d``. .. versionadded:: 2.2 Moved from ``flask.url_for``, which calls this method. """ req_ctx = _cv_request.get(None) if req_ctx is not None: url_adapter = req_ctx.url_adapter blueprint_name = req_ctx.request.blueprint # If the endpoint starts with "." and the request matches a # blueprint, the endpoint is relative to the blueprint. if endpoint[:1] == ".": if blueprint_name is not None: endpoint = f"{blueprint_name}{endpoint}" else: endpoint = endpoint[1:] # When in a request, generate a URL without scheme and # domain by default, unless a scheme is given. if _external is None: _external = _scheme is not None else: app_ctx = _cv_app.get(None) # If called by helpers.url_for, an app context is active, # use its url_adapter. Otherwise, app.url_for was called # directly, build an adapter. if app_ctx is not None: url_adapter = app_ctx.url_adapter else: url_adapter = self.create_url_adapter(None) if url_adapter is None: raise RuntimeError( "Unable to build URLs outside an active request" " without 'SERVER_NAME' configured. Also configure" " 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as" " needed." ) # When outside a request, generate a URL with scheme and # domain by default. if _external is None: _external = True # It is an error to set _scheme when _external=False, in order # to avoid accidental insecure URLs. if _scheme is not None and not _external: raise ValueError("When specifying '_scheme', '_external' must be True.") self.inject_url_defaults(endpoint, values) try: rv = url_adapter.build( # type: ignore[union-attr] endpoint, values, method=_method, url_scheme=_scheme, force_external=_external, ) except BuildError as error: values.update( _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external ) return self.handle_url_build_error(error, endpoint, values) if _anchor is not None: rv = f"{rv}#{url_quote(_anchor)}" return rv def redirect(self, location: str, code: int = 302) -> BaseResponse: """Create a redirect response object. This is called by :func:`flask.redirect`, and can be called directly as well. :param location: The URL to redirect to. :param code: The status code for the redirect. .. versionadded:: 2.2 Moved from ``flask.redirect``, which calls this method. """ return _wz_redirect(location, code=code, Response=self.response_class) def make_response(self, rv: ft.ResponseReturnValue) -> Response: """Convert the return value from a view function to an instance of :attr:`response_class`. :param rv: the return value from the view function. The view function must return a response. Returning ``None``, or the view ending without returning, is not allowed. The following types are allowed for ``view_rv``: ``str`` A response object is created with the string encoded to UTF-8 as the body. ``bytes`` A response object is created with the bytes as the body. ``dict`` A dictionary that will be jsonify'd before being returned. ``list`` A list that will be jsonify'd before being returned. ``generator`` or ``iterator`` A generator that returns ``str`` or ``bytes`` to be streamed as the response. ``tuple`` Either ``(body, status, headers)``, ``(body, status)``, or ``(body, headers)``, where ``body`` is any of the other types allowed here, ``status`` is a string or an integer, and ``headers`` is a dictionary or a list of ``(key, value)`` tuples. If ``body`` is a :attr:`response_class` instance, ``status`` overwrites the exiting value and ``headers`` are extended. :attr:`response_class` The object is returned unchanged. other :class:`~werkzeug.wrappers.Response` class The object is coerced to :attr:`response_class`. :func:`callable` The function is called as a WSGI application. The result is used to create a response object. .. versionchanged:: 2.2 A generator will be converted to a streaming response. A list will be converted to a JSON response. .. versionchanged:: 1.1 A dict will be converted to a JSON response. .. versionchanged:: 0.9 Previously a tuple was interpreted as the arguments for the response object. """ status = headers = None # unpack tuple returns if isinstance(rv, tuple): len_rv = len(rv) # a 3-tuple is unpacked directly if len_rv == 3: rv, status, headers = rv # type: ignore[misc] # decide if a 2-tuple has status or headers elif len_rv == 2: if isinstance(rv[1], (Headers, dict, tuple, list)): rv, headers = rv else: rv, status = rv # type: ignore[assignment,misc] # other sized tuples are not allowed else: raise TypeError( "The view function did not return a valid response tuple." " The tuple must have the form (body, status, headers)," " (body, status), or (body, headers)." ) # the body must not be None if rv is None: raise TypeError( f"The view function for {request.endpoint!r} did not" " return a valid response. The function either returned" " None or ended without a return statement." ) # make sure the body is an instance of the response class if not isinstance(rv, self.response_class): if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, _abc_Iterator): # let the response class set the status and headers instead of # waiting to do it manually, so that the class can handle any # special logic rv = self.response_class( rv, status=status, headers=headers, # type: ignore[arg-type] ) status = headers = None elif isinstance(rv, (dict, list)): rv = self.json.response(rv) elif isinstance(rv, BaseResponse) or callable(rv): # evaluate a WSGI callable, or coerce a different response # class to the correct type try: rv = self.response_class.force_type( rv, request.environ # type: ignore[arg-type] ) except TypeError as e: raise TypeError( f"{e}\nThe view function did not return a valid" " response. The return type must be a string," " dict, list, tuple with headers or status," " Response instance, or WSGI callable, but it" f" was a {type(rv).__name__}." ).with_traceback(sys.exc_info()[2]) from None else: raise TypeError( "The view function did not return a valid" " response. The return type must be a string," " dict, list, tuple with headers or status," " Response instance, or WSGI callable, but it was a" f" {type(rv).__name__}." ) rv = t.cast(Response, rv) # prefer the status if it was provided if status is not None: if isinstance(status, (str, bytes, bytearray)): rv.status = status else: rv.status_code = status # extend existing headers with provided headers if headers: rv.headers.update(headers) # type: ignore[arg-type] return rv def create_url_adapter( self, request: t.Optional[Request] ) -> t.Optional[MapAdapter]: """Creates a URL adapter for the given request. The URL adapter is created at a point where the request context is not yet set up so the request is passed explicitly. .. versionadded:: 0.6 .. versionchanged:: 0.9 This can now also be called without a request object when the URL adapter is created for the application context. .. versionchanged:: 1.0 :data:`SERVER_NAME` no longer implicitly enables subdomain matching. Use :attr:`subdomain_matching` instead. """ if request is not None: # If subdomain matching is disabled (the default), use the # default subdomain in all cases. This should be the default # in Werkzeug but it currently does not have that feature. if not self.subdomain_matching: subdomain = self.url_map.default_subdomain or None else: subdomain = None return self.url_map.bind_to_environ( request.environ, server_name=self.config["SERVER_NAME"], subdomain=subdomain, ) # We need at the very least the server name to be set for this # to work. if self.config["SERVER_NAME"] is not None: return self.url_map.bind( self.config["SERVER_NAME"], script_name=self.config["APPLICATION_ROOT"], url_scheme=self.config["PREFERRED_URL_SCHEME"], ) return None def inject_url_defaults(self, endpoint: str, values: dict) -> None: """Injects the URL defaults for the given endpoint directly into the values dictionary passed. This is used internally and automatically called on URL building. .. versionadded:: 0.7 """ names: t.Iterable[t.Optional[str]] = (None,) # url_for may be called outside a request context, parse the # passed endpoint instead of using request.blueprints. if "." in endpoint: names = chain( names, reversed(_split_blueprint_path(endpoint.rpartition(".")[0])) ) for name in names: if name in self.url_default_functions: for func in self.url_default_functions[name]: func(endpoint, values) def handle_url_build_error( self, error: BuildError, endpoint: str, values: t.Dict[str, t.Any] ) -> str: """Called by :meth:`.url_for` if a :exc:`~werkzeug.routing.BuildError` was raised. If this returns a value, it will be returned by ``url_for``, otherwise the error will be re-raised. Each function in :attr:`url_build_error_handlers` is called with ``error``, ``endpoint`` and ``values``. If a function returns ``None`` or raises a ``BuildError``, it is skipped. Otherwise, its return value is returned by ``url_for``. :param error: The active ``BuildError`` being handled. :param endpoint: The endpoint being built. :param values: The keyword arguments passed to ``url_for``. """ for handler in self.url_build_error_handlers: try: rv = handler(error, endpoint, values) except BuildError as e: # make error available outside except block error = e else: if rv is not None: return rv # Re-raise if called with an active exception, otherwise raise # the passed in exception. if error is sys.exc_info()[1]: raise raise error def preprocess_request(self) -> t.Optional[ft.ResponseReturnValue]: """Called before the request is dispatched. Calls :attr:`url_value_preprocessors` registered with the app and the current blueprint (if any). Then calls :attr:`before_request_funcs` registered with the app and the blueprint. If any :meth:`before_request` handler returns a non-None value, the value is handled as if it was the return value from the view, and further request handling is stopped. """ names = (None, *reversed(request.blueprints)) for name in names: if name in self.url_value_preprocessors: for url_func in self.url_value_preprocessors[name]: url_func(request.endpoint, request.view_args) for name in names: if name in self.before_request_funcs: for before_func in self.before_request_funcs[name]: rv = self.ensure_sync(before_func)() if rv is not None: return rv return None def process_response(self, response: Response) -> Response: """Can be overridden in order to modify the response object before it's sent to the WSGI server. By default this will call all the :meth:`after_request` decorated functions. .. versionchanged:: 0.5 As of Flask 0.5 the functions registered for after request execution are called in reverse order of registration. :param response: a :attr:`response_class` object. :return: a new response object or the same, has to be an instance of :attr:`response_class`. """ ctx = request_ctx._get_current_object() # type: ignore[attr-defined] for func in ctx._after_request_functions: response = self.ensure_sync(func)(response) for name in chain(request.blueprints, (None,)): if name in self.after_request_funcs: for func in reversed(self.after_request_funcs[name]): response = self.ensure_sync(func)(response) if not self.session_interface.is_null_session(ctx.session): self.session_interface.save_session(self, ctx.session, response) return response def do_teardown_request( self, exc: t.Optional[BaseException] = _sentinel # type: ignore ) -> None: """Called after the request is dispatched and the response is returned, right before the request context is popped. This calls all functions decorated with :meth:`teardown_request`, and :meth:`Blueprint.teardown_request` if a blueprint handled the request. Finally, the :data:`request_tearing_down` signal is sent. This is called by :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`, which may be delayed during testing to maintain access to resources. :param exc: An unhandled exception raised while dispatching the request. Detected from the current exception information if not passed. Passed to each teardown function. .. versionchanged:: 0.9 Added the ``exc`` argument. """ if exc is _sentinel: exc = sys.exc_info()[1] for name in chain(request.blueprints, (None,)): if name in self.teardown_request_funcs: for func in reversed(self.teardown_request_funcs[name]): self.ensure_sync(func)(exc) request_tearing_down.send(self, exc=exc) def do_teardown_appcontext( self, exc: t.Optional[BaseException] = _sentinel # type: ignore ) -> None: """Called right before the application context is popped. When handling a request, the application context is popped after the request context. See :meth:`do_teardown_request`. This calls all functions decorated with :meth:`teardown_appcontext`. Then the :data:`appcontext_tearing_down` signal is sent. This is called by :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`. .. versionadded:: 0.9 """ if exc is _sentinel: exc = sys.exc_info()[1] for func in reversed(self.teardown_appcontext_funcs): self.ensure_sync(func)(exc) appcontext_tearing_down.send(self, exc=exc) def app_context(self) -> AppContext: """Create an :class:`~flask.ctx.AppContext`. Use as a ``with`` block to push the context, which will make :data:`current_app` point at this application. An application context is automatically pushed by :meth:`RequestContext.push() <flask.ctx.RequestContext.push>` when handling a request, and when running a CLI command. Use this to manually create a context outside of these situations. :: with app.app_context(): init_db() See :doc:`/appcontext`. .. versionadded:: 0.9 """ return AppContext(self) def request_context(self, environ: dict) -> RequestContext: """Create a :class:`~flask.ctx.RequestContext` representing a WSGI environment. Use a ``with`` block to push the context, which will make :data:`request` point at this request. See :doc:`/reqcontext`. Typically you should not call this from your own code. A request context is automatically pushed by the :meth:`wsgi_app` when handling a request. Use :meth:`test_request_context` to create an environment and context instead of this method. :param environ: a WSGI environment """ return RequestContext(self, environ) def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> RequestContext: """Create a :class:`~flask.ctx.RequestContext` for a WSGI environment created from the given values. This is mostly useful during testing, where you may want to run a function that uses request data without dispatching a full request. See :doc:`/reqcontext`. Use a ``with`` block to push the context, which will make :data:`request` point at the request for the created environment. :: with test_request_context(...): generate_report() When using the shell, it may be easier to push and pop the context manually to avoid indentation. :: ctx = app.test_request_context(...) ctx.push() ... ctx.pop() Takes the same arguments as Werkzeug's :class:`~werkzeug.test.EnvironBuilder`, with some defaults from the application. See the linked Werkzeug docs for most of the available arguments. Flask-specific behavior is listed here. :param path: URL path being requested. :param base_url: Base URL where the app is being served, which ``path`` is relative to. If not given, built from :data:`PREFERRED_URL_SCHEME`, ``subdomain``, :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`. :param subdomain: Subdomain name to append to :data:`SERVER_NAME`. :param url_scheme: Scheme to use instead of :data:`PREFERRED_URL_SCHEME`. :param data: The request body, either as a string or a dict of form keys and values. :param json: If given, this is serialized as JSON and passed as ``data``. Also defaults ``content_type`` to ``application/json``. :param args: other positional arguments passed to :class:`~werkzeug.test.EnvironBuilder`. :param kwargs: other keyword arguments passed to :class:`~werkzeug.test.EnvironBuilder`. """ from .testing import EnvironBuilder builder = EnvironBuilder(self, *args, **kwargs) try: return self.request_context(builder.get_environ()) finally: builder.close() def wsgi_app(self, environ: dict, start_response: t.Callable) -> t.Any: """The actual WSGI application. This is not implemented in :meth:`__call__` so that middlewares can be applied without losing a reference to the app object. Instead of doing this:: app = MyMiddleware(app) It's a better idea to do this instead:: app.wsgi_app = MyMiddleware(app.wsgi_app) Then you still have the original application object around and can continue to call methods on it. .. versionchanged:: 0.7 Teardown events for the request and app contexts are called even if an unhandled error occurs. Other events may not be called depending on when an error occurs during dispatch. See :ref:`callbacks-and-errors`. :param environ: A WSGI environment. :param start_response: A callable accepting a status code, a list of headers, and an optional exception context to start the response. """ ctx = self.request_context(environ) error: t.Optional[BaseException] = None try: try: ctx.push() response = self.full_dispatch_request() except Exception as e: error = e response = self.handle_exception(e) except: # noqa: B001 error = sys.exc_info()[1] raise return response(environ, start_response) finally: if "werkzeug.debug.preserve_context" in environ: environ["werkzeug.debug.preserve_context"](_cv_app.get()) environ["werkzeug.debug.preserve_context"](_cv_request.get()) if error is not None and self.should_ignore_error(error): error = None ctx.pop(error) def __call__(self, environ: dict, start_response: t.Callable) -> t.Any: """The WSGI server calls the Flask application object as the WSGI application. This calls :meth:`wsgi_app`, which can be wrapped to apply middleware. """ return self.wsgi_app(environ, start_response) class Blueprint(Scaffold): """Represents a blueprint, a collection of routes and other app-related functions that can be registered on a real application later. A blueprint is an object that allows defining application functions without requiring an application object ahead of time. It uses the same decorators as :class:`~flask.Flask`, but defers the need for an application by recording them for later registration. Decorating a function with a blueprint creates a deferred function that is called with :class:`~flask.blueprints.BlueprintSetupState` when the blueprint is registered on an application. See :doc:`/blueprints` for more information. :param name: The name of the blueprint. Will be prepended to each endpoint name. :param import_name: The name of the blueprint package, usually ``__name__``. This helps locate the ``root_path`` for the blueprint. :param static_folder: A folder with static files that should be served by the blueprint's static route. The path is relative to the blueprint's root path. Blueprint static files are disabled by default. :param static_url_path: The url to serve static files from. Defaults to ``static_folder``. If the blueprint does not have a ``url_prefix``, the app's static route will take precedence, and the blueprint's static files won't be accessible. :param template_folder: A folder with templates that should be added to the app's template search path. The path is relative to the blueprint's root path. Blueprint templates are disabled by default. Blueprint templates have a lower precedence than those in the app's templates folder. :param url_prefix: A path to prepend to all of the blueprint's URLs, to make them distinct from the rest of the app's routes. :param subdomain: A subdomain that blueprint routes will match on by default. :param url_defaults: A dict of default values that blueprint routes will receive by default. :param root_path: By default, the blueprint will automatically set this based on ``import_name``. In certain situations this automatic detection can fail, so the path can be specified manually instead. .. versionchanged:: 1.1.0 Blueprints have a ``cli`` group to register nested CLI commands. The ``cli_group`` parameter controls the name of the group under the ``flask`` command. .. versionadded:: 0.7 """ _got_registered_once = False _json_encoder: t.Union[t.Type[json.JSONEncoder], None] = None _json_decoder: t.Union[t.Type[json.JSONDecoder], None] = None def json_encoder( self, ) -> t.Union[t.Type[json.JSONEncoder], None]: """Blueprint-local JSON encoder class to use. Set to ``None`` to use the app's. .. deprecated:: 2.2 Will be removed in Flask 2.3. Customize :attr:`json_provider_class` instead. .. versionadded:: 0.10 """ import warnings warnings.warn( "'bp.json_encoder' is deprecated and will be removed in Flask 2.3." " Customize 'app.json_provider_class' or 'app.json' instead.", DeprecationWarning, stacklevel=2, ) return self._json_encoder def json_encoder(self, value: t.Union[t.Type[json.JSONEncoder], None]) -> None: import warnings warnings.warn( "'bp.json_encoder' is deprecated and will be removed in Flask 2.3." " Customize 'app.json_provider_class' or 'app.json' instead.", DeprecationWarning, stacklevel=2, ) self._json_encoder = value def json_decoder( self, ) -> t.Union[t.Type[json.JSONDecoder], None]: """Blueprint-local JSON decoder class to use. Set to ``None`` to use the app's. .. deprecated:: 2.2 Will be removed in Flask 2.3. Customize :attr:`json_provider_class` instead. .. versionadded:: 0.10 """ import warnings warnings.warn( "'bp.json_decoder' is deprecated and will be removed in Flask 2.3." " Customize 'app.json_provider_class' or 'app.json' instead.", DeprecationWarning, stacklevel=2, ) return self._json_decoder def json_decoder(self, value: t.Union[t.Type[json.JSONDecoder], None]) -> None: import warnings warnings.warn( "'bp.json_decoder' is deprecated and will be removed in Flask 2.3." " Customize 'app.json_provider_class' or 'app.json' instead.", DeprecationWarning, stacklevel=2, ) self._json_decoder = value def __init__( self, name: str, import_name: str, static_folder: t.Optional[t.Union[str, os.PathLike]] = None, static_url_path: t.Optional[str] = None, template_folder: t.Optional[t.Union[str, os.PathLike]] = None, url_prefix: t.Optional[str] = None, subdomain: t.Optional[str] = None, url_defaults: t.Optional[dict] = None, root_path: t.Optional[str] = None, cli_group: t.Optional[str] = _sentinel, # type: ignore ): super().__init__( import_name=import_name, static_folder=static_folder, static_url_path=static_url_path, template_folder=template_folder, root_path=root_path, ) if "." in name: raise ValueError("'name' may not contain a dot '.' character.") self.name = name self.url_prefix = url_prefix self.subdomain = subdomain self.deferred_functions: t.List[DeferredSetupFunction] = [] if url_defaults is None: url_defaults = {} self.url_values_defaults = url_defaults self.cli_group = cli_group self._blueprints: t.List[t.Tuple["Blueprint", dict]] = [] def _check_setup_finished(self, f_name: str) -> None: if self._got_registered_once: import warnings warnings.warn( f"The setup method '{f_name}' can no longer be called on" f" the blueprint '{self.name}'. It has already been" " registered at least once, any changes will not be" " applied consistently.\n" "Make sure all imports, decorators, functions, etc." " needed to set up the blueprint are done before" " registering it.\n" "This warning will become an exception in Flask 2.3.", UserWarning, stacklevel=3, ) def record(self, func: t.Callable) -> None: """Registers a function that is called when the blueprint is registered on the application. This function is called with the state as argument as returned by the :meth:`make_setup_state` method. """ self.deferred_functions.append(func) def record_once(self, func: t.Callable) -> None: """Works like :meth:`record` but wraps the function in another function that will ensure the function is only called once. If the blueprint is registered a second time on the application, the function passed is not called. """ def wrapper(state: BlueprintSetupState) -> None: if state.first_registration: func(state) self.record(update_wrapper(wrapper, func)) def make_setup_state( self, app: "Flask", options: dict, first_registration: bool = False ) -> BlueprintSetupState: """Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState` object that is later passed to the register callback functions. Subclasses can override this to return a subclass of the setup state. """ return BlueprintSetupState(self, app, options, first_registration) def register_blueprint(self, blueprint: "Blueprint", **options: t.Any) -> None: """Register a :class:`~flask.Blueprint` on this blueprint. Keyword arguments passed to this method will override the defaults set on the blueprint. .. versionchanged:: 2.0.1 The ``name`` option can be used to change the (pre-dotted) name the blueprint is registered with. This allows the same blueprint to be registered multiple times with unique names for ``url_for``. .. versionadded:: 2.0 """ if blueprint is self: raise ValueError("Cannot register a blueprint on itself") self._blueprints.append((blueprint, options)) def register(self, app: "Flask", options: dict) -> None: """Called by :meth:`Flask.register_blueprint` to register all views and callbacks registered on the blueprint with the application. Creates a :class:`.BlueprintSetupState` and calls each :meth:`record` callback with it. :param app: The application this blueprint is being registered with. :param options: Keyword arguments forwarded from :meth:`~Flask.register_blueprint`. .. versionchanged:: 2.0.1 Nested blueprints are registered with their dotted name. This allows different blueprints with the same name to be nested at different locations. .. versionchanged:: 2.0.1 The ``name`` option can be used to change the (pre-dotted) name the blueprint is registered with. This allows the same blueprint to be registered multiple times with unique names for ``url_for``. .. versionchanged:: 2.0.1 Registering the same blueprint with the same name multiple times is deprecated and will become an error in Flask 2.1. """ name_prefix = options.get("name_prefix", "") self_name = options.get("name", self.name) name = f"{name_prefix}.{self_name}".lstrip(".") if name in app.blueprints: bp_desc = "this" if app.blueprints[name] is self else "a different" existing_at = f" '{name}'" if self_name != name else "" raise ValueError( f"The name '{self_name}' is already registered for" f" {bp_desc} blueprint{existing_at}. Use 'name=' to" f" provide a unique name." ) first_bp_registration = not any(bp is self for bp in app.blueprints.values()) first_name_registration = name not in app.blueprints app.blueprints[name] = self self._got_registered_once = True state = self.make_setup_state(app, options, first_bp_registration) if self.has_static_folder: state.add_url_rule( f"{self.static_url_path}/<path:filename>", view_func=self.send_static_file, endpoint="static", ) # Merge blueprint data into parent. if first_bp_registration or first_name_registration: def extend(bp_dict, parent_dict): for key, values in bp_dict.items(): key = name if key is None else f"{name}.{key}" parent_dict[key].extend(values) for key, value in self.error_handler_spec.items(): key = name if key is None else f"{name}.{key}" value = defaultdict( dict, { code: { exc_class: func for exc_class, func in code_values.items() } for code, code_values in value.items() }, ) app.error_handler_spec[key] = value for endpoint, func in self.view_functions.items(): app.view_functions[endpoint] = func extend(self.before_request_funcs, app.before_request_funcs) extend(self.after_request_funcs, app.after_request_funcs) extend( self.teardown_request_funcs, app.teardown_request_funcs, ) extend(self.url_default_functions, app.url_default_functions) extend(self.url_value_preprocessors, app.url_value_preprocessors) extend(self.template_context_processors, app.template_context_processors) for deferred in self.deferred_functions: deferred(state) cli_resolved_group = options.get("cli_group", self.cli_group) if self.cli.commands: if cli_resolved_group is None: app.cli.commands.update(self.cli.commands) elif cli_resolved_group is _sentinel: self.cli.name = name app.cli.add_command(self.cli) else: self.cli.name = cli_resolved_group app.cli.add_command(self.cli) for blueprint, bp_options in self._blueprints: bp_options = bp_options.copy() bp_url_prefix = bp_options.get("url_prefix") if bp_url_prefix is None: bp_url_prefix = blueprint.url_prefix if state.url_prefix is not None and bp_url_prefix is not None: bp_options["url_prefix"] = ( state.url_prefix.rstrip("/") + "/" + bp_url_prefix.lstrip("/") ) elif bp_url_prefix is not None: bp_options["url_prefix"] = bp_url_prefix elif state.url_prefix is not None: bp_options["url_prefix"] = state.url_prefix bp_options["name_prefix"] = name blueprint.register(app, bp_options) def add_url_rule( self, rule: str, endpoint: t.Optional[str] = None, view_func: t.Optional[ft.RouteCallable] = None, provide_automatic_options: t.Optional[bool] = None, **options: t.Any, ) -> None: """Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for full documentation. The URL rule is prefixed with the blueprint's URL prefix. The endpoint name, used with :func:`url_for`, is prefixed with the blueprint's name. """ if endpoint and "." in endpoint: raise ValueError("'endpoint' may not contain a dot '.' character.") if view_func and hasattr(view_func, "__name__") and "." in view_func.__name__: raise ValueError("'view_func' name may not contain a dot '.' character.") self.record( lambda s: s.add_url_rule( rule, endpoint, view_func, provide_automatic_options=provide_automatic_options, **options, ) ) def app_template_filter( self, name: t.Optional[str] = None ) -> t.Callable[[T_template_filter], T_template_filter]: """Register a template filter, available in any template rendered by the application. Equivalent to :meth:`.Flask.template_filter`. :param name: the optional name of the filter, otherwise the function name will be used. """ def decorator(f: T_template_filter) -> T_template_filter: self.add_app_template_filter(f, name=name) return f return decorator def add_app_template_filter( self, f: ft.TemplateFilterCallable, name: t.Optional[str] = None ) -> None: """Register a template filter, available in any template rendered by the application. Works like the :meth:`app_template_filter` decorator. Equivalent to :meth:`.Flask.add_template_filter`. :param name: the optional name of the filter, otherwise the function name will be used. """ def register_template(state: BlueprintSetupState) -> None: state.app.jinja_env.filters[name or f.__name__] = f self.record_once(register_template) def app_template_test( self, name: t.Optional[str] = None ) -> t.Callable[[T_template_test], T_template_test]: """Register a template test, available in any template rendered by the application. Equivalent to :meth:`.Flask.template_test`. .. versionadded:: 0.10 :param name: the optional name of the test, otherwise the function name will be used. """ def decorator(f: T_template_test) -> T_template_test: self.add_app_template_test(f, name=name) return f return decorator def add_app_template_test( self, f: ft.TemplateTestCallable, name: t.Optional[str] = None ) -> None: """Register a template test, available in any template rendered by the application. Works like the :meth:`app_template_test` decorator. Equivalent to :meth:`.Flask.add_template_test`. .. versionadded:: 0.10 :param name: the optional name of the test, otherwise the function name will be used. """ def register_template(state: BlueprintSetupState) -> None: state.app.jinja_env.tests[name or f.__name__] = f self.record_once(register_template) def app_template_global( self, name: t.Optional[str] = None ) -> t.Callable[[T_template_global], T_template_global]: """Register a template global, available in any template rendered by the application. Equivalent to :meth:`.Flask.template_global`. .. versionadded:: 0.10 :param name: the optional name of the global, otherwise the function name will be used. """ def decorator(f: T_template_global) -> T_template_global: self.add_app_template_global(f, name=name) return f return decorator def add_app_template_global( self, f: ft.TemplateGlobalCallable, name: t.Optional[str] = None ) -> None: """Register a template global, available in any template rendered by the application. Works like the :meth:`app_template_global` decorator. Equivalent to :meth:`.Flask.add_template_global`. .. versionadded:: 0.10 :param name: the optional name of the global, otherwise the function name will be used. """ def register_template(state: BlueprintSetupState) -> None: state.app.jinja_env.globals[name or f.__name__] = f self.record_once(register_template) def before_app_request(self, f: T_before_request) -> T_before_request: """Like :meth:`before_request`, but before every request, not only those handled by the blueprint. Equivalent to :meth:`.Flask.before_request`. """ self.record_once( lambda s: s.app.before_request_funcs.setdefault(None, []).append(f) ) return f def before_app_first_request( self, f: T_before_first_request ) -> T_before_first_request: """Register a function to run before the first request to the application is handled by the worker. Equivalent to :meth:`.Flask.before_first_request`. .. deprecated:: 2.2 Will be removed in Flask 2.3. Run setup code when creating the application instead. """ import warnings warnings.warn( "'before_app_first_request' is deprecated and will be" " removed in Flask 2.3. Use 'record_once' instead to run" " setup code when registering the blueprint.", DeprecationWarning, stacklevel=2, ) self.record_once(lambda s: s.app.before_first_request_funcs.append(f)) return f def after_app_request(self, f: T_after_request) -> T_after_request: """Like :meth:`after_request`, but after every request, not only those handled by the blueprint. Equivalent to :meth:`.Flask.after_request`. """ self.record_once( lambda s: s.app.after_request_funcs.setdefault(None, []).append(f) ) return f def teardown_app_request(self, f: T_teardown) -> T_teardown: """Like :meth:`teardown_request`, but after every request, not only those handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`. """ self.record_once( lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f) ) return f def app_context_processor( self, f: T_template_context_processor ) -> T_template_context_processor: """Like :meth:`context_processor`, but for templates rendered by every view, not only by the blueprint. Equivalent to :meth:`.Flask.context_processor`. """ self.record_once( lambda s: s.app.template_context_processors.setdefault(None, []).append(f) ) return f def app_errorhandler( self, code: t.Union[t.Type[Exception], int] ) -> t.Callable[[T_error_handler], T_error_handler]: """Like :meth:`errorhandler`, but for every request, not only those handled by the blueprint. Equivalent to :meth:`.Flask.errorhandler`. """ def decorator(f: T_error_handler) -> T_error_handler: self.record_once(lambda s: s.app.errorhandler(code)(f)) return f return decorator def app_url_value_preprocessor( self, f: T_url_value_preprocessor ) -> T_url_value_preprocessor: """Like :meth:`url_value_preprocessor`, but for every request, not only those handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`. """ self.record_once( lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f) ) return f def app_url_defaults(self, f: T_url_defaults) -> T_url_defaults: """Like :meth:`url_defaults`, but for every request, not only those handled by the blueprint. Equivalent to :meth:`.Flask.url_defaults`. """ self.record_once( lambda s: s.app.url_default_functions.setdefault(None, []).append(f) ) return f request_ctx: "RequestContext" = LocalProxy( # type: ignore[assignment] _cv_request, unbound_message=_no_req_msg ) The provided code snippet includes necessary dependencies for implementing the `explain_template_loading_attempts` function. Write a Python function `def explain_template_loading_attempts(app: Flask, template, attempts) -> None` to solve the following problem: This should help developers understand what failed Here is the function: def explain_template_loading_attempts(app: Flask, template, attempts) -> None: """This should help developers understand what failed""" info = [f"Locating template {template!r}:"] total_found = 0 blueprint = None if request_ctx and request_ctx.request.blueprint is not None: blueprint = request_ctx.request.blueprint for idx, (loader, srcobj, triple) in enumerate(attempts): if isinstance(srcobj, Flask): src_info = f"application {srcobj.import_name!r}" elif isinstance(srcobj, Blueprint): src_info = f"blueprint {srcobj.name!r} ({srcobj.import_name})" else: src_info = repr(srcobj) info.append(f"{idx + 1:5}: trying loader of {src_info}") for line in _dump_loader_info(loader): info.append(f" {line}") if triple is None: detail = "no match" else: detail = f"found ({triple[1] or '<string>'!r})" total_found += 1 info.append(f" -> {detail}") seems_fishy = False if total_found == 0: info.append("Error: the template could not be found.") seems_fishy = True elif total_found > 1: info.append("Warning: multiple loaders returned a match for the template.") seems_fishy = True if blueprint is not None and seems_fishy: info.append( " The template was looked up from an endpoint that belongs" f" to the blueprint {blueprint!r}." ) info.append(" Maybe you did not place a template in the right folder?") info.append(" See https://flask.palletsprojects.com/blueprints/#templates") app.logger.info("\n".join(info))
This should help developers understand what failed
174,823
import logging import sys import typing as t from werkzeug.local import LocalProxy from .globals import request if t.TYPE_CHECKING: # pragma: no cover from .app import Flask import typing as t request: "Request" = LocalProxy( # type: ignore[assignment] _cv_request, "request", unbound_message=_no_req_msg ) The provided code snippet includes necessary dependencies for implementing the `wsgi_errors_stream` function. Write a Python function `def wsgi_errors_stream() -> t.TextIO` to solve the following problem: Find the most appropriate error stream for the application. If a request is active, log to ``wsgi.errors``, otherwise use ``sys.stderr``. If you configure your own :class:`logging.StreamHandler`, you may want to use this for the stream. If you are using file or dict configuration and can't import this directly, you can refer to it as ``ext://flask.logging.wsgi_errors_stream``. Here is the function: def wsgi_errors_stream() -> t.TextIO: """Find the most appropriate error stream for the application. If a request is active, log to ``wsgi.errors``, otherwise use ``sys.stderr``. If you configure your own :class:`logging.StreamHandler`, you may want to use this for the stream. If you are using file or dict configuration and can't import this directly, you can refer to it as ``ext://flask.logging.wsgi_errors_stream``. """ return request.environ["wsgi.errors"] if request else sys.stderr
Find the most appropriate error stream for the application. If a request is active, log to ``wsgi.errors``, otherwise use ``sys.stderr``. If you configure your own :class:`logging.StreamHandler`, you may want to use this for the stream. If you are using file or dict configuration and can't import this directly, you can refer to it as ``ext://flask.logging.wsgi_errors_stream``.
174,824
import logging import sys import typing as t from werkzeug.local import LocalProxy from .globals import request def has_level_handler(logger: logging.Logger) -> bool: """Check if there is a handler in the logging chain that will handle the given logger's :meth:`effective level <~logging.Logger.getEffectiveLevel>`. """ level = logger.getEffectiveLevel() current = logger while current: if any(handler.level <= level for handler in current.handlers): return True if not current.propagate: break current = current.parent # type: ignore return False default_handler = logging.StreamHandler(wsgi_errors_stream) default_handler.setFormatter( logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s") ) import logging The provided code snippet includes necessary dependencies for implementing the `create_logger` function. Write a Python function `def create_logger(app: "Flask") -> logging.Logger` to solve the following problem: Get the Flask app's logger and configure it if needed. The logger name will be the same as :attr:`app.import_name <flask.Flask.name>`. When :attr:`~flask.Flask.debug` is enabled, set the logger level to :data:`logging.DEBUG` if it is not set. If there is no handler for the logger's effective level, add a :class:`~logging.StreamHandler` for :func:`~flask.logging.wsgi_errors_stream` with a basic format. Here is the function: def create_logger(app: "Flask") -> logging.Logger: """Get the Flask app's logger and configure it if needed. The logger name will be the same as :attr:`app.import_name <flask.Flask.name>`. When :attr:`~flask.Flask.debug` is enabled, set the logger level to :data:`logging.DEBUG` if it is not set. If there is no handler for the logger's effective level, add a :class:`~logging.StreamHandler` for :func:`~flask.logging.wsgi_errors_stream` with a basic format. """ logger = logging.getLogger(app.name) if app.debug and not logger.level: logger.setLevel(logging.DEBUG) if not has_level_handler(logger): logger.addHandler(default_handler) return logger
Get the Flask app's logger and configure it if needed. The logger name will be the same as :attr:`app.import_name <flask.Flask.name>`. When :attr:`~flask.Flask.debug` is enabled, set the logger level to :data:`logging.DEBUG` if it is not set. If there is no handler for the logger's effective level, add a :class:`~logging.StreamHandler` for :func:`~flask.logging.wsgi_errors_stream` with a basic format.
174,825
import contextvars import sys import typing as t from functools import update_wrapper from types import TracebackType from werkzeug.exceptions import HTTPException from . import typing as ft from .globals import _cv_app from .globals import _cv_request from .signals import appcontext_popped from .signals import appcontext_pushed _cv_request: ContextVar["RequestContext"] = ContextVar("flask.request_ctx") The provided code snippet includes necessary dependencies for implementing the `after_this_request` function. Write a Python function `def after_this_request(f: ft.AfterRequestCallable) -> ft.AfterRequestCallable` to solve the following problem: Executes a function after this request. This is useful to modify response objects. The function is passed the response object and has to return the same or a new one. Example:: @app.route('/') def index(): @after_this_request def add_header(response): response.headers['X-Foo'] = 'Parachute' return response return 'Hello World!' This is more useful if a function other than the view function wants to modify a response. For instance think of a decorator that wants to add some headers without converting the return value into a response object. .. versionadded:: 0.9 Here is the function: def after_this_request(f: ft.AfterRequestCallable) -> ft.AfterRequestCallable: """Executes a function after this request. This is useful to modify response objects. The function is passed the response object and has to return the same or a new one. Example:: @app.route('/') def index(): @after_this_request def add_header(response): response.headers['X-Foo'] = 'Parachute' return response return 'Hello World!' This is more useful if a function other than the view function wants to modify a response. For instance think of a decorator that wants to add some headers without converting the return value into a response object. .. versionadded:: 0.9 """ ctx = _cv_request.get(None) if ctx is None: raise RuntimeError( "'after_this_request' can only be used when a request" " context is active, such as in a view function." ) ctx._after_request_functions.append(f) return f
Executes a function after this request. This is useful to modify response objects. The function is passed the response object and has to return the same or a new one. Example:: @app.route('/') def index(): @after_this_request def add_header(response): response.headers['X-Foo'] = 'Parachute' return response return 'Hello World!' This is more useful if a function other than the view function wants to modify a response. For instance think of a decorator that wants to add some headers without converting the return value into a response object. .. versionadded:: 0.9
174,826
import contextvars import sys import typing as t from functools import update_wrapper from types import TracebackType from werkzeug.exceptions import HTTPException from . import typing as ft from .globals import _cv_app from .globals import _cv_request from .signals import appcontext_popped from .signals import appcontext_pushed if t.TYPE_CHECKING: # pragma: no cover from .app import Flask from .sessions import SessionMixin from .wrappers import Request import typing as t def update_wrapper(wrapper: _T, wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> _T: ... _cv_request: ContextVar["RequestContext"] = ContextVar("flask.request_ctx") The provided code snippet includes necessary dependencies for implementing the `copy_current_request_context` function. Write a Python function `def copy_current_request_context(f: t.Callable) -> t.Callable` to solve the following problem: A helper function that decorates a function to retain the current request context. This is useful when working with greenlets. The moment the function is decorated a copy of the request context is created and then pushed when the function is called. The current session is also included in the copied request context. Example:: import gevent from flask import copy_current_request_context @app.route('/') def index(): @copy_current_request_context def do_some_work(): # do some work here, it can access flask.request or # flask.session like you would otherwise in the view function. ... gevent.spawn(do_some_work) return 'Regular response' .. versionadded:: 0.10 Here is the function: def copy_current_request_context(f: t.Callable) -> t.Callable: """A helper function that decorates a function to retain the current request context. This is useful when working with greenlets. The moment the function is decorated a copy of the request context is created and then pushed when the function is called. The current session is also included in the copied request context. Example:: import gevent from flask import copy_current_request_context @app.route('/') def index(): @copy_current_request_context def do_some_work(): # do some work here, it can access flask.request or # flask.session like you would otherwise in the view function. ... gevent.spawn(do_some_work) return 'Regular response' .. versionadded:: 0.10 """ ctx = _cv_request.get(None) if ctx is None: raise RuntimeError( "'copy_current_request_context' can only be used when a" " request context is active, such as in a view function." ) ctx = ctx.copy() def wrapper(*args, **kwargs): with ctx: return ctx.app.ensure_sync(f)(*args, **kwargs) return update_wrapper(wrapper, f)
A helper function that decorates a function to retain the current request context. This is useful when working with greenlets. The moment the function is decorated a copy of the request context is created and then pushed when the function is called. The current session is also included in the copied request context. Example:: import gevent from flask import copy_current_request_context @app.route('/') def index(): @copy_current_request_context def do_some_work(): # do some work here, it can access flask.request or # flask.session like you would otherwise in the view function. ... gevent.spawn(do_some_work) return 'Regular response' .. versionadded:: 0.10
174,827
import contextvars import sys import typing as t from functools import update_wrapper from types import TracebackType from werkzeug.exceptions import HTTPException from . import typing as ft from .globals import _cv_app from .globals import _cv_request from .signals import appcontext_popped from .signals import appcontext_pushed _cv_request: ContextVar["RequestContext"] = ContextVar("flask.request_ctx") The provided code snippet includes necessary dependencies for implementing the `has_request_context` function. Write a Python function `def has_request_context() -> bool` to solve the following problem: If you have code that wants to test if a request context is there or not this function can be used. For instance, you may want to take advantage of request information if the request object is available, but fail silently if it is unavailable. :: class User(db.Model): def __init__(self, username, remote_addr=None): self.username = username if remote_addr is None and has_request_context(): remote_addr = request.remote_addr self.remote_addr = remote_addr Alternatively you can also just test any of the context bound objects (such as :class:`request` or :class:`g`) for truthness:: class User(db.Model): def __init__(self, username, remote_addr=None): self.username = username if remote_addr is None and request: remote_addr = request.remote_addr self.remote_addr = remote_addr .. versionadded:: 0.7 Here is the function: def has_request_context() -> bool: """If you have code that wants to test if a request context is there or not this function can be used. For instance, you may want to take advantage of request information if the request object is available, but fail silently if it is unavailable. :: class User(db.Model): def __init__(self, username, remote_addr=None): self.username = username if remote_addr is None and has_request_context(): remote_addr = request.remote_addr self.remote_addr = remote_addr Alternatively you can also just test any of the context bound objects (such as :class:`request` or :class:`g`) for truthness:: class User(db.Model): def __init__(self, username, remote_addr=None): self.username = username if remote_addr is None and request: remote_addr = request.remote_addr self.remote_addr = remote_addr .. versionadded:: 0.7 """ return _cv_request.get(None) is not None
If you have code that wants to test if a request context is there or not this function can be used. For instance, you may want to take advantage of request information if the request object is available, but fail silently if it is unavailable. :: class User(db.Model): def __init__(self, username, remote_addr=None): self.username = username if remote_addr is None and has_request_context(): remote_addr = request.remote_addr self.remote_addr = remote_addr Alternatively you can also just test any of the context bound objects (such as :class:`request` or :class:`g`) for truthness:: class User(db.Model): def __init__(self, username, remote_addr=None): self.username = username if remote_addr is None and request: remote_addr = request.remote_addr self.remote_addr = remote_addr .. versionadded:: 0.7
174,828
import contextvars import sys import typing as t from functools import update_wrapper from types import TracebackType from werkzeug.exceptions import HTTPException from . import typing as ft from .globals import _cv_app from .globals import _cv_request from .signals import appcontext_popped from .signals import appcontext_pushed _cv_app: ContextVar["AppContext"] = ContextVar("flask.app_ctx") The provided code snippet includes necessary dependencies for implementing the `has_app_context` function. Write a Python function `def has_app_context() -> bool` to solve the following problem: Works like :func:`has_request_context` but for the application context. You can also just do a boolean check on the :data:`current_app` object instead. .. versionadded:: 0.9 Here is the function: def has_app_context() -> bool: """Works like :func:`has_request_context` but for the application context. You can also just do a boolean check on the :data:`current_app` object instead. .. versionadded:: 0.9 """ return _cv_app.get(None) is not None
Works like :func:`has_request_context` but for the application context. You can also just do a boolean check on the :data:`current_app` object instead. .. versionadded:: 0.9
174,829
import functools import inspect import json import logging import os import sys import typing as t import weakref from collections.abc import Iterator as _abc_Iterator from datetime import timedelta from itertools import chain from threading import Lock from types import TracebackType import click from werkzeug.datastructures import Headers from werkzeug.datastructures import ImmutableDict from werkzeug.exceptions import Aborter from werkzeug.exceptions import BadRequest from werkzeug.exceptions import BadRequestKeyError from werkzeug.exceptions import HTTPException from werkzeug.exceptions import InternalServerError from werkzeug.routing import BuildError from werkzeug.routing import Map from werkzeug.routing import MapAdapter from werkzeug.routing import RequestRedirect from werkzeug.routing import RoutingException from werkzeug.routing import Rule from werkzeug.serving import is_running_from_reloader from werkzeug.urls import url_quote from werkzeug.utils import redirect as _wz_redirect from werkzeug.wrappers import Response as BaseResponse from . import cli from . import typing as ft from .config import Config from .config import ConfigAttribute from .ctx import _AppCtxGlobals from .ctx import AppContext from .ctx import RequestContext from .globals import _cv_app from .globals import _cv_request from .globals import g from .globals import request from .globals import request_ctx from .globals import session from .helpers import _split_blueprint_path from .helpers import get_debug_flag from .helpers import get_flashed_messages from .helpers import get_load_dotenv from .helpers import locked_cached_property from .json.provider import DefaultJSONProvider from .json.provider import JSONProvider from .logging import create_logger from .scaffold import _endpoint_from_view_func from .scaffold import _sentinel from .scaffold import find_package from .scaffold import Scaffold from .scaffold import setupmethod from .sessions import SecureCookieSessionInterface from .sessions import SessionInterface from .signals import appcontext_tearing_down from .signals import got_request_exception from .signals import request_finished from .signals import request_started from .signals import request_tearing_down from .templating import DispatchingJinjaLoader from .templating import Environment from .wrappers import Request from .wrappers import Response if t.TYPE_CHECKING: # pragma: no cover import typing_extensions as te from .blueprints import Blueprint from .testing import FlaskClient from .testing import FlaskCliRunner import typing as t def iscoroutinefunction(func: t.Any) -> bool: while inspect.ismethod(func): func = func.__func__ while isinstance(func, functools.partial): func = func.func return inspect.iscoroutinefunction(func)
null
174,830
import functools import inspect import json import logging import os import sys import typing as t import weakref from collections.abc import Iterator as _abc_Iterator from datetime import timedelta from itertools import chain from threading import Lock from types import TracebackType import click from werkzeug.datastructures import Headers from werkzeug.datastructures import ImmutableDict from werkzeug.exceptions import Aborter from werkzeug.exceptions import BadRequest from werkzeug.exceptions import BadRequestKeyError from werkzeug.exceptions import HTTPException from werkzeug.exceptions import InternalServerError from werkzeug.routing import BuildError from werkzeug.routing import Map from werkzeug.routing import MapAdapter from werkzeug.routing import RequestRedirect from werkzeug.routing import RoutingException from werkzeug.routing import Rule from werkzeug.serving import is_running_from_reloader from werkzeug.urls import url_quote from werkzeug.utils import redirect as _wz_redirect from werkzeug.wrappers import Response as BaseResponse from . import cli from . import typing as ft from .config import Config from .config import ConfigAttribute from .ctx import _AppCtxGlobals from .ctx import AppContext from .ctx import RequestContext from .globals import _cv_app from .globals import _cv_request from .globals import g from .globals import request from .globals import request_ctx from .globals import session from .helpers import _split_blueprint_path from .helpers import get_debug_flag from .helpers import get_flashed_messages from .helpers import get_load_dotenv from .helpers import locked_cached_property from .json.provider import DefaultJSONProvider from .json.provider import JSONProvider from .logging import create_logger from .scaffold import _endpoint_from_view_func from .scaffold import _sentinel from .scaffold import find_package from .scaffold import Scaffold from .scaffold import setupmethod from .sessions import SecureCookieSessionInterface from .sessions import SessionInterface from .signals import appcontext_tearing_down from .signals import got_request_exception from .signals import request_finished from .signals import request_started from .signals import request_tearing_down from .templating import DispatchingJinjaLoader from .templating import Environment from .wrappers import Request from .wrappers import Response if t.TYPE_CHECKING: # pragma: no cover import typing_extensions as te from .blueprints import Blueprint from .testing import FlaskClient from .testing import FlaskCliRunner import typing as t class timedelta(SupportsAbs[timedelta]): min: ClassVar[timedelta] max: ClassVar[timedelta] resolution: ClassVar[timedelta] if sys.version_info >= (3, 6): def __init__( self, days: float = ..., seconds: float = ..., microseconds: float = ..., milliseconds: float = ..., minutes: float = ..., hours: float = ..., weeks: float = ..., *, fold: int = ..., ) -> None: ... else: def __init__( self, days: float = ..., seconds: float = ..., microseconds: float = ..., milliseconds: float = ..., minutes: float = ..., hours: float = ..., weeks: float = ..., ) -> None: ... def days(self) -> int: ... def seconds(self) -> int: ... def microseconds(self) -> int: ... def total_seconds(self) -> float: ... def __add__(self, other: timedelta) -> timedelta: ... def __radd__(self, other: timedelta) -> timedelta: ... def __sub__(self, other: timedelta) -> timedelta: ... def __rsub__(self, other: timedelta) -> timedelta: ... def __neg__(self) -> timedelta: ... def __pos__(self) -> timedelta: ... def __abs__(self) -> timedelta: ... def __mul__(self, other: float) -> timedelta: ... def __rmul__(self, other: float) -> timedelta: ... def __floordiv__(self, other: timedelta) -> int: ... def __floordiv__(self, other: int) -> timedelta: ... if sys.version_info >= (3,): def __truediv__(self, other: timedelta) -> float: ... def __truediv__(self, other: float) -> timedelta: ... def __mod__(self, other: timedelta) -> timedelta: ... def __divmod__(self, other: timedelta) -> Tuple[int, timedelta]: ... else: def __div__(self, other: timedelta) -> float: ... def __div__(self, other: float) -> timedelta: ... def __le__(self, other: timedelta) -> bool: ... def __lt__(self, other: timedelta) -> bool: ... def __ge__(self, other: timedelta) -> bool: ... def __gt__(self, other: timedelta) -> bool: ... def __hash__(self) -> int: ... def _make_timedelta(value: t.Union[timedelta, int, None]) -> t.Optional[timedelta]: if value is None or isinstance(value, timedelta): return value return timedelta(seconds=value)
null
174,831
import importlib.util import json import os import pathlib import pkgutil import sys import typing as t from collections import defaultdict from datetime import timedelta from functools import update_wrapper from jinja2 import FileSystemLoader from werkzeug.exceptions import default_exceptions from werkzeug.exceptions import HTTPException from . import typing as ft from .cli import AppGroup from .globals import current_app from .helpers import get_root_path from .helpers import locked_cached_property from .helpers import send_from_directory from .templating import _default_template_ctx_processor if t.TYPE_CHECKING: # pragma: no cover from .wrappers import Response F = t.TypeVar("F", bound=t.Callable[..., t.Any]) import typing as t def update_wrapper(wrapper: _T, wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> _T: ... def setupmethod(f: F) -> F: f_name = f.__name__ def wrapper_func(self, *args: t.Any, **kwargs: t.Any) -> t.Any: self._check_setup_finished(f_name) return f(self, *args, **kwargs) return t.cast(F, update_wrapper(wrapper_func, f))
null
174,832
import importlib.util import json import os import pathlib import pkgutil import sys import typing as t from collections import defaultdict from datetime import timedelta from functools import update_wrapper from jinja2 import FileSystemLoader from werkzeug.exceptions import default_exceptions from werkzeug.exceptions import HTTPException from . import typing as ft from .cli import AppGroup from .globals import current_app from .helpers import get_root_path from .helpers import locked_cached_property from .helpers import send_from_directory from .templating import _default_template_ctx_processor if t.TYPE_CHECKING: # pragma: no cover from .wrappers import Response import typing as t The provided code snippet includes necessary dependencies for implementing the `_endpoint_from_view_func` function. Write a Python function `def _endpoint_from_view_func(view_func: t.Callable) -> str` to solve the following problem: Internal helper that returns the default endpoint for a given function. This always is the function name. Here is the function: def _endpoint_from_view_func(view_func: t.Callable) -> str: """Internal helper that returns the default endpoint for a given function. This always is the function name. """ assert view_func is not None, "expected view func if endpoint is not provided." return view_func.__name__
Internal helper that returns the default endpoint for a given function. This always is the function name.
174,833
import importlib.util import json import os import pathlib import pkgutil import sys import typing as t from collections import defaultdict from datetime import timedelta from functools import update_wrapper from jinja2 import FileSystemLoader from werkzeug.exceptions import default_exceptions from werkzeug.exceptions import HTTPException from . import typing as ft from .cli import AppGroup from .globals import current_app from .helpers import get_root_path from .helpers import locked_cached_property from .helpers import send_from_directory from .templating import _default_template_ctx_processor def _path_is_relative_to(path: pathlib.PurePath, base: str) -> bool: # Path.is_relative_to doesn't exist until Python 3.9 try: path.relative_to(base) return True except ValueError: return False def _find_package_path(import_name): """Find the path that contains the package or module.""" root_mod_name, _, _ = import_name.partition(".") try: root_spec = importlib.util.find_spec(root_mod_name) if root_spec is None: raise ValueError("not found") # ImportError: the machinery told us it does not exist # ValueError: # - the module name was invalid # - the module name is __main__ # - *we* raised `ValueError` due to `root_spec` being `None` except (ImportError, ValueError): pass # handled below else: # namespace package if root_spec.origin in {"namespace", None}: package_spec = importlib.util.find_spec(import_name) if package_spec is not None and package_spec.submodule_search_locations: # Pick the path in the namespace that contains the submodule. package_path = pathlib.Path( os.path.commonpath(package_spec.submodule_search_locations) ) search_locations = ( location for location in root_spec.submodule_search_locations if _path_is_relative_to(package_path, location) ) else: # Pick the first path. search_locations = iter(root_spec.submodule_search_locations) return os.path.dirname(next(search_locations)) # a package (with __init__.py) elif root_spec.submodule_search_locations: return os.path.dirname(os.path.dirname(root_spec.origin)) # just a normal module else: return os.path.dirname(root_spec.origin) # we were unable to find the `package_path` using PEP 451 loaders loader = pkgutil.get_loader(root_mod_name) if loader is None or root_mod_name == "__main__": # import name is not found, or interactive/main module return os.getcwd() if hasattr(loader, "get_filename"): filename = loader.get_filename(root_mod_name) elif hasattr(loader, "archive"): # zipimporter's loader.archive points to the .egg or .zip file. filename = loader.archive else: # At least one loader is missing both get_filename and archive: # Google App Engine's HardenedModulesHook, use __file__. filename = importlib.import_module(root_mod_name).__file__ package_path = os.path.abspath(os.path.dirname(filename)) # If the imported name is a package, filename is currently pointing # to the root of the package, need to get the current directory. if _matching_loader_thinks_module_is_package(loader, root_mod_name): package_path = os.path.dirname(package_path) return package_path The provided code snippet includes necessary dependencies for implementing the `find_package` function. Write a Python function `def find_package(import_name: str)` to solve the following problem: Find the prefix that a package is installed under, and the path that it would be imported from. The prefix is the directory containing the standard directory hierarchy (lib, bin, etc.). If the package is not installed to the system (:attr:`sys.prefix`) or a virtualenv (``site-packages``), ``None`` is returned. The path is the entry in :attr:`sys.path` that contains the package for import. If the package is not installed, it's assumed that the package was imported from the current working directory. Here is the function: def find_package(import_name: str): """Find the prefix that a package is installed under, and the path that it would be imported from. The prefix is the directory containing the standard directory hierarchy (lib, bin, etc.). If the package is not installed to the system (:attr:`sys.prefix`) or a virtualenv (``site-packages``), ``None`` is returned. The path is the entry in :attr:`sys.path` that contains the package for import. If the package is not installed, it's assumed that the package was imported from the current working directory. """ package_path = _find_package_path(import_name) py_prefix = os.path.abspath(sys.prefix) # installed to the system if _path_is_relative_to(pathlib.PurePath(package_path), py_prefix): return py_prefix, package_path site_parent, site_folder = os.path.split(package_path) # installed to a virtualenv if site_folder.lower() == "site-packages": parent, folder = os.path.split(site_parent) # Windows (prefix/lib/site-packages) if folder.lower() == "lib": return parent, package_path # Unix (prefix/lib/pythonX.Y/site-packages) if os.path.basename(parent).lower() == "lib": return os.path.dirname(parent), package_path # something else (prefix/site-packages) return site_parent, package_path # not installed return None, package_path
Find the prefix that a package is installed under, and the path that it would be imported from. The prefix is the directory containing the standard directory hierarchy (lib, bin, etc.). If the package is not installed to the system (:attr:`sys.prefix`) or a virtualenv (``site-packages``), ``None`` is returned. The path is the entry in :attr:`sys.path` that contains the package for import. If the package is not installed, it's assumed that the package was imported from the current working directory.
174,834
import typing as t from contextvars import ContextVar from werkzeug.local import LocalProxy if t.TYPE_CHECKING: # pragma: no cover from .app import Flask from .ctx import _AppCtxGlobals from .ctx import AppContext from .ctx import RequestContext from .sessions import SessionMixin from .wrappers import Request __app_ctx_stack = _FakeStack("app", _cv_app) __request_ctx_stack = _FakeStack("request", _cv_request) import typing as t def __getattr__(name: str) -> t.Any: if name == "_app_ctx_stack": import warnings warnings.warn( "'_app_ctx_stack' is deprecated and will be removed in Flask 2.3.", DeprecationWarning, stacklevel=2, ) return __app_ctx_stack if name == "_request_ctx_stack": import warnings warnings.warn( "'_request_ctx_stack' is deprecated and will be removed in Flask 2.3.", DeprecationWarning, stacklevel=2, ) return __request_ctx_stack raise AttributeError(name)
null
174,835
from __future__ import annotations import dataclasses import decimal import json import typing as t import uuid import weakref from datetime import date from werkzeug.http import http_date from ..globals import request if t.TYPE_CHECKING: # pragma: no cover from ..app import Flask from ..wrappers import Response class date: min: ClassVar[date] max: ClassVar[date] resolution: ClassVar[timedelta] def __new__(cls: Type[_S], year: int, month: int, day: int) -> _S: ... def fromtimestamp(cls: Type[_S], __timestamp: float) -> _S: ... def today(cls: Type[_S]) -> _S: ... def fromordinal(cls: Type[_S], n: int) -> _S: ... if sys.version_info >= (3, 7): def fromisoformat(cls: Type[_S], date_string: str) -> _S: ... if sys.version_info >= (3, 8): def fromisocalendar(cls: Type[_S], year: int, week: int, day: int) -> _S: ... def year(self) -> int: ... def month(self) -> int: ... def day(self) -> int: ... def ctime(self) -> str: ... def strftime(self, fmt: _Text) -> str: ... if sys.version_info >= (3,): def __format__(self, fmt: str) -> str: ... else: def __format__(self, fmt: AnyStr) -> AnyStr: ... def isoformat(self) -> str: ... def timetuple(self) -> struct_time: ... def toordinal(self) -> int: ... def replace(self, year: int = ..., month: int = ..., day: int = ...) -> date: ... def __le__(self, other: date) -> bool: ... def __lt__(self, other: date) -> bool: ... def __ge__(self, other: date) -> bool: ... def __gt__(self, other: date) -> bool: ... if sys.version_info >= (3, 8): def __add__(self: _S, other: timedelta) -> _S: ... def __radd__(self: _S, other: timedelta) -> _S: ... else: def __add__(self, other: timedelta) -> date: ... def __radd__(self, other: timedelta) -> date: ... def __sub__(self, other: timedelta) -> date: ... def __sub__(self, other: date) -> timedelta: ... def __hash__(self) -> int: ... def weekday(self) -> int: ... def isoweekday(self) -> int: ... def isocalendar(self) -> Tuple[int, int, int]: ... def http_date( timestamp: t.Optional[t.Union[datetime, date, int, float, struct_time]] = None ) -> str: """Format a datetime object or timestamp into an :rfc:`2822` date string. This is a wrapper for :func:`email.utils.format_datetime`. It assumes naive datetime objects are in UTC instead of raising an exception. :param timestamp: The datetime or timestamp to format. Defaults to the current time. .. versionchanged:: 2.0 Use ``email.utils.format_datetime``. Accept ``date`` objects. """ if isinstance(timestamp, date): if not isinstance(timestamp, datetime): # Assume plain date is midnight UTC. timestamp = datetime.combine(timestamp, time(), tzinfo=timezone.utc) else: # Ensure datetime is timezone-aware. timestamp = _dt_as_utc(timestamp) return email.utils.format_datetime(timestamp, usegmt=True) if isinstance(timestamp, struct_time): timestamp = mktime(timestamp) return email.utils.formatdate(timestamp, usegmt=True) def _default(o: t.Any) -> t.Any: if isinstance(o, date): return http_date(o) if isinstance(o, (decimal.Decimal, uuid.UUID)): return str(o) if dataclasses and dataclasses.is_dataclass(o): return dataclasses.asdict(o) if hasattr(o, "__html__"): return str(o.__html__()) raise TypeError(f"Object of type {type(o).__name__} is not JSON serializable")
null
174,836
import os import pkgutil import socket import sys import typing as t from datetime import datetime from functools import lru_cache from functools import update_wrapper from threading import RLock import werkzeug.utils from werkzeug.exceptions import abort as _wz_abort from werkzeug.utils import redirect as _wz_redirect from .globals import _cv_request from .globals import current_app from .globals import request from .globals import request_ctx from .globals import session from .signals import message_flashed The provided code snippet includes necessary dependencies for implementing the `get_env` function. Write a Python function `def get_env() -> str` to solve the following problem: Get the environment the app is running in, indicated by the :envvar:`FLASK_ENV` environment variable. The default is ``'production'``. .. deprecated:: 2.2 Will be removed in Flask 2.3. Here is the function: def get_env() -> str: """Get the environment the app is running in, indicated by the :envvar:`FLASK_ENV` environment variable. The default is ``'production'``. .. deprecated:: 2.2 Will be removed in Flask 2.3. """ import warnings warnings.warn( "'FLASK_ENV' and 'get_env' are deprecated and will be removed" " in Flask 2.3. Use 'FLASK_DEBUG' instead.", DeprecationWarning, stacklevel=2, ) return os.environ.get("FLASK_ENV") or "production"
Get the environment the app is running in, indicated by the :envvar:`FLASK_ENV` environment variable. The default is ``'production'``. .. deprecated:: 2.2 Will be removed in Flask 2.3.
174,837
import os import pkgutil import socket import sys import typing as t from datetime import datetime from functools import lru_cache from functools import update_wrapper from threading import RLock import werkzeug.utils from werkzeug.exceptions import abort as _wz_abort from werkzeug.utils import redirect as _wz_redirect from .globals import _cv_request from .globals import current_app from .globals import request from .globals import request_ctx from .globals import session from .signals import message_flashed The provided code snippet includes necessary dependencies for implementing the `get_load_dotenv` function. Write a Python function `def get_load_dotenv(default: bool = True) -> bool` to solve the following problem: Get whether the user has disabled loading default dotenv files by setting :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load the files. :param default: What to return if the env var isn't set. Here is the function: def get_load_dotenv(default: bool = True) -> bool: """Get whether the user has disabled loading default dotenv files by setting :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load the files. :param default: What to return if the env var isn't set. """ val = os.environ.get("FLASK_SKIP_DOTENV") if not val: return default return val.lower() in ("0", "false", "no")
Get whether the user has disabled loading default dotenv files by setting :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load the files. :param default: What to return if the env var isn't set.
174,838
import os import pkgutil import socket import sys import typing as t from datetime import datetime from functools import lru_cache from functools import update_wrapper from threading import RLock import werkzeug.utils from werkzeug.exceptions import abort as _wz_abort from werkzeug.utils import redirect as _wz_redirect from .globals import _cv_request from .globals import current_app from .globals import request from .globals import request_ctx from .globals import session from .signals import message_flashed if t.TYPE_CHECKING: # pragma: no cover from werkzeug.wrappers import Response as BaseResponse from .wrappers import Response import typing_extensions as te import typing as t current_app: "Flask" = LocalProxy( # type: ignore[assignment] _cv_app, "app", unbound_message=_no_app_msg ) The provided code snippet includes necessary dependencies for implementing the `make_response` function. Write a Python function `def make_response(*args: t.Any) -> "Response"` to solve the following problem: Sometimes it is necessary to set additional headers in a view. Because views do not have to return response objects but can return a value that is converted into a response object by Flask itself, it becomes tricky to add headers to it. This function can be called instead of using a return and you will get a response object which you can use to attach headers. If view looked like this and you want to add a new header:: def index(): return render_template('index.html', foo=42) You can now do something like this:: def index(): response = make_response(render_template('index.html', foo=42)) response.headers['X-Parachutes'] = 'parachutes are cool' return response This function accepts the very same arguments you can return from a view function. This for example creates a response with a 404 error code:: response = make_response(render_template('not_found.html'), 404) The other use case of this function is to force the return value of a view function into a response which is helpful with view decorators:: response = make_response(view_function()) response.headers['X-Parachutes'] = 'parachutes are cool' Internally this function does the following things: - if no arguments are passed, it creates a new response argument - if one argument is passed, :meth:`flask.Flask.make_response` is invoked with it. - if more than one argument is passed, the arguments are passed to the :meth:`flask.Flask.make_response` function as tuple. .. versionadded:: 0.6 Here is the function: def make_response(*args: t.Any) -> "Response": """Sometimes it is necessary to set additional headers in a view. Because views do not have to return response objects but can return a value that is converted into a response object by Flask itself, it becomes tricky to add headers to it. This function can be called instead of using a return and you will get a response object which you can use to attach headers. If view looked like this and you want to add a new header:: def index(): return render_template('index.html', foo=42) You can now do something like this:: def index(): response = make_response(render_template('index.html', foo=42)) response.headers['X-Parachutes'] = 'parachutes are cool' return response This function accepts the very same arguments you can return from a view function. This for example creates a response with a 404 error code:: response = make_response(render_template('not_found.html'), 404) The other use case of this function is to force the return value of a view function into a response which is helpful with view decorators:: response = make_response(view_function()) response.headers['X-Parachutes'] = 'parachutes are cool' Internally this function does the following things: - if no arguments are passed, it creates a new response argument - if one argument is passed, :meth:`flask.Flask.make_response` is invoked with it. - if more than one argument is passed, the arguments are passed to the :meth:`flask.Flask.make_response` function as tuple. .. versionadded:: 0.6 """ if not args: return current_app.response_class() if len(args) == 1: args = args[0] return current_app.make_response(args) # type: ignore
Sometimes it is necessary to set additional headers in a view. Because views do not have to return response objects but can return a value that is converted into a response object by Flask itself, it becomes tricky to add headers to it. This function can be called instead of using a return and you will get a response object which you can use to attach headers. If view looked like this and you want to add a new header:: def index(): return render_template('index.html', foo=42) You can now do something like this:: def index(): response = make_response(render_template('index.html', foo=42)) response.headers['X-Parachutes'] = 'parachutes are cool' return response This function accepts the very same arguments you can return from a view function. This for example creates a response with a 404 error code:: response = make_response(render_template('not_found.html'), 404) The other use case of this function is to force the return value of a view function into a response which is helpful with view decorators:: response = make_response(view_function()) response.headers['X-Parachutes'] = 'parachutes are cool' Internally this function does the following things: - if no arguments are passed, it creates a new response argument - if one argument is passed, :meth:`flask.Flask.make_response` is invoked with it. - if more than one argument is passed, the arguments are passed to the :meth:`flask.Flask.make_response` function as tuple. .. versionadded:: 0.6
174,839
import os import pkgutil import socket import sys import typing as t from datetime import datetime from functools import lru_cache from functools import update_wrapper from threading import RLock import werkzeug.utils from werkzeug.exceptions import abort as _wz_abort from werkzeug.utils import redirect as _wz_redirect from .globals import _cv_request from .globals import current_app from .globals import request from .globals import request_ctx from .globals import session from .signals import message_flashed if t.TYPE_CHECKING: # pragma: no cover from werkzeug.wrappers import Response as BaseResponse from .wrappers import Response import typing_extensions as te import typing as t current_app: "Flask" = LocalProxy( # type: ignore[assignment] _cv_app, "app", unbound_message=_no_app_msg ) The provided code snippet includes necessary dependencies for implementing the `url_for` function. Write a Python function `def url_for( endpoint: str, *, _anchor: t.Optional[str] = None, _method: t.Optional[str] = None, _scheme: t.Optional[str] = None, _external: t.Optional[bool] = None, **values: t.Any, ) -> str` to solve the following problem: Generate a URL to the given endpoint with the given values. This requires an active request or application context, and calls :meth:`current_app.url_for() <flask.Flask.url_for>`. See that method for full documentation. :param endpoint: The endpoint name associated with the URL to generate. If this starts with a ``.``, the current blueprint name (if any) will be used. :param _anchor: If given, append this as ``#anchor`` to the URL. :param _method: If given, generate the URL associated with this method for the endpoint. :param _scheme: If given, the URL will have this scheme if it is external. :param _external: If given, prefer the URL to be internal (False) or require it to be external (True). External URLs include the scheme and domain. When not in an active request, URLs are external by default. :param values: Values to use for the variable parts of the URL rule. Unknown keys are appended as query string arguments, like ``?a=b&c=d``. .. versionchanged:: 2.2 Calls ``current_app.url_for``, allowing an app to override the behavior. .. versionchanged:: 0.10 The ``_scheme`` parameter was added. .. versionchanged:: 0.9 The ``_anchor`` and ``_method`` parameters were added. .. versionchanged:: 0.9 Calls ``app.handle_url_build_error`` on build errors. Here is the function: def url_for( endpoint: str, *, _anchor: t.Optional[str] = None, _method: t.Optional[str] = None, _scheme: t.Optional[str] = None, _external: t.Optional[bool] = None, **values: t.Any, ) -> str: """Generate a URL to the given endpoint with the given values. This requires an active request or application context, and calls :meth:`current_app.url_for() <flask.Flask.url_for>`. See that method for full documentation. :param endpoint: The endpoint name associated with the URL to generate. If this starts with a ``.``, the current blueprint name (if any) will be used. :param _anchor: If given, append this as ``#anchor`` to the URL. :param _method: If given, generate the URL associated with this method for the endpoint. :param _scheme: If given, the URL will have this scheme if it is external. :param _external: If given, prefer the URL to be internal (False) or require it to be external (True). External URLs include the scheme and domain. When not in an active request, URLs are external by default. :param values: Values to use for the variable parts of the URL rule. Unknown keys are appended as query string arguments, like ``?a=b&c=d``. .. versionchanged:: 2.2 Calls ``current_app.url_for``, allowing an app to override the behavior. .. versionchanged:: 0.10 The ``_scheme`` parameter was added. .. versionchanged:: 0.9 The ``_anchor`` and ``_method`` parameters were added. .. versionchanged:: 0.9 Calls ``app.handle_url_build_error`` on build errors. """ return current_app.url_for( endpoint, _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external, **values, )
Generate a URL to the given endpoint with the given values. This requires an active request or application context, and calls :meth:`current_app.url_for() <flask.Flask.url_for>`. See that method for full documentation. :param endpoint: The endpoint name associated with the URL to generate. If this starts with a ``.``, the current blueprint name (if any) will be used. :param _anchor: If given, append this as ``#anchor`` to the URL. :param _method: If given, generate the URL associated with this method for the endpoint. :param _scheme: If given, the URL will have this scheme if it is external. :param _external: If given, prefer the URL to be internal (False) or require it to be external (True). External URLs include the scheme and domain. When not in an active request, URLs are external by default. :param values: Values to use for the variable parts of the URL rule. Unknown keys are appended as query string arguments, like ``?a=b&c=d``. .. versionchanged:: 2.2 Calls ``current_app.url_for``, allowing an app to override the behavior. .. versionchanged:: 0.10 The ``_scheme`` parameter was added. .. versionchanged:: 0.9 The ``_anchor`` and ``_method`` parameters were added. .. versionchanged:: 0.9 Calls ``app.handle_url_build_error`` on build errors.
174,840
import os import pkgutil import socket import sys import typing as t from datetime import datetime from functools import lru_cache from functools import update_wrapper from threading import RLock import werkzeug.utils from werkzeug.exceptions import abort as _wz_abort from werkzeug.utils import redirect as _wz_redirect from .globals import _cv_request from .globals import current_app from .globals import request from .globals import request_ctx from .globals import session from .signals import message_flashed if t.TYPE_CHECKING: # pragma: no cover from werkzeug.wrappers import Response as BaseResponse from .wrappers import Response import typing_extensions as te import typing as t current_app: "Flask" = LocalProxy( # type: ignore[assignment] _cv_app, "app", unbound_message=_no_app_msg ) The provided code snippet includes necessary dependencies for implementing the `redirect` function. Write a Python function `def redirect( location: str, code: int = 302, Response: t.Optional[t.Type["BaseResponse"]] = None ) -> "BaseResponse"` to solve the following problem: Create a redirect response object. If :data:`~flask.current_app` is available, it will use its :meth:`~flask.Flask.redirect` method, otherwise it will use :func:`werkzeug.utils.redirect`. :param location: The URL to redirect to. :param code: The status code for the redirect. :param Response: The response class to use. Not used when ``current_app`` is active, which uses ``app.response_class``. .. versionadded:: 2.2 Calls ``current_app.redirect`` if available instead of always using Werkzeug's default ``redirect``. Here is the function: def redirect( location: str, code: int = 302, Response: t.Optional[t.Type["BaseResponse"]] = None ) -> "BaseResponse": """Create a redirect response object. If :data:`~flask.current_app` is available, it will use its :meth:`~flask.Flask.redirect` method, otherwise it will use :func:`werkzeug.utils.redirect`. :param location: The URL to redirect to. :param code: The status code for the redirect. :param Response: The response class to use. Not used when ``current_app`` is active, which uses ``app.response_class``. .. versionadded:: 2.2 Calls ``current_app.redirect`` if available instead of always using Werkzeug's default ``redirect``. """ if current_app: return current_app.redirect(location, code=code) return _wz_redirect(location, code=code, Response=Response)
Create a redirect response object. If :data:`~flask.current_app` is available, it will use its :meth:`~flask.Flask.redirect` method, otherwise it will use :func:`werkzeug.utils.redirect`. :param location: The URL to redirect to. :param code: The status code for the redirect. :param Response: The response class to use. Not used when ``current_app`` is active, which uses ``app.response_class``. .. versionadded:: 2.2 Calls ``current_app.redirect`` if available instead of always using Werkzeug's default ``redirect``.
174,841
import os import pkgutil import socket import sys import typing as t from datetime import datetime from functools import lru_cache from functools import update_wrapper from threading import RLock import werkzeug.utils from werkzeug.exceptions import abort as _wz_abort from werkzeug.utils import redirect as _wz_redirect from .globals import _cv_request from .globals import current_app from .globals import request from .globals import request_ctx from .globals import session from .signals import message_flashed if t.TYPE_CHECKING: # pragma: no cover from werkzeug.wrappers import Response as BaseResponse from .wrappers import Response import typing_extensions as te import typing as t current_app: "Flask" = LocalProxy( # type: ignore[assignment] _cv_app, "app", unbound_message=_no_app_msg ) The provided code snippet includes necessary dependencies for implementing the `abort` function. Write a Python function `def abort( code: t.Union[int, "BaseResponse"], *args: t.Any, **kwargs: t.Any ) -> "te.NoReturn"` to solve the following problem: Raise an :exc:`~werkzeug.exceptions.HTTPException` for the given status code. If :data:`~flask.current_app` is available, it will call its :attr:`~flask.Flask.aborter` object, otherwise it will use :func:`werkzeug.exceptions.abort`. :param code: The status code for the exception, which must be registered in ``app.aborter``. :param args: Passed to the exception. :param kwargs: Passed to the exception. .. versionadded:: 2.2 Calls ``current_app.aborter`` if available instead of always using Werkzeug's default ``abort``. Here is the function: def abort( code: t.Union[int, "BaseResponse"], *args: t.Any, **kwargs: t.Any ) -> "te.NoReturn": """Raise an :exc:`~werkzeug.exceptions.HTTPException` for the given status code. If :data:`~flask.current_app` is available, it will call its :attr:`~flask.Flask.aborter` object, otherwise it will use :func:`werkzeug.exceptions.abort`. :param code: The status code for the exception, which must be registered in ``app.aborter``. :param args: Passed to the exception. :param kwargs: Passed to the exception. .. versionadded:: 2.2 Calls ``current_app.aborter`` if available instead of always using Werkzeug's default ``abort``. """ if current_app: current_app.aborter(code, *args, **kwargs) _wz_abort(code, *args, **kwargs)
Raise an :exc:`~werkzeug.exceptions.HTTPException` for the given status code. If :data:`~flask.current_app` is available, it will call its :attr:`~flask.Flask.aborter` object, otherwise it will use :func:`werkzeug.exceptions.abort`. :param code: The status code for the exception, which must be registered in ``app.aborter``. :param args: Passed to the exception. :param kwargs: Passed to the exception. .. versionadded:: 2.2 Calls ``current_app.aborter`` if available instead of always using Werkzeug's default ``abort``.
174,842
import os import pkgutil import socket import sys import typing as t from datetime import datetime from functools import lru_cache from functools import update_wrapper from threading import RLock import werkzeug.utils from werkzeug.exceptions import abort as _wz_abort from werkzeug.utils import redirect as _wz_redirect from .globals import _cv_request from .globals import current_app from .globals import request from .globals import request_ctx from .globals import session from .signals import message_flashed if t.TYPE_CHECKING: # pragma: no cover from werkzeug.wrappers import Response as BaseResponse from .wrappers import Response import typing_extensions as te import typing as t current_app: "Flask" = LocalProxy( # type: ignore[assignment] _cv_app, "app", unbound_message=_no_app_msg ) The provided code snippet includes necessary dependencies for implementing the `get_template_attribute` function. Write a Python function `def get_template_attribute(template_name: str, attribute: str) -> t.Any` to solve the following problem: Loads a macro (or variable) a template exports. This can be used to invoke a macro from within Python code. If you for example have a template named :file:`_cider.html` with the following contents: .. sourcecode:: html+jinja {% macro hello(name) %}Hello {{ name }}!{% endmacro %} You can access this from Python code like this:: hello = get_template_attribute('_cider.html', 'hello') return hello('World') .. versionadded:: 0.2 :param template_name: the name of the template :param attribute: the name of the variable of macro to access Here is the function: def get_template_attribute(template_name: str, attribute: str) -> t.Any: """Loads a macro (or variable) a template exports. This can be used to invoke a macro from within Python code. If you for example have a template named :file:`_cider.html` with the following contents: .. sourcecode:: html+jinja {% macro hello(name) %}Hello {{ name }}!{% endmacro %} You can access this from Python code like this:: hello = get_template_attribute('_cider.html', 'hello') return hello('World') .. versionadded:: 0.2 :param template_name: the name of the template :param attribute: the name of the variable of macro to access """ return getattr(current_app.jinja_env.get_template(template_name).module, attribute)
Loads a macro (or variable) a template exports. This can be used to invoke a macro from within Python code. If you for example have a template named :file:`_cider.html` with the following contents: .. sourcecode:: html+jinja {% macro hello(name) %}Hello {{ name }}!{% endmacro %} You can access this from Python code like this:: hello = get_template_attribute('_cider.html', 'hello') return hello('World') .. versionadded:: 0.2 :param template_name: the name of the template :param attribute: the name of the variable of macro to access
174,843
import os import pkgutil import socket import sys import typing as t from datetime import datetime from functools import lru_cache from functools import update_wrapper from threading import RLock import werkzeug.utils from werkzeug.exceptions import abort as _wz_abort from werkzeug.utils import redirect as _wz_redirect from .globals import _cv_request from .globals import current_app from .globals import request from .globals import request_ctx from .globals import session from .signals import message_flashed current_app: "Flask" = LocalProxy( # type: ignore[assignment] _cv_app, "app", unbound_message=_no_app_msg ) session: "SessionMixin" = LocalProxy( # type: ignore[assignment] _cv_request, "session", unbound_message=_no_req_msg ) message_flashed = _signals.signal("message-flashed") The provided code snippet includes necessary dependencies for implementing the `flash` function. Write a Python function `def flash(message: str, category: str = "message") -> None` to solve the following problem: Flashes a message to the next request. In order to remove the flashed message from the session and to display it to the user, the template has to call :func:`get_flashed_messages`. .. versionchanged:: 0.3 `category` parameter added. :param message: the message to be flashed. :param category: the category for the message. The following values are recommended: ``'message'`` for any kind of message, ``'error'`` for errors, ``'info'`` for information messages and ``'warning'`` for warnings. However any kind of string can be used as category. Here is the function: def flash(message: str, category: str = "message") -> None: """Flashes a message to the next request. In order to remove the flashed message from the session and to display it to the user, the template has to call :func:`get_flashed_messages`. .. versionchanged:: 0.3 `category` parameter added. :param message: the message to be flashed. :param category: the category for the message. The following values are recommended: ``'message'`` for any kind of message, ``'error'`` for errors, ``'info'`` for information messages and ``'warning'`` for warnings. However any kind of string can be used as category. """ # Original implementation: # # session.setdefault('_flashes', []).append((category, message)) # # This assumed that changes made to mutable structures in the session are # always in sync with the session object, which is not true for session # implementations that use external storage for keeping their keys/values. flashes = session.get("_flashes", []) flashes.append((category, message)) session["_flashes"] = flashes message_flashed.send( current_app._get_current_object(), # type: ignore message=message, category=category, )
Flashes a message to the next request. In order to remove the flashed message from the session and to display it to the user, the template has to call :func:`get_flashed_messages`. .. versionchanged:: 0.3 `category` parameter added. :param message: the message to be flashed. :param category: the category for the message. The following values are recommended: ``'message'`` for any kind of message, ``'error'`` for errors, ``'info'`` for information messages and ``'warning'`` for warnings. However any kind of string can be used as category.
174,844
import os import pkgutil import socket import sys import typing as t from datetime import datetime from functools import lru_cache from functools import update_wrapper from threading import RLock import werkzeug.utils from werkzeug.exceptions import abort as _wz_abort from werkzeug.utils import redirect as _wz_redirect from .globals import _cv_request from .globals import current_app from .globals import request from .globals import request_ctx from .globals import session from .signals import message_flashed if t.TYPE_CHECKING: # pragma: no cover from werkzeug.wrappers import Response as BaseResponse from .wrappers import Response import typing_extensions as te import typing as t request_ctx: "RequestContext" = LocalProxy( # type: ignore[assignment] _cv_request, unbound_message=_no_req_msg ) session: "SessionMixin" = LocalProxy( # type: ignore[assignment] _cv_request, "session", unbound_message=_no_req_msg ) The provided code snippet includes necessary dependencies for implementing the `get_flashed_messages` function. Write a Python function `def get_flashed_messages( with_categories: bool = False, category_filter: t.Iterable[str] = () ) -> t.Union[t.List[str], t.List[t.Tuple[str, str]]]` to solve the following problem: Pulls all flashed messages from the session and returns them. Further calls in the same request to the function will return the same messages. By default just the messages are returned, but when `with_categories` is set to ``True``, the return value will be a list of tuples in the form ``(category, message)`` instead. Filter the flashed messages to one or more categories by providing those categories in `category_filter`. This allows rendering categories in separate html blocks. The `with_categories` and `category_filter` arguments are distinct: * `with_categories` controls whether categories are returned with message text (``True`` gives a tuple, where ``False`` gives just the message text). * `category_filter` filters the messages down to only those matching the provided categories. See :doc:`/patterns/flashing` for examples. .. versionchanged:: 0.3 `with_categories` parameter added. .. versionchanged:: 0.9 `category_filter` parameter added. :param with_categories: set to ``True`` to also receive categories. :param category_filter: filter of categories to limit return values. Only categories in the list will be returned. Here is the function: def get_flashed_messages( with_categories: bool = False, category_filter: t.Iterable[str] = () ) -> t.Union[t.List[str], t.List[t.Tuple[str, str]]]: """Pulls all flashed messages from the session and returns them. Further calls in the same request to the function will return the same messages. By default just the messages are returned, but when `with_categories` is set to ``True``, the return value will be a list of tuples in the form ``(category, message)`` instead. Filter the flashed messages to one or more categories by providing those categories in `category_filter`. This allows rendering categories in separate html blocks. The `with_categories` and `category_filter` arguments are distinct: * `with_categories` controls whether categories are returned with message text (``True`` gives a tuple, where ``False`` gives just the message text). * `category_filter` filters the messages down to only those matching the provided categories. See :doc:`/patterns/flashing` for examples. .. versionchanged:: 0.3 `with_categories` parameter added. .. versionchanged:: 0.9 `category_filter` parameter added. :param with_categories: set to ``True`` to also receive categories. :param category_filter: filter of categories to limit return values. Only categories in the list will be returned. """ flashes = request_ctx.flashes if flashes is None: flashes = session.pop("_flashes") if "_flashes" in session else [] request_ctx.flashes = flashes if category_filter: flashes = list(filter(lambda f: f[0] in category_filter, flashes)) if not with_categories: return [x[1] for x in flashes] return flashes
Pulls all flashed messages from the session and returns them. Further calls in the same request to the function will return the same messages. By default just the messages are returned, but when `with_categories` is set to ``True``, the return value will be a list of tuples in the form ``(category, message)`` instead. Filter the flashed messages to one or more categories by providing those categories in `category_filter`. This allows rendering categories in separate html blocks. The `with_categories` and `category_filter` arguments are distinct: * `with_categories` controls whether categories are returned with message text (``True`` gives a tuple, where ``False`` gives just the message text). * `category_filter` filters the messages down to only those matching the provided categories. See :doc:`/patterns/flashing` for examples. .. versionchanged:: 0.3 `with_categories` parameter added. .. versionchanged:: 0.9 `category_filter` parameter added. :param with_categories: set to ``True`` to also receive categories. :param category_filter: filter of categories to limit return values. Only categories in the list will be returned.
174,845
import os import pkgutil import socket import sys import typing as t from datetime import datetime from functools import lru_cache from functools import update_wrapper from threading import RLock import werkzeug.utils from werkzeug.exceptions import abort as _wz_abort from werkzeug.utils import redirect as _wz_redirect from .globals import _cv_request from .globals import current_app from .globals import request from .globals import request_ctx from .globals import session from .signals import message_flashed if t.TYPE_CHECKING: # pragma: no cover from werkzeug.wrappers import Response as BaseResponse from .wrappers import Response import typing_extensions as te def _prepare_send_file_kwargs(**kwargs: t.Any) -> t.Dict[str, t.Any]: if kwargs.get("max_age") is None: kwargs["max_age"] = current_app.get_send_file_max_age kwargs.update( environ=request.environ, use_x_sendfile=current_app.config["USE_X_SENDFILE"], response_class=current_app.response_class, _root_path=current_app.root_path, # type: ignore ) return kwargs import typing as t class datetime(date): min: ClassVar[datetime] max: ClassVar[datetime] resolution: ClassVar[timedelta] if sys.version_info >= (3, 6): def __new__( cls: Type[_S], year: int, month: int, day: int, hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., *, fold: int = ..., ) -> _S: ... else: def __new__( cls: Type[_S], year: int, month: int, day: int, hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., ) -> _S: ... def year(self) -> int: ... def month(self) -> int: ... def day(self) -> int: ... def hour(self) -> int: ... def minute(self) -> int: ... def second(self) -> int: ... def microsecond(self) -> int: ... def tzinfo(self) -> Optional[_tzinfo]: ... if sys.version_info >= (3, 6): def fold(self) -> int: ... def fromtimestamp(cls: Type[_S], t: float, tz: Optional[_tzinfo] = ...) -> _S: ... def utcfromtimestamp(cls: Type[_S], t: float) -> _S: ... def today(cls: Type[_S]) -> _S: ... def fromordinal(cls: Type[_S], n: int) -> _S: ... if sys.version_info >= (3, 8): def now(cls: Type[_S], tz: Optional[_tzinfo] = ...) -> _S: ... else: def now(cls: Type[_S], tz: None = ...) -> _S: ... def now(cls, tz: _tzinfo) -> datetime: ... def utcnow(cls: Type[_S]) -> _S: ... if sys.version_info >= (3, 6): def combine(cls, date: _date, time: _time, tzinfo: Optional[_tzinfo] = ...) -> datetime: ... else: def combine(cls, date: _date, time: _time) -> datetime: ... if sys.version_info >= (3, 7): def fromisoformat(cls: Type[_S], date_string: str) -> _S: ... def strftime(self, fmt: _Text) -> str: ... if sys.version_info >= (3,): def __format__(self, fmt: str) -> str: ... else: def __format__(self, fmt: AnyStr) -> AnyStr: ... def toordinal(self) -> int: ... def timetuple(self) -> struct_time: ... if sys.version_info >= (3, 3): def timestamp(self) -> float: ... def utctimetuple(self) -> struct_time: ... def date(self) -> _date: ... def time(self) -> _time: ... def timetz(self) -> _time: ... if sys.version_info >= (3, 6): def replace( self, year: int = ..., month: int = ..., day: int = ..., hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., *, fold: int = ..., ) -> datetime: ... else: def replace( self, year: int = ..., month: int = ..., day: int = ..., hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., ) -> datetime: ... if sys.version_info >= (3, 8): def astimezone(self: _S, tz: Optional[_tzinfo] = ...) -> _S: ... elif sys.version_info >= (3, 3): def astimezone(self, tz: Optional[_tzinfo] = ...) -> datetime: ... else: def astimezone(self, tz: _tzinfo) -> datetime: ... def ctime(self) -> str: ... if sys.version_info >= (3, 6): def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ... else: def isoformat(self, sep: str = ...) -> str: ... def strptime(cls, date_string: _Text, format: _Text) -> datetime: ... def utcoffset(self) -> Optional[timedelta]: ... def tzname(self) -> Optional[str]: ... def dst(self) -> Optional[timedelta]: ... def __le__(self, other: datetime) -> bool: ... # type: ignore def __lt__(self, other: datetime) -> bool: ... # type: ignore def __ge__(self, other: datetime) -> bool: ... # type: ignore def __gt__(self, other: datetime) -> bool: ... # type: ignore if sys.version_info >= (3, 8): def __add__(self: _S, other: timedelta) -> _S: ... def __radd__(self: _S, other: timedelta) -> _S: ... else: def __add__(self, other: timedelta) -> datetime: ... def __radd__(self, other: timedelta) -> datetime: ... def __sub__(self, other: datetime) -> timedelta: ... def __sub__(self, other: timedelta) -> datetime: ... def __hash__(self) -> int: ... def weekday(self) -> int: ... def isoweekday(self) -> int: ... def isocalendar(self) -> Tuple[int, int, int]: ... request: "Request" = LocalProxy( # type: ignore[assignment] _cv_request, "request", unbound_message=_no_req_msg ) The provided code snippet includes necessary dependencies for implementing the `send_file` function. Write a Python function `def send_file( path_or_file: t.Union[os.PathLike, str, t.BinaryIO], mimetype: t.Optional[str] = None, as_attachment: bool = False, download_name: t.Optional[str] = None, conditional: bool = True, etag: t.Union[bool, str] = True, last_modified: t.Optional[t.Union[datetime, int, float]] = None, max_age: t.Optional[ t.Union[int, t.Callable[[t.Optional[str]], t.Optional[int]]] ] = None, ) -> "Response"` to solve the following problem: Send the contents of a file to the client. The first argument can be a file path or a file-like object. Paths are preferred in most cases because Werkzeug can manage the file and get extra information from the path. Passing a file-like object requires that the file is opened in binary mode, and is mostly useful when building a file in memory with :class:`io.BytesIO`. Never pass file paths provided by a user. The path is assumed to be trusted, so a user could craft a path to access a file you didn't intend. Use :func:`send_from_directory` to safely serve user-requested paths from within a directory. If the WSGI server sets a ``file_wrapper`` in ``environ``, it is used, otherwise Werkzeug's built-in wrapper is used. Alternatively, if the HTTP server supports ``X-Sendfile``, configuring Flask with ``USE_X_SENDFILE = True`` will tell the server to send the given path, which is much more efficient than reading it in Python. :param path_or_file: The path to the file to send, relative to the current working directory if a relative path is given. Alternatively, a file-like object opened in binary mode. Make sure the file pointer is seeked to the start of the data. :param mimetype: The MIME type to send for the file. If not provided, it will try to detect it from the file name. :param as_attachment: Indicate to a browser that it should offer to save the file instead of displaying it. :param download_name: The default name browsers will use when saving the file. Defaults to the passed file name. :param conditional: Enable conditional and range responses based on request headers. Requires passing a file path and ``environ``. :param etag: Calculate an ETag for the file, which requires passing a file path. Can also be a string to use instead. :param last_modified: The last modified time to send for the file, in seconds. If not provided, it will try to detect it from the file path. :param max_age: How long the client should cache the file, in seconds. If set, ``Cache-Control`` will be ``public``, otherwise it will be ``no-cache`` to prefer conditional caching. .. versionchanged:: 2.0 ``download_name`` replaces the ``attachment_filename`` parameter. If ``as_attachment=False``, it is passed with ``Content-Disposition: inline`` instead. .. versionchanged:: 2.0 ``max_age`` replaces the ``cache_timeout`` parameter. ``conditional`` is enabled and ``max_age`` is not set by default. .. versionchanged:: 2.0 ``etag`` replaces the ``add_etags`` parameter. It can be a string to use instead of generating one. .. versionchanged:: 2.0 Passing a file-like object that inherits from :class:`~io.TextIOBase` will raise a :exc:`ValueError` rather than sending an empty file. .. versionadded:: 2.0 Moved the implementation to Werkzeug. This is now a wrapper to pass some Flask-specific arguments. .. versionchanged:: 1.1 ``filename`` may be a :class:`~os.PathLike` object. .. versionchanged:: 1.1 Passing a :class:`~io.BytesIO` object supports range requests. .. versionchanged:: 1.0.3 Filenames are encoded with ASCII instead of Latin-1 for broader compatibility with WSGI servers. .. versionchanged:: 1.0 UTF-8 filenames as specified in :rfc:`2231` are supported. .. versionchanged:: 0.12 The filename is no longer automatically inferred from file objects. If you want to use automatic MIME and etag support, pass a filename via ``filename_or_fp`` or ``attachment_filename``. .. versionchanged:: 0.12 ``attachment_filename`` is preferred over ``filename`` for MIME detection. .. versionchanged:: 0.9 ``cache_timeout`` defaults to :meth:`Flask.get_send_file_max_age`. .. versionchanged:: 0.7 MIME guessing and etag support for file-like objects was deprecated because it was unreliable. Pass a filename if you are able to, otherwise attach an etag yourself. .. versionchanged:: 0.5 The ``add_etags``, ``cache_timeout`` and ``conditional`` parameters were added. The default behavior is to add etags. .. versionadded:: 0.2 Here is the function: def send_file( path_or_file: t.Union[os.PathLike, str, t.BinaryIO], mimetype: t.Optional[str] = None, as_attachment: bool = False, download_name: t.Optional[str] = None, conditional: bool = True, etag: t.Union[bool, str] = True, last_modified: t.Optional[t.Union[datetime, int, float]] = None, max_age: t.Optional[ t.Union[int, t.Callable[[t.Optional[str]], t.Optional[int]]] ] = None, ) -> "Response": """Send the contents of a file to the client. The first argument can be a file path or a file-like object. Paths are preferred in most cases because Werkzeug can manage the file and get extra information from the path. Passing a file-like object requires that the file is opened in binary mode, and is mostly useful when building a file in memory with :class:`io.BytesIO`. Never pass file paths provided by a user. The path is assumed to be trusted, so a user could craft a path to access a file you didn't intend. Use :func:`send_from_directory` to safely serve user-requested paths from within a directory. If the WSGI server sets a ``file_wrapper`` in ``environ``, it is used, otherwise Werkzeug's built-in wrapper is used. Alternatively, if the HTTP server supports ``X-Sendfile``, configuring Flask with ``USE_X_SENDFILE = True`` will tell the server to send the given path, which is much more efficient than reading it in Python. :param path_or_file: The path to the file to send, relative to the current working directory if a relative path is given. Alternatively, a file-like object opened in binary mode. Make sure the file pointer is seeked to the start of the data. :param mimetype: The MIME type to send for the file. If not provided, it will try to detect it from the file name. :param as_attachment: Indicate to a browser that it should offer to save the file instead of displaying it. :param download_name: The default name browsers will use when saving the file. Defaults to the passed file name. :param conditional: Enable conditional and range responses based on request headers. Requires passing a file path and ``environ``. :param etag: Calculate an ETag for the file, which requires passing a file path. Can also be a string to use instead. :param last_modified: The last modified time to send for the file, in seconds. If not provided, it will try to detect it from the file path. :param max_age: How long the client should cache the file, in seconds. If set, ``Cache-Control`` will be ``public``, otherwise it will be ``no-cache`` to prefer conditional caching. .. versionchanged:: 2.0 ``download_name`` replaces the ``attachment_filename`` parameter. If ``as_attachment=False``, it is passed with ``Content-Disposition: inline`` instead. .. versionchanged:: 2.0 ``max_age`` replaces the ``cache_timeout`` parameter. ``conditional`` is enabled and ``max_age`` is not set by default. .. versionchanged:: 2.0 ``etag`` replaces the ``add_etags`` parameter. It can be a string to use instead of generating one. .. versionchanged:: 2.0 Passing a file-like object that inherits from :class:`~io.TextIOBase` will raise a :exc:`ValueError` rather than sending an empty file. .. versionadded:: 2.0 Moved the implementation to Werkzeug. This is now a wrapper to pass some Flask-specific arguments. .. versionchanged:: 1.1 ``filename`` may be a :class:`~os.PathLike` object. .. versionchanged:: 1.1 Passing a :class:`~io.BytesIO` object supports range requests. .. versionchanged:: 1.0.3 Filenames are encoded with ASCII instead of Latin-1 for broader compatibility with WSGI servers. .. versionchanged:: 1.0 UTF-8 filenames as specified in :rfc:`2231` are supported. .. versionchanged:: 0.12 The filename is no longer automatically inferred from file objects. If you want to use automatic MIME and etag support, pass a filename via ``filename_or_fp`` or ``attachment_filename``. .. versionchanged:: 0.12 ``attachment_filename`` is preferred over ``filename`` for MIME detection. .. versionchanged:: 0.9 ``cache_timeout`` defaults to :meth:`Flask.get_send_file_max_age`. .. versionchanged:: 0.7 MIME guessing and etag support for file-like objects was deprecated because it was unreliable. Pass a filename if you are able to, otherwise attach an etag yourself. .. versionchanged:: 0.5 The ``add_etags``, ``cache_timeout`` and ``conditional`` parameters were added. The default behavior is to add etags. .. versionadded:: 0.2 """ return werkzeug.utils.send_file( # type: ignore[return-value] **_prepare_send_file_kwargs( path_or_file=path_or_file, environ=request.environ, mimetype=mimetype, as_attachment=as_attachment, download_name=download_name, conditional=conditional, etag=etag, last_modified=last_modified, max_age=max_age, ) )
Send the contents of a file to the client. The first argument can be a file path or a file-like object. Paths are preferred in most cases because Werkzeug can manage the file and get extra information from the path. Passing a file-like object requires that the file is opened in binary mode, and is mostly useful when building a file in memory with :class:`io.BytesIO`. Never pass file paths provided by a user. The path is assumed to be trusted, so a user could craft a path to access a file you didn't intend. Use :func:`send_from_directory` to safely serve user-requested paths from within a directory. If the WSGI server sets a ``file_wrapper`` in ``environ``, it is used, otherwise Werkzeug's built-in wrapper is used. Alternatively, if the HTTP server supports ``X-Sendfile``, configuring Flask with ``USE_X_SENDFILE = True`` will tell the server to send the given path, which is much more efficient than reading it in Python. :param path_or_file: The path to the file to send, relative to the current working directory if a relative path is given. Alternatively, a file-like object opened in binary mode. Make sure the file pointer is seeked to the start of the data. :param mimetype: The MIME type to send for the file. If not provided, it will try to detect it from the file name. :param as_attachment: Indicate to a browser that it should offer to save the file instead of displaying it. :param download_name: The default name browsers will use when saving the file. Defaults to the passed file name. :param conditional: Enable conditional and range responses based on request headers. Requires passing a file path and ``environ``. :param etag: Calculate an ETag for the file, which requires passing a file path. Can also be a string to use instead. :param last_modified: The last modified time to send for the file, in seconds. If not provided, it will try to detect it from the file path. :param max_age: How long the client should cache the file, in seconds. If set, ``Cache-Control`` will be ``public``, otherwise it will be ``no-cache`` to prefer conditional caching. .. versionchanged:: 2.0 ``download_name`` replaces the ``attachment_filename`` parameter. If ``as_attachment=False``, it is passed with ``Content-Disposition: inline`` instead. .. versionchanged:: 2.0 ``max_age`` replaces the ``cache_timeout`` parameter. ``conditional`` is enabled and ``max_age`` is not set by default. .. versionchanged:: 2.0 ``etag`` replaces the ``add_etags`` parameter. It can be a string to use instead of generating one. .. versionchanged:: 2.0 Passing a file-like object that inherits from :class:`~io.TextIOBase` will raise a :exc:`ValueError` rather than sending an empty file. .. versionadded:: 2.0 Moved the implementation to Werkzeug. This is now a wrapper to pass some Flask-specific arguments. .. versionchanged:: 1.1 ``filename`` may be a :class:`~os.PathLike` object. .. versionchanged:: 1.1 Passing a :class:`~io.BytesIO` object supports range requests. .. versionchanged:: 1.0.3 Filenames are encoded with ASCII instead of Latin-1 for broader compatibility with WSGI servers. .. versionchanged:: 1.0 UTF-8 filenames as specified in :rfc:`2231` are supported. .. versionchanged:: 0.12 The filename is no longer automatically inferred from file objects. If you want to use automatic MIME and etag support, pass a filename via ``filename_or_fp`` or ``attachment_filename``. .. versionchanged:: 0.12 ``attachment_filename`` is preferred over ``filename`` for MIME detection. .. versionchanged:: 0.9 ``cache_timeout`` defaults to :meth:`Flask.get_send_file_max_age`. .. versionchanged:: 0.7 MIME guessing and etag support for file-like objects was deprecated because it was unreliable. Pass a filename if you are able to, otherwise attach an etag yourself. .. versionchanged:: 0.5 The ``add_etags``, ``cache_timeout`` and ``conditional`` parameters were added. The default behavior is to add etags. .. versionadded:: 0.2
174,846
import os import pkgutil import socket import sys import typing as t from datetime import datetime from functools import lru_cache from functools import update_wrapper from threading import RLock import werkzeug.utils from werkzeug.exceptions import abort as _wz_abort from werkzeug.utils import redirect as _wz_redirect from .globals import _cv_request from .globals import current_app from .globals import request from .globals import request_ctx from .globals import session from .signals import message_flashed if t.TYPE_CHECKING: # pragma: no cover from werkzeug.wrappers import Response as BaseResponse from .wrappers import Response import typing_extensions as te def _prepare_send_file_kwargs(**kwargs: t.Any) -> t.Dict[str, t.Any]: if kwargs.get("max_age") is None: kwargs["max_age"] = current_app.get_send_file_max_age kwargs.update( environ=request.environ, use_x_sendfile=current_app.config["USE_X_SENDFILE"], response_class=current_app.response_class, _root_path=current_app.root_path, # type: ignore ) return kwargs import typing as t The provided code snippet includes necessary dependencies for implementing the `send_from_directory` function. Write a Python function `def send_from_directory( directory: t.Union[os.PathLike, str], path: t.Union[os.PathLike, str], **kwargs: t.Any, ) -> "Response"` to solve the following problem: Send a file from within a directory using :func:`send_file`. .. code-block:: python @app.route("/uploads/<path:name>") def download_file(name): return send_from_directory( app.config['UPLOAD_FOLDER'], name, as_attachment=True ) This is a secure way to serve files from a folder, such as static files or uploads. Uses :func:`~werkzeug.security.safe_join` to ensure the path coming from the client is not maliciously crafted to point outside the specified directory. If the final path does not point to an existing regular file, raises a 404 :exc:`~werkzeug.exceptions.NotFound` error. :param directory: The directory that ``path`` must be located under, relative to the current application's root path. :param path: The path to the file to send, relative to ``directory``. :param kwargs: Arguments to pass to :func:`send_file`. .. versionchanged:: 2.0 ``path`` replaces the ``filename`` parameter. .. versionadded:: 2.0 Moved the implementation to Werkzeug. This is now a wrapper to pass some Flask-specific arguments. .. versionadded:: 0.5 Here is the function: def send_from_directory( directory: t.Union[os.PathLike, str], path: t.Union[os.PathLike, str], **kwargs: t.Any, ) -> "Response": """Send a file from within a directory using :func:`send_file`. .. code-block:: python @app.route("/uploads/<path:name>") def download_file(name): return send_from_directory( app.config['UPLOAD_FOLDER'], name, as_attachment=True ) This is a secure way to serve files from a folder, such as static files or uploads. Uses :func:`~werkzeug.security.safe_join` to ensure the path coming from the client is not maliciously crafted to point outside the specified directory. If the final path does not point to an existing regular file, raises a 404 :exc:`~werkzeug.exceptions.NotFound` error. :param directory: The directory that ``path`` must be located under, relative to the current application's root path. :param path: The path to the file to send, relative to ``directory``. :param kwargs: Arguments to pass to :func:`send_file`. .. versionchanged:: 2.0 ``path`` replaces the ``filename`` parameter. .. versionadded:: 2.0 Moved the implementation to Werkzeug. This is now a wrapper to pass some Flask-specific arguments. .. versionadded:: 0.5 """ return werkzeug.utils.send_from_directory( # type: ignore[return-value] directory, path, **_prepare_send_file_kwargs(**kwargs) )
Send a file from within a directory using :func:`send_file`. .. code-block:: python @app.route("/uploads/<path:name>") def download_file(name): return send_from_directory( app.config['UPLOAD_FOLDER'], name, as_attachment=True ) This is a secure way to serve files from a folder, such as static files or uploads. Uses :func:`~werkzeug.security.safe_join` to ensure the path coming from the client is not maliciously crafted to point outside the specified directory. If the final path does not point to an existing regular file, raises a 404 :exc:`~werkzeug.exceptions.NotFound` error. :param directory: The directory that ``path`` must be located under, relative to the current application's root path. :param path: The path to the file to send, relative to ``directory``. :param kwargs: Arguments to pass to :func:`send_file`. .. versionchanged:: 2.0 ``path`` replaces the ``filename`` parameter. .. versionadded:: 2.0 Moved the implementation to Werkzeug. This is now a wrapper to pass some Flask-specific arguments. .. versionadded:: 0.5
174,847
import os import pkgutil import socket import sys import typing as t from datetime import datetime from functools import lru_cache from functools import update_wrapper from threading import RLock import werkzeug.utils from werkzeug.exceptions import abort as _wz_abort from werkzeug.utils import redirect as _wz_redirect from .globals import _cv_request from .globals import current_app from .globals import request from .globals import request_ctx from .globals import session from .signals import message_flashed The provided code snippet includes necessary dependencies for implementing the `get_root_path` function. Write a Python function `def get_root_path(import_name: str) -> str` to solve the following problem: Find the root path of a package, or the path that contains a module. If it cannot be found, returns the current working directory. Not to be confused with the value returned by :func:`find_package`. :meta private: Here is the function: def get_root_path(import_name: str) -> str: """Find the root path of a package, or the path that contains a module. If it cannot be found, returns the current working directory. Not to be confused with the value returned by :func:`find_package`. :meta private: """ # Module already imported and has a file attribute. Use that first. mod = sys.modules.get(import_name) if mod is not None and hasattr(mod, "__file__") and mod.__file__ is not None: return os.path.dirname(os.path.abspath(mod.__file__)) # Next attempt: check the loader. loader = pkgutil.get_loader(import_name) # Loader does not exist or we're referring to an unloaded main # module or a main module without path (interactive sessions), go # with the current working directory. if loader is None or import_name == "__main__": return os.getcwd() if hasattr(loader, "get_filename"): filepath = loader.get_filename(import_name) else: # Fall back to imports. __import__(import_name) mod = sys.modules[import_name] filepath = getattr(mod, "__file__", None) # If we don't have a file path it might be because it is a # namespace package. In this case pick the root path from the # first module that is contained in the package. if filepath is None: raise RuntimeError( "No root path can be found for the provided module" f" {import_name!r}. This can happen because the module" " came from an import hook that does not provide file" " name information or because it's a namespace package." " In this case the root path needs to be explicitly" " provided." ) # filepath is import_name.py for a module, or __init__.py for a package. return os.path.dirname(os.path.abspath(filepath))
Find the root path of a package, or the path that contains a module. If it cannot be found, returns the current working directory. Not to be confused with the value returned by :func:`find_package`. :meta private:
174,848
import os import pkgutil import socket import sys import typing as t from datetime import datetime from functools import lru_cache from functools import update_wrapper from threading import RLock import werkzeug.utils from werkzeug.exceptions import abort as _wz_abort from werkzeug.utils import redirect as _wz_redirect from .globals import _cv_request from .globals import current_app from .globals import request from .globals import request_ctx from .globals import session from .signals import message_flashed The provided code snippet includes necessary dependencies for implementing the `is_ip` function. Write a Python function `def is_ip(value: str) -> bool` to solve the following problem: Determine if the given string is an IP address. :param value: value to check :type value: str :return: True if string is an IP address :rtype: bool Here is the function: def is_ip(value: str) -> bool: """Determine if the given string is an IP address. :param value: value to check :type value: str :return: True if string is an IP address :rtype: bool """ for family in (socket.AF_INET, socket.AF_INET6): try: socket.inet_pton(family, value) except OSError: pass else: return True return False
Determine if the given string is an IP address. :param value: value to check :type value: str :return: True if string is an IP address :rtype: bool
174,849
import os import pkgutil import socket import sys import typing as t from datetime import datetime from functools import lru_cache from functools import update_wrapper from threading import RLock import werkzeug.utils from werkzeug.exceptions import abort as _wz_abort from werkzeug.utils import redirect as _wz_redirect from .globals import _cv_request from .globals import current_app from .globals import request from .globals import request_ctx from .globals import session from .signals import message_flashed if t.TYPE_CHECKING: # pragma: no cover from werkzeug.wrappers import Response as BaseResponse from .wrappers import Response import typing_extensions as te import typing as t def _split_blueprint_path(name: str) -> t.List[str]: out: t.List[str] = [name] if "." in name: out.extend(_split_blueprint_path(name.rpartition(".")[0])) return out
null
174,850
import typing as t from jinja2 import BaseLoader from jinja2 import Environment as BaseEnvironment from jinja2 import Template from jinja2 import TemplateNotFound from .globals import _cv_app from .globals import _cv_request from .globals import current_app from .globals import request from .helpers import stream_with_context from .signals import before_render_template from .signals import template_rendered if t.TYPE_CHECKING: # pragma: no cover from .app import Flask from .scaffold import Scaffold import typing as t _cv_app: ContextVar["AppContext"] = ContextVar("flask.app_ctx") _cv_request: ContextVar["RequestContext"] = ContextVar("flask.request_ctx") request: "Request" = LocalProxy( # type: ignore[assignment] _cv_request, "request", unbound_message=_no_req_msg ) The provided code snippet includes necessary dependencies for implementing the `_default_template_ctx_processor` function. Write a Python function `def _default_template_ctx_processor() -> t.Dict[str, t.Any]` to solve the following problem: Default template context processor. Injects `request`, `session` and `g`. Here is the function: def _default_template_ctx_processor() -> t.Dict[str, t.Any]: """Default template context processor. Injects `request`, `session` and `g`. """ appctx = _cv_app.get(None) reqctx = _cv_request.get(None) rv: t.Dict[str, t.Any] = {} if appctx is not None: rv["g"] = appctx.g if reqctx is not None: rv["request"] = reqctx.request rv["session"] = reqctx.session return rv
Default template context processor. Injects `request`, `session` and `g`.
174,851
import typing as t from jinja2 import BaseLoader from jinja2 import Environment as BaseEnvironment from jinja2 import Template from jinja2 import TemplateNotFound from .globals import _cv_app from .globals import _cv_request from .globals import current_app from .globals import request from .helpers import stream_with_context from .signals import before_render_template from .signals import template_rendered if t.TYPE_CHECKING: # pragma: no cover from .app import Flask from .scaffold import Scaffold def _render(app: "Flask", template: Template, context: t.Dict[str, t.Any]) -> str: app.update_template_context(context) before_render_template.send(app, template=template, context=context) rv = template.render(context) template_rendered.send(app, template=template, context=context) return rv import typing as t current_app: "Flask" = LocalProxy( # type: ignore[assignment] _cv_app, "app", unbound_message=_no_app_msg ) The provided code snippet includes necessary dependencies for implementing the `render_template` function. Write a Python function `def render_template( template_name_or_list: t.Union[str, Template, t.List[t.Union[str, Template]]], **context: t.Any ) -> str` to solve the following problem: Render a template by name with the given context. :param template_name_or_list: The name of the template to render. If a list is given, the first name to exist will be rendered. :param context: The variables to make available in the template. Here is the function: def render_template( template_name_or_list: t.Union[str, Template, t.List[t.Union[str, Template]]], **context: t.Any ) -> str: """Render a template by name with the given context. :param template_name_or_list: The name of the template to render. If a list is given, the first name to exist will be rendered. :param context: The variables to make available in the template. """ app = current_app._get_current_object() # type: ignore[attr-defined] template = app.jinja_env.get_or_select_template(template_name_or_list) return _render(app, template, context)
Render a template by name with the given context. :param template_name_or_list: The name of the template to render. If a list is given, the first name to exist will be rendered. :param context: The variables to make available in the template.
174,852
import typing as t from jinja2 import BaseLoader from jinja2 import Environment as BaseEnvironment from jinja2 import Template from jinja2 import TemplateNotFound from .globals import _cv_app from .globals import _cv_request from .globals import current_app from .globals import request from .helpers import stream_with_context from .signals import before_render_template from .signals import template_rendered if t.TYPE_CHECKING: # pragma: no cover from .app import Flask from .scaffold import Scaffold def _render(app: "Flask", template: Template, context: t.Dict[str, t.Any]) -> str: app.update_template_context(context) before_render_template.send(app, template=template, context=context) rv = template.render(context) template_rendered.send(app, template=template, context=context) return rv import typing as t current_app: "Flask" = LocalProxy( # type: ignore[assignment] _cv_app, "app", unbound_message=_no_app_msg ) The provided code snippet includes necessary dependencies for implementing the `render_template_string` function. Write a Python function `def render_template_string(source: str, **context: t.Any) -> str` to solve the following problem: Render a template from the given source string with the given context. :param source: The source code of the template to render. :param context: The variables to make available in the template. Here is the function: def render_template_string(source: str, **context: t.Any) -> str: """Render a template from the given source string with the given context. :param source: The source code of the template to render. :param context: The variables to make available in the template. """ app = current_app._get_current_object() # type: ignore[attr-defined] template = app.jinja_env.from_string(source) return _render(app, template, context)
Render a template from the given source string with the given context. :param source: The source code of the template to render. :param context: The variables to make available in the template.
174,853
import typing as t from jinja2 import BaseLoader from jinja2 import Environment as BaseEnvironment from jinja2 import Template from jinja2 import TemplateNotFound from .globals import _cv_app from .globals import _cv_request from .globals import current_app from .globals import request from .helpers import stream_with_context from .signals import before_render_template from .signals import template_rendered if t.TYPE_CHECKING: # pragma: no cover from .app import Flask from .scaffold import Scaffold def _stream( app: "Flask", template: Template, context: t.Dict[str, t.Any] ) -> t.Iterator[str]: app.update_template_context(context) before_render_template.send(app, template=template, context=context) def generate() -> t.Iterator[str]: yield from template.generate(context) template_rendered.send(app, template=template, context=context) rv = generate() # If a request context is active, keep it while generating. if request: rv = stream_with_context(rv) return rv import typing as t current_app: "Flask" = LocalProxy( # type: ignore[assignment] _cv_app, "app", unbound_message=_no_app_msg ) The provided code snippet includes necessary dependencies for implementing the `stream_template` function. Write a Python function `def stream_template( template_name_or_list: t.Union[str, Template, t.List[t.Union[str, Template]]], **context: t.Any ) -> t.Iterator[str]` to solve the following problem: Render a template by name with the given context as a stream. This returns an iterator of strings, which can be used as a streaming response from a view. :param template_name_or_list: The name of the template to render. If a list is given, the first name to exist will be rendered. :param context: The variables to make available in the template. .. versionadded:: 2.2 Here is the function: def stream_template( template_name_or_list: t.Union[str, Template, t.List[t.Union[str, Template]]], **context: t.Any ) -> t.Iterator[str]: """Render a template by name with the given context as a stream. This returns an iterator of strings, which can be used as a streaming response from a view. :param template_name_or_list: The name of the template to render. If a list is given, the first name to exist will be rendered. :param context: The variables to make available in the template. .. versionadded:: 2.2 """ app = current_app._get_current_object() # type: ignore[attr-defined] template = app.jinja_env.get_or_select_template(template_name_or_list) return _stream(app, template, context)
Render a template by name with the given context as a stream. This returns an iterator of strings, which can be used as a streaming response from a view. :param template_name_or_list: The name of the template to render. If a list is given, the first name to exist will be rendered. :param context: The variables to make available in the template. .. versionadded:: 2.2
174,854
import typing as t from jinja2 import BaseLoader from jinja2 import Environment as BaseEnvironment from jinja2 import Template from jinja2 import TemplateNotFound from .globals import _cv_app from .globals import _cv_request from .globals import current_app from .globals import request from .helpers import stream_with_context from .signals import before_render_template from .signals import template_rendered if t.TYPE_CHECKING: # pragma: no cover from .app import Flask from .scaffold import Scaffold def _stream( app: "Flask", template: Template, context: t.Dict[str, t.Any] ) -> t.Iterator[str]: app.update_template_context(context) before_render_template.send(app, template=template, context=context) def generate() -> t.Iterator[str]: yield from template.generate(context) template_rendered.send(app, template=template, context=context) rv = generate() # If a request context is active, keep it while generating. if request: rv = stream_with_context(rv) return rv import typing as t current_app: "Flask" = LocalProxy( # type: ignore[assignment] _cv_app, "app", unbound_message=_no_app_msg ) The provided code snippet includes necessary dependencies for implementing the `stream_template_string` function. Write a Python function `def stream_template_string(source: str, **context: t.Any) -> t.Iterator[str]` to solve the following problem: Render a template from the given source string with the given context as a stream. This returns an iterator of strings, which can be used as a streaming response from a view. :param source: The source code of the template to render. :param context: The variables to make available in the template. .. versionadded:: 2.2 Here is the function: def stream_template_string(source: str, **context: t.Any) -> t.Iterator[str]: """Render a template from the given source string with the given context as a stream. This returns an iterator of strings, which can be used as a streaming response from a view. :param source: The source code of the template to render. :param context: The variables to make available in the template. .. versionadded:: 2.2 """ app = current_app._get_current_object() # type: ignore[attr-defined] template = app.jinja_env.from_string(source) return _stream(app, template, context)
Render a template from the given source string with the given context as a stream. This returns an iterator of strings, which can be used as a streaming response from a view. :param source: The source code of the template to render. :param context: The variables to make available in the template. .. versionadded:: 2.2
174,927
import ctypes from typing import no_type_check The provided code snippet includes necessary dependencies for implementing the `send_interrupt` function. Write a Python function `def send_interrupt(interrupt_handle)` to solve the following problem: Sends an interrupt event using the specified handle. Here is the function: def send_interrupt(interrupt_handle): """Sends an interrupt event using the specified handle.""" ctypes.windll.kernel32.SetEvent(interrupt_handle)
Sends an interrupt event using the specified handle.
174,928
import asyncio import os import socket import typing as t import uuid from functools import wraps import zmq from traitlets import Any, Bool, Dict, DottedObjectName, Instance, Unicode, default, observe from traitlets.config.configurable import LoggingConfigurable from traitlets.utils.importstring import import_item from .kernelspec import NATIVE_KERNEL_NAME, KernelSpecManager from .manager import KernelManager from .utils import ensure_async, run_sync def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> Callable[[_T], _T]: ... The provided code snippet includes necessary dependencies for implementing the `kernel_method` function. Write a Python function `def kernel_method(f: t.Callable) -> t.Callable` to solve the following problem: decorator for proxying MKM.method(kernel_id) to individual KMs by ID Here is the function: def kernel_method(f: t.Callable) -> t.Callable: """decorator for proxying MKM.method(kernel_id) to individual KMs by ID""" @wraps(f) def wrapped( self: t.Any, kernel_id: str, *args: t.Any, **kwargs: t.Any ) -> t.Union[t.Callable, t.Awaitable]: # get the kernel km = self.get_kernel(kernel_id) method = getattr(km, f.__name__) # call the kernel's method r = method(*args, **kwargs) # last thing, call anything defined in the actual class method # such as logging messages f(self, kernel_id, *args, **kwargs) # return the method result return r return wrapped
decorator for proxying MKM.method(kernel_id) to individual KMs by ID
174,929
import typing as t import zmq from tornado import ioloop from traitlets import Instance, Type from zmq.eventloop.zmqstream import ZMQStream from ..manager import AsyncKernelManager, KernelManager from .restarter import AsyncIOLoopKernelRestarter, IOLoopKernelRestarter class ZMQStream: """A utility class to register callbacks when a zmq socket sends and receives For use with tornado IOLoop. There are three main methods Methods: * **on_recv(callback, copy=True):** register a callback to be run every time the socket has something to receive * **on_send(callback):** register a callback to be run every time you call send * **send_multipart(self, msg, flags=0, copy=False, callback=None):** perform a send that will trigger the callback if callback is passed, on_send is also called. There are also send_multipart(), send_json(), send_pyobj() Three other methods for deactivating the callbacks: * **stop_on_recv():** turn off the recv callback * **stop_on_send():** turn off the send callback which simply call ``on_<evt>(None)``. The entire socket interface, excluding direct recv methods, is also provided, primarily through direct-linking the methods. e.g. >>> stream.bind is stream.socket.bind True .. versionadded:: 25 send/recv callbacks can be coroutines. .. versionchanged:: 25 ZMQStreams only support base zmq.Socket classes (this has always been true, but not enforced). If ZMQStreams are created with e.g. async Socket subclasses, a RuntimeWarning will be shown, and the socket cast back to the default zmq.Socket before connecting events. Previously, using async sockets (or any zmq.Socket subclass) would result in undefined behavior for the arguments passed to callback functions. Now, the callback functions reliably get the return value of the base `zmq.Socket` send/recv_multipart methods (the list of message frames). """ socket: zmq.Socket io_loop: IOLoop poller: zmq.Poller _send_queue: Queue _recv_callback: Optional[Callable] _send_callback: Optional[Callable] _close_callback: Optional[Callable] _state: int = 0 _flushed: bool = False _recv_copy: bool = False _fd: int def __init__(self, socket: "zmq.Socket", io_loop: Optional[IOLoop] = None): if isinstance(socket, zmq._future._AsyncSocket): warnings.warn( f"""ZMQStream only supports the base zmq.Socket class. Use zmq.Socket(shadow=other_socket) or `ctx.socket(zmq.{socket._type_name}, socket_class=zmq.Socket)` to create a base zmq.Socket object, no matter what other kind of socket your Context creates. """, RuntimeWarning, stacklevel=2, ) # shadow back to base zmq.Socket, # otherwise callbacks like `on_recv` will get the wrong types. socket = zmq.Socket(shadow=socket) self.socket = socket # IOLoop.current() is deprecated if called outside the event loop # that means self.io_loop = io_loop or IOLoop.current() self.poller = zmq.Poller() self._fd = cast(int, self.socket.FD) self._send_queue = Queue() self._recv_callback = None self._send_callback = None self._close_callback = None self._recv_copy = False self._flushed = False self._state = 0 self._init_io_state() # shortcircuit some socket methods self.bind = self.socket.bind self.bind_to_random_port = self.socket.bind_to_random_port self.connect = self.socket.connect self.setsockopt = self.socket.setsockopt self.getsockopt = self.socket.getsockopt self.setsockopt_string = self.socket.setsockopt_string self.getsockopt_string = self.socket.getsockopt_string self.setsockopt_unicode = self.socket.setsockopt_unicode self.getsockopt_unicode = self.socket.getsockopt_unicode def stop_on_recv(self): """Disable callback and automatic receiving.""" return self.on_recv(None) def stop_on_send(self): """Disable callback on sending.""" return self.on_send(None) def stop_on_err(self): """DEPRECATED, does nothing""" gen_log.warn("on_err does nothing, and will be removed") def on_err(self, callback: Callable): """DEPRECATED, does nothing""" gen_log.warn("on_err does nothing, and will be removed") def on_recv( self, callback: Callable[[List[bytes]], Any], ) -> None: ... def on_recv( self, callback: Callable[[List[bytes]], Any], copy: Literal[True], ) -> None: ... def on_recv( self, callback: Callable[[List[zmq.Frame]], Any], copy: Literal[False], ) -> None: ... def on_recv( self, callback: Union[ Callable[[List[zmq.Frame]], Any], Callable[[List[bytes]], Any], ], copy: bool = ..., ): ... def on_recv( self, callback: Union[ Callable[[List[zmq.Frame]], Any], Callable[[List[bytes]], Any], ], copy: bool = True, ) -> None: """Register a callback for when a message is ready to recv. There can be only one callback registered at a time, so each call to `on_recv` replaces previously registered callbacks. on_recv(None) disables recv event polling. Use on_recv_stream(callback) instead, to register a callback that will receive both this ZMQStream and the message, instead of just the message. Parameters ---------- callback : callable callback must take exactly one argument, which will be a list, as returned by socket.recv_multipart() if callback is None, recv callbacks are disabled. copy : bool copy is passed directly to recv, so if copy is False, callback will receive Message objects. If copy is True, then callback will receive bytes/str objects. Returns : None """ self._check_closed() assert callback is None or callable(callback) self._recv_callback = callback self._recv_copy = copy if callback is None: self._drop_io_state(zmq.POLLIN) else: self._add_io_state(zmq.POLLIN) def on_recv_stream( self, callback: Callable[["ZMQStream", List[bytes]], Any], ) -> None: ... def on_recv_stream( self, callback: Callable[["ZMQStream", List[bytes]], Any], copy: Literal[True], ) -> None: ... def on_recv_stream( self, callback: Callable[["ZMQStream", List[zmq.Frame]], Any], copy: Literal[False], ) -> None: ... def on_recv_stream( self, callback: Union[ Callable[["ZMQStream", List[zmq.Frame]], Any], Callable[["ZMQStream", List[bytes]], Any], ], copy: bool = ..., ): ... def on_recv_stream( self, callback: Union[ Callable[["ZMQStream", List[zmq.Frame]], Any], Callable[["ZMQStream", List[bytes]], Any], ], copy: bool = True, ): """Same as on_recv, but callback will get this stream as first argument callback must take exactly two arguments, as it will be called as:: callback(stream, msg) Useful when a single callback should be used with multiple streams. """ if callback is None: self.stop_on_recv() else: def stream_callback(msg): return callback(self, msg) self.on_recv(stream_callback, copy=copy) def on_send( self, callback: Callable[[Sequence[Any], Optional[zmq.MessageTracker]], Any] ): """Register a callback to be called on each send There will be two arguments:: callback(msg, status) * `msg` will be the list of sendable objects that was just sent * `status` will be the return result of socket.send_multipart(msg) - MessageTracker or None. Non-copying sends return a MessageTracker object whose `done` attribute will be True when the send is complete. This allows users to track when an object is safe to write to again. The second argument will always be None if copy=True on the send. Use on_send_stream(callback) to register a callback that will be passed this ZMQStream as the first argument, in addition to the other two. on_send(None) disables recv event polling. Parameters ---------- callback : callable callback must take exactly two arguments, which will be the message being sent (always a list), and the return result of socket.send_multipart(msg) - MessageTracker or None. if callback is None, send callbacks are disabled. """ self._check_closed() assert callback is None or callable(callback) self._send_callback = callback def on_send_stream( self, callback: Callable[ ["ZMQStream", Sequence[Any], Optional[zmq.MessageTracker]], Any ], ): """Same as on_send, but callback will get this stream as first argument Callback will be passed three arguments:: callback(stream, msg, status) Useful when a single callback should be used with multiple streams. """ if callback is None: self.stop_on_send() else: self.on_send(lambda msg, status: callback(self, msg, status)) def send(self, msg, flags=0, copy=True, track=False, callback=None, **kwargs): """Send a message, optionally also register a new callback for sends. See zmq.socket.send for details. """ return self.send_multipart( [msg], flags=flags, copy=copy, track=track, callback=callback, **kwargs ) def send_multipart( self, msg: Sequence[Any], flags: int = 0, copy: bool = True, track: bool = False, callback: Optional[Callable] = None, **kwargs: Any, ) -> None: """Send a multipart message, optionally also register a new callback for sends. See zmq.socket.send_multipart for details. """ kwargs.update(dict(flags=flags, copy=copy, track=track)) self._send_queue.put((msg, kwargs)) callback = callback or self._send_callback if callback is not None: self.on_send(callback) else: # noop callback self.on_send(lambda *args: None) self._add_io_state(zmq.POLLOUT) def send_string( self, u: str, flags: int = 0, encoding: str = 'utf-8', callback: Optional[Callable] = None, **kwargs: Any, ): """Send a unicode message with an encoding. See zmq.socket.send_unicode for details. """ if not isinstance(u, str): raise TypeError("unicode/str objects only") return self.send(u.encode(encoding), flags=flags, callback=callback, **kwargs) send_unicode = send_string def send_json( self, obj: Any, flags: int = 0, callback: Optional[Callable] = None, **kwargs: Any, ): """Send json-serialized version of an object. See zmq.socket.send_json for details. """ msg = jsonapi.dumps(obj) return self.send(msg, flags=flags, callback=callback, **kwargs) def send_pyobj( self, obj: Any, flags: int = 0, protocol: int = -1, callback: Optional[Callable] = None, **kwargs: Any, ): """Send a Python object as a message using pickle to serialize. See zmq.socket.send_json for details. """ msg = pickle.dumps(obj, protocol) return self.send(msg, flags, callback=callback, **kwargs) def _finish_flush(self): """callback for unsetting _flushed flag.""" self._flushed = False def flush(self, flag: int = zmq.POLLIN | zmq.POLLOUT, limit: Optional[int] = None): """Flush pending messages. This method safely handles all pending incoming and/or outgoing messages, bypassing the inner loop, passing them to the registered callbacks. A limit can be specified, to prevent blocking under high load. flush will return the first time ANY of these conditions are met: * No more events matching the flag are pending. * the total number of events handled reaches the limit. Note that if ``flag|POLLIN != 0``, recv events will be flushed even if no callback is registered, unlike normal IOLoop operation. This allows flush to be used to remove *and ignore* incoming messages. Parameters ---------- flag : int, default=POLLIN|POLLOUT 0MQ poll flags. If flag|POLLIN, recv events will be flushed. If flag|POLLOUT, send events will be flushed. Both flags can be set at once, which is the default. limit : None or int, optional The maximum number of messages to send or receive. Both send and recv count against this limit. Returns ------- int : count of events handled (both send and recv) """ self._check_closed() # unset self._flushed, so callbacks will execute, in case flush has # already been called this iteration already_flushed = self._flushed self._flushed = False # initialize counters count = 0 def update_flag(): """Update the poll flag, to prevent registering POLLOUT events if we don't have pending sends.""" return flag & zmq.POLLIN | (self.sending() and flag & zmq.POLLOUT) flag = update_flag() if not flag: # nothing to do return 0 self.poller.register(self.socket, flag) events = self.poller.poll(0) while events and (not limit or count < limit): s, event = events[0] if event & POLLIN: # receiving self._handle_recv() count += 1 if self.socket is None: # break if socket was closed during callback break if event & POLLOUT and self.sending(): self._handle_send() count += 1 if self.socket is None: # break if socket was closed during callback break flag = update_flag() if flag: self.poller.register(self.socket, flag) events = self.poller.poll(0) else: events = [] if count: # only bypass loop if we actually flushed something # skip send/recv callbacks this iteration self._flushed = True # reregister them at the end of the loop if not already_flushed: # don't need to do it again self.io_loop.add_callback(self._finish_flush) elif already_flushed: self._flushed = True # update ioloop poll state, which may have changed self._rebuild_io_state() return count def set_close_callback(self, callback: Optional[Callable]): """Call the given callback when the stream is closed.""" self._close_callback = callback def close(self, linger: Optional[int] = None) -> None: """Close this stream.""" if self.socket is not None: if self.socket.closed: # fallback on raw fd for closed sockets # hopefully this happened promptly after close, # otherwise somebody else may have the FD warnings.warn( "Unregistering FD %s after closing socket. " "This could result in unregistering handlers for the wrong socket. " "Please use stream.close() instead of closing the socket directly." % self._fd, stacklevel=2, ) self.io_loop.remove_handler(self._fd) else: self.io_loop.remove_handler(self.socket) self.socket.close(linger) self.socket = None # type: ignore if self._close_callback: self._run_callback(self._close_callback) def receiving(self) -> bool: """Returns True if we are currently receiving from the stream.""" return self._recv_callback is not None def sending(self) -> bool: """Returns True if we are currently sending to the stream.""" return not self._send_queue.empty() def closed(self) -> bool: if self.socket is None: return True if self.socket.closed: # underlying socket has been closed, but not by us! # trigger our cleanup self.close() return True return False def _run_callback(self, callback, *args, **kwargs): """Wrap running callbacks in try/except to allow us to close our socket.""" try: f = callback(*args, **kwargs) if isinstance(f, Awaitable): f = asyncio.ensure_future(f) else: f = None except Exception: gen_log.error("Uncaught exception in ZMQStream callback", exc_info=True) # Re-raise the exception so that IOLoop.handle_callback_exception # can see it and log the error raise if f is not None: # handle async callbacks def _log_error(f): try: f.result() except Exception: gen_log.error( "Uncaught exception in ZMQStream callback", exc_info=True ) f.add_done_callback(_log_error) def _handle_events(self, fd, events): """This method is the actual handler for IOLoop, that gets called whenever an event on my socket is posted. It dispatches to _handle_recv, etc.""" if not self.socket: gen_log.warning("Got events for closed stream %s", self) return try: zmq_events = self.socket.EVENTS except zmq.ContextTerminated: gen_log.warning("Got events for stream %s after terminating context", self) # trigger close check, this will unregister callbacks self.closed() return except zmq.ZMQError as e: # run close check # shadow sockets may have been closed elsewhere, # which should show up as ENOTSOCK here if self.closed(): gen_log.warning( "Got events for stream %s attached to closed socket: %s", self, e ) else: gen_log.error("Error getting events for %s: %s", self, e) return try: # dispatch events: if zmq_events & zmq.POLLIN and self.receiving(): self._handle_recv() if not self.socket: return if zmq_events & zmq.POLLOUT and self.sending(): self._handle_send() if not self.socket: return # rebuild the poll state self._rebuild_io_state() except Exception: gen_log.error("Uncaught exception in zmqstream callback", exc_info=True) raise def _handle_recv(self): """Handle a recv event.""" if self._flushed: return try: msg = self.socket.recv_multipart(zmq.NOBLOCK, copy=self._recv_copy) except zmq.ZMQError as e: if e.errno == zmq.EAGAIN: # state changed since poll event pass else: raise else: if self._recv_callback: callback = self._recv_callback self._run_callback(callback, msg) def _handle_send(self): """Handle a send event.""" if self._flushed: return if not self.sending(): gen_log.error("Shouldn't have handled a send event") return msg, kwargs = self._send_queue.get() try: status = self.socket.send_multipart(msg, **kwargs) except zmq.ZMQError as e: gen_log.error("SEND Error: %s", e) status = e if self._send_callback: callback = self._send_callback self._run_callback(callback, msg, status) def _check_closed(self): if not self.socket: raise OSError("Stream is closed") def _rebuild_io_state(self): """rebuild io state based on self.sending() and receiving()""" if self.socket is None: return state = 0 if self.receiving(): state |= zmq.POLLIN if self.sending(): state |= zmq.POLLOUT self._state = state self._update_handler(state) def _add_io_state(self, state): """Add io_state to poller.""" self._state = self._state | state self._update_handler(self._state) def _drop_io_state(self, state): """Stop poller from watching an io_state.""" self._state = self._state & (~state) self._update_handler(self._state) def _update_handler(self, state): """Update IOLoop handler with state.""" if self.socket is None: return if state & self.socket.events: # events still exist that haven't been processed # explicitly schedule handling to avoid missing events due to edge-triggered FDs self.io_loop.add_callback(lambda: self._handle_events(self.socket, 0)) def _init_io_state(self): """initialize the ioloop event handler""" self.io_loop.add_handler(self.socket, self._handle_events, self.io_loop.READ) The provided code snippet includes necessary dependencies for implementing the `as_zmqstream` function. Write a Python function `def as_zmqstream(f)` to solve the following problem: Convert a socket to a zmq stream. Here is the function: def as_zmqstream(f): """Convert a socket to a zmq stream.""" def wrapped(self, *args, **kwargs): save_socket_class = None # zmqstreams only support sync sockets if self.context._socket_class is not zmq.Socket: save_socket_class = self.context._socket_class self.context._socket_class = zmq.Socket try: socket = f(self, *args, **kwargs) finally: if save_socket_class: # restore default socket class self.context._socket_class = save_socket_class return ZMQStream(socket, self.loop) return wrapped
Convert a socket to a zmq stream.
174,930
import json import os import re import shutil import warnings from jupyter_core.paths import SYSTEM_JUPYTER_PATH, jupyter_data_dir, jupyter_path from traitlets import Bool, CaselessStrEnum, Dict, HasTraits, List, Set, Type, Unicode, observe from traitlets.config import LoggingConfigurable from .provisioning import KernelProvisionerFactory as KPF pjoin = os.path.join def _is_valid_kernel_name(name): """Check that a kernel name is valid.""" # quote is not unicode-safe on Python 2 return _kernel_name_pat.match(name) _kernel_name_description = ( "Kernel names can only contain ASCII letters and numbers and these separators:" " - . _ (hyphen, period, and underscore)." ) def _is_kernel_dir(path): """Is ``path`` a kernel directory?""" return os.path.isdir(path) and os.path.isfile(pjoin(path, "kernel.json")) The provided code snippet includes necessary dependencies for implementing the `_list_kernels_in` function. Write a Python function `def _list_kernels_in(dir)` to solve the following problem: Return a mapping of kernel names to resource directories from dir. If dir is None or does not exist, returns an empty dict. Here is the function: def _list_kernels_in(dir): """Return a mapping of kernel names to resource directories from dir. If dir is None or does not exist, returns an empty dict. """ if dir is None or not os.path.isdir(dir): return {} kernels = {} for f in os.listdir(dir): path = pjoin(dir, f) if not _is_kernel_dir(path): continue key = f.lower() if not _is_valid_kernel_name(key): warnings.warn( f"Invalid kernelspec directory name ({_kernel_name_description}): {path}", stacklevel=3, ) kernels[key] = path return kernels
Return a mapping of kernel names to resource directories from dir. If dir is None or does not exist, returns an empty dict.
174,931
import json import os import re import shutil import warnings from jupyter_core.paths import SYSTEM_JUPYTER_PATH, jupyter_data_dir, jupyter_path from traitlets import Bool, CaselessStrEnum, Dict, HasTraits, List, Set, Type, Unicode, observe from traitlets.config import LoggingConfigurable from .provisioning import KernelProvisionerFactory as KPF class KernelSpecManager(LoggingConfigurable): """A manager for kernel specs.""" kernel_spec_class = Type( KernelSpec, config=True, help="""The kernel spec class. This is configurable to allow subclassing of the KernelSpecManager for customized behavior. """, ) ensure_native_kernel = Bool( True, config=True, help="""If there is no Python kernelspec registered and the IPython kernel is available, ensure it is added to the spec list. """, ) data_dir = Unicode() def _data_dir_default(self): return jupyter_data_dir() user_kernel_dir = Unicode() def _user_kernel_dir_default(self): return pjoin(self.data_dir, "kernels") whitelist = Set( config=True, help="""Deprecated, use `KernelSpecManager.allowed_kernelspecs` """, ) allowed_kernelspecs = Set( config=True, help="""List of allowed kernel names. By default, all installed kernels are allowed. """, ) kernel_dirs = List( help="List of kernel directories to search. Later ones take priority over earlier." ) _deprecated_aliases = { "whitelist": ("allowed_kernelspecs", "7.0"), } # Method copied from # https://github.com/jupyterhub/jupyterhub/blob/d1a85e53dccfc7b1dd81b0c1985d158cc6b61820/jupyterhub/auth.py#L143-L161 def _deprecated_trait(self, change): """observer for deprecated traits""" old_attr = change.name new_attr, version = self._deprecated_aliases[old_attr] new_value = getattr(self, new_attr) if new_value != change.new: # only warn if different # protects backward-compatible config from warnings # if they set the same value under both names self.log.warning( ( "{cls}.{old} is deprecated in jupyter_client " "{version}, use {cls}.{new} instead" ).format( cls=self.__class__.__name__, old=old_attr, new=new_attr, version=version, ) ) setattr(self, new_attr, change.new) def _kernel_dirs_default(self): dirs = jupyter_path("kernels") # At some point, we should stop adding .ipython/kernels to the path, # but the cost to keeping it is very small. try: # this should always be valid on IPython 3+ from IPython.paths import get_ipython_dir dirs.append(os.path.join(get_ipython_dir(), "kernels")) except ModuleNotFoundError: pass return dirs def find_kernel_specs(self): """Returns a dict mapping kernel names to resource directories.""" d = {} for kernel_dir in self.kernel_dirs: kernels = _list_kernels_in(kernel_dir) for kname, spec in kernels.items(): if kname not in d: self.log.debug("Found kernel %s in %s", kname, kernel_dir) d[kname] = spec if self.ensure_native_kernel and NATIVE_KERNEL_NAME not in d: try: from ipykernel.kernelspec import RESOURCES self.log.debug( "Native kernel (%s) available from %s", NATIVE_KERNEL_NAME, RESOURCES, ) d[NATIVE_KERNEL_NAME] = RESOURCES except ImportError: self.log.warning("Native kernel (%s) is not available", NATIVE_KERNEL_NAME) if self.allowed_kernelspecs: # filter if there's an allow list d = {name: spec for name, spec in d.items() if name in self.allowed_kernelspecs} return d # TODO: Caching? def _get_kernel_spec_by_name(self, kernel_name, resource_dir): """Returns a :class:`KernelSpec` instance for a given kernel_name and resource_dir. """ kspec = None if kernel_name == NATIVE_KERNEL_NAME: try: from ipykernel.kernelspec import RESOURCES, get_kernel_dict except ImportError: # It should be impossible to reach this, but let's play it safe pass else: if resource_dir == RESOURCES: kspec = self.kernel_spec_class(resource_dir=resource_dir, **get_kernel_dict()) if not kspec: kspec = self.kernel_spec_class.from_resource_dir(resource_dir) if not KPF.instance(parent=self.parent).is_provisioner_available(kspec): raise NoSuchKernel(kernel_name) return kspec def _find_spec_directory(self, kernel_name): """Find the resource directory of a named kernel spec""" for kernel_dir in [kd for kd in self.kernel_dirs if os.path.isdir(kd)]: files = os.listdir(kernel_dir) for f in files: path = pjoin(kernel_dir, f) if f.lower() == kernel_name and _is_kernel_dir(path): return path if kernel_name == NATIVE_KERNEL_NAME: try: from ipykernel.kernelspec import RESOURCES except ImportError: pass else: return RESOURCES def get_kernel_spec(self, kernel_name): """Returns a :class:`KernelSpec` instance for the given kernel_name. Raises :exc:`NoSuchKernel` if the given kernel name is not found. """ if not _is_valid_kernel_name(kernel_name): self.log.warning( f"Kernelspec name {kernel_name} is invalid: {_kernel_name_description}" ) resource_dir = self._find_spec_directory(kernel_name.lower()) if resource_dir is None: self.log.warning("Kernelspec name %s cannot be found!", kernel_name) raise NoSuchKernel(kernel_name) return self._get_kernel_spec_by_name(kernel_name, resource_dir) def get_all_specs(self): """Returns a dict mapping kernel names to kernelspecs. Returns a dict of the form:: { 'kernel_name': { 'resource_dir': '/path/to/kernel_name', 'spec': {"the spec itself": ...} }, ... } """ d = self.find_kernel_specs() res = {} for kname, resource_dir in d.items(): try: if self.__class__ is KernelSpecManager: spec = self._get_kernel_spec_by_name(kname, resource_dir) else: # avoid calling private methods in subclasses, # which may have overridden find_kernel_specs # and get_kernel_spec, but not the newer get_all_specs spec = self.get_kernel_spec(kname) res[kname] = {"resource_dir": resource_dir, "spec": spec.to_dict()} except NoSuchKernel: pass # The appropriate warning has already been logged except Exception: self.log.warning("Error loading kernelspec %r", kname, exc_info=True) return res def remove_kernel_spec(self, name): """Remove a kernel spec directory by name. Returns the path that was deleted. """ save_native = self.ensure_native_kernel try: self.ensure_native_kernel = False specs = self.find_kernel_specs() finally: self.ensure_native_kernel = save_native spec_dir = specs[name] self.log.debug("Removing %s", spec_dir) if os.path.islink(spec_dir): os.remove(spec_dir) else: shutil.rmtree(spec_dir) return spec_dir def _get_destination_dir(self, kernel_name, user=False, prefix=None): if user: return os.path.join(self.user_kernel_dir, kernel_name) elif prefix: return os.path.join(os.path.abspath(prefix), "share", "jupyter", "kernels", kernel_name) else: return os.path.join(SYSTEM_JUPYTER_PATH[0], "kernels", kernel_name) def install_kernel_spec( self, source_dir, kernel_name=None, user=False, replace=None, prefix=None ): """Install a kernel spec by copying its directory. If ``kernel_name`` is not given, the basename of ``source_dir`` will be used. If ``user`` is False, it will attempt to install into the systemwide kernel registry. If the process does not have appropriate permissions, an :exc:`OSError` will be raised. If ``prefix`` is given, the kernelspec will be installed to PREFIX/share/jupyter/kernels/KERNEL_NAME. This can be sys.prefix for installation inside virtual or conda envs. """ source_dir = source_dir.rstrip("/\\") if not kernel_name: kernel_name = os.path.basename(source_dir) kernel_name = kernel_name.lower() if not _is_valid_kernel_name(kernel_name): msg = f"Invalid kernel name {kernel_name!r}. {_kernel_name_description}" raise ValueError(msg) if user and prefix: msg = "Can't specify both user and prefix. Please choose one or the other." raise ValueError(msg) if replace is not None: warnings.warn( "replace is ignored. Installing a kernelspec always replaces an existing " "installation", DeprecationWarning, stacklevel=2, ) destination = self._get_destination_dir(kernel_name, user=user, prefix=prefix) self.log.debug("Installing kernelspec in %s", destination) kernel_dir = os.path.dirname(destination) if kernel_dir not in self.kernel_dirs: self.log.warning( "Installing to %s, which is not in %s. The kernelspec may not be found.", kernel_dir, self.kernel_dirs, ) if os.path.isdir(destination): self.log.info("Removing existing kernelspec in %s", destination) shutil.rmtree(destination) shutil.copytree(source_dir, destination) self.log.info("Installed kernelspec %s in %s", kernel_name, destination) return destination def install_native_kernel_spec(self, user=False): """DEPRECATED: Use ipykernel.kernelspec.install""" warnings.warn( "install_native_kernel_spec is deprecated. Use ipykernel.kernelspec import install.", stacklevel=2, ) from ipykernel.kernelspec import install install(self, user=user) The provided code snippet includes necessary dependencies for implementing the `find_kernel_specs` function. Write a Python function `def find_kernel_specs()` to solve the following problem: Returns a dict mapping kernel names to resource directories. Here is the function: def find_kernel_specs(): """Returns a dict mapping kernel names to resource directories.""" return KernelSpecManager().find_kernel_specs()
Returns a dict mapping kernel names to resource directories.
174,932
import json import os import re import shutil import warnings from jupyter_core.paths import SYSTEM_JUPYTER_PATH, jupyter_data_dir, jupyter_path from traitlets import Bool, CaselessStrEnum, Dict, HasTraits, List, Set, Type, Unicode, observe from traitlets.config import LoggingConfigurable from .provisioning import KernelProvisionerFactory as KPF class KernelSpecManager(LoggingConfigurable): """A manager for kernel specs.""" kernel_spec_class = Type( KernelSpec, config=True, help="""The kernel spec class. This is configurable to allow subclassing of the KernelSpecManager for customized behavior. """, ) ensure_native_kernel = Bool( True, config=True, help="""If there is no Python kernelspec registered and the IPython kernel is available, ensure it is added to the spec list. """, ) data_dir = Unicode() def _data_dir_default(self): return jupyter_data_dir() user_kernel_dir = Unicode() def _user_kernel_dir_default(self): return pjoin(self.data_dir, "kernels") whitelist = Set( config=True, help="""Deprecated, use `KernelSpecManager.allowed_kernelspecs` """, ) allowed_kernelspecs = Set( config=True, help="""List of allowed kernel names. By default, all installed kernels are allowed. """, ) kernel_dirs = List( help="List of kernel directories to search. Later ones take priority over earlier." ) _deprecated_aliases = { "whitelist": ("allowed_kernelspecs", "7.0"), } # Method copied from # https://github.com/jupyterhub/jupyterhub/blob/d1a85e53dccfc7b1dd81b0c1985d158cc6b61820/jupyterhub/auth.py#L143-L161 def _deprecated_trait(self, change): """observer for deprecated traits""" old_attr = change.name new_attr, version = self._deprecated_aliases[old_attr] new_value = getattr(self, new_attr) if new_value != change.new: # only warn if different # protects backward-compatible config from warnings # if they set the same value under both names self.log.warning( ( "{cls}.{old} is deprecated in jupyter_client " "{version}, use {cls}.{new} instead" ).format( cls=self.__class__.__name__, old=old_attr, new=new_attr, version=version, ) ) setattr(self, new_attr, change.new) def _kernel_dirs_default(self): dirs = jupyter_path("kernels") # At some point, we should stop adding .ipython/kernels to the path, # but the cost to keeping it is very small. try: # this should always be valid on IPython 3+ from IPython.paths import get_ipython_dir dirs.append(os.path.join(get_ipython_dir(), "kernels")) except ModuleNotFoundError: pass return dirs def find_kernel_specs(self): """Returns a dict mapping kernel names to resource directories.""" d = {} for kernel_dir in self.kernel_dirs: kernels = _list_kernels_in(kernel_dir) for kname, spec in kernels.items(): if kname not in d: self.log.debug("Found kernel %s in %s", kname, kernel_dir) d[kname] = spec if self.ensure_native_kernel and NATIVE_KERNEL_NAME not in d: try: from ipykernel.kernelspec import RESOURCES self.log.debug( "Native kernel (%s) available from %s", NATIVE_KERNEL_NAME, RESOURCES, ) d[NATIVE_KERNEL_NAME] = RESOURCES except ImportError: self.log.warning("Native kernel (%s) is not available", NATIVE_KERNEL_NAME) if self.allowed_kernelspecs: # filter if there's an allow list d = {name: spec for name, spec in d.items() if name in self.allowed_kernelspecs} return d # TODO: Caching? def _get_kernel_spec_by_name(self, kernel_name, resource_dir): """Returns a :class:`KernelSpec` instance for a given kernel_name and resource_dir. """ kspec = None if kernel_name == NATIVE_KERNEL_NAME: try: from ipykernel.kernelspec import RESOURCES, get_kernel_dict except ImportError: # It should be impossible to reach this, but let's play it safe pass else: if resource_dir == RESOURCES: kspec = self.kernel_spec_class(resource_dir=resource_dir, **get_kernel_dict()) if not kspec: kspec = self.kernel_spec_class.from_resource_dir(resource_dir) if not KPF.instance(parent=self.parent).is_provisioner_available(kspec): raise NoSuchKernel(kernel_name) return kspec def _find_spec_directory(self, kernel_name): """Find the resource directory of a named kernel spec""" for kernel_dir in [kd for kd in self.kernel_dirs if os.path.isdir(kd)]: files = os.listdir(kernel_dir) for f in files: path = pjoin(kernel_dir, f) if f.lower() == kernel_name and _is_kernel_dir(path): return path if kernel_name == NATIVE_KERNEL_NAME: try: from ipykernel.kernelspec import RESOURCES except ImportError: pass else: return RESOURCES def get_kernel_spec(self, kernel_name): """Returns a :class:`KernelSpec` instance for the given kernel_name. Raises :exc:`NoSuchKernel` if the given kernel name is not found. """ if not _is_valid_kernel_name(kernel_name): self.log.warning( f"Kernelspec name {kernel_name} is invalid: {_kernel_name_description}" ) resource_dir = self._find_spec_directory(kernel_name.lower()) if resource_dir is None: self.log.warning("Kernelspec name %s cannot be found!", kernel_name) raise NoSuchKernel(kernel_name) return self._get_kernel_spec_by_name(kernel_name, resource_dir) def get_all_specs(self): """Returns a dict mapping kernel names to kernelspecs. Returns a dict of the form:: { 'kernel_name': { 'resource_dir': '/path/to/kernel_name', 'spec': {"the spec itself": ...} }, ... } """ d = self.find_kernel_specs() res = {} for kname, resource_dir in d.items(): try: if self.__class__ is KernelSpecManager: spec = self._get_kernel_spec_by_name(kname, resource_dir) else: # avoid calling private methods in subclasses, # which may have overridden find_kernel_specs # and get_kernel_spec, but not the newer get_all_specs spec = self.get_kernel_spec(kname) res[kname] = {"resource_dir": resource_dir, "spec": spec.to_dict()} except NoSuchKernel: pass # The appropriate warning has already been logged except Exception: self.log.warning("Error loading kernelspec %r", kname, exc_info=True) return res def remove_kernel_spec(self, name): """Remove a kernel spec directory by name. Returns the path that was deleted. """ save_native = self.ensure_native_kernel try: self.ensure_native_kernel = False specs = self.find_kernel_specs() finally: self.ensure_native_kernel = save_native spec_dir = specs[name] self.log.debug("Removing %s", spec_dir) if os.path.islink(spec_dir): os.remove(spec_dir) else: shutil.rmtree(spec_dir) return spec_dir def _get_destination_dir(self, kernel_name, user=False, prefix=None): if user: return os.path.join(self.user_kernel_dir, kernel_name) elif prefix: return os.path.join(os.path.abspath(prefix), "share", "jupyter", "kernels", kernel_name) else: return os.path.join(SYSTEM_JUPYTER_PATH[0], "kernels", kernel_name) def install_kernel_spec( self, source_dir, kernel_name=None, user=False, replace=None, prefix=None ): """Install a kernel spec by copying its directory. If ``kernel_name`` is not given, the basename of ``source_dir`` will be used. If ``user`` is False, it will attempt to install into the systemwide kernel registry. If the process does not have appropriate permissions, an :exc:`OSError` will be raised. If ``prefix`` is given, the kernelspec will be installed to PREFIX/share/jupyter/kernels/KERNEL_NAME. This can be sys.prefix for installation inside virtual or conda envs. """ source_dir = source_dir.rstrip("/\\") if not kernel_name: kernel_name = os.path.basename(source_dir) kernel_name = kernel_name.lower() if not _is_valid_kernel_name(kernel_name): msg = f"Invalid kernel name {kernel_name!r}. {_kernel_name_description}" raise ValueError(msg) if user and prefix: msg = "Can't specify both user and prefix. Please choose one or the other." raise ValueError(msg) if replace is not None: warnings.warn( "replace is ignored. Installing a kernelspec always replaces an existing " "installation", DeprecationWarning, stacklevel=2, ) destination = self._get_destination_dir(kernel_name, user=user, prefix=prefix) self.log.debug("Installing kernelspec in %s", destination) kernel_dir = os.path.dirname(destination) if kernel_dir not in self.kernel_dirs: self.log.warning( "Installing to %s, which is not in %s. The kernelspec may not be found.", kernel_dir, self.kernel_dirs, ) if os.path.isdir(destination): self.log.info("Removing existing kernelspec in %s", destination) shutil.rmtree(destination) shutil.copytree(source_dir, destination) self.log.info("Installed kernelspec %s in %s", kernel_name, destination) return destination def install_native_kernel_spec(self, user=False): """DEPRECATED: Use ipykernel.kernelspec.install""" warnings.warn( "install_native_kernel_spec is deprecated. Use ipykernel.kernelspec import install.", stacklevel=2, ) from ipykernel.kernelspec import install install(self, user=user) The provided code snippet includes necessary dependencies for implementing the `get_kernel_spec` function. Write a Python function `def get_kernel_spec(kernel_name)` to solve the following problem: Returns a :class:`KernelSpec` instance for the given kernel_name. Raises KeyError if the given kernel name is not found. Here is the function: def get_kernel_spec(kernel_name): """Returns a :class:`KernelSpec` instance for the given kernel_name. Raises KeyError if the given kernel name is not found. """ return KernelSpecManager().get_kernel_spec(kernel_name)
Returns a :class:`KernelSpec` instance for the given kernel_name. Raises KeyError if the given kernel name is not found.
174,933
import json import os import re import shutil import warnings from jupyter_core.paths import SYSTEM_JUPYTER_PATH, jupyter_data_dir, jupyter_path from traitlets import Bool, CaselessStrEnum, Dict, HasTraits, List, Set, Type, Unicode, observe from traitlets.config import LoggingConfigurable from .provisioning import KernelProvisionerFactory as KPF class KernelSpecManager(LoggingConfigurable): """A manager for kernel specs.""" kernel_spec_class = Type( KernelSpec, config=True, help="""The kernel spec class. This is configurable to allow subclassing of the KernelSpecManager for customized behavior. """, ) ensure_native_kernel = Bool( True, config=True, help="""If there is no Python kernelspec registered and the IPython kernel is available, ensure it is added to the spec list. """, ) data_dir = Unicode() def _data_dir_default(self): return jupyter_data_dir() user_kernel_dir = Unicode() def _user_kernel_dir_default(self): return pjoin(self.data_dir, "kernels") whitelist = Set( config=True, help="""Deprecated, use `KernelSpecManager.allowed_kernelspecs` """, ) allowed_kernelspecs = Set( config=True, help="""List of allowed kernel names. By default, all installed kernels are allowed. """, ) kernel_dirs = List( help="List of kernel directories to search. Later ones take priority over earlier." ) _deprecated_aliases = { "whitelist": ("allowed_kernelspecs", "7.0"), } # Method copied from # https://github.com/jupyterhub/jupyterhub/blob/d1a85e53dccfc7b1dd81b0c1985d158cc6b61820/jupyterhub/auth.py#L143-L161 def _deprecated_trait(self, change): """observer for deprecated traits""" old_attr = change.name new_attr, version = self._deprecated_aliases[old_attr] new_value = getattr(self, new_attr) if new_value != change.new: # only warn if different # protects backward-compatible config from warnings # if they set the same value under both names self.log.warning( ( "{cls}.{old} is deprecated in jupyter_client " "{version}, use {cls}.{new} instead" ).format( cls=self.__class__.__name__, old=old_attr, new=new_attr, version=version, ) ) setattr(self, new_attr, change.new) def _kernel_dirs_default(self): dirs = jupyter_path("kernels") # At some point, we should stop adding .ipython/kernels to the path, # but the cost to keeping it is very small. try: # this should always be valid on IPython 3+ from IPython.paths import get_ipython_dir dirs.append(os.path.join(get_ipython_dir(), "kernels")) except ModuleNotFoundError: pass return dirs def find_kernel_specs(self): """Returns a dict mapping kernel names to resource directories.""" d = {} for kernel_dir in self.kernel_dirs: kernels = _list_kernels_in(kernel_dir) for kname, spec in kernels.items(): if kname not in d: self.log.debug("Found kernel %s in %s", kname, kernel_dir) d[kname] = spec if self.ensure_native_kernel and NATIVE_KERNEL_NAME not in d: try: from ipykernel.kernelspec import RESOURCES self.log.debug( "Native kernel (%s) available from %s", NATIVE_KERNEL_NAME, RESOURCES, ) d[NATIVE_KERNEL_NAME] = RESOURCES except ImportError: self.log.warning("Native kernel (%s) is not available", NATIVE_KERNEL_NAME) if self.allowed_kernelspecs: # filter if there's an allow list d = {name: spec for name, spec in d.items() if name in self.allowed_kernelspecs} return d # TODO: Caching? def _get_kernel_spec_by_name(self, kernel_name, resource_dir): """Returns a :class:`KernelSpec` instance for a given kernel_name and resource_dir. """ kspec = None if kernel_name == NATIVE_KERNEL_NAME: try: from ipykernel.kernelspec import RESOURCES, get_kernel_dict except ImportError: # It should be impossible to reach this, but let's play it safe pass else: if resource_dir == RESOURCES: kspec = self.kernel_spec_class(resource_dir=resource_dir, **get_kernel_dict()) if not kspec: kspec = self.kernel_spec_class.from_resource_dir(resource_dir) if not KPF.instance(parent=self.parent).is_provisioner_available(kspec): raise NoSuchKernel(kernel_name) return kspec def _find_spec_directory(self, kernel_name): """Find the resource directory of a named kernel spec""" for kernel_dir in [kd for kd in self.kernel_dirs if os.path.isdir(kd)]: files = os.listdir(kernel_dir) for f in files: path = pjoin(kernel_dir, f) if f.lower() == kernel_name and _is_kernel_dir(path): return path if kernel_name == NATIVE_KERNEL_NAME: try: from ipykernel.kernelspec import RESOURCES except ImportError: pass else: return RESOURCES def get_kernel_spec(self, kernel_name): """Returns a :class:`KernelSpec` instance for the given kernel_name. Raises :exc:`NoSuchKernel` if the given kernel name is not found. """ if not _is_valid_kernel_name(kernel_name): self.log.warning( f"Kernelspec name {kernel_name} is invalid: {_kernel_name_description}" ) resource_dir = self._find_spec_directory(kernel_name.lower()) if resource_dir is None: self.log.warning("Kernelspec name %s cannot be found!", kernel_name) raise NoSuchKernel(kernel_name) return self._get_kernel_spec_by_name(kernel_name, resource_dir) def get_all_specs(self): """Returns a dict mapping kernel names to kernelspecs. Returns a dict of the form:: { 'kernel_name': { 'resource_dir': '/path/to/kernel_name', 'spec': {"the spec itself": ...} }, ... } """ d = self.find_kernel_specs() res = {} for kname, resource_dir in d.items(): try: if self.__class__ is KernelSpecManager: spec = self._get_kernel_spec_by_name(kname, resource_dir) else: # avoid calling private methods in subclasses, # which may have overridden find_kernel_specs # and get_kernel_spec, but not the newer get_all_specs spec = self.get_kernel_spec(kname) res[kname] = {"resource_dir": resource_dir, "spec": spec.to_dict()} except NoSuchKernel: pass # The appropriate warning has already been logged except Exception: self.log.warning("Error loading kernelspec %r", kname, exc_info=True) return res def remove_kernel_spec(self, name): """Remove a kernel spec directory by name. Returns the path that was deleted. """ save_native = self.ensure_native_kernel try: self.ensure_native_kernel = False specs = self.find_kernel_specs() finally: self.ensure_native_kernel = save_native spec_dir = specs[name] self.log.debug("Removing %s", spec_dir) if os.path.islink(spec_dir): os.remove(spec_dir) else: shutil.rmtree(spec_dir) return spec_dir def _get_destination_dir(self, kernel_name, user=False, prefix=None): if user: return os.path.join(self.user_kernel_dir, kernel_name) elif prefix: return os.path.join(os.path.abspath(prefix), "share", "jupyter", "kernels", kernel_name) else: return os.path.join(SYSTEM_JUPYTER_PATH[0], "kernels", kernel_name) def install_kernel_spec( self, source_dir, kernel_name=None, user=False, replace=None, prefix=None ): """Install a kernel spec by copying its directory. If ``kernel_name`` is not given, the basename of ``source_dir`` will be used. If ``user`` is False, it will attempt to install into the systemwide kernel registry. If the process does not have appropriate permissions, an :exc:`OSError` will be raised. If ``prefix`` is given, the kernelspec will be installed to PREFIX/share/jupyter/kernels/KERNEL_NAME. This can be sys.prefix for installation inside virtual or conda envs. """ source_dir = source_dir.rstrip("/\\") if not kernel_name: kernel_name = os.path.basename(source_dir) kernel_name = kernel_name.lower() if not _is_valid_kernel_name(kernel_name): msg = f"Invalid kernel name {kernel_name!r}. {_kernel_name_description}" raise ValueError(msg) if user and prefix: msg = "Can't specify both user and prefix. Please choose one or the other." raise ValueError(msg) if replace is not None: warnings.warn( "replace is ignored. Installing a kernelspec always replaces an existing " "installation", DeprecationWarning, stacklevel=2, ) destination = self._get_destination_dir(kernel_name, user=user, prefix=prefix) self.log.debug("Installing kernelspec in %s", destination) kernel_dir = os.path.dirname(destination) if kernel_dir not in self.kernel_dirs: self.log.warning( "Installing to %s, which is not in %s. The kernelspec may not be found.", kernel_dir, self.kernel_dirs, ) if os.path.isdir(destination): self.log.info("Removing existing kernelspec in %s", destination) shutil.rmtree(destination) shutil.copytree(source_dir, destination) self.log.info("Installed kernelspec %s in %s", kernel_name, destination) return destination def install_native_kernel_spec(self, user=False): """DEPRECATED: Use ipykernel.kernelspec.install""" warnings.warn( "install_native_kernel_spec is deprecated. Use ipykernel.kernelspec import install.", stacklevel=2, ) from ipykernel.kernelspec import install install(self, user=user) The provided code snippet includes necessary dependencies for implementing the `install_native_kernel_spec` function. Write a Python function `def install_native_kernel_spec(user=False)` to solve the following problem: Install the native kernel spec. Here is the function: def install_native_kernel_spec(user=False): """Install the native kernel spec.""" return KernelSpecManager().install_native_kernel_spec(user=user)
Install the native kernel spec.
174,934
import errno import glob import json import os import socket import stat import tempfile import warnings from getpass import getpass from typing import Any, Dict, List, Optional, Set, Tuple, Union, cast import zmq from jupyter_core.paths import jupyter_data_dir, jupyter_runtime_dir, secure_write from traitlets import Bool, CaselessStrEnum, Instance, Integer, Type, Unicode, observe from traitlets.config import LoggingConfigurable, SingletonConfigurable from .localinterfaces import localhost from .utils import _filefind KernelConnectionInfo = Dict[str, Union[int, str, bytes]] Optional: _SpecialForm = ... List = _Alias() class Tuple(BaseTypingInstance): def _is_homogenous(self): # To specify a variable-length tuple of homogeneous type, Tuple[T, ...] # is used. return self._generics_manager.is_homogenous_tuple() def py__simple_getitem__(self, index): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) else: if isinstance(index, int): return self._generics_manager.get_index_and_execute(index) debug.dbg('The getitem type on Tuple was %s' % index) return NO_VALUES def py__iter__(self, contextualized_node=None): if self._is_homogenous(): yield LazyKnownValues(self._generics_manager.get_index_and_execute(0)) else: for v in self._generics_manager.to_tuple(): yield LazyKnownValues(v.execute_annotation()) def py__getitem__(self, index_value_set, contextualized_node): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) return ValueSet.from_sets( self._generics_manager.to_tuple() ).execute_annotation() def _get_wrapped_value(self): tuple_, = self.inference_state.builtins_module \ .py__getattribute__('tuple').execute_annotation() return tuple_ def name(self): return self._wrapped_value.name def infer_type_vars(self, value_set): # Circular from jedi.inference.gradual.annotation import merge_pairwise_generics, merge_type_var_dicts value_set = value_set.filter( lambda x: x.py__name__().lower() == 'tuple', ) if self._is_homogenous(): # The parameter annotation is of the form `Tuple[T, ...]`, # so we treat the incoming tuple like a iterable sequence # rather than a positional container of elements. return self._class_value.get_generics()[0].infer_type_vars( value_set.merge_types_of_iterate(), ) else: # The parameter annotation has only explicit type parameters # (e.g: `Tuple[T]`, `Tuple[T, U]`, `Tuple[T, U, V]`, etc.) so we # treat the incoming values as needing to match the annotation # exactly, just as we would for non-tuple annotations. type_var_dict = {} for element in value_set: try: method = element.get_annotated_class_object except AttributeError: # This might still happen, because the tuple name matching # above is not 100% correct, so just catch the remaining # cases here. continue py_class = method() merge_type_var_dicts( type_var_dict, merge_pairwise_generics(self._class_value, py_class), ) return type_var_dict def secure_write(fname: str, binary: bool = False) -> Iterator[Any]: """Opens a file in the most restricted pattern available for writing content. This limits the file mode to `0o0600` and yields the resulting opened filed handle. Parameters ---------- fname : unicode The path to the file to write binary: boolean Indicates that the file is binary """ mode = "wb" if binary else "w" encoding = None if binary else "utf-8" open_flag = os.O_CREAT | os.O_WRONLY | os.O_TRUNC try: os.remove(fname) except OSError: # Skip any issues with the file not existing pass if os.name == "nt": if allow_insecure_writes: # Mounted file systems can have a number of failure modes inside this block. # For windows machines in insecure mode we simply skip this to avoid failures :/ issue_insecure_write_warning() else: # Python on windows does not respect the group and public bits for chmod, so we need # to take additional steps to secure the contents. # Touch file pre-emptively to avoid editing permissions in open files in Windows fd = os.open(fname, open_flag, 0o0600) os.close(fd) open_flag = os.O_WRONLY | os.O_TRUNC win32_restrict_file_to_user(fname) with os.fdopen(os.open(fname, open_flag, 0o0600), mode, encoding=encoding) as f: if os.name != "nt": # Enforce that the file got the requested permissions before writing file_mode = get_file_mode(fname) if file_mode != 0o0600: # noqa if allow_insecure_writes: issue_insecure_write_warning() else: msg = ( "Permissions assignment failed for secure file: '{file}'." " Got '{permissions}' instead of '0o0600'.".format( file=fname, permissions=oct(file_mode) ) ) raise RuntimeError(msg) yield f def localhost(): """return ip for localhost (almost always 127.0.0.1)""" return LOCALHOST The provided code snippet includes necessary dependencies for implementing the `write_connection_file` function. Write a Python function `def write_connection_file( fname: Optional[str] = None, shell_port: int = 0, iopub_port: int = 0, stdin_port: int = 0, hb_port: int = 0, control_port: int = 0, ip: str = "", key: bytes = b"", transport: str = "tcp", signature_scheme: str = "hmac-sha256", kernel_name: str = "", ) -> Tuple[str, KernelConnectionInfo]` to solve the following problem: Generates a JSON config file, including the selection of random ports. Parameters ---------- fname : unicode The path to the file to write shell_port : int, optional The port to use for ROUTER (shell) channel. iopub_port : int, optional The port to use for the SUB channel. stdin_port : int, optional The port to use for the ROUTER (raw input) channel. control_port : int, optional The port to use for the ROUTER (control) channel. hb_port : int, optional The port to use for the heartbeat REP channel. ip : str, optional The ip address the kernel will bind to. key : str, optional The Session key used for message authentication. signature_scheme : str, optional The scheme used for message authentication. This has the form 'digest-hash', where 'digest' is the scheme used for digests, and 'hash' is the name of the hash function used by the digest scheme. Currently, 'hmac' is the only supported digest scheme, and 'sha256' is the default hash function. kernel_name : str, optional The name of the kernel currently connected to. Here is the function: def write_connection_file( fname: Optional[str] = None, shell_port: int = 0, iopub_port: int = 0, stdin_port: int = 0, hb_port: int = 0, control_port: int = 0, ip: str = "", key: bytes = b"", transport: str = "tcp", signature_scheme: str = "hmac-sha256", kernel_name: str = "", ) -> Tuple[str, KernelConnectionInfo]: """Generates a JSON config file, including the selection of random ports. Parameters ---------- fname : unicode The path to the file to write shell_port : int, optional The port to use for ROUTER (shell) channel. iopub_port : int, optional The port to use for the SUB channel. stdin_port : int, optional The port to use for the ROUTER (raw input) channel. control_port : int, optional The port to use for the ROUTER (control) channel. hb_port : int, optional The port to use for the heartbeat REP channel. ip : str, optional The ip address the kernel will bind to. key : str, optional The Session key used for message authentication. signature_scheme : str, optional The scheme used for message authentication. This has the form 'digest-hash', where 'digest' is the scheme used for digests, and 'hash' is the name of the hash function used by the digest scheme. Currently, 'hmac' is the only supported digest scheme, and 'sha256' is the default hash function. kernel_name : str, optional The name of the kernel currently connected to. """ if not ip: ip = localhost() # default to temporary connector file if not fname: fd, fname = tempfile.mkstemp(".json") os.close(fd) # Find open ports as necessary. ports: List[int] = [] sockets: List[socket.socket] = [] ports_needed = ( int(shell_port <= 0) + int(iopub_port <= 0) + int(stdin_port <= 0) + int(control_port <= 0) + int(hb_port <= 0) ) if transport == "tcp": for _ in range(ports_needed): sock = socket.socket() # struct.pack('ii', (0,0)) is 8 null bytes sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, b"\0" * 8) sock.bind((ip, 0)) sockets.append(sock) for sock in sockets: port = sock.getsockname()[1] sock.close() ports.append(port) else: N = 1 for _ in range(ports_needed): while os.path.exists(f"{ip}-{str(N)}"): N += 1 ports.append(N) N += 1 if shell_port <= 0: shell_port = ports.pop(0) if iopub_port <= 0: iopub_port = ports.pop(0) if stdin_port <= 0: stdin_port = ports.pop(0) if control_port <= 0: control_port = ports.pop(0) if hb_port <= 0: hb_port = ports.pop(0) cfg: KernelConnectionInfo = { "shell_port": shell_port, "iopub_port": iopub_port, "stdin_port": stdin_port, "control_port": control_port, "hb_port": hb_port, } cfg["ip"] = ip cfg["key"] = key.decode() cfg["transport"] = transport cfg["signature_scheme"] = signature_scheme cfg["kernel_name"] = kernel_name # Only ever write this file as user read/writeable # This would otherwise introduce a vulnerability as a file has secrets # which would let others execute arbitrary code as you with secure_write(fname) as f: f.write(json.dumps(cfg, indent=2)) if hasattr(stat, "S_ISVTX"): # set the sticky bit on the parent directory of the file # to ensure only owner can remove it runtime_dir = os.path.dirname(fname) if runtime_dir: permissions = os.stat(runtime_dir).st_mode new_permissions = permissions | stat.S_ISVTX if new_permissions != permissions: try: os.chmod(runtime_dir, new_permissions) except OSError as e: if e.errno == errno.EPERM: # suppress permission errors setting sticky bit on runtime_dir, # which we may not own. pass return fname, cfg
Generates a JSON config file, including the selection of random ports. Parameters ---------- fname : unicode The path to the file to write shell_port : int, optional The port to use for ROUTER (shell) channel. iopub_port : int, optional The port to use for the SUB channel. stdin_port : int, optional The port to use for the ROUTER (raw input) channel. control_port : int, optional The port to use for the ROUTER (control) channel. hb_port : int, optional The port to use for the heartbeat REP channel. ip : str, optional The ip address the kernel will bind to. key : str, optional The Session key used for message authentication. signature_scheme : str, optional The scheme used for message authentication. This has the form 'digest-hash', where 'digest' is the scheme used for digests, and 'hash' is the name of the hash function used by the digest scheme. Currently, 'hmac' is the only supported digest scheme, and 'sha256' is the default hash function. kernel_name : str, optional The name of the kernel currently connected to.
174,935
import errno import glob import json import os import socket import stat import tempfile import warnings from getpass import getpass from typing import Any, Dict, List, Optional, Set, Tuple, Union, cast import zmq from jupyter_core.paths import jupyter_data_dir, jupyter_runtime_dir, secure_write from traitlets import Bool, CaselessStrEnum, Instance, Integer, Type, Unicode, observe from traitlets.config import LoggingConfigurable, SingletonConfigurable from .localinterfaces import localhost from .utils import _filefind Union: _SpecialForm = ... Optional: _SpecialForm = ... List = _Alias() def jupyter_runtime_dir() -> str: """Return the runtime dir for transient jupyter files. Returns JUPYTER_RUNTIME_DIR if defined. The default is now (data_dir)/runtime on all platforms; we no longer use XDG_RUNTIME_DIR after various problems. """ env = os.environ if env.get("JUPYTER_RUNTIME_DIR"): return env["JUPYTER_RUNTIME_DIR"] return pjoin(jupyter_data_dir(), "runtime") def _filefind(filename, path_dirs=None): """Find a file by looking through a sequence of paths. This iterates through a sequence of paths looking for a file and returns the full, absolute path of the first occurence of the file. If no set of path dirs is given, the filename is tested as is, after running through :func:`expandvars` and :func:`expanduser`. Thus a simple call:: filefind('myfile.txt') will find the file in the current working dir, but:: filefind('~/myfile.txt') Will find the file in the users home directory. This function does not automatically try any paths, such as the cwd or the user's home directory. Parameters ---------- filename : str The filename to look for. path_dirs : str, None or sequence of str The sequence of paths to look for the file in. If None, the filename need to be absolute or be in the cwd. If a string, the string is put into a sequence and the searched. If a sequence, walk through each element and join with ``filename``, calling :func:`expandvars` and :func:`expanduser` before testing for existence. Returns ------- Raises :exc:`IOError` or returns absolute path to file. """ # If paths are quoted, abspath gets confused, strip them... filename = filename.strip('"').strip("'") # If the input is an absolute path, just check it exists if os.path.isabs(filename) and os.path.isfile(filename): return filename if path_dirs is None: path_dirs = ("",) elif isinstance(path_dirs, str): path_dirs = (path_dirs,) for path in path_dirs: if path == ".": path = os.getcwd() # noqa testname = _expand_path(os.path.join(path, filename)) if os.path.isfile(testname): return os.path.abspath(testname) msg = f"File {filename!r} does not exist in any of the search paths: {path_dirs!r}" raise OSError(msg) The provided code snippet includes necessary dependencies for implementing the `find_connection_file` function. Write a Python function `def find_connection_file( filename: str = "kernel-*.json", path: Optional[Union[str, List[str]]] = None, profile: Optional[str] = None, ) -> str` to solve the following problem: find a connection file, and return its absolute path. The current working directory and optional search path will be searched for the file if it is not given by absolute path. If the argument does not match an existing file, it will be interpreted as a fileglob, and the matching file in the profile's security dir with the latest access time will be used. Parameters ---------- filename : str The connection file or fileglob to search for. path : str or list of strs[optional] Paths in which to search for connection files. Returns ------- str : The absolute path of the connection file. Here is the function: def find_connection_file( filename: str = "kernel-*.json", path: Optional[Union[str, List[str]]] = None, profile: Optional[str] = None, ) -> str: """find a connection file, and return its absolute path. The current working directory and optional search path will be searched for the file if it is not given by absolute path. If the argument does not match an existing file, it will be interpreted as a fileglob, and the matching file in the profile's security dir with the latest access time will be used. Parameters ---------- filename : str The connection file or fileglob to search for. path : str or list of strs[optional] Paths in which to search for connection files. Returns ------- str : The absolute path of the connection file. """ if profile is not None: warnings.warn("Jupyter has no profiles. profile=%s has been ignored." % profile) if path is None: path = [".", jupyter_runtime_dir()] if isinstance(path, str): path = [path] try: # first, try explicit name return _filefind(filename, path) except OSError: pass # not found by full name if "*" in filename: # given as a glob already pat = filename else: # accept any substring match pat = "*%s*" % filename matches = [] for p in path: matches.extend(glob.glob(os.path.join(p, pat))) matches = [os.path.abspath(m) for m in matches] if not matches: msg = f"Could not find {filename!r} in {path!r}" raise OSError(msg) elif len(matches) == 1: return matches[0] else: # get most recent match, by access time: return sorted(matches, key=lambda f: os.stat(f).st_atime)[-1]
find a connection file, and return its absolute path. The current working directory and optional search path will be searched for the file if it is not given by absolute path. If the argument does not match an existing file, it will be interpreted as a fileglob, and the matching file in the profile's security dir with the latest access time will be used. Parameters ---------- filename : str The connection file or fileglob to search for. path : str or list of strs[optional] Paths in which to search for connection files. Returns ------- str : The absolute path of the connection file.
174,936
import errno import glob import json import os import socket import stat import tempfile import warnings from getpass import getpass from typing import Any, Dict, List, Optional, Set, Tuple, Union, cast import zmq from jupyter_core.paths import jupyter_data_dir, jupyter_runtime_dir, secure_write from traitlets import Bool, CaselessStrEnum, Instance, Integer, Type, Unicode, observe from traitlets.config import LoggingConfigurable, SingletonConfigurable from .localinterfaces import localhost from .utils import _filefind KernelConnectionInfo = Dict[str, Union[int, str, bytes]] def getpass(prompt: str = ..., stream: Optional[TextIO] = ...) -> str: ... Any = object() Union: _SpecialForm = ... Optional: _SpecialForm = ... Dict = _Alias() def cast(typ: Type[_T], val: Any) -> _T: ... def cast(typ: str, val: Any) -> Any: ... def cast(typ: object, val: Any) -> Any: ... class Tuple(BaseTypingInstance): def _is_homogenous(self): # To specify a variable-length tuple of homogeneous type, Tuple[T, ...] # is used. return self._generics_manager.is_homogenous_tuple() def py__simple_getitem__(self, index): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) else: if isinstance(index, int): return self._generics_manager.get_index_and_execute(index) debug.dbg('The getitem type on Tuple was %s' % index) return NO_VALUES def py__iter__(self, contextualized_node=None): if self._is_homogenous(): yield LazyKnownValues(self._generics_manager.get_index_and_execute(0)) else: for v in self._generics_manager.to_tuple(): yield LazyKnownValues(v.execute_annotation()) def py__getitem__(self, index_value_set, contextualized_node): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) return ValueSet.from_sets( self._generics_manager.to_tuple() ).execute_annotation() def _get_wrapped_value(self): tuple_, = self.inference_state.builtins_module \ .py__getattribute__('tuple').execute_annotation() return tuple_ def name(self): return self._wrapped_value.name def infer_type_vars(self, value_set): # Circular from jedi.inference.gradual.annotation import merge_pairwise_generics, merge_type_var_dicts value_set = value_set.filter( lambda x: x.py__name__().lower() == 'tuple', ) if self._is_homogenous(): # The parameter annotation is of the form `Tuple[T, ...]`, # so we treat the incoming tuple like a iterable sequence # rather than a positional container of elements. return self._class_value.get_generics()[0].infer_type_vars( value_set.merge_types_of_iterate(), ) else: # The parameter annotation has only explicit type parameters # (e.g: `Tuple[T]`, `Tuple[T, U]`, `Tuple[T, U, V]`, etc.) so we # treat the incoming values as needing to match the annotation # exactly, just as we would for non-tuple annotations. type_var_dict = {} for element in value_set: try: method = element.get_annotated_class_object except AttributeError: # This might still happen, because the tuple name matching # above is not 100% correct, so just catch the remaining # cases here. continue py_class = method() merge_type_var_dicts( type_var_dict, merge_pairwise_generics(self._class_value, py_class), ) return type_var_dict The provided code snippet includes necessary dependencies for implementing the `tunnel_to_kernel` function. Write a Python function `def tunnel_to_kernel( connection_info: Union[str, KernelConnectionInfo], sshserver: str, sshkey: Optional[str] = None, ) -> Tuple[Any, ...]` to solve the following problem: tunnel connections to a kernel via ssh This will open five SSH tunnels from localhost on this machine to the ports associated with the kernel. They can be either direct localhost-localhost tunnels, or if an intermediate server is necessary, the kernel must be listening on a public IP. Parameters ---------- connection_info : dict or str (path) Either a connection dict, or the path to a JSON connection file sshserver : str The ssh sever to use to tunnel to the kernel. Can be a full `user@server:port` string. ssh config aliases are respected. sshkey : str [optional] Path to file containing ssh key to use for authentication. Only necessary if your ssh config does not already associate a keyfile with the host. Returns ------- (shell, iopub, stdin, hb, control) : ints The five ports on localhost that have been forwarded to the kernel. Here is the function: def tunnel_to_kernel( connection_info: Union[str, KernelConnectionInfo], sshserver: str, sshkey: Optional[str] = None, ) -> Tuple[Any, ...]: """tunnel connections to a kernel via ssh This will open five SSH tunnels from localhost on this machine to the ports associated with the kernel. They can be either direct localhost-localhost tunnels, or if an intermediate server is necessary, the kernel must be listening on a public IP. Parameters ---------- connection_info : dict or str (path) Either a connection dict, or the path to a JSON connection file sshserver : str The ssh sever to use to tunnel to the kernel. Can be a full `user@server:port` string. ssh config aliases are respected. sshkey : str [optional] Path to file containing ssh key to use for authentication. Only necessary if your ssh config does not already associate a keyfile with the host. Returns ------- (shell, iopub, stdin, hb, control) : ints The five ports on localhost that have been forwarded to the kernel. """ from .ssh import tunnel if isinstance(connection_info, str): # it's a path, unpack it with open(connection_info) as f: connection_info = json.loads(f.read()) cf = cast(Dict[str, Any], connection_info) lports = tunnel.select_random_ports(5) rports = ( cf["shell_port"], cf["iopub_port"], cf["stdin_port"], cf["hb_port"], cf["control_port"], ) remote_ip = cf["ip"] if tunnel.try_passwordless_ssh(sshserver, sshkey): password: Union[bool, str] = False else: password = getpass("SSH Password for %s: " % sshserver) for lp, rp in zip(lports, rports): tunnel.ssh_tunnel(lp, rp, sshserver, remote_ip, sshkey, password) return tuple(lports)
tunnel connections to a kernel via ssh This will open five SSH tunnels from localhost on this machine to the ports associated with the kernel. They can be either direct localhost-localhost tunnels, or if an intermediate server is necessary, the kernel must be listening on a public IP. Parameters ---------- connection_info : dict or str (path) Either a connection dict, or the path to a JSON connection file sshserver : str The ssh sever to use to tunnel to the kernel. Can be a full `user@server:port` string. ssh config aliases are respected. sshkey : str [optional] Path to file containing ssh key to use for authentication. Only necessary if your ssh config does not already associate a keyfile with the host. Returns ------- (shell, iopub, stdin, hb, control) : ints The five ports on localhost that have been forwarded to the kernel.
174,937
import os import sys import warnings from subprocess import PIPE, Popen from typing import Any, Dict, List, Optional from traitlets.log import get_logger PIPE: int class Popen(Generic[AnyStr]): args: _CMD stdin: Optional[IO[AnyStr]] stdout: Optional[IO[AnyStr]] stderr: Optional[IO[AnyStr]] pid: int returncode: int universal_newlines: bool # Technically it is wrong that Popen provides __new__ instead of __init__ # but this shouldn't come up hopefully? if sys.version_info >= (3, 7): # text is added in 3.7 def __new__( cls, args: _CMD, bufsize: int = ..., executable: Optional[AnyPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Optional[Any] = ..., creationflags: int = ..., restore_signals: bool = ..., start_new_session: bool = ..., pass_fds: Any = ..., *, text: Optional[bool] = ..., encoding: str, errors: Optional[str] = ..., ) -> Popen[str]: ... def __new__( cls, args: _CMD, bufsize: int = ..., executable: Optional[AnyPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Optional[Any] = ..., creationflags: int = ..., restore_signals: bool = ..., start_new_session: bool = ..., pass_fds: Any = ..., *, text: Optional[bool] = ..., encoding: Optional[str] = ..., errors: str, ) -> Popen[str]: ... def __new__( cls, args: _CMD, bufsize: int = ..., executable: Optional[AnyPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., env: Optional[_ENV] = ..., *, universal_newlines: Literal[True], startupinfo: Optional[Any] = ..., creationflags: int = ..., restore_signals: bool = ..., start_new_session: bool = ..., pass_fds: Any = ..., # where the *real* keyword only args start text: Optional[bool] = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., ) -> Popen[str]: ... def __new__( cls, args: _CMD, bufsize: int = ..., executable: Optional[AnyPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Optional[Any] = ..., creationflags: int = ..., restore_signals: bool = ..., start_new_session: bool = ..., pass_fds: Any = ..., *, text: Literal[True], encoding: Optional[str] = ..., errors: Optional[str] = ..., ) -> Popen[str]: ... def __new__( cls, args: _CMD, bufsize: int = ..., executable: Optional[AnyPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., env: Optional[_ENV] = ..., universal_newlines: Literal[False] = ..., startupinfo: Optional[Any] = ..., creationflags: int = ..., restore_signals: bool = ..., start_new_session: bool = ..., pass_fds: Any = ..., *, text: Literal[None, False] = ..., encoding: None = ..., errors: None = ..., ) -> Popen[bytes]: ... def __new__( cls, args: _CMD, bufsize: int = ..., executable: Optional[AnyPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Optional[Any] = ..., creationflags: int = ..., restore_signals: bool = ..., start_new_session: bool = ..., pass_fds: Any = ..., *, text: Optional[bool] = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., ) -> Popen[Any]: ... else: def __new__( cls, args: _CMD, bufsize: int = ..., executable: Optional[AnyPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Optional[Any] = ..., creationflags: int = ..., restore_signals: bool = ..., start_new_session: bool = ..., pass_fds: Any = ..., *, encoding: str, errors: Optional[str] = ..., ) -> Popen[str]: ... def __new__( cls, args: _CMD, bufsize: int = ..., executable: Optional[AnyPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Optional[Any] = ..., creationflags: int = ..., restore_signals: bool = ..., start_new_session: bool = ..., pass_fds: Any = ..., *, encoding: Optional[str] = ..., errors: str, ) -> Popen[str]: ... def __new__( cls, args: _CMD, bufsize: int = ..., executable: Optional[AnyPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., env: Optional[_ENV] = ..., *, universal_newlines: Literal[True], startupinfo: Optional[Any] = ..., creationflags: int = ..., restore_signals: bool = ..., start_new_session: bool = ..., pass_fds: Any = ..., # where the *real* keyword only args start encoding: Optional[str] = ..., errors: Optional[str] = ..., ) -> Popen[str]: ... def __new__( cls, args: _CMD, bufsize: int = ..., executable: Optional[AnyPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., env: Optional[_ENV] = ..., universal_newlines: Literal[False] = ..., startupinfo: Optional[Any] = ..., creationflags: int = ..., restore_signals: bool = ..., start_new_session: bool = ..., pass_fds: Any = ..., *, encoding: None = ..., errors: None = ..., ) -> Popen[bytes]: ... def __new__( cls, args: _CMD, bufsize: int = ..., executable: Optional[AnyPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Optional[Any] = ..., creationflags: int = ..., restore_signals: bool = ..., start_new_session: bool = ..., pass_fds: Any = ..., *, encoding: Optional[str] = ..., errors: Optional[str] = ..., ) -> Popen[Any]: ... def poll(self) -> Optional[int]: ... if sys.version_info >= (3, 7): def wait(self, timeout: Optional[float] = ...) -> int: ... else: def wait(self, timeout: Optional[float] = ..., endtime: Optional[float] = ...) -> int: ... # Return str/bytes def communicate( self, input: Optional[AnyStr] = ..., timeout: Optional[float] = ..., # morally this should be optional ) -> Tuple[AnyStr, AnyStr]: ... def send_signal(self, sig: int) -> None: ... def terminate(self) -> None: ... def kill(self) -> None: ... def __enter__(self: _S) -> _S: ... def __exit__( self, type: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType] ) -> None: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... Any = object() Optional: _SpecialForm = ... List = _Alias() Dict = _Alias() def get_logger(): """Grab the global logger instance. If a global Application is instantiated, grab its logger. Otherwise, grab the root logger. """ global _logger if _logger is None: from .config import Application if Application.initialized(): _logger = Application.instance().log else: _logger = logging.getLogger("traitlets") # Add a NullHandler to silence warnings about not being # initialized, per best practice for libraries. _logger.addHandler(logging.NullHandler()) return _logger def create_interrupt_event(): """Create an interrupt event handle. The parent process should call this to create the interrupt event that is passed to the child process. It should store this handle and use it with ``send_interrupt`` to interrupt the child process. """ # Create a security attributes struct that permits inheritance of the # handle by new processes. # FIXME: We can clean up this mess by requiring pywin32 for IPython. class SECURITY_ATTRIBUTES(ctypes.Structure): # noqa _fields_ = [ ("nLength", ctypes.c_int), ("lpSecurityDescriptor", ctypes.c_void_p), ("bInheritHandle", ctypes.c_int), ] sa = SECURITY_ATTRIBUTES() sa_p = ctypes.pointer(sa) sa.nLength = ctypes.sizeof(SECURITY_ATTRIBUTES) sa.lpSecurityDescriptor = 0 sa.bInheritHandle = 1 return ctypes.windll.kernel32.CreateEventA( sa_p, False, False, "" # lpEventAttributes # bManualReset # bInitialState ) # lpName CREATE_NEW_PROCESS_GROUP: int DUPLICATE_SAME_ACCESS: int def DuplicateHandle( __source_process_handle: int, __source_handle: int, __target_process_handle: int, __desired_access: int, __inherit_handle: bool, __options: int = ..., ) -> int: ... def GetCurrentProcess() -> int: ... The provided code snippet includes necessary dependencies for implementing the `launch_kernel` function. Write a Python function `def launch_kernel( cmd: List[str], stdin: Optional[int] = None, stdout: Optional[int] = None, stderr: Optional[int] = None, env: Optional[Dict[str, str]] = None, independent: bool = False, cwd: Optional[str] = None, **kw: Any, ) -> Popen` to solve the following problem: Launches a localhost kernel, binding to the specified ports. Parameters ---------- cmd : Popen list, A string of Python code that imports and executes a kernel entry point. stdin, stdout, stderr : optional (default None) Standards streams, as defined in subprocess.Popen. env: dict, optional Environment variables passed to the kernel independent : bool, optional (default False) If set, the kernel process is guaranteed to survive if this process dies. If not set, an effort is made to ensure that the kernel is killed when this process dies. Note that in this case it is still good practice to kill kernels manually before exiting. cwd : path, optional The working dir of the kernel process (default: cwd of this process). **kw: optional Additional arguments for Popen Returns ------- Popen instance for the kernel subprocess Here is the function: def launch_kernel( cmd: List[str], stdin: Optional[int] = None, stdout: Optional[int] = None, stderr: Optional[int] = None, env: Optional[Dict[str, str]] = None, independent: bool = False, cwd: Optional[str] = None, **kw: Any, ) -> Popen: """Launches a localhost kernel, binding to the specified ports. Parameters ---------- cmd : Popen list, A string of Python code that imports and executes a kernel entry point. stdin, stdout, stderr : optional (default None) Standards streams, as defined in subprocess.Popen. env: dict, optional Environment variables passed to the kernel independent : bool, optional (default False) If set, the kernel process is guaranteed to survive if this process dies. If not set, an effort is made to ensure that the kernel is killed when this process dies. Note that in this case it is still good practice to kill kernels manually before exiting. cwd : path, optional The working dir of the kernel process (default: cwd of this process). **kw: optional Additional arguments for Popen Returns ------- Popen instance for the kernel subprocess """ # Popen will fail (sometimes with a deadlock) if stdin, stdout, and stderr # are invalid. Unfortunately, there is in general no way to detect whether # they are valid. The following two blocks redirect them to (temporary) # pipes in certain important cases. # If this process has been backgrounded, our stdin is invalid. Since there # is no compelling reason for the kernel to inherit our stdin anyway, we'll # place this one safe and always redirect. redirect_in = True _stdin = PIPE if stdin is None else stdin # If this process in running on pythonw, we know that stdin, stdout, and # stderr are all invalid. redirect_out = sys.executable.endswith("pythonw.exe") if redirect_out: blackhole = open(os.devnull, "w") # noqa _stdout = blackhole if stdout is None else stdout _stderr = blackhole if stderr is None else stderr else: _stdout, _stderr = stdout, stderr env = env if (env is not None) else os.environ.copy() kwargs = kw.copy() main_args = { "stdin": _stdin, "stdout": _stdout, "stderr": _stderr, "cwd": cwd, "env": env, } kwargs.update(main_args) # Spawn a kernel. if sys.platform == "win32": if cwd: kwargs["cwd"] = cwd from .win_interrupt import create_interrupt_event # Create a Win32 event for interrupting the kernel # and store it in an environment variable. interrupt_event = create_interrupt_event() env["JPY_INTERRUPT_EVENT"] = str(interrupt_event) # deprecated old env name: env["IPY_INTERRUPT_EVENT"] = env["JPY_INTERRUPT_EVENT"] try: from _winapi import ( CREATE_NEW_PROCESS_GROUP, DUPLICATE_SAME_ACCESS, DuplicateHandle, GetCurrentProcess, ) except: # noqa from _subprocess import ( CREATE_NEW_PROCESS_GROUP, DUPLICATE_SAME_ACCESS, DuplicateHandle, GetCurrentProcess, ) # create a handle on the parent to be inherited if independent: kwargs["creationflags"] = CREATE_NEW_PROCESS_GROUP else: pid = GetCurrentProcess() handle = DuplicateHandle( pid, pid, pid, 0, True, DUPLICATE_SAME_ACCESS, # Inheritable by new processes. ) env["JPY_PARENT_PID"] = str(int(handle)) # Prevent creating new console window on pythonw if redirect_out: kwargs["creationflags"] = ( kwargs.setdefault("creationflags", 0) | 0x08000000 ) # CREATE_NO_WINDOW # Avoid closing the above parent and interrupt handles. # close_fds is True by default on Python >=3.7 # or when no stream is captured on Python <3.7 # (we always capture stdin, so this is already False by default on <3.7) kwargs["close_fds"] = False else: # Create a new session. # This makes it easier to interrupt the kernel, # because we want to interrupt the whole process group. # We don't use setpgrp, which is known to cause problems for kernels starting # certain interactive subprocesses, such as bash -i. kwargs["start_new_session"] = True if not independent: env["JPY_PARENT_PID"] = str(os.getpid()) try: # Allow to use ~/ in the command or its arguments cmd = [os.path.expanduser(s) for s in cmd] proc = Popen(cmd, **kwargs) except Exception as ex: try: msg = "Failed to run command:\n{}\n PATH={!r}\n with kwargs:\n{!r}\n" # exclude environment variables, # which may contain access tokens and the like. without_env = {key: value for key, value in kwargs.items() if key != "env"} msg = msg.format(cmd, env.get("PATH", os.defpath), without_env) get_logger().error(msg) except Exception as ex2: # Don't let a formatting/logger issue lead to the wrong exception warnings.warn(f"Failed to run command: '{cmd}' due to exception: {ex}") warnings.warn(f"The following exception occurred handling the previous failure: {ex2}") raise ex if sys.platform == "win32": # Attach the interrupt event to the Popen objet so it can be used later. proc.win32_interrupt_event = interrupt_event # Clean up pipes created to work around Popen bug. if redirect_in and stdin is None: assert proc.stdin is not None proc.stdin.close() return proc
Launches a localhost kernel, binding to the specified ports. Parameters ---------- cmd : Popen list, A string of Python code that imports and executes a kernel entry point. stdin, stdout, stderr : optional (default None) Standards streams, as defined in subprocess.Popen. env: dict, optional Environment variables passed to the kernel independent : bool, optional (default False) If set, the kernel process is guaranteed to survive if this process dies. If not set, an effort is made to ensure that the kernel is killed when this process dies. Note that in this case it is still good practice to kill kernels manually before exiting. cwd : path, optional The working dir of the kernel process (default: cwd of this process). **kw: optional Additional arguments for Popen Returns ------- Popen instance for the kernel subprocess
174,938
import atexit import os import re import signal import socket import sys import warnings from getpass import getpass, getuser from multiprocessing import Process def open_tunnel(addr, server, keyfile=None, password=None, paramiko=None, timeout=60): """Open a tunneled connection from a 0MQ url. For use inside tunnel_connection. Returns ------- (url, tunnel) : (str, object) The 0MQ url that has been forwarded, and the tunnel object """ lport = select_random_ports(1)[0] _, addr = addr.split("://") ip, rport = addr.split(":") rport = int(rport) paramiko = sys.platform == "win32" if paramiko is None else paramiko_tunnel tunnelf = paramiko_tunnel if paramiko else openssh_tunnel tunnel = tunnelf( lport, rport, server, remoteip=ip, keyfile=keyfile, password=password, timeout=timeout, ) return "tcp://127.0.0.1:%i" % lport, tunnel The provided code snippet includes necessary dependencies for implementing the `tunnel_connection` function. Write a Python function `def tunnel_connection(socket, addr, server, keyfile=None, password=None, paramiko=None, timeout=60)` to solve the following problem: Connect a socket to an address via an ssh tunnel. This is a wrapper for socket.connect(addr), when addr is not accessible from the local machine. It simply creates an ssh tunnel using the remaining args, and calls socket.connect('tcp://localhost:lport') where lport is the randomly selected local port of the tunnel. Here is the function: def tunnel_connection(socket, addr, server, keyfile=None, password=None, paramiko=None, timeout=60): """Connect a socket to an address via an ssh tunnel. This is a wrapper for socket.connect(addr), when addr is not accessible from the local machine. It simply creates an ssh tunnel using the remaining args, and calls socket.connect('tcp://localhost:lport') where lport is the randomly selected local port of the tunnel. """ new_url, tunnel = open_tunnel( addr, server, keyfile=keyfile, password=password, paramiko=paramiko, timeout=timeout, ) socket.connect(new_url) return tunnel
Connect a socket to an address via an ssh tunnel. This is a wrapper for socket.connect(addr), when addr is not accessible from the local machine. It simply creates an ssh tunnel using the remaining args, and calls socket.connect('tcp://localhost:lport') where lport is the randomly selected local port of the tunnel.
174,939
import hashlib import hmac import json import logging import os import pickle import pprint import random import typing as t import warnings from binascii import b2a_hex from datetime import datetime, timezone from hmac import compare_digest from typing import Optional, Union import zmq.asyncio from tornado.ioloop import IOLoop from traitlets import ( Any, Bool, CBytes, CUnicode, Dict, DottedObjectName, Instance, Integer, Set, TraitError, Unicode, observe, ) from traitlets.config.configurable import Configurable, LoggingConfigurable from traitlets.log import get_logger from traitlets.utils.importstring import import_item from zmq.eventloop.zmqstream import ZMQStream from ._version import protocol_version from .adapter import adapt from .jsonutil import extract_dates, json_clean, json_default, squash_dates The provided code snippet includes necessary dependencies for implementing the `squash_unicode` function. Write a Python function `def squash_unicode(obj)` to solve the following problem: coerce unicode back to bytestrings. Here is the function: def squash_unicode(obj): """coerce unicode back to bytestrings.""" if isinstance(obj, dict): for key in list(obj.keys()): obj[key] = squash_unicode(obj[key]) if isinstance(key, str): obj[squash_unicode(key)] = obj.pop(key) elif isinstance(obj, list): for i, v in enumerate(obj): obj[i] = squash_unicode(v) elif isinstance(obj, str): obj = obj.encode("utf8") return obj
coerce unicode back to bytestrings.
174,940
import hashlib import hmac import json import logging import os import pickle import pprint import random import typing as t import warnings from binascii import b2a_hex from datetime import datetime, timezone from hmac import compare_digest from typing import Optional, Union import zmq.asyncio from tornado.ioloop import IOLoop from traitlets import ( Any, Bool, CBytes, CUnicode, Dict, DottedObjectName, Instance, Integer, Set, TraitError, Unicode, observe, ) from traitlets.config.configurable import Configurable, LoggingConfigurable from traitlets.log import get_logger from traitlets.utils.importstring import import_item from zmq.eventloop.zmqstream import ZMQStream from ._version import protocol_version from .adapter import adapt from .jsonutil import extract_dates, json_clean, json_default, squash_dates def json_default(obj): """default function for packing objects in JSON.""" if isinstance(obj, datetime): obj = _ensure_tzinfo(obj) return obj.isoformat().replace('+00:00', 'Z') if isinstance(obj, bytes): return b2a_base64(obj, newline=False).decode('ascii') if isinstance(obj, Iterable): return list(obj) if isinstance(obj, numbers.Integral): return int(obj) if isinstance(obj, numbers.Real): return float(obj) raise TypeError("%r is not JSON serializable" % obj) def json_clean(obj): # types that are 'atomic' and ok in json as-is. atomic_ok = (str, type(None)) # containers that we need to convert into lists container_to_list = (tuple, set, types.GeneratorType) # Since bools are a subtype of Integrals, which are a subtype of Reals, # we have to check them in that order. if isinstance(obj, bool): return obj if isinstance(obj, numbers.Integral): # cast int to int, in case subclasses override __str__ (e.g. boost enum, #4598) return int(obj) if isinstance(obj, numbers.Real): # cast out-of-range floats to their reprs if math.isnan(obj) or math.isinf(obj): return repr(obj) return float(obj) if isinstance(obj, atomic_ok): return obj if isinstance(obj, bytes): # unanmbiguous binary data is base64-encoded # (this probably should have happened upstream) return b2a_base64(obj, newline=False).decode('ascii') if isinstance(obj, container_to_list) or ( hasattr(obj, '__iter__') and hasattr(obj, next_attr_name) ): obj = list(obj) if isinstance(obj, list): return [json_clean(x) for x in obj] if isinstance(obj, dict): # First, validate that the dict won't lose data in conversion due to # key collisions after stringification. This can happen with keys like # True and 'true' or 1 and '1', which collide in JSON. nkeys = len(obj) nkeys_collapsed = len(set(map(str, obj))) if nkeys != nkeys_collapsed: msg = ( 'dict cannot be safely converted to JSON: ' 'key collision would lead to dropped values' ) raise ValueError(msg) # If all OK, proceed by making the new dict that will be json-safe out = {} for k, v in obj.items(): out[str(k)] = json_clean(v) return out if isinstance(obj, datetime): return obj.strftime(ISO8601) # we don't understand it, it's probably an unserializable object raise ValueError("Can't clean for JSON: %r" % obj) The provided code snippet includes necessary dependencies for implementing the `json_packer` function. Write a Python function `def json_packer(obj)` to solve the following problem: Convert a json object to a bytes. Here is the function: def json_packer(obj): """Convert a json object to a bytes.""" try: return json.dumps( obj, default=json_default, ensure_ascii=False, allow_nan=False, ).encode("utf8", errors="surrogateescape") except (TypeError, ValueError) as e: # Fallback to trying to clean the json before serializing packed = json.dumps( json_clean(obj), default=json_default, ensure_ascii=False, allow_nan=False, ).encode("utf8", errors="surrogateescape") warnings.warn( f"Message serialization failed with:\n{e}\n" "Supporting this message is deprecated in jupyter-client 7, please make " "sure your message is JSON-compliant", stacklevel=2, ) return packed
Convert a json object to a bytes.
174,941
import hashlib import hmac import json import logging import os import pickle import pprint import random import typing as t import warnings from binascii import b2a_hex from datetime import datetime, timezone from hmac import compare_digest from typing import Optional, Union import zmq.asyncio from tornado.ioloop import IOLoop from traitlets import ( Any, Bool, CBytes, CUnicode, Dict, DottedObjectName, Instance, Integer, Set, TraitError, Unicode, observe, ) from traitlets.config.configurable import Configurable, LoggingConfigurable from traitlets.log import get_logger from traitlets.utils.importstring import import_item from zmq.eventloop.zmqstream import ZMQStream from ._version import protocol_version from .adapter import adapt from .jsonutil import extract_dates, json_clean, json_default, squash_dates The provided code snippet includes necessary dependencies for implementing the `json_unpacker` function. Write a Python function `def json_unpacker(s)` to solve the following problem: Convert a json bytes or string to an object. Here is the function: def json_unpacker(s): """Convert a json bytes or string to an object.""" if isinstance(s, bytes): s = s.decode("utf8", "replace") return json.loads(s)
Convert a json bytes or string to an object.
174,942
import hashlib import hmac import json import logging import os import pickle import pprint import random import typing as t import warnings from binascii import b2a_hex from datetime import datetime, timezone from hmac import compare_digest from typing import Optional, Union import zmq.asyncio from tornado.ioloop import IOLoop from traitlets import ( Any, Bool, CBytes, CUnicode, Dict, DottedObjectName, Instance, Integer, Set, TraitError, Unicode, observe, ) from traitlets.config.configurable import Configurable, LoggingConfigurable from traitlets.log import get_logger from traitlets.utils.importstring import import_item from zmq.eventloop.zmqstream import ZMQStream from ._version import protocol_version from .adapter import adapt from .jsonutil import extract_dates, json_clean, json_default, squash_dates PICKLE_PROTOCOL = pickle.DEFAULT_PROTOCOL def squash_dates(obj): """squash datetime objects into ISO8601 strings""" if isinstance(obj, dict): obj = dict(obj) # don't clobber for k, v in obj.items(): obj[k] = squash_dates(v) elif isinstance(obj, (list, tuple)): obj = [squash_dates(o) for o in obj] elif isinstance(obj, datetime): obj = obj.isoformat() return obj The provided code snippet includes necessary dependencies for implementing the `pickle_packer` function. Write a Python function `def pickle_packer(o)` to solve the following problem: Pack an object using the pickle module. Here is the function: def pickle_packer(o): """Pack an object using the pickle module.""" return pickle.dumps(squash_dates(o), PICKLE_PROTOCOL)
Pack an object using the pickle module.
174,943
import hashlib import hmac import json import logging import os import pickle import pprint import random import typing as t import warnings from binascii import b2a_hex from datetime import datetime, timezone from hmac import compare_digest from typing import Optional, Union import zmq.asyncio from tornado.ioloop import IOLoop from traitlets import ( Any, Bool, CBytes, CUnicode, Dict, DottedObjectName, Instance, Integer, Set, TraitError, Unicode, observe, ) from traitlets.config.configurable import Configurable, LoggingConfigurable from traitlets.log import get_logger from traitlets.utils.importstring import import_item from zmq.eventloop.zmqstream import ZMQStream from ._version import protocol_version from .adapter import adapt from .jsonutil import extract_dates, json_clean, json_default, squash_dates def new_id_bytes() -> bytes: """Return new_id as ascii bytes""" return new_id().encode("ascii") class Session(Configurable): """Object for handling serialization and sending of messages. The Session object handles building messages and sending them with ZMQ sockets or ZMQStream objects. Objects can communicate with each other over the network via Session objects, and only need to work with the dict-based IPython message spec. The Session will handle serialization/deserialization, security, and metadata. Sessions support configurable serialization via packer/unpacker traits, and signing with HMAC digests via the key/keyfile traits. Parameters ---------- debug : bool whether to trigger extra debugging statements packer/unpacker : str : 'json', 'pickle' or import_string importstrings for methods to serialize message parts. If just 'json' or 'pickle', predefined JSON and pickle packers will be used. Otherwise, the entire importstring must be used. The functions must accept at least valid JSON input, and output *bytes*. For example, to use msgpack: packer = 'msgpack.packb', unpacker='msgpack.unpackb' pack/unpack : callables You can also set the pack/unpack callables for serialization directly. session : bytes the ID of this Session object. The default is to generate a new UUID. username : unicode username added to message headers. The default is to ask the OS. key : bytes The key used to initialize an HMAC signature. If unset, messages will not be signed or checked. keyfile : filepath The file containing a key. If this is set, `key` will be initialized to the contents of the file. """ debug = Bool(False, config=True, help="""Debug output in the Session""") check_pid = Bool( True, config=True, help="""Whether to check PID to protect against calls after fork. This check can be disabled if fork-safety is handled elsewhere. """, ) packer = DottedObjectName( "json", config=True, help="""The name of the packer for serializing messages. Should be one of 'json', 'pickle', or an import name for a custom callable serializer.""", ) def _packer_changed(self, change): new = change["new"] if new.lower() == "json": self.pack = json_packer self.unpack = json_unpacker self.unpacker = new elif new.lower() == "pickle": self.pack = pickle_packer self.unpack = pickle_unpacker self.unpacker = new else: self.pack = import_item(str(new)) unpacker = DottedObjectName( "json", config=True, help="""The name of the unpacker for unserializing messages. Only used with custom functions for `packer`.""", ) def _unpacker_changed(self, change): new = change["new"] if new.lower() == "json": self.pack = json_packer self.unpack = json_unpacker self.packer = new elif new.lower() == "pickle": self.pack = pickle_packer self.unpack = pickle_unpacker self.packer = new else: self.unpack = import_item(str(new)) session = CUnicode("", config=True, help="""The UUID identifying this session.""") def _session_default(self) -> str: u = new_id() self.bsession = u.encode("ascii") return u def _session_changed(self, change): self.bsession = self.session.encode("ascii") # bsession is the session as bytes bsession = CBytes(b"") username = Unicode( os.environ.get("USER", "username"), help="""Username for the Session. Default is your system username.""", config=True, ) metadata = Dict( {}, config=True, help="Metadata dictionary, which serves as the default top-level metadata dict for each " "message.", ) # if 0, no adapting to do. adapt_version = Integer(0) # message signature related traits: key = CBytes(config=True, help="""execution key, for signing messages.""") def _key_default(self) -> bytes: return new_id_bytes() def _key_changed(self, change): self._new_auth() signature_scheme = Unicode( "hmac-sha256", config=True, help="""The digest scheme used to construct the message signatures. Must have the form 'hmac-HASH'.""", ) def _signature_scheme_changed(self, change): new = change["new"] if not new.startswith("hmac-"): raise TraitError("signature_scheme must start with 'hmac-', got %r" % new) hash_name = new.split("-", 1)[1] try: self.digest_mod = getattr(hashlib, hash_name) except AttributeError as e: raise TraitError("hashlib has no such attribute: %s" % hash_name) from e self._new_auth() digest_mod = Any() def _digest_mod_default(self) -> t.Callable: return hashlib.sha256 auth = Instance(hmac.HMAC, allow_none=True) def _new_auth(self) -> None: if self.key: self.auth = hmac.HMAC(self.key, digestmod=self.digest_mod) else: self.auth = None digest_history = Set() digest_history_size = Integer( 2**16, config=True, help="""The maximum number of digests to remember. The digest history will be culled when it exceeds this value. """, ) keyfile = Unicode("", config=True, help="""path to file containing execution key.""") def _keyfile_changed(self, change): with open(change["new"], "rb") as f: self.key = f.read().strip() # for protecting against sends from forks pid = Integer() # serialization traits: pack = Any(default_packer) # the actual packer function def _pack_changed(self, change): new = change["new"] if not callable(new): raise TypeError("packer must be callable, not %s" % type(new)) unpack = Any(default_unpacker) # the actual packer function def _unpack_changed(self, change): # unpacker is not checked - it is assumed to be new = change["new"] if not callable(new): raise TypeError("unpacker must be callable, not %s" % type(new)) # thresholds: copy_threshold = Integer( 2**16, config=True, help="Threshold (in bytes) beyond which a buffer should be sent without copying.", ) buffer_threshold = Integer( MAX_BYTES, config=True, help="Threshold (in bytes) beyond which an object's buffer should be extracted to avoid " "pickling.", ) item_threshold = Integer( MAX_ITEMS, config=True, help="""The maximum number of items for a container to be introspected for custom serialization. Containers larger than this are pickled outright. """, ) def __init__(self, **kwargs): """create a Session object Parameters ---------- debug : bool whether to trigger extra debugging statements packer/unpacker : str : 'json', 'pickle' or import_string importstrings for methods to serialize message parts. If just 'json' or 'pickle', predefined JSON and pickle packers will be used. Otherwise, the entire importstring must be used. The functions must accept at least valid JSON input, and output *bytes*. For example, to use msgpack: packer = 'msgpack.packb', unpacker='msgpack.unpackb' pack/unpack : callables You can also set the pack/unpack callables for serialization directly. session : unicode (must be ascii) the ID of this Session object. The default is to generate a new UUID. bsession : bytes The session as bytes username : unicode username added to message headers. The default is to ask the OS. key : bytes The key used to initialize an HMAC signature. If unset, messages will not be signed or checked. signature_scheme : str The message digest scheme. Currently must be of the form 'hmac-HASH', where 'HASH' is a hashing function available in Python's hashlib. The default is 'hmac-sha256'. This is ignored if 'key' is empty. keyfile : filepath The file containing a key. If this is set, `key` will be initialized to the contents of the file. """ super().__init__(**kwargs) self._check_packers() self.none = self.pack({}) # ensure self._session_default() if necessary, so bsession is defined: self.session self.pid = os.getpid() self._new_auth() if not self.key: get_logger().warning( "Message signing is disabled. This is insecure and not recommended!" ) def clone(self) -> "Session": """Create a copy of this Session Useful when connecting multiple times to a given kernel. This prevents a shared digest_history warning about duplicate digests due to multiple connections to IOPub in the same process. .. versionadded:: 5.1 """ # make a copy new_session = type(self)() for name in self.traits(): setattr(new_session, name, getattr(self, name)) # fork digest_history new_session.digest_history = set() new_session.digest_history.update(self.digest_history) return new_session message_count = 0 def msg_id(self) -> str: message_number = self.message_count self.message_count += 1 return f"{self.session}_{os.getpid()}_{message_number}" def _check_packers(self) -> None: """check packers for datetime support.""" pack = self.pack unpack = self.unpack # check simple serialization msg_list = {"a": [1, "hi"]} try: packed = pack(msg_list) except Exception as e: msg = f"packer '{self.packer}' could not serialize a simple message: {e}" raise ValueError(msg) from e # ensure packed message is bytes if not isinstance(packed, bytes): raise ValueError("message packed to %r, but bytes are required" % type(packed)) # check that unpack is pack's inverse try: unpacked = unpack(packed) assert unpacked == msg_list except Exception as e: msg = ( f"unpacker '{self.unpacker}' could not handle output from packer" f" '{self.packer}': {e}" ) raise ValueError(msg) from e # check datetime support msg_datetime = {"t": utcnow()} try: unpacked = unpack(pack(msg_datetime)) if isinstance(unpacked["t"], datetime): msg = "Shouldn't deserialize to datetime" raise ValueError(msg) except Exception: self.pack = lambda o: pack(squash_dates(o)) self.unpack = lambda s: unpack(s) def msg_header(self, msg_type: str) -> t.Dict[str, t.Any]: """Create a header for a message type.""" return msg_header(self.msg_id, msg_type, self.username, self.session) def msg( self, msg_type: str, content: t.Optional[t.Dict] = None, parent: t.Optional[t.Dict[str, t.Any]] = None, header: t.Optional[t.Dict[str, t.Any]] = None, metadata: t.Optional[t.Dict[str, t.Any]] = None, ) -> t.Dict[str, t.Any]: """Return the nested message dict. This format is different from what is sent over the wire. The serialize/deserialize methods converts this nested message dict to the wire format, which is a list of message parts. """ msg = {} header = self.msg_header(msg_type) if header is None else header msg["header"] = header msg["msg_id"] = header["msg_id"] msg["msg_type"] = header["msg_type"] msg["parent_header"] = {} if parent is None else extract_header(parent) msg["content"] = {} if content is None else content msg["metadata"] = self.metadata.copy() if metadata is not None: msg["metadata"].update(metadata) return msg def sign(self, msg_list: t.List) -> bytes: """Sign a message with HMAC digest. If no auth, return b''. Parameters ---------- msg_list : list The [p_header,p_parent,p_content] part of the message list. """ if self.auth is None: return b"" h = self.auth.copy() for m in msg_list: h.update(m) return h.hexdigest().encode() def serialize( self, msg: t.Dict[str, t.Any], ident: t.Optional[t.Union[t.List[bytes], bytes]] = None, ) -> t.List[bytes]: """Serialize the message components to bytes. This is roughly the inverse of deserialize. The serialize/deserialize methods work with full message lists, whereas pack/unpack work with the individual message parts in the message list. Parameters ---------- msg : dict or Message The next message dict as returned by the self.msg method. Returns ------- msg_list : list The list of bytes objects to be sent with the format:: [ident1, ident2, ..., DELIM, HMAC, p_header, p_parent, p_metadata, p_content, buffer1, buffer2, ...] In this list, the ``p_*`` entities are the packed or serialized versions, so if JSON is used, these are utf8 encoded JSON strings. """ content = msg.get("content", {}) if content is None: content = self.none elif isinstance(content, dict): content = self.pack(content) elif isinstance(content, bytes): # content is already packed, as in a relayed message pass elif isinstance(content, str): # should be bytes, but JSON often spits out unicode content = content.encode("utf8") else: raise TypeError("Content incorrect type: %s" % type(content)) real_message = [ self.pack(msg["header"]), self.pack(msg["parent_header"]), self.pack(msg["metadata"]), content, ] to_send = [] if isinstance(ident, list): # accept list of idents to_send.extend(ident) elif ident is not None: to_send.append(ident) to_send.append(DELIM) signature = self.sign(real_message) to_send.append(signature) to_send.extend(real_message) return to_send def send( self, stream: Optional[Union[zmq.sugar.socket.Socket, ZMQStream]], msg_or_type: t.Union[t.Dict[str, t.Any], str], content: t.Optional[t.Dict[str, t.Any]] = None, parent: t.Optional[t.Dict[str, t.Any]] = None, ident: t.Optional[t.Union[bytes, t.List[bytes]]] = None, buffers: t.Optional[t.List[bytes]] = None, track: bool = False, header: t.Optional[t.Dict[str, t.Any]] = None, metadata: t.Optional[t.Dict[str, t.Any]] = None, ) -> t.Optional[t.Dict[str, t.Any]]: """Build and send a message via stream or socket. The message format used by this function internally is as follows: [ident1,ident2,...,DELIM,HMAC,p_header,p_parent,p_content, buffer1,buffer2,...] The serialize/deserialize methods convert the nested message dict into this format. Parameters ---------- stream : zmq.Socket or ZMQStream The socket-like object used to send the data. msg_or_type : str or Message/dict Normally, msg_or_type will be a msg_type unless a message is being sent more than once. If a header is supplied, this can be set to None and the msg_type will be pulled from the header. content : dict or None The content of the message (ignored if msg_or_type is a message). header : dict or None The header dict for the message (ignored if msg_to_type is a message). parent : Message or dict or None The parent or parent header describing the parent of this message (ignored if msg_or_type is a message). ident : bytes or list of bytes The zmq.IDENTITY routing path. metadata : dict or None The metadata describing the message buffers : list or None The already-serialized buffers to be appended to the message. track : bool Whether to track. Only for use with Sockets, because ZMQStream objects cannot track messages. Returns ------- msg : dict The constructed message. """ if not isinstance(stream, zmq.Socket): # ZMQStreams and dummy sockets do not support tracking. track = False if isinstance(stream, zmq.asyncio.Socket): assert stream is not None stream = zmq.Socket.shadow(stream.underlying) if isinstance(msg_or_type, (Message, dict)): # We got a Message or message dict, not a msg_type so don't # build a new Message. msg = msg_or_type buffers = buffers or msg.get("buffers", []) else: msg = self.msg( msg_or_type, content=content, parent=parent, header=header, metadata=metadata, ) if self.check_pid and os.getpid() != self.pid: get_logger().warning("WARNING: attempted to send message from fork\n%s", msg) return None buffers = [] if buffers is None else buffers for idx, buf in enumerate(buffers): if isinstance(buf, memoryview): view = buf else: try: # check to see if buf supports the buffer protocol. view = memoryview(buf) except TypeError as e: emsg = "Buffer objects must support the buffer protocol." raise TypeError(emsg) from e # memoryview.contiguous is new in 3.3, # just skip the check on Python 2 if hasattr(view, "contiguous") and not view.contiguous: # zmq requires memoryviews to be contiguous raise ValueError("Buffer %i (%r) is not contiguous" % (idx, buf)) if self.adapt_version: msg = adapt(msg, self.adapt_version) to_send = self.serialize(msg, ident) to_send.extend(buffers) longest = max([len(s) for s in to_send]) copy = longest < self.copy_threshold if stream and buffers and track and not copy: # only really track when we are doing zero-copy buffers tracker = stream.send_multipart(to_send, copy=False, track=True) elif stream: # use dummy tracker, which will be done immediately tracker = DONE stream.send_multipart(to_send, copy=copy) if self.debug: pprint.pprint(msg) pprint.pprint(to_send) pprint.pprint(buffers) msg["tracker"] = tracker return msg def send_raw( self, stream: zmq.sugar.socket.Socket, msg_list: t.List, flags: int = 0, copy: bool = True, ident: t.Optional[t.Union[bytes, t.List[bytes]]] = None, ) -> None: """Send a raw message via ident path. This method is used to send a already serialized message. Parameters ---------- stream : ZMQStream or Socket The ZMQ stream or socket to use for sending the message. msg_list : list The serialized list of messages to send. This only includes the [p_header,p_parent,p_metadata,p_content,buffer1,buffer2,...] portion of the message. ident : ident or list A single ident or a list of idents to use in sending. """ to_send = [] if isinstance(ident, bytes): ident = [ident] if ident is not None: to_send.extend(ident) to_send.append(DELIM) # Don't include buffers in signature (per spec). to_send.append(self.sign(msg_list[0:4])) to_send.extend(msg_list) if isinstance(stream, zmq.asyncio.Socket): stream = zmq.Socket.shadow(stream.underlying) stream.send_multipart(to_send, flags, copy=copy) def recv( self, socket: zmq.sugar.socket.Socket, mode: int = zmq.NOBLOCK, content: bool = True, copy: bool = True, ) -> t.Tuple[t.Optional[t.List[bytes]], t.Optional[t.Dict[str, t.Any]]]: """Receive and unpack a message. Parameters ---------- socket : ZMQStream or Socket The socket or stream to use in receiving. Returns ------- [idents], msg [idents] is a list of idents and msg is a nested message dict of same format as self.msg returns. """ if isinstance(socket, ZMQStream): socket = socket.socket if isinstance(socket, zmq.asyncio.Socket): socket = zmq.Socket.shadow(socket.underlying) try: msg_list = socket.recv_multipart(mode, copy=copy) except zmq.ZMQError as e: if e.errno == zmq.EAGAIN: # We can convert EAGAIN to None as we know in this case # recv_multipart won't return None. return None, None else: raise # split multipart message into identity list and message dict # invalid large messages can cause very expensive string comparisons idents, msg_list = self.feed_identities(msg_list, copy) try: return idents, self.deserialize(msg_list, content=content, copy=copy) except Exception as e: # TODO: handle it raise e def feed_identities( self, msg_list: t.Union[t.List[bytes], t.List[zmq.Message]], copy: bool = True ) -> t.Tuple[t.List[bytes], t.Union[t.List[bytes], t.List[zmq.Message]]]: """Split the identities from the rest of the message. Feed until DELIM is reached, then return the prefix as idents and remainder as msg_list. This is easily broken by setting an IDENT to DELIM, but that would be silly. Parameters ---------- msg_list : a list of Message or bytes objects The message to be split. copy : bool flag determining whether the arguments are bytes or Messages Returns ------- (idents, msg_list) : two lists idents will always be a list of bytes, each of which is a ZMQ identity. msg_list will be a list of bytes or zmq.Messages of the form [HMAC,p_header,p_parent,p_content,buffer1,buffer2,...] and should be unpackable/unserializable via self.deserialize at this point. """ if copy: msg_list = t.cast(t.List[bytes], msg_list) idx = msg_list.index(DELIM) return msg_list[:idx], msg_list[idx + 1 :] else: msg_list = t.cast(t.List[zmq.Message], msg_list) failed = True for idx, m in enumerate(msg_list): # noqa if m.bytes == DELIM: failed = False break if failed: msg = "DELIM not in msg_list" raise ValueError(msg) idents, msg_list = msg_list[:idx], msg_list[idx + 1 :] return [bytes(m.bytes) for m in idents], msg_list def _add_digest(self, signature: bytes) -> None: """add a digest to history to protect against replay attacks""" if self.digest_history_size == 0: # no history, never add digests return self.digest_history.add(signature) if len(self.digest_history) > self.digest_history_size: # threshold reached, cull 10% self._cull_digest_history() def _cull_digest_history(self) -> None: """cull the digest history Removes a randomly selected 10% of the digest history """ current = len(self.digest_history) n_to_cull = max(int(current // 10), current - self.digest_history_size) if n_to_cull >= current: self.digest_history = set() return to_cull = random.sample(tuple(sorted(self.digest_history)), n_to_cull) self.digest_history.difference_update(to_cull) def deserialize( self, msg_list: t.Union[t.List[bytes], t.List[zmq.Message]], content: bool = True, copy: bool = True, ) -> t.Dict[str, t.Any]: """Unserialize a msg_list to a nested message dict. This is roughly the inverse of serialize. The serialize/deserialize methods work with full message lists, whereas pack/unpack work with the individual message parts in the message list. Parameters ---------- msg_list : list of bytes or Message objects The list of message parts of the form [HMAC,p_header,p_parent, p_metadata,p_content,buffer1,buffer2,...]. content : bool (True) Whether to unpack the content dict (True), or leave it packed (False). copy : bool (True) Whether msg_list contains bytes (True) or the non-copying Message objects in each place (False). Returns ------- msg : dict The nested message dict with top-level keys [header, parent_header, content, buffers]. The buffers are returned as memoryviews. """ minlen = 5 message = {} if not copy: # pyzmq didn't copy the first parts of the message, so we'll do it msg_list = t.cast(t.List[zmq.Message], msg_list) msg_list_beginning = [bytes(msg.bytes) for msg in msg_list[:minlen]] msg_list = t.cast(t.List[bytes], msg_list) msg_list = msg_list_beginning + msg_list[minlen:] msg_list = t.cast(t.List[bytes], msg_list) if self.auth is not None: signature = msg_list[0] if not signature: msg = "Unsigned Message" raise ValueError(msg) if signature in self.digest_history: raise ValueError("Duplicate Signature: %r" % signature) if content: # Only store signature if we are unpacking content, don't store if just peeking. self._add_digest(signature) check = self.sign(msg_list[1:5]) if not compare_digest(signature, check): msg = "Invalid Signature: %r" % signature raise ValueError(msg) if not len(msg_list) >= minlen: msg = "malformed message, must have at least %i elements" % minlen raise TypeError(msg) header = self.unpack(msg_list[1]) message["header"] = extract_dates(header) message["msg_id"] = header["msg_id"] message["msg_type"] = header["msg_type"] message["parent_header"] = extract_dates(self.unpack(msg_list[2])) message["metadata"] = self.unpack(msg_list[3]) if content: message["content"] = self.unpack(msg_list[4]) else: message["content"] = msg_list[4] buffers = [memoryview(b) for b in msg_list[5:]] if buffers and buffers[0].shape is None: # force copy to workaround pyzmq #646 msg_list = t.cast(t.List[zmq.Message], msg_list) buffers = [memoryview(bytes(b.bytes)) for b in msg_list[5:]] message["buffers"] = buffers if self.debug: pprint.pprint(message) # adapt to the current version return adapt(message) def unserialize(self, *args: t.Any, **kwargs: t.Any) -> t.Dict[str, t.Any]: """**DEPRECATED** Use deserialize instead.""" # pragma: no cover warnings.warn( "Session.unserialize is deprecated. Use Session.deserialize.", DeprecationWarning, ) return self.deserialize(*args, **kwargs) The provided code snippet includes necessary dependencies for implementing the `default_secure` function. Write a Python function `def default_secure(cfg: t.Any) -> None` to solve the following problem: Set the default behavior for a config environment to be secure. If Session.key/keyfile have not been set, set Session.key to a new random UUID. Here is the function: def default_secure(cfg: t.Any) -> None: # pragma: no cover """Set the default behavior for a config environment to be secure. If Session.key/keyfile have not been set, set Session.key to a new random UUID. """ warnings.warn("default_secure is deprecated", DeprecationWarning) if "Session" in cfg and ("key" in cfg.Session or "keyfile" in cfg.Session): return # key/keyfile not specified, generate new UUID: cfg.Session.key = new_id_bytes()
Set the default behavior for a config environment to be secure. If Session.key/keyfile have not been set, set Session.key to a new random UUID.
174,944
import hashlib import hmac import json import logging import os import pickle import pprint import random import typing as t import warnings from binascii import b2a_hex from datetime import datetime, timezone from hmac import compare_digest from typing import Optional, Union import zmq.asyncio from tornado.ioloop import IOLoop from traitlets import ( Any, Bool, CBytes, CUnicode, Dict, DottedObjectName, Instance, Integer, Set, TraitError, Unicode, observe, ) from traitlets.config.configurable import Configurable, LoggingConfigurable from traitlets.log import get_logger from traitlets.utils.importstring import import_item from zmq.eventloop.zmqstream import ZMQStream from ._version import protocol_version from .adapter import adapt from .jsonutil import extract_dates, json_clean, json_default, squash_dates def utcnow() -> datetime: """Return timezone-aware UTC timestamp""" return datetime.utcnow().replace(tzinfo=utc) # noqa protocol_version = "%i.%i" % protocol_version_info The provided code snippet includes necessary dependencies for implementing the `msg_header` function. Write a Python function `def msg_header(msg_id: str, msg_type: str, username: str, session: "Session") -> t.Dict[str, t.Any]` to solve the following problem: Create a new message header Here is the function: def msg_header(msg_id: str, msg_type: str, username: str, session: "Session") -> t.Dict[str, t.Any]: """Create a new message header""" date = utcnow() version = protocol_version return locals()
Create a new message header
174,945
import hashlib import hmac import json import logging import os import pickle import pprint import random import typing as t import warnings from binascii import b2a_hex from datetime import datetime, timezone from hmac import compare_digest from typing import Optional, Union import zmq.asyncio from tornado.ioloop import IOLoop from traitlets import ( Any, Bool, CBytes, CUnicode, Dict, DottedObjectName, Instance, Integer, Set, TraitError, Unicode, observe, ) from traitlets.config.configurable import Configurable, LoggingConfigurable from traitlets.log import get_logger from traitlets.utils.importstring import import_item from zmq.eventloop.zmqstream import ZMQStream from ._version import protocol_version from .adapter import adapt from .jsonutil import extract_dates, json_clean, json_default, squash_dates The provided code snippet includes necessary dependencies for implementing the `extract_header` function. Write a Python function `def extract_header(msg_or_header: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]` to solve the following problem: Given a message or header, return the header. Here is the function: def extract_header(msg_or_header: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]: """Given a message or header, return the header.""" if not msg_or_header: return {} try: # See if msg_or_header is the entire message. h = msg_or_header["header"] except KeyError: try: # See if msg_or_header is just the header h = msg_or_header["msg_id"] except KeyError: raise else: h = msg_or_header if not isinstance(h, dict): h = dict(h) return h
Given a message or header, return the header.
174,946
import math import numbers import re import types import warnings from binascii import b2a_base64 from collections.abc import Iterable from datetime import datetime from typing import Optional, Union from dateutil.parser import parse as _dateutil_parse from dateutil.tz import tzlocal def json_default(obj): """default function for packing objects in JSON.""" if isinstance(obj, datetime): obj = _ensure_tzinfo(obj) return obj.isoformat().replace('+00:00', 'Z') if isinstance(obj, bytes): return b2a_base64(obj, newline=False).decode('ascii') if isinstance(obj, Iterable): return list(obj) if isinstance(obj, numbers.Integral): return int(obj) if isinstance(obj, numbers.Real): return float(obj) raise TypeError("%r is not JSON serializable" % obj) The provided code snippet includes necessary dependencies for implementing the `date_default` function. Write a Python function `def date_default(obj)` to solve the following problem: DEPRECATED: Use jupyter_client.jsonutil.json_default Here is the function: def date_default(obj): """DEPRECATED: Use jupyter_client.jsonutil.json_default""" warnings.warn( "date_default is deprecated since jupyter_client 7.0.0." " Use jupyter_client.jsonutil.json_default.", stacklevel=2, ) return json_default(obj)
DEPRECATED: Use jupyter_client.jsonutil.json_default
174,947
from traitlets import Type from ..channels import HBChannel, ZMQSocketChannel from ..client import KernelClient, reqrep from ..utils import run_sync The provided code snippet includes necessary dependencies for implementing the `wrapped` function. Write a Python function `def wrapped(meth, channel)` to solve the following problem: Wrap a method on a channel and handle replies. Here is the function: def wrapped(meth, channel): """Wrap a method on a channel and handle replies.""" def _(self, *args, **kwargs): reply = kwargs.pop("reply", False) timeout = kwargs.pop("timeout", None) msg_id = meth(self, *args, **kwargs) if not reply: return msg_id return self._recv_reply(msg_id, timeout=timeout, channel=channel) return _
Wrap a method on a channel and handle replies.
174,948
import os import re import socket import subprocess from subprocess import PIPE, Popen from typing import Iterable, List from warnings import warn The provided code snippet includes necessary dependencies for implementing the `_only_once` function. Write a Python function `def _only_once(f)` to solve the following problem: decorator to only run a function once Here is the function: def _only_once(f): """decorator to only run a function once""" f.called = False def wrapped(**kwargs): if f.called: return ret = f(**kwargs) f.called = True return ret return wrapped
decorator to only run a function once
174,949
import os import re import socket import subprocess from subprocess import PIPE, Popen from typing import Iterable, List from warnings import warn def _load_ips(suppress_exceptions=True): """load the IPs that point to this machine This function will only ever be called once. It will use netifaces to do it quickly if available. Then it will fallback on parsing the output of ifconfig / ip addr / ipconfig, as appropriate. Finally, it will fallback on socket.gethostbyname_ex, which can be slow. """ try: # first priority, use netifaces try: return _load_ips_netifaces() except ImportError: pass # second priority, parse subprocess output (how reliable is this?) if os.name == "nt": try: return _load_ips_ipconfig() except (OSError, NoIPAddresses): pass else: try: return _load_ips_ip() except (OSError, NoIPAddresses): pass try: return _load_ips_ifconfig() except (OSError, NoIPAddresses): pass # lowest priority, use gethostbyname return _load_ips_gethostbyname() except Exception as e: if not suppress_exceptions: raise # unexpected error shouldn't crash, load dumb default values instead. warn("Unexpected error discovering local network interfaces: %s" % e) _load_ips_dumb() The provided code snippet includes necessary dependencies for implementing the `_requires_ips` function. Write a Python function `def _requires_ips(f)` to solve the following problem: decorator to ensure load_ips has been run before f Here is the function: def _requires_ips(f): """decorator to ensure load_ips has been run before f""" def ips_loaded(*args, **kwargs): _load_ips() return f(*args, **kwargs) return ips_loaded
decorator to ensure load_ips has been run before f
174,950
import os import re import socket import subprocess from subprocess import PIPE, Popen from typing import Iterable, List from warnings import warn LOCAL_IPS: List = [] The provided code snippet includes necessary dependencies for implementing the `is_local_ip` function. Write a Python function `def is_local_ip(ip)` to solve the following problem: does `ip` point to this machine? Here is the function: def is_local_ip(ip): """does `ip` point to this machine?""" return ip in LOCAL_IPS
does `ip` point to this machine?
174,951
import os import re import socket import subprocess from subprocess import PIPE, Popen from typing import Iterable, List from warnings import warn PUBLIC_IPS: List = [] The provided code snippet includes necessary dependencies for implementing the `is_public_ip` function. Write a Python function `def is_public_ip(ip)` to solve the following problem: is `ip` a publicly visible address? Here is the function: def is_public_ip(ip): """is `ip` a publicly visible address?""" return ip in PUBLIC_IPS
is `ip` a publicly visible address?
174,952
import asyncio import inspect import sys import time import typing as t from functools import partial from getpass import getpass from queue import Empty import zmq.asyncio from jupyter_core.utils import ensure_async from traitlets import Any, Bool, Instance, Type from .channels import major_protocol_version from .channelsabc import ChannelABC, HBChannelABC from .clientabc import KernelClientABC from .connect import ConnectionFileMixin from .session import Session The provided code snippet includes necessary dependencies for implementing the `validate_string_dict` function. Write a Python function `def validate_string_dict(dct: t.Dict[str, str]) -> None` to solve the following problem: Validate that the input is a dict with string keys and values. Raises ValueError if not. Here is the function: def validate_string_dict(dct: t.Dict[str, str]) -> None: """Validate that the input is a dict with string keys and values. Raises ValueError if not.""" for k, v in dct.items(): if not isinstance(k, str): raise ValueError("key %r in dict must be a string" % k) if not isinstance(v, str): raise ValueError("value %r in dict must be a string" % v)
Validate that the input is a dict with string keys and values. Raises ValueError if not.
174,953
import asyncio import inspect import sys import time import typing as t from functools import partial from getpass import getpass from queue import Empty import zmq.asyncio from jupyter_core.utils import ensure_async from traitlets import Any, Bool, Instance, Type from .channels import major_protocol_version from .channelsabc import ChannelABC, HBChannelABC from .clientabc import KernelClientABC from .connect import ConnectionFileMixin from .session import Session def reqrep(wrapped: t.Callable, meth: t.Callable, channel: str = "shell") -> t.Callable: wrapped = wrapped(meth, channel) if not meth.__doc__: # python -OO removes docstrings, # so don't bother building the wrapped docstring return wrapped basedoc, _ = meth.__doc__.split("Returns\n", 1) parts = [basedoc.strip()] if "Parameters" not in basedoc: parts.append( """ Parameters ---------- """ ) parts.append( """ reply: bool (default: False) Whether to wait for and return reply timeout: float or None (default: None) Timeout to use when waiting for a reply Returns ------- msg_id: str The msg_id of the request sent, if reply=False (default) reply: dict The reply message for this request, if reply=True """ ) wrapped.__doc__ = "\n".join(parts) return wrapped
null
174,954
import asyncio import functools import os import re import signal import sys import typing as t import uuid from asyncio.futures import Future from concurrent.futures import Future as CFuture from contextlib import contextmanager from enum import Enum import zmq from jupyter_core.utils import run_sync from traitlets import ( Any, Bool, DottedObjectName, Float, Instance, Type, Unicode, default, observe, observe_compat, ) from traitlets.utils.importstring import import_item from . import kernelspec from .asynchronous import AsyncKernelClient from .blocking import BlockingKernelClient from .client import KernelClient from .connect import ConnectionFileMixin from .managerabc import KernelManagerABC from .provisioning import KernelProvisionerBase from .provisioning import KernelProvisionerFactory as KPF F = t.TypeVar('F', bound=t.Callable[..., t.Any]) def _get_future() -> t.Union[Future, CFuture]: """Get an appropriate Future object""" try: asyncio.get_running_loop() return Future() except RuntimeError: # No event loop running, use concurrent future return CFuture() The provided code snippet includes necessary dependencies for implementing the `in_pending_state` function. Write a Python function `def in_pending_state(method: F) -> F` to solve the following problem: Sets the kernel to a pending state by creating a fresh Future for the KernelManager's `ready` attribute. Once the method is finished, set the Future's results. Here is the function: def in_pending_state(method: F) -> F: """Sets the kernel to a pending state by creating a fresh Future for the KernelManager's `ready` attribute. Once the method is finished, set the Future's results. """ @t.no_type_check @functools.wraps(method) async def wrapper(self, *args, **kwargs): """Create a future for the decorated method.""" if self._attempted_start or not self._ready: self._ready = _get_future() try: # call wrapped method, await, and set the result or exception. out = await method(self, *args, **kwargs) # Add a small sleep to ensure tests can capture the state before done await asyncio.sleep(0.01) self._ready.set_result(None) return out except Exception as e: self._ready.set_exception(e) self.log.exception(self._ready.exception()) raise e return t.cast(F, wrapper)
Sets the kernel to a pending state by creating a fresh Future for the KernelManager's `ready` attribute. Once the method is finished, set the Future's results.
174,955
import asyncio import functools import os import re import signal import sys import typing as t import uuid from asyncio.futures import Future from concurrent.futures import Future as CFuture from contextlib import contextmanager from enum import Enum import zmq from jupyter_core.utils import run_sync from traitlets import ( Any, Bool, DottedObjectName, Float, Instance, Type, Unicode, default, observe, observe_compat, ) from traitlets.utils.importstring import import_item from . import kernelspec from .asynchronous import AsyncKernelClient from .blocking import BlockingKernelClient from .client import KernelClient from .connect import ConnectionFileMixin from .managerabc import KernelManagerABC from .provisioning import KernelProvisionerBase from .provisioning import KernelProvisionerFactory as KPF class AsyncKernelManager(KernelManager): """An async kernel manager.""" # the class to create with our `client` method client_class: DottedObjectName = DottedObjectName( "jupyter_client.asynchronous.AsyncKernelClient" ) client_factory: Type = Type(klass="jupyter_client.asynchronous.AsyncKernelClient") # The PyZMQ Context to use for communication with the kernel. context: Instance = Instance(zmq.asyncio.Context) def _context_default(self) -> zmq.asyncio.Context: self._created_context = True return zmq.asyncio.Context() def client(self, **kwargs: t.Any) -> AsyncKernelClient: # type:ignore """Get a client for the manager.""" return super().client(**kwargs) # type:ignore _launch_kernel = KernelManager._async_launch_kernel # type:ignore[assignment] start_kernel: t.Callable[ ..., t.Awaitable ] = KernelManager._async_start_kernel # type:ignore[assignment] pre_start_kernel: t.Callable[ ..., t.Awaitable ] = KernelManager._async_pre_start_kernel # type:ignore[assignment] post_start_kernel: t.Callable[ ..., t.Awaitable ] = KernelManager._async_post_start_kernel # type:ignore[assignment] request_shutdown: t.Callable[ ..., t.Awaitable ] = KernelManager._async_request_shutdown # type:ignore[assignment] finish_shutdown: t.Callable[ ..., t.Awaitable ] = KernelManager._async_finish_shutdown # type:ignore[assignment] cleanup_resources: t.Callable[ ..., t.Awaitable ] = KernelManager._async_cleanup_resources # type:ignore[assignment] shutdown_kernel: t.Callable[ ..., t.Awaitable ] = KernelManager._async_shutdown_kernel # type:ignore[assignment] restart_kernel: t.Callable[ ..., t.Awaitable ] = KernelManager._async_restart_kernel # type:ignore[assignment] _send_kernel_sigterm = KernelManager._async_send_kernel_sigterm # type:ignore[assignment] _kill_kernel = KernelManager._async_kill_kernel # type:ignore[assignment] interrupt_kernel: t.Callable[ ..., t.Awaitable ] = KernelManager._async_interrupt_kernel # type:ignore[assignment] signal_kernel: t.Callable[ ..., t.Awaitable ] = KernelManager._async_signal_kernel # type:ignore[assignment] is_alive: t.Callable[ ..., t.Awaitable ] = KernelManager._async_is_alive # type:ignore[assignment] The provided code snippet includes necessary dependencies for implementing the `start_new_async_kernel` function. Write a Python function `async def start_new_async_kernel( startup_timeout: float = 60, kernel_name: str = "python", **kwargs: t.Any ) -> t.Tuple[AsyncKernelManager, AsyncKernelClient]` to solve the following problem: Start a new kernel, and return its Manager and Client Here is the function: async def start_new_async_kernel( startup_timeout: float = 60, kernel_name: str = "python", **kwargs: t.Any ) -> t.Tuple[AsyncKernelManager, AsyncKernelClient]: """Start a new kernel, and return its Manager and Client""" km = AsyncKernelManager(kernel_name=kernel_name) await km.start_kernel(**kwargs) kc = km.client() kc.start_channels() try: await kc.wait_for_ready(timeout=startup_timeout) except RuntimeError: kc.stop_channels() await km.shutdown_kernel() raise return (km, kc)
Start a new kernel, and return its Manager and Client
174,956
import asyncio import functools import os import re import signal import sys import typing as t import uuid from asyncio.futures import Future from concurrent.futures import Future as CFuture from contextlib import contextmanager from enum import Enum import zmq from jupyter_core.utils import run_sync from traitlets import ( Any, Bool, DottedObjectName, Float, Instance, Type, Unicode, default, observe, observe_compat, ) from traitlets.utils.importstring import import_item from . import kernelspec from .asynchronous import AsyncKernelClient from .blocking import BlockingKernelClient from .client import KernelClient from .connect import ConnectionFileMixin from .managerabc import KernelManagerABC from .provisioning import KernelProvisionerBase from .provisioning import KernelProvisionerFactory as KPF def start_new_kernel( startup_timeout: float = 60, kernel_name: str = "python", **kwargs: t.Any ) -> t.Tuple[KernelManager, BlockingKernelClient]: """Start a new kernel, and return its Manager and Client""" km = KernelManager(kernel_name=kernel_name) km.start_kernel(**kwargs) kc = km.client() kc.start_channels() try: kc.wait_for_ready(timeout=startup_timeout) except RuntimeError: kc.stop_channels() km.shutdown_kernel() raise return km, kc class KernelClient(ConnectionFileMixin): """Communicates with a single kernel on any host via zmq channels. There are five channels associated with each kernel: * shell: for request/reply calls to the kernel. * iopub: for the kernel to publish results to frontends. * hb: for monitoring the kernel's heartbeat. * stdin: for frontends to reply to raw_input calls in the kernel. * control: for kernel management calls to the kernel. The messages that can be sent on these channels are exposed as methods of the client (KernelClient.execute, complete, history, etc.). These methods only send the message, they don't wait for a reply. To get results, use e.g. :meth:`get_shell_msg` to fetch messages from the shell channel. """ # The PyZMQ Context to use for communication with the kernel. context = Instance(zmq.Context) _created_context = Bool(False) def _context_default(self) -> zmq.Context: self._created_context = True return zmq.Context() # The classes to use for the various channels shell_channel_class = Type(ChannelABC) iopub_channel_class = Type(ChannelABC) stdin_channel_class = Type(ChannelABC) hb_channel_class = Type(HBChannelABC) control_channel_class = Type(ChannelABC) # Protected traits _shell_channel = Any() _iopub_channel = Any() _stdin_channel = Any() _hb_channel = Any() _control_channel = Any() # flag for whether execute requests should be allowed to call raw_input: allow_stdin: bool = True def __del__(self): """Handle garbage collection. Destroy context if applicable.""" if self._created_context and self.context and not self.context.closed: if self.channels_running: if self.log: self.log.warning("Could not destroy zmq context for %s", self) else: if self.log: self.log.debug("Destroying zmq context for %s", self) self.context.destroy() try: super_del = super().__del__ # type:ignore[misc] except AttributeError: pass else: super_del() # -------------------------------------------------------------------------- # Channel proxy methods # -------------------------------------------------------------------------- async def _async_get_shell_msg(self, *args: t.Any, **kwargs: t.Any) -> t.Dict[str, t.Any]: """Get a message from the shell channel""" return await ensure_async(self.shell_channel.get_msg(*args, **kwargs)) async def _async_get_iopub_msg(self, *args: t.Any, **kwargs: t.Any) -> t.Dict[str, t.Any]: """Get a message from the iopub channel""" return await ensure_async(self.iopub_channel.get_msg(*args, **kwargs)) async def _async_get_stdin_msg(self, *args: t.Any, **kwargs: t.Any) -> t.Dict[str, t.Any]: """Get a message from the stdin channel""" return await ensure_async(self.stdin_channel.get_msg(*args, **kwargs)) async def _async_get_control_msg(self, *args: t.Any, **kwargs: t.Any) -> t.Dict[str, t.Any]: """Get a message from the control channel""" return await ensure_async(self.control_channel.get_msg(*args, **kwargs)) async def _async_wait_for_ready(self, timeout: t.Optional[float] = None) -> None: """Waits for a response when a client is blocked - Sets future time for timeout - Blocks on shell channel until a message is received - Exit if the kernel has died - If client times out before receiving a message from the kernel, send RuntimeError - Flush the IOPub channel """ if timeout is None: timeout = float("inf") abs_timeout = time.time() + timeout from .manager import KernelManager if not isinstance(self.parent, KernelManager): # This Client was not created by a KernelManager, # so wait for kernel to become responsive to heartbeats # before checking for kernel_info reply while not await self._async_is_alive(): if time.time() > abs_timeout: raise RuntimeError( "Kernel didn't respond to heartbeats in %d seconds and timed out" % timeout ) await asyncio.sleep(0.2) # Wait for kernel info reply on shell channel while True: self.kernel_info() try: msg = await ensure_async(self.shell_channel.get_msg(timeout=1)) except Empty: pass else: if msg["msg_type"] == "kernel_info_reply": # Checking that IOPub is connected. If it is not connected, start over. try: await ensure_async(self.iopub_channel.get_msg(timeout=0.2)) except Empty: pass else: self._handle_kernel_info_reply(msg) break if not await self._async_is_alive(): msg = "Kernel died before replying to kernel_info" raise RuntimeError(msg) # Check if current time is ready check time plus timeout if time.time() > abs_timeout: raise RuntimeError("Kernel didn't respond in %d seconds" % timeout) # Flush IOPub channel while True: try: msg = await ensure_async(self.iopub_channel.get_msg(timeout=0.2)) except Empty: break async def _async_recv_reply( self, msg_id: str, timeout: t.Optional[float] = None, channel: str = "shell" ) -> t.Dict[str, t.Any]: """Receive and return the reply for a given request""" if timeout is not None: deadline = time.monotonic() + timeout while True: if timeout is not None: timeout = max(0, deadline - time.monotonic()) try: if channel == "control": reply = await self._async_get_control_msg(timeout=timeout) else: reply = await self._async_get_shell_msg(timeout=timeout) except Empty as e: msg = "Timeout waiting for reply" raise TimeoutError(msg) from e if reply["parent_header"].get("msg_id") != msg_id: # not my reply, someone may have forgotten to retrieve theirs continue return reply async def _stdin_hook_default(self, msg: t.Dict[str, t.Any]) -> None: """Handle an input request""" content = msg["content"] prompt = getpass if content.get("password", False) else input try: raw_data = prompt(content["prompt"]) # type:ignore[operator] except EOFError: # turn EOFError into EOF character raw_data = "\x04" except KeyboardInterrupt: sys.stdout.write("\n") return # only send stdin reply if there *was not* another request # or execution finished while we were reading. if not (await self.stdin_channel.msg_ready() or await self.shell_channel.msg_ready()): self.input(raw_data) def _output_hook_default(self, msg: t.Dict[str, t.Any]) -> None: """Default hook for redisplaying plain-text output""" msg_type = msg["header"]["msg_type"] content = msg["content"] if msg_type == "stream": stream = getattr(sys, content["name"]) stream.write(content["text"]) elif msg_type in ("display_data", "execute_result"): sys.stdout.write(content["data"].get("text/plain", "")) elif msg_type == "error": sys.stderr.write("\n".join(content["traceback"])) def _output_hook_kernel( self, session: Session, socket: zmq.sugar.socket.Socket, parent_header: t.Any, msg: t.Dict[str, t.Any], ) -> None: """Output hook when running inside an IPython kernel adds rich output support. """ msg_type = msg["header"]["msg_type"] if msg_type in ("display_data", "execute_result", "error"): session.send(socket, msg_type, msg["content"], parent=parent_header) else: self._output_hook_default(msg) # -------------------------------------------------------------------------- # Channel management methods # -------------------------------------------------------------------------- def start_channels( self, shell: bool = True, iopub: bool = True, stdin: bool = True, hb: bool = True, control: bool = True, ) -> None: """Starts the channels for this kernel. This will create the channels if they do not exist and then start them (their activity runs in a thread). If port numbers of 0 are being used (random ports) then you must first call :meth:`start_kernel`. If the channels have been stopped and you call this, :class:`RuntimeError` will be raised. """ if iopub: self.iopub_channel.start() if shell: self.shell_channel.start() if stdin: self.stdin_channel.start() self.allow_stdin = True else: self.allow_stdin = False if hb: self.hb_channel.start() if control: self.control_channel.start() def stop_channels(self) -> None: """Stops all the running channels for this kernel. This stops their event loops and joins their threads. """ if self.shell_channel.is_alive(): self.shell_channel.stop() if self.iopub_channel.is_alive(): self.iopub_channel.stop() if self.stdin_channel.is_alive(): self.stdin_channel.stop() if self.hb_channel.is_alive(): self.hb_channel.stop() if self.control_channel.is_alive(): self.control_channel.stop() def channels_running(self) -> bool: """Are any of the channels created and running?""" return ( (self._shell_channel and self.shell_channel.is_alive()) or (self._iopub_channel and self.iopub_channel.is_alive()) or (self._stdin_channel and self.stdin_channel.is_alive()) or (self._hb_channel and self.hb_channel.is_alive()) or (self._control_channel and self.control_channel.is_alive()) ) ioloop = None # Overridden in subclasses that use pyzmq event loop def shell_channel(self) -> t.Any: """Get the shell channel object for this kernel.""" if self._shell_channel is None: url = self._make_url("shell") self.log.debug("connecting shell channel to %s", url) socket = self.connect_shell(identity=self.session.bsession) self._shell_channel = self.shell_channel_class(socket, self.session, self.ioloop) return self._shell_channel def iopub_channel(self) -> t.Any: """Get the iopub channel object for this kernel.""" if self._iopub_channel is None: url = self._make_url("iopub") self.log.debug("connecting iopub channel to %s", url) socket = self.connect_iopub() self._iopub_channel = self.iopub_channel_class(socket, self.session, self.ioloop) return self._iopub_channel def stdin_channel(self) -> t.Any: """Get the stdin channel object for this kernel.""" if self._stdin_channel is None: url = self._make_url("stdin") self.log.debug("connecting stdin channel to %s", url) socket = self.connect_stdin(identity=self.session.bsession) self._stdin_channel = self.stdin_channel_class(socket, self.session, self.ioloop) return self._stdin_channel def hb_channel(self) -> t.Any: """Get the hb channel object for this kernel.""" if self._hb_channel is None: url = self._make_url("hb") self.log.debug("connecting heartbeat channel to %s", url) self._hb_channel = self.hb_channel_class(self.context, self.session, url) return self._hb_channel def control_channel(self) -> t.Any: """Get the control channel object for this kernel.""" if self._control_channel is None: url = self._make_url("control") self.log.debug("connecting control channel to %s", url) socket = self.connect_control(identity=self.session.bsession) self._control_channel = self.control_channel_class(socket, self.session, self.ioloop) return self._control_channel async def _async_is_alive(self) -> bool: """Is the kernel process still running?""" from .manager import KernelManager if isinstance(self.parent, KernelManager): # This KernelClient was created by a KernelManager, # we can ask the parent KernelManager: return await self.parent._async_is_alive() if self._hb_channel is not None: # We don't have access to the KernelManager, # so we use the heartbeat. return self._hb_channel.is_beating() # no heartbeat and not local, we can't tell if it's running, # so naively return True return True async def _async_execute_interactive( self, code: str, silent: bool = False, store_history: bool = True, user_expressions: t.Optional[t.Dict[str, t.Any]] = None, allow_stdin: t.Optional[bool] = None, stop_on_error: bool = True, timeout: t.Optional[float] = None, output_hook: t.Optional[t.Callable] = None, stdin_hook: t.Optional[t.Callable] = None, ) -> t.Dict[str, t.Any]: """Execute code in the kernel interactively Output will be redisplayed, and stdin prompts will be relayed as well. If an IPython kernel is detected, rich output will be displayed. You can pass a custom output_hook callable that will be called with every IOPub message that is produced instead of the default redisplay. .. versionadded:: 5.0 Parameters ---------- code : str A string of code in the kernel's language. silent : bool, optional (default False) If set, the kernel will execute the code as quietly possible, and will force store_history to be False. store_history : bool, optional (default True) If set, the kernel will store command history. This is forced to be False if silent is True. user_expressions : dict, optional A dict mapping names to expressions to be evaluated in the user's dict. The expression values are returned as strings formatted using :func:`repr`. allow_stdin : bool, optional (default self.allow_stdin) Flag for whether the kernel can send stdin requests to frontends. Some frontends (e.g. the Notebook) do not support stdin requests. If raw_input is called from code executed from such a frontend, a StdinNotImplementedError will be raised. stop_on_error: bool, optional (default True) Flag whether to abort the execution queue, if an exception is encountered. timeout: float or None (default: None) Timeout to use when waiting for a reply output_hook: callable(msg) Function to be called with output messages. If not specified, output will be redisplayed. stdin_hook: callable(msg) Function or awaitable to be called with stdin_request messages. If not specified, input/getpass will be called. Returns ------- reply: dict The reply message for this request """ if not self.iopub_channel.is_alive(): emsg = "IOPub channel must be running to receive output" raise RuntimeError(emsg) if allow_stdin is None: allow_stdin = self.allow_stdin if allow_stdin and not self.stdin_channel.is_alive(): emsg = "stdin channel must be running to allow input" raise RuntimeError(emsg) msg_id = await ensure_async( self.execute( code, silent=silent, store_history=store_history, user_expressions=user_expressions, allow_stdin=allow_stdin, stop_on_error=stop_on_error, ) ) if stdin_hook is None: stdin_hook = self._stdin_hook_default # detect IPython kernel if output_hook is None and "IPython" in sys.modules: from IPython import get_ipython ip = get_ipython() in_kernel = getattr(ip, "kernel", False) if in_kernel: output_hook = partial( self._output_hook_kernel, ip.display_pub.session, ip.display_pub.pub_socket, ip.display_pub.parent_header, ) if output_hook is None: # default: redisplay plain-text outputs output_hook = self._output_hook_default # set deadline based on timeout if timeout is not None: deadline = time.monotonic() + timeout else: timeout_ms = None poller = zmq.Poller() iopub_socket = self.iopub_channel.socket poller.register(iopub_socket, zmq.POLLIN) if allow_stdin: stdin_socket = self.stdin_channel.socket poller.register(stdin_socket, zmq.POLLIN) else: stdin_socket = None # wait for output and redisplay it while True: if timeout is not None: timeout = max(0, deadline - time.monotonic()) timeout_ms = int(1000 * timeout) events = dict(poller.poll(timeout_ms)) if not events: emsg = "Timeout waiting for output" raise TimeoutError(emsg) if stdin_socket in events: req = await ensure_async(self.stdin_channel.get_msg(timeout=0)) res = stdin_hook(req) if inspect.isawaitable(res): await res continue if iopub_socket not in events: continue msg = await ensure_async(self.iopub_channel.get_msg(timeout=0)) if msg["parent_header"].get("msg_id") != msg_id: # not from my request continue output_hook(msg) # stop on idle if ( msg["header"]["msg_type"] == "status" and msg["content"]["execution_state"] == "idle" ): break # output is done, get the reply if timeout is not None: timeout = max(0, deadline - time.monotonic()) return await self._async_recv_reply(msg_id, timeout=timeout) # Methods to send specific messages on channels def execute( self, code: str, silent: bool = False, store_history: bool = True, user_expressions: t.Optional[t.Dict[str, t.Any]] = None, allow_stdin: t.Optional[bool] = None, stop_on_error: bool = True, ) -> str: """Execute code in the kernel. Parameters ---------- code : str A string of code in the kernel's language. silent : bool, optional (default False) If set, the kernel will execute the code as quietly possible, and will force store_history to be False. store_history : bool, optional (default True) If set, the kernel will store command history. This is forced to be False if silent is True. user_expressions : dict, optional A dict mapping names to expressions to be evaluated in the user's dict. The expression values are returned as strings formatted using :func:`repr`. allow_stdin : bool, optional (default self.allow_stdin) Flag for whether the kernel can send stdin requests to frontends. Some frontends (e.g. the Notebook) do not support stdin requests. If raw_input is called from code executed from such a frontend, a StdinNotImplementedError will be raised. stop_on_error: bool, optional (default True) Flag whether to abort the execution queue, if an exception is encountered. Returns ------- The msg_id of the message sent. """ if user_expressions is None: user_expressions = {} if allow_stdin is None: allow_stdin = self.allow_stdin # Don't waste network traffic if inputs are invalid if not isinstance(code, str): raise ValueError("code %r must be a string" % code) validate_string_dict(user_expressions) # Create class for content/msg creation. Related to, but possibly # not in Session. content = { "code": code, "silent": silent, "store_history": store_history, "user_expressions": user_expressions, "allow_stdin": allow_stdin, "stop_on_error": stop_on_error, } msg = self.session.msg("execute_request", content) self.shell_channel.send(msg) return msg["header"]["msg_id"] def complete(self, code: str, cursor_pos: t.Optional[int] = None) -> str: """Tab complete text in the kernel's namespace. Parameters ---------- code : str The context in which completion is requested. Can be anything between a variable name and an entire cell. cursor_pos : int, optional The position of the cursor in the block of code where the completion was requested. Default: ``len(code)`` Returns ------- The msg_id of the message sent. """ if cursor_pos is None: cursor_pos = len(code) content = {"code": code, "cursor_pos": cursor_pos} msg = self.session.msg("complete_request", content) self.shell_channel.send(msg) return msg["header"]["msg_id"] def inspect(self, code: str, cursor_pos: t.Optional[int] = None, detail_level: int = 0) -> str: """Get metadata information about an object in the kernel's namespace. It is up to the kernel to determine the appropriate object to inspect. Parameters ---------- code : str The context in which info is requested. Can be anything between a variable name and an entire cell. cursor_pos : int, optional The position of the cursor in the block of code where the info was requested. Default: ``len(code)`` detail_level : int, optional The level of detail for the introspection (0-2) Returns ------- The msg_id of the message sent. """ if cursor_pos is None: cursor_pos = len(code) content = { "code": code, "cursor_pos": cursor_pos, "detail_level": detail_level, } msg = self.session.msg("inspect_request", content) self.shell_channel.send(msg) return msg["header"]["msg_id"] def history( self, raw: bool = True, output: bool = False, hist_access_type: str = "range", **kwargs: t.Any, ) -> str: """Get entries from the kernel's history list. Parameters ---------- raw : bool If True, return the raw input. output : bool If True, then return the output as well. hist_access_type : str 'range' (fill in session, start and stop params), 'tail' (fill in n) or 'search' (fill in pattern param). session : int For a range request, the session from which to get lines. Session numbers are positive integers; negative ones count back from the current session. start : int The first line number of a history range. stop : int The final (excluded) line number of a history range. n : int The number of lines of history to get for a tail request. pattern : str The glob-syntax pattern for a search request. Returns ------- The ID of the message sent. """ if hist_access_type == "range": kwargs.setdefault("session", 0) kwargs.setdefault("start", 0) content = dict(raw=raw, output=output, hist_access_type=hist_access_type, **kwargs) msg = self.session.msg("history_request", content) self.shell_channel.send(msg) return msg["header"]["msg_id"] def kernel_info(self) -> str: """Request kernel info Returns ------- The msg_id of the message sent """ msg = self.session.msg("kernel_info_request") self.shell_channel.send(msg) return msg["header"]["msg_id"] def comm_info(self, target_name: t.Optional[str] = None) -> str: """Request comm info Returns ------- The msg_id of the message sent """ content = {} if target_name is None else {"target_name": target_name} msg = self.session.msg("comm_info_request", content) self.shell_channel.send(msg) return msg["header"]["msg_id"] def _handle_kernel_info_reply(self, msg: t.Dict[str, t.Any]) -> None: """handle kernel info reply sets protocol adaptation version. This might be run from a separate thread. """ adapt_version = int(msg["content"]["protocol_version"].split(".")[0]) if adapt_version != major_protocol_version: self.session.adapt_version = adapt_version def is_complete(self, code: str) -> str: """Ask the kernel whether some code is complete and ready to execute. Returns ------- The ID of the message sent. """ msg = self.session.msg("is_complete_request", {"code": code}) self.shell_channel.send(msg) return msg["header"]["msg_id"] def input(self, string: str) -> None: """Send a string of raw input to the kernel. This should only be called in response to the kernel sending an ``input_request`` message on the stdin channel. Returns ------- The ID of the message sent. """ content = {"value": string} msg = self.session.msg("input_reply", content) self.stdin_channel.send(msg) def shutdown(self, restart: bool = False) -> str: """Request an immediate kernel shutdown on the control channel. Upon receipt of the (empty) reply, client code can safely assume that the kernel has shut down and it's safe to forcefully terminate it if it's still alive. The kernel will send the reply via a function registered with Python's atexit module, ensuring it's truly done as the kernel is done with all normal operation. Returns ------- The msg_id of the message sent """ # Send quit message to kernel. Once we implement kernel-side setattr, # this should probably be done that way, but for now this will do. msg = self.session.msg("shutdown_request", {"restart": restart}) self.control_channel.send(msg) return msg["header"]["msg_id"] The provided code snippet includes necessary dependencies for implementing the `run_kernel` function. Write a Python function `def run_kernel(**kwargs: t.Any) -> t.Iterator[KernelClient]` to solve the following problem: Context manager to create a kernel in a subprocess. The kernel is shut down when the context exits. Returns ------- kernel_client: connected KernelClient instance Here is the function: def run_kernel(**kwargs: t.Any) -> t.Iterator[KernelClient]: """Context manager to create a kernel in a subprocess. The kernel is shut down when the context exits. Returns ------- kernel_client: connected KernelClient instance """ km, kc = start_new_kernel(**kwargs) try: yield kc finally: kc.stop_channels() km.shutdown_kernel(now=True)
Context manager to create a kernel in a subprocess. The kernel is shut down when the context exits. Returns ------- kernel_client: connected KernelClient instance
174,957
import zmq.asyncio from traitlets import Instance, Type from ..channels import AsyncZMQSocketChannel, HBChannel from ..client import KernelClient, reqrep The provided code snippet includes necessary dependencies for implementing the `wrapped` function. Write a Python function `def wrapped(meth, channel)` to solve the following problem: Wrap a method on a channel and handle replies. Here is the function: def wrapped(meth, channel): """Wrap a method on a channel and handle replies.""" def _(self, *args, **kwargs): reply = kwargs.pop("reply", False) timeout = kwargs.pop("timeout", None) msg_id = meth(self, *args, **kwargs) if not reply: return msg_id return self._recv_reply(msg_id, timeout=timeout, channel=channel) return _
Wrap a method on a channel and handle replies.
174,958
import json import re from typing import Any, Dict, List, Tuple from ._version import protocol_version_info def code_to_line(code: str, cursor_pos: int) -> Tuple[str, int]: """Turn a multiline code block and cursor position into a single line and new cursor position. For adapting ``complete_`` and ``object_info_request``. """ if not code: return "", 0 for line in code.splitlines(True): n = len(line) if cursor_pos > n: cursor_pos -= n else: break return line, cursor_pos _match_bracket = re.compile(r"\([^\(\)]+\)", re.UNICODE) _end_bracket = re.compile(r"\([^\(]*$", re.UNICODE) _identifier = re.compile(r"[a-z_][0-9a-z._]*", re.I | re.UNICODE) The provided code snippet includes necessary dependencies for implementing the `extract_oname_v4` function. Write a Python function `def extract_oname_v4(code: str, cursor_pos: int) -> str` to solve the following problem: Reimplement token-finding logic from IPython 2.x javascript for adapting object_info_request from v5 to v4 Here is the function: def extract_oname_v4(code: str, cursor_pos: int) -> str: """Reimplement token-finding logic from IPython 2.x javascript for adapting object_info_request from v5 to v4 """ line, _ = code_to_line(code, cursor_pos) oldline = line line = _match_bracket.sub("", line) while oldline != line: oldline = line line = _match_bracket.sub("", line) # remove everything after last open bracket line = _end_bracket.sub("", line) matches = _identifier.findall(line) if matches: return matches[-1] else: return ""
Reimplement token-finding logic from IPython 2.x javascript for adapting object_info_request from v5 to v4
174,959
import json import re from typing import Any, Dict, List, Tuple from ._version import protocol_version_info List = _Alias() The provided code snippet includes necessary dependencies for implementing the `_version_str_to_list` function. Write a Python function `def _version_str_to_list(version: str) -> List[int]` to solve the following problem: convert a version string to a list of ints non-int segments are excluded Here is the function: def _version_str_to_list(version: str) -> List[int]: """convert a version string to a list of ints non-int segments are excluded """ v = [] for part in version.split("."): try: v.append(int(part)) except ValueError: pass return v
convert a version string to a list of ints non-int segments are excluded
174,960
import json import re from typing import Any, Dict, List, Tuple from ._version import protocol_version_info adapters = { (5, 4): V5toV4(), (4, 5): V4toV5(), } Any = object() Dict = _Alias() protocol_version_info = (5, 3) def utcnow() -> datetime: """Return timezone-aware UTC timestamp""" return datetime.utcnow().replace(tzinfo=utc) # noqa The provided code snippet includes necessary dependencies for implementing the `adapt` function. Write a Python function `def adapt(msg: Dict[str, Any], to_version: int = protocol_version_info[0]) -> Dict[str, Any]` to solve the following problem: Adapt a single message to a target version Parameters ---------- msg : dict A Jupyter message. to_version : int, optional The target major version. If unspecified, adapt to the current version. Returns ------- msg : dict A Jupyter message appropriate in the new version. Here is the function: def adapt(msg: Dict[str, Any], to_version: int = protocol_version_info[0]) -> Dict[str, Any]: """Adapt a single message to a target version Parameters ---------- msg : dict A Jupyter message. to_version : int, optional The target major version. If unspecified, adapt to the current version. Returns ------- msg : dict A Jupyter message appropriate in the new version. """ from .session import utcnow header = msg["header"] if "date" not in header: header["date"] = utcnow() if "version" in header: from_version = int(header["version"].split(".")[0]) else: # assume last version before adding the key to the header from_version = 4 adapter = adapters.get((from_version, to_version), None) if adapter is None: return msg return adapter(msg)
Adapt a single message to a target version Parameters ---------- msg : dict A Jupyter message. to_version : int, optional The target major version. If unspecified, adapt to the current version. Returns ------- msg : dict A Jupyter message appropriate in the new version.
175,031
from __future__ import absolute_import, division, print_function import collections import itertools import re from ._structures import Infinity def _parse_version_parts(s): for part in _legacy_version_component_re.split(s): part = _legacy_version_replacement_map.get(part, part) if not part or part == ".": continue if part[:1] in "0123456789": # pad for numeric comparison yield part.zfill(8) else: yield "*" + part # ensure that alpha/beta/candidate are before final yield "*final" def _legacy_cmpkey(version): # We hardcode an epoch of -1 here. A PEP 440 version can only have a epoch # greater than or equal to 0. This will effectively put the LegacyVersion, # which uses the defacto standard originally implemented by setuptools, # as before all PEP 440 versions. epoch = -1 # This scheme is taken from pkg_resources.parse_version setuptools prior to # it's adoption of the packaging library. parts = [] for part in _parse_version_parts(version.lower()): if part.startswith("*"): # remove "-" before a prerelease tag if part < "*final": while parts and parts[-1] == "*final-": parts.pop() # remove trailing zeros from each series of numeric parts while parts and parts[-1] == "00000000": parts.pop() parts.append(part) parts = tuple(parts) return epoch, parts
null
175,039
from __future__ import absolute_import, division, print_function import operator import os import platform import sys from pkg_resources.extern.pyparsing import ParseException, ParseResults, stringStart, stringEnd from pkg_resources.extern.pyparsing import ZeroOrMore, Group, Forward, QuotedString from pkg_resources.extern.pyparsing import Literal as L from ._compat import string_types from .specifiers import Specifier, InvalidSpecifier def _coerce_parse_result(results): if isinstance(results, ParseResults): return [_coerce_parse_result(i) for i in results] else: return results
null
175,040
from __future__ import absolute_import, division, print_function import operator import os import platform import sys from pkg_resources.extern.pyparsing import ParseException, ParseResults, stringStart, stringEnd from pkg_resources.extern.pyparsing import ZeroOrMore, Group, Forward, QuotedString from pkg_resources.extern.pyparsing import Literal as L from ._compat import string_types from .specifiers import Specifier, InvalidSpecifier def _format_marker(marker, first=True): assert isinstance(marker, (list, tuple, string_types)) # Sometimes we have a structure like [[...]] which is a single item list # where the single item is itself it's own list. In that case we want skip # the rest of this function so that we don't get extraneous () on the # outside. if ( isinstance(marker, list) and len(marker) == 1 and isinstance(marker[0], (list, tuple)) ): return _format_marker(marker[0]) if isinstance(marker, list): inner = (_format_marker(m, first=False) for m in marker) if first: return " ".join(inner) else: return "(" + " ".join(inner) + ")" elif isinstance(marker, tuple): return " ".join([m.serialize() for m in marker]) else: return marker
null
175,041
from __future__ import absolute_import, division, print_function import operator import os import platform import sys from pkg_resources.extern.pyparsing import ParseException, ParseResults, stringStart, stringEnd from pkg_resources.extern.pyparsing import ZeroOrMore, Group, Forward, QuotedString from pkg_resources.extern.pyparsing import Literal as L from ._compat import string_types from .specifiers import Specifier, InvalidSpecifier class Variable(Node): def serialize(self): return str(self) def _eval_op(lhs, op, rhs): try: spec = Specifier("".join([op.serialize(), rhs])) except InvalidSpecifier: pass else: return spec.contains(lhs) oper = _operators.get(op.serialize()) if oper is None: raise UndefinedComparison( "Undefined {0!r} on {1!r} and {2!r}.".format(op, lhs, rhs) ) return oper(lhs, rhs) def _get_env(environment, name): value = environment.get(name, _undefined) if value is _undefined: raise UndefinedEnvironmentName( "{0!r} does not exist in evaluation environment.".format(name) ) return value def _evaluate_markers(markers, environment): groups = [[]] for marker in markers: assert isinstance(marker, (list, tuple, string_types)) if isinstance(marker, list): groups[-1].append(_evaluate_markers(marker, environment)) elif isinstance(marker, tuple): lhs, op, rhs = marker if isinstance(lhs, Variable): lhs_value = _get_env(environment, lhs.value) rhs_value = rhs.value else: lhs_value = lhs.value rhs_value = _get_env(environment, rhs.value) groups[-1].append(_eval_op(lhs_value, op, rhs_value)) else: assert marker in ["and", "or"] if marker == "or": groups.append([]) return any(all(item) for item in groups)
null
175,042
from __future__ import absolute_import, division, print_function import operator import os import platform import sys from pkg_resources.extern.pyparsing import ParseException, ParseResults, stringStart, stringEnd from pkg_resources.extern.pyparsing import ZeroOrMore, Group, Forward, QuotedString from pkg_resources.extern.pyparsing import Literal as L from ._compat import string_types from .specifiers import Specifier, InvalidSpecifier def format_full_version(info): version = "{0.major}.{0.minor}.{0.micro}".format(info) kind = info.releaselevel if kind != "final": version += kind[0] + str(info.serial) return version def default_environment(): if hasattr(sys, "implementation"): iver = format_full_version(sys.implementation.version) implementation_name = sys.implementation.name else: iver = "0" implementation_name = "" return { "implementation_name": implementation_name, "implementation_version": iver, "os_name": os.name, "platform_machine": platform.machine(), "platform_release": platform.release(), "platform_system": platform.system(), "platform_version": platform.version(), "python_full_version": platform.python_version(), "platform_python_implementation": platform.python_implementation(), "python_version": ".".join(platform.python_version_tuple()[:2]), "sys_platform": sys.platform, }
null
175,047
from __future__ import annotations import os import sys from configparser import ConfigParser from pathlib import Path from .api import PlatformDirsABC def getuid() -> int: raise RuntimeError("should only be used on Linux")
null
175,048
from __future__ import annotations import os import sys from configparser import ConfigParser from pathlib import Path from .api import PlatformDirsABC class Unix(PlatformDirsABC): """ On Unix/Linux, we follow the `XDG Basedir Spec <https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html>`_. The spec allows overriding directories with environment variables. The examples show are the default values, alongside the name of the environment variable that overrides them. Makes use of the `appname <platformdirs.api.PlatformDirsABC.appname>`, `version <platformdirs.api.PlatformDirsABC.version>`, `multipath <platformdirs.api.PlatformDirsABC.multipath>`, `opinion <platformdirs.api.PlatformDirsABC.opinion>`, `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`. """ def user_data_dir(self) -> str: """ :return: data directory tied to the user, e.g. ``~/.local/share/$appname/$version`` or ``$XDG_DATA_HOME/$appname/$version`` """ path = os.environ.get("XDG_DATA_HOME", "") if not path.strip(): path = os.path.expanduser("~/.local/share") return self._append_app_name_and_version(path) def site_data_dir(self) -> str: """ :return: data directories shared by users (if `multipath <platformdirs.api.PlatformDirsABC.multipath>` is enabled and ``XDG_DATA_DIR`` is set and a multi path the response is also a multi path separated by the OS path separator), e.g. ``/usr/local/share/$appname/$version`` or ``/usr/share/$appname/$version`` """ # XDG default for $XDG_DATA_DIRS; only first, if multipath is False path = os.environ.get("XDG_DATA_DIRS", "") if not path.strip(): path = f"/usr/local/share{os.pathsep}/usr/share" return self._with_multi_path(path) def _with_multi_path(self, path: str) -> str: path_list = path.split(os.pathsep) if not self.multipath: path_list = path_list[0:1] path_list = [self._append_app_name_and_version(os.path.expanduser(p)) for p in path_list] return os.pathsep.join(path_list) def user_config_dir(self) -> str: """ :return: config directory tied to the user, e.g. ``~/.config/$appname/$version`` or ``$XDG_CONFIG_HOME/$appname/$version`` """ path = os.environ.get("XDG_CONFIG_HOME", "") if not path.strip(): path = os.path.expanduser("~/.config") return self._append_app_name_and_version(path) def site_config_dir(self) -> str: """ :return: config directories shared by users (if `multipath <platformdirs.api.PlatformDirsABC.multipath>` is enabled and ``XDG_DATA_DIR`` is set and a multi path the response is also a multi path separated by the OS path separator), e.g. ``/etc/xdg/$appname/$version`` """ # XDG default for $XDG_CONFIG_DIRS only first, if multipath is False path = os.environ.get("XDG_CONFIG_DIRS", "") if not path.strip(): path = "/etc/xdg" return self._with_multi_path(path) def user_cache_dir(self) -> str: """ :return: cache directory tied to the user, e.g. ``~/.cache/$appname/$version`` or ``~/$XDG_CACHE_HOME/$appname/$version`` """ path = os.environ.get("XDG_CACHE_HOME", "") if not path.strip(): path = os.path.expanduser("~/.cache") return self._append_app_name_and_version(path) def site_cache_dir(self) -> str: """ :return: cache directory shared by users, e.g. ``/var/tmp/$appname/$version`` """ return self._append_app_name_and_version("/var/tmp") def user_state_dir(self) -> str: """ :return: state directory tied to the user, e.g. ``~/.local/state/$appname/$version`` or ``$XDG_STATE_HOME/$appname/$version`` """ path = os.environ.get("XDG_STATE_HOME", "") if not path.strip(): path = os.path.expanduser("~/.local/state") return self._append_app_name_and_version(path) def user_log_dir(self) -> str: """ :return: log directory tied to the user, same as `user_state_dir` if not opinionated else ``log`` in it """ path = self.user_state_dir if self.opinion: path = os.path.join(path, "log") return path def user_documents_dir(self) -> str: """ :return: documents directory tied to the user, e.g. ``~/Documents`` """ documents_dir = _get_user_dirs_folder("XDG_DOCUMENTS_DIR") if documents_dir is None: documents_dir = os.environ.get("XDG_DOCUMENTS_DIR", "").strip() if not documents_dir: documents_dir = os.path.expanduser("~/Documents") return documents_dir def user_runtime_dir(self) -> str: """ :return: runtime directory tied to the user, e.g. ``/run/user/$(id -u)/$appname/$version`` or ``$XDG_RUNTIME_DIR/$appname/$version`` """ path = os.environ.get("XDG_RUNTIME_DIR", "") if not path.strip(): path = f"/run/user/{getuid()}" return self._append_app_name_and_version(path) def site_data_path(self) -> Path: """:return: data path shared by users. Only return first item, even if ``multipath`` is set to ``True``""" return self._first_item_as_path_if_multipath(self.site_data_dir) def site_config_path(self) -> Path: """:return: config path shared by the users. Only return first item, even if ``multipath`` is set to ``True``""" return self._first_item_as_path_if_multipath(self.site_config_dir) def site_cache_path(self) -> Path: """:return: cache path shared by users. Only return first item, even if ``multipath`` is set to ``True``""" return self._first_item_as_path_if_multipath(self.site_cache_dir) def _first_item_as_path_if_multipath(self, directory: str) -> Path: if self.multipath: # If multipath is True, the first path is returned. directory = directory.split(os.pathsep)[0] return Path(directory) class ConfigParser(RawConfigParser): ... The provided code snippet includes necessary dependencies for implementing the `_get_user_dirs_folder` function. Write a Python function `def _get_user_dirs_folder(key: str) -> str | None` to solve the following problem: Return directory from user-dirs.dirs config file. See https://freedesktop.org/wiki/Software/xdg-user-dirs/ Here is the function: def _get_user_dirs_folder(key: str) -> str | None: """Return directory from user-dirs.dirs config file. See https://freedesktop.org/wiki/Software/xdg-user-dirs/""" user_dirs_config_path = os.path.join(Unix().user_config_dir, "user-dirs.dirs") if os.path.exists(user_dirs_config_path): parser = ConfigParser() with open(user_dirs_config_path) as stream: # Add fake section header, so ConfigParser doesn't complain parser.read_string(f"[top]\n{stream.read()}") if key not in parser["top"]: return None path = parser["top"][key].strip('"') # Handle relative home paths path = path.replace("$HOME", os.path.expanduser("~")) return path return None
Return directory from user-dirs.dirs config file. See https://freedesktop.org/wiki/Software/xdg-user-dirs/
175,049
from __future__ import annotations import ctypes import os import sys from functools import lru_cache from typing import Callable from .api import PlatformDirsABC def get_win_folder_from_env_vars(csidl_name: str) -> str: """Get folder from environment variables.""" if csidl_name == "CSIDL_PERSONAL": # does not have an environment name return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Documents") env_var_name = { "CSIDL_APPDATA": "APPDATA", "CSIDL_COMMON_APPDATA": "ALLUSERSPROFILE", "CSIDL_LOCAL_APPDATA": "LOCALAPPDATA", }.get(csidl_name) if env_var_name is None: raise ValueError(f"Unknown CSIDL name: {csidl_name}") result = os.environ.get(env_var_name) if result is None: raise ValueError(f"Unset environment variable: {env_var_name}") return result def get_win_folder_from_registry(csidl_name: str) -> str: """Get folder from the registry. This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names. """ shell_folder_name = { "CSIDL_APPDATA": "AppData", "CSIDL_COMMON_APPDATA": "Common AppData", "CSIDL_LOCAL_APPDATA": "Local AppData", "CSIDL_PERSONAL": "Personal", }.get(csidl_name) if shell_folder_name is None: raise ValueError(f"Unknown CSIDL name: {csidl_name}") if sys.platform != "win32": # only needed for mypy type checker to know that this code runs only on Windows raise NotImplementedError import winreg key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") directory, _ = winreg.QueryValueEx(key, shell_folder_name) return str(directory) def get_win_folder_via_ctypes(csidl_name: str) -> str: """Get folder with ctypes.""" csidl_const = { "CSIDL_APPDATA": 26, "CSIDL_COMMON_APPDATA": 35, "CSIDL_LOCAL_APPDATA": 28, "CSIDL_PERSONAL": 5, }.get(csidl_name) if csidl_const is None: raise ValueError(f"Unknown CSIDL name: {csidl_name}") buf = ctypes.create_unicode_buffer(1024) windll = getattr(ctypes, "windll") # noqa: B009 # using getattr to avoid false positive with mypy type checker windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf) # Downgrade to short path name if it has highbit chars. if any(ord(c) > 255 for c in buf): buf2 = ctypes.create_unicode_buffer(1024) if windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024): buf = buf2 return buf.value class Callable(BaseTypingInstance): def py__call__(self, arguments): """ def x() -> Callable[[Callable[..., _T]], _T]: ... """ # The 0th index are the arguments. try: param_values = self._generics_manager[0] result_values = self._generics_manager[1] except IndexError: debug.warning('Callable[...] defined without two arguments') return NO_VALUES else: from jedi.inference.gradual.annotation import infer_return_for_callable return infer_return_for_callable(arguments, param_values, result_values) def py__get__(self, instance, class_value): return ValueSet([self]) def _pick_get_win_folder() -> Callable[[str], str]: if hasattr(ctypes, "windll"): return get_win_folder_via_ctypes try: import winreg # noqa: F401 except ImportError: return get_win_folder_from_env_vars else: return get_win_folder_from_registry
null
175,050
from __future__ import annotations import os import re import sys from functools import lru_cache from typing import cast from .api import PlatformDirsABC import sys if sys.version_info >= (3, 8): # pragma: no cover (py38+) from typing import Literal else: # pragma: no cover (py38+) from typing_extensions import Literal The provided code snippet includes necessary dependencies for implementing the `_android_folder` function. Write a Python function `def _android_folder() -> str | None` to solve the following problem: :return: base folder for the Android OS or None if cannot be found Here is the function: def _android_folder() -> str | None: """:return: base folder for the Android OS or None if cannot be found""" try: # First try to get path to android app via pyjnius from jnius import autoclass Context = autoclass("android.content.Context") # noqa: N806 result: str | None = Context.getFilesDir().getParentFile().getAbsolutePath() except Exception: # if fails find an android folder looking path on the sys.path pattern = re.compile(r"/data/(data|user/\d+)/(.+)/files") for path in sys.path: if pattern.match(path): result = path.split("/files")[0] break else: result = None return result
:return: base folder for the Android OS or None if cannot be found
175,051
from __future__ import annotations import os import re import sys from functools import lru_cache from typing import cast from .api import PlatformDirsABC The provided code snippet includes necessary dependencies for implementing the `_android_documents_folder` function. Write a Python function `def _android_documents_folder() -> str` to solve the following problem: :return: documents folder for the Android OS Here is the function: def _android_documents_folder() -> str: """:return: documents folder for the Android OS""" # Get directories with pyjnius try: from jnius import autoclass Context = autoclass("android.content.Context") # noqa: N806 Environment = autoclass("android.os.Environment") # noqa: N806 documents_dir: str = Context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath() except Exception: documents_dir = "/storage/emulated/0/Documents" return documents_dir
:return: documents folder for the Android OS
175,052
def EIRESID(x): return -1 * (int)(x)
null
175,053
import pythoncom import win32con import win32gui from win32com.shell import shell, shellcon class ShellExtension: _reg_progid_ = "Python.ShellExtension.CopyHook" _reg_desc_ = "Python Sample Shell Extension (copy hook)" _reg_clsid_ = "{1845b6ba-2bbd-4197-b930-46d8651497c1}" _com_interfaces_ = [shell.IID_ICopyHook] _public_methods_ = ["CopyCallBack"] def CopyCallBack(self, hwnd, func, flags, srcName, srcAttr, destName, destAttr): # This function should return: # IDYES Allows the operation. # IDNO Prevents the operation on this folder but continues with any other operations that have been approved (for example, a batch copy operation). # IDCANCEL Prevents the current operation and cancels any pending operations. print("CopyCallBack", hwnd, func, flags, srcName, srcAttr, destName, destAttr) return win32gui.MessageBox( hwnd, "Allow operation?", "CopyHook", win32con.MB_YESNO ) def DllRegisterServer(): import winreg key = winreg.CreateKey( winreg.HKEY_CLASSES_ROOT, "directory\\shellex\\CopyHookHandlers\\" + ShellExtension._reg_desc_, ) winreg.SetValueEx(key, None, 0, winreg.REG_SZ, ShellExtension._reg_clsid_) key = winreg.CreateKey( winreg.HKEY_CLASSES_ROOT, "*\\shellex\\CopyHookHandlers\\" + ShellExtension._reg_desc_, ) winreg.SetValueEx(key, None, 0, winreg.REG_SZ, ShellExtension._reg_clsid_) print(ShellExtension._reg_desc_, "registration complete.")
null
175,054
import pythoncom import win32con import win32gui from win32com.shell import shell, shellcon class ShellExtension: _reg_progid_ = "Python.ShellExtension.CopyHook" _reg_desc_ = "Python Sample Shell Extension (copy hook)" _reg_clsid_ = "{1845b6ba-2bbd-4197-b930-46d8651497c1}" _com_interfaces_ = [shell.IID_ICopyHook] _public_methods_ = ["CopyCallBack"] def CopyCallBack(self, hwnd, func, flags, srcName, srcAttr, destName, destAttr): # This function should return: # IDYES Allows the operation. # IDNO Prevents the operation on this folder but continues with any other operations that have been approved (for example, a batch copy operation). # IDCANCEL Prevents the current operation and cancels any pending operations. print("CopyCallBack", hwnd, func, flags, srcName, srcAttr, destName, destAttr) return win32gui.MessageBox( hwnd, "Allow operation?", "CopyHook", win32con.MB_YESNO ) def DllUnregisterServer(): import winreg try: key = winreg.DeleteKey( winreg.HKEY_CLASSES_ROOT, "directory\\shellex\\CopyHookHandlers\\" + ShellExtension._reg_desc_, ) except WindowsError as details: import errno if details.errno != errno.ENOENT: raise try: key = winreg.DeleteKey( winreg.HKEY_CLASSES_ROOT, "*\\shellex\\CopyHookHandlers\\" + ShellExtension._reg_desc_, ) except WindowsError as details: import errno if details.errno != errno.ENOENT: raise print(ShellExtension._reg_desc_, "unregistration complete.")
null
175,055
import pythoncom import win32con import win32gui from win32com.shell import shell, shellcon class ShellExtension: def Initialize(self, folder, dataobj, hkey): def QueryContextMenu(self, hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags): def InvokeCommand(self, ci): def GetCommandString(self, cmd, typ): def DllRegisterServer(): import winreg key = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, "Python.File\\shellex") subkey = winreg.CreateKey(key, "ContextMenuHandlers") subkey2 = winreg.CreateKey(subkey, "PythonSample") winreg.SetValueEx(subkey2, None, 0, winreg.REG_SZ, ShellExtension._reg_clsid_) print(ShellExtension._reg_desc_, "registration complete.")
null
175,056
import pythoncom import win32con import win32gui from win32com.shell import shell, shellcon class ShellExtension: _reg_progid_ = "Python.ShellExtension.ContextMenu" _reg_desc_ = "Python Sample Shell Extension (context menu)" _reg_clsid_ = "{CED0336C-C9EE-4a7f-8D7F-C660393C381F}" _com_interfaces_ = [shell.IID_IShellExtInit, shell.IID_IContextMenu] _public_methods_ = shellcon.IContextMenu_Methods + shellcon.IShellExtInit_Methods def Initialize(self, folder, dataobj, hkey): print("Init", folder, dataobj, hkey) self.dataobj = dataobj def QueryContextMenu(self, hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags): print("QCM", hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags) # Query the items clicked on format_etc = win32con.CF_HDROP, None, 1, -1, pythoncom.TYMED_HGLOBAL sm = self.dataobj.GetData(format_etc) num_files = shell.DragQueryFile(sm.data_handle, -1) if num_files > 1: msg = "&Hello from Python (with %d files selected)" % num_files else: fname = shell.DragQueryFile(sm.data_handle, 0) msg = "&Hello from Python (with '%s' selected)" % fname idCmd = idCmdFirst items = ["First Python content menu item"] if ( uFlags & 0x000F ) == shellcon.CMF_NORMAL: # Check == here, since CMF_NORMAL=0 print("CMF_NORMAL...") items.append(msg) elif uFlags & shellcon.CMF_VERBSONLY: print("CMF_VERBSONLY...") items.append(msg + " - shortcut") elif uFlags & shellcon.CMF_EXPLORE: print("CMF_EXPLORE...") items.append(msg + " - normal file, right-click in Explorer") elif uFlags & CMF_DEFAULTONLY: print("CMF_DEFAULTONLY...\r\n") else: print("** unknown flags", uFlags) win32gui.InsertMenu( hMenu, indexMenu, win32con.MF_SEPARATOR | win32con.MF_BYPOSITION, 0, None ) indexMenu += 1 for item in items: win32gui.InsertMenu( hMenu, indexMenu, win32con.MF_STRING | win32con.MF_BYPOSITION, idCmd, item, ) indexMenu += 1 idCmd += 1 win32gui.InsertMenu( hMenu, indexMenu, win32con.MF_SEPARATOR | win32con.MF_BYPOSITION, 0, None ) indexMenu += 1 return idCmd - idCmdFirst # Must return number of menu items we added. def InvokeCommand(self, ci): mask, hwnd, verb, params, dir, nShow, hotkey, hicon = ci win32gui.MessageBox(hwnd, "Hello", "Wow", win32con.MB_OK) def GetCommandString(self, cmd, typ): # If GetCommandString returns the same string for all items then # the shell seems to ignore all but one. This is even true in # Win7 etc where there is no status bar (and hence this string seems # ignored) return "Hello from Python (cmd=%d)!!" % (cmd,) def DllUnregisterServer(): import winreg try: key = winreg.DeleteKey( winreg.HKEY_CLASSES_ROOT, "Python.File\\shellex\\ContextMenuHandlers\\PythonSample", ) except WindowsError as details: import errno if details.errno != errno.ENOENT: raise print(ShellExtension._reg_desc_, "unregistration complete.")
null
175,057
import _thread import os import pyclbr import sys import commctrl import pythoncom import win32api import win32con import win32gui import win32gui_struct import winerror from pywin.scintilla import scintillacon from win32com.server.exception import COMException from win32com.server.util import NewEnum, wrap from win32com.shell import shell, shellcon from win32com.util import IIDToInterfaceName def GetFolderAndPIDLForPath(filename): desktop = shell.SHGetDesktopFolder() info = desktop.ParseDisplayName(0, None, os.path.abspath(filename)) cchEaten, pidl, attr = info # We must walk the ID list, looking for one child at a time. folder = desktop while len(pidl) > 1: this = pidl.pop(0) folder = folder.BindToObject([this], None, shell.IID_IShellFolder) # We are left with the pidl for the specific item. Leave it as # a list, so it remains a valid PIDL. return folder, pidl
null
175,058
import _thread import os import pyclbr import sys import commctrl import pythoncom import win32api import win32con import win32gui import win32gui_struct import winerror from pywin.scintilla import scintillacon from win32com.server.exception import COMException from win32com.server.util import NewEnum, wrap from win32com.shell import shell, shellcon from win32com.util import IIDToInterfaceName clbr_modules = {} def get_clbr_for_file(path): try: objects = clbr_modules[path] except KeyError: dir, filename = os.path.split(path) base, ext = os.path.splitext(filename) objects = pyclbr.readmodule_ex(base, [dir]) clbr_modules[path] = objects return objects
null
175,059
import _thread import os import pyclbr import sys import commctrl import pythoncom import win32api import win32con import win32gui import win32gui_struct import winerror from pywin.scintilla import scintillacon from win32com.server.exception import COMException from win32com.server.util import NewEnum, wrap from win32com.shell import shell, shellcon from win32com.util import IIDToInterfaceName class ShellFolderRoot(ShellFolderFileSystem): _reg_progid_ = "Python.ShellExtension.Folder" _reg_desc_ = "Python Path Shell Browser" _reg_clsid_ = "{f6287035-3074-4cb5-a8a6-d3c80e206944}" def GetClassID(self): return self._reg_clsid_ def Initialize(self, pidl): # This is the PIDL of us, as created by the shell. This is our # top-level ID. All other items under us have PIDLs defined # by us - see the notes at the top of the file. # print "Initialize called with pidl", repr(pidl) self.pidl = pidl def CreateViewObject(self, hwnd, iid): return wrap(FileSystemView(self, hwnd), iid, useDispatcher=debug > 0) def EnumObjects(self, hwndOwner, flags): items = [["directory\0" + p] for p in sys.path if os.path.isdir(p)] return NewEnum(items, iid=shell.IID_IEnumIDList, useDispatcher=(debug > 0)) def GetDisplayNameOf(self, pidl, flags): ## return full path for sys.path dirs, since they don't appear under a parent folder final_pidl = pidl[-1] display_name = final_pidl.split("\0")[-1] return display_name def DllRegisterServer(): import winreg key = winreg.CreateKey( winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\" "Explorer\\Desktop\\Namespace\\" + ShellFolderRoot._reg_clsid_, ) winreg.SetValueEx(key, None, 0, winreg.REG_SZ, ShellFolderRoot._reg_desc_) # And special shell keys under our CLSID key = winreg.CreateKey( winreg.HKEY_CLASSES_ROOT, "CLSID\\" + ShellFolderRoot._reg_clsid_ + "\\ShellFolder", ) # 'Attributes' is an int stored as a binary! use struct attr = ( shellcon.SFGAO_FOLDER | shellcon.SFGAO_HASSUBFOLDER | shellcon.SFGAO_BROWSABLE ) import struct s = struct.pack("i", attr) winreg.SetValueEx(key, "Attributes", 0, winreg.REG_BINARY, s) print(ShellFolderRoot._reg_desc_, "registration complete.")
null
175,060
import _thread import os import pyclbr import sys import commctrl import pythoncom import win32api import win32con import win32gui import win32gui_struct import winerror from pywin.scintilla import scintillacon from win32com.server.exception import COMException from win32com.server.util import NewEnum, wrap from win32com.shell import shell, shellcon from win32com.util import IIDToInterfaceName class ShellFolderRoot(ShellFolderFileSystem): def GetClassID(self): def Initialize(self, pidl): def CreateViewObject(self, hwnd, iid): def EnumObjects(self, hwndOwner, flags): def GetDisplayNameOf(self, pidl, flags): def DllUnregisterServer(): import winreg try: key = winreg.DeleteKey( winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\" "Explorer\\Desktop\\Namespace\\" + ShellFolderRoot._reg_clsid_, ) except WindowsError as details: import errno if details.errno != errno.ENOENT: raise print(ShellFolderRoot._reg_desc_, "unregistration complete.")
null
175,061
import os import stat import sys import pythoncom import win32gui import winerror from win32com.server.exception import COMException from win32com.shell import shell, shellcon class EmptyVolumeCache: _reg_progid_ = "Python.ShellExtension.EmptyVolumeCache" _reg_desc_ = "Python Sample Shell Extension (disk cleanup)" _reg_clsid_ = "{EADD0777-2968-4c72-A999-2BF5F756259C}" _reg_icon_ = ico _com_interfaces_ = [shell.IID_IEmptyVolumeCache, shell.IID_IEmptyVolumeCache2] _public_methods_ = IEmptyVolumeCache_Methods + IEmptyVolumeCache2_Methods def Initialize(self, hkey, volume, flags): # This should never be called, except on win98. print("Unless we are on 98, Initialize call is unexpected!") raise COMException(hresult=winerror.E_NOTIMPL) def InitializeEx(self, hkey, volume, key_name, flags): # Must return a tuple of: # (display_name, description, button_name, flags) print("InitializeEx called with", hkey, volume, key_name, flags) self.volume = volume if flags & shellcon.EVCF_SETTINGSMODE: print("We are being run on a schedule") # In this case, "because there is no opportunity for user # feedback, only those files that are extremely safe to clean up # should be touched. You should ignore the initialization # method's pcwszVolume parameter and clean unneeded files # regardless of what drive they are on." self.volume = None # flag as 'any disk will do' elif flags & shellcon.EVCF_OUTOFDISKSPACE: # In this case, "the handler should be aggressive about deleting # files, even if it results in a performance loss. However, the # handler obviously should not delete files that would cause an # application to fail or the user to lose data." print("We are being run as we are out of disk-space") else: # This case is not documented - we are guessing :) print("We are being run because the user asked") # For the sake of demo etc, we tell the shell to only show us when # there are > 0 bytes available. Our GetSpaceUsed will check the # volume, so will return 0 when we are on a different disk flags = shellcon.EVCF_DONTSHOWIFZERO | shellcon.EVCF_ENABLEBYDEFAULT return ( "pywin32 compiled files", "Removes all .pyc and .pyo files in the pywin32 directories", "click me!", flags, ) def _GetDirectories(self): root_dir = os.path.abspath(os.path.dirname(os.path.dirname(win32gui.__file__))) if self.volume is not None and not root_dir.lower().startswith( self.volume.lower() ): return [] return [ os.path.join(root_dir, p) for p in ("win32", "win32com", "win32comext", "isapi") ] def _WalkCallback(self, arg, directory, files): # callback function for os.path.walk - no need to be member, but its # close to the callers :) callback, total_list = arg for file in files: fqn = os.path.join(directory, file).lower() if file.endswith(".pyc") or file.endswith(".pyo"): # See below - total_list == None means delete files, # otherwise it is a list where the result is stored. Its a # list simply due to the way os.walk works - only [0] is # referenced if total_list is None: print("Deleting file", fqn) # Should do callback.PurgeProcess - left as an exercise :) os.remove(fqn) else: total_list[0] += os.stat(fqn)[stat.ST_SIZE] # and callback to the tool if callback: # for the sake of seeing the progress bar do its thing, # we take longer than we need to... # ACK - for some bizarre reason this screws up the XP # cleanup manager - clues welcome!! :) ## print "Looking in", directory, ", but waiting a while..." ## time.sleep(3) # now do it used = total_list[0] callback.ScanProgress(used, 0, "Looking at " + fqn) def GetSpaceUsed(self, callback): total = [0] # See _WalkCallback above try: for d in self._GetDirectories(): os.path.walk(d, self._WalkCallback, (callback, total)) print("After looking in", d, "we have", total[0], "bytes") except pythoncom.error as exc: # This will be raised by the callback when the user selects 'cancel'. if exc.hresult != winerror.E_ABORT: raise # that's the documented error code! print("User cancelled the operation") return total[0] def Purge(self, amt_to_free, callback): print("Purging", amt_to_free, "bytes...") # we ignore amt_to_free - it is generally what we returned for # GetSpaceUsed try: for d in self._GetDirectories(): os.path.walk(d, self._WalkCallback, (callback, None)) except pythoncom.error as exc: # This will be raised by the callback when the user selects 'cancel'. if exc.hresult != winerror.E_ABORT: raise # that's the documented error code! print("User cancelled the operation") def ShowProperties(self, hwnd): raise COMException(hresult=winerror.E_NOTIMPL) def Deactivate(self): print("Deactivate called") return 0 def DllRegisterServer(): # Also need to register specially in: # HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches # See link at top of file. import winreg kn = r"Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\%s" % ( EmptyVolumeCache._reg_desc_, ) key = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, kn) winreg.SetValueEx(key, None, 0, winreg.REG_SZ, EmptyVolumeCache._reg_clsid_)
null