index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
9,572
asyncclick.types
convert
Convert the value to the correct type. This is not called if the value is ``None`` (the missing value). This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types. The ``param`` and ``ctx`` arguments may be ``None`` in certain situations, such as when converting prompt input. If the value cannot be converted, call :meth:`fail` with a descriptive message. :param value: The value to convert. :param param: The parameter that is using this type to convert its value. May be ``None``. :param ctx: The current context that arrived at this value. May be ``None``.
def convert( self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"] ) -> t.Any: """Convert the value to the correct type. This is not called if the value is ``None`` (the missing value). This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types. The ``param`` and ``ctx`` arguments may be ``None`` in certain situations, such as when converting prompt input. If the value cannot be converted, call :meth:`fail` with a descriptive message. :param value: The value to convert. :param param: The parameter that is using this type to convert its value. May be ``None``. :param ctx: The current context that arrived at this value. May be ``None``. """ return value
(self, value: Any, param: Optional[ForwardRef('Parameter')], ctx: Optional[ForwardRef('Context')]) -> Any
9,578
asyncclick.types
to_info_dict
Gather information that could be useful for a tool generating user-facing documentation. Use :meth:`click.Context.to_info_dict` to traverse the entire CLI structure. .. versionadded:: 8.0
import os import stat import sys import typing as t from datetime import datetime from gettext import gettext as _ from gettext import ngettext from ._compat import _get_argv_encoding from ._compat import open_stream from .exceptions import BadParameter from .utils import format_filename from .utils import LazyFile from .utils import safecall if t.TYPE_CHECKING: import typing_extensions as te from .core import Context from .core import Parameter from .shell_completion import CompletionItem class ParamType: """Represents the type of a parameter. Validates and converts values from the command line or Python into the correct type. To implement a custom type, subclass and implement at least the following: - The :attr:`name` class attribute must be set. - Calling an instance of the type with ``None`` must return ``None``. This is already implemented by default. - :meth:`convert` must convert string values to the correct type. - :meth:`convert` must accept values that are already the correct type. - It must be able to convert a value if the ``ctx`` and ``param`` arguments are ``None``. This can occur when converting prompt input. """ is_composite: t.ClassVar[bool] = False arity: t.ClassVar[int] = 1 #: the descriptive name of this type name: str #: if a list of this type is expected and the value is pulled from a #: string environment variable, this is what splits it up. `None` #: means any whitespace. For all parameters the general rule is that #: whitespace splits them up. The exception are paths and files which #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on #: Windows). envvar_list_splitter: t.ClassVar[t.Optional[str]] = None async def to_info_dict(self) -> t.Dict[str, t.Any]: """Gather information that could be useful for a tool generating user-facing documentation. Use :meth:`click.Context.to_info_dict` to traverse the entire CLI structure. .. versionadded:: 8.0 """ # The class name without the "ParamType" suffix. param_type = type(self).__name__.partition("ParamType")[0] param_type = param_type.partition("ParameterType")[0] # Custom subclasses might not remember to set a name. if hasattr(self, "name"): name = self.name else: name = param_type return {"param_type": param_type, "name": name} def __call__( self, value: t.Any, param: t.Optional["Parameter"] = None, ctx: t.Optional["Context"] = None, ) -> t.Any: if value is not None: return self.convert(value, param, ctx) def get_metavar(self, param: "Parameter") -> t.Optional[str]: """Returns the metavar default for this param if it provides one.""" def get_missing_message(self, param: "Parameter") -> t.Optional[str]: """Optionally might return extra information about a missing parameter. .. versionadded:: 2.0 """ def convert( self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"] ) -> t.Any: """Convert the value to the correct type. This is not called if the value is ``None`` (the missing value). This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types. The ``param`` and ``ctx`` arguments may be ``None`` in certain situations, such as when converting prompt input. If the value cannot be converted, call :meth:`fail` with a descriptive message. :param value: The value to convert. :param param: The parameter that is using this type to convert its value. May be ``None``. :param ctx: The current context that arrived at this value. May be ``None``. """ return value def split_envvar_value(self, rv: str) -> t.Sequence[str]: """Given a value from an environment variable this splits it up into small chunks depending on the defined envvar list splitter. If the splitter is set to `None`, which means that whitespace splits, then leading and trailing whitespace is ignored. Otherwise, leading and trailing splitters usually lead to empty items being included. """ return (rv or "").split(self.envvar_list_splitter) def fail( self, message: str, param: t.Optional["Parameter"] = None, ctx: t.Optional["Context"] = None, ) -> "t.NoReturn": """Helper method to fail with an invalid value message.""" raise BadParameter(message, ctx=ctx, param=param) def shell_complete( self, ctx: "Context", param: "Parameter", incomplete: str ) -> t.List["CompletionItem"]: """Return a list of :class:`~click.shell_completion.CompletionItem` objects for the incomplete value. Most types do not provide completions, but some do, and this allows custom types to provide custom completions as well. :param ctx: Invocation context for this command. :param param: The parameter that is requesting completion. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0 """ return []
(self) -> Dict[str, Any]
9,579
asyncclick.core
Parameter
A parameter to a command comes in two versions: they are either :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently not supported by design as some of the internals for parsing are intentionally not finalized. Some settings are supported by both options and arguments. :param param_decls: the parameter declarations for this option or argument. This is a list of flags or argument names. :param type: the type that should be used. Either a :class:`ParamType` or a Python type. The latter is converted into the former automatically if supported. :param required: controls if this is optional or not. :param default: the default value if omitted. This can also be a callable, in which case it's invoked when the default is needed without any arguments. :param callback: A function to further process or validate the value after type conversion. It is called as ``f(ctx, param, value)`` and must return the value. It is called for all sources, including prompts. :param nargs: the number of arguments to match. If not ``1`` the return value is a tuple instead of single value. The default for nargs is ``1`` (except if the type is a tuple, then it's the arity of the tuple). If ``nargs=-1``, all remaining parameters are collected. :param metavar: how the value is represented in the help page. :param expose_value: if this is `True` then the value is passed onwards to the command callback and stored on the context, otherwise it's skipped. :param is_eager: eager values are processed before non eager ones. This should not be set for arguments or it will inverse the order of processing. :param envvar: a string or list of strings that are environment variables that should be checked. :param shell_complete: A function that returns custom shell completions. Used instead of the param's type completion if given. Takes ``ctx, param, incomplete`` and must return a list of :class:`~click.shell_completion.CompletionItem` or a list of strings. .. versionchanged:: 8.0 ``process_value`` validates required parameters and bounded ``nargs``, and invokes the parameter callback before returning the value. This allows the callback to validate prompts. ``full_process_value`` is removed. .. versionchanged:: 8.0 ``autocompletion`` is renamed to ``shell_complete`` and has new semantics described above. The old name is deprecated and will be removed in 8.1, until then it will be wrapped to match the new requirements. .. versionchanged:: 8.0 For ``multiple=True, nargs>1``, the default must be a list of tuples. .. versionchanged:: 8.0 Setting a default is no longer required for ``nargs>1``, it will default to ``None``. ``multiple=True`` or ``nargs=-1`` will default to ``()``. .. versionchanged:: 7.1 Empty environment variables are ignored rather than taking the empty string value. This makes it possible for scripts to clear variables if they can't unset them. .. versionchanged:: 2.0 Changed signature for parameter callback to also be passed the parameter. The old callback format will still work, but it will raise a warning to give you a chance to migrate the code easier.
class Parameter: r"""A parameter to a command comes in two versions: they are either :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently not supported by design as some of the internals for parsing are intentionally not finalized. Some settings are supported by both options and arguments. :param param_decls: the parameter declarations for this option or argument. This is a list of flags or argument names. :param type: the type that should be used. Either a :class:`ParamType` or a Python type. The latter is converted into the former automatically if supported. :param required: controls if this is optional or not. :param default: the default value if omitted. This can also be a callable, in which case it's invoked when the default is needed without any arguments. :param callback: A function to further process or validate the value after type conversion. It is called as ``f(ctx, param, value)`` and must return the value. It is called for all sources, including prompts. :param nargs: the number of arguments to match. If not ``1`` the return value is a tuple instead of single value. The default for nargs is ``1`` (except if the type is a tuple, then it's the arity of the tuple). If ``nargs=-1``, all remaining parameters are collected. :param metavar: how the value is represented in the help page. :param expose_value: if this is `True` then the value is passed onwards to the command callback and stored on the context, otherwise it's skipped. :param is_eager: eager values are processed before non eager ones. This should not be set for arguments or it will inverse the order of processing. :param envvar: a string or list of strings that are environment variables that should be checked. :param shell_complete: A function that returns custom shell completions. Used instead of the param's type completion if given. Takes ``ctx, param, incomplete`` and must return a list of :class:`~click.shell_completion.CompletionItem` or a list of strings. .. versionchanged:: 8.0 ``process_value`` validates required parameters and bounded ``nargs``, and invokes the parameter callback before returning the value. This allows the callback to validate prompts. ``full_process_value`` is removed. .. versionchanged:: 8.0 ``autocompletion`` is renamed to ``shell_complete`` and has new semantics described above. The old name is deprecated and will be removed in 8.1, until then it will be wrapped to match the new requirements. .. versionchanged:: 8.0 For ``multiple=True, nargs>1``, the default must be a list of tuples. .. versionchanged:: 8.0 Setting a default is no longer required for ``nargs>1``, it will default to ``None``. ``multiple=True`` or ``nargs=-1`` will default to ``()``. .. versionchanged:: 7.1 Empty environment variables are ignored rather than taking the empty string value. This makes it possible for scripts to clear variables if they can't unset them. .. versionchanged:: 2.0 Changed signature for parameter callback to also be passed the parameter. The old callback format will still work, but it will raise a warning to give you a chance to migrate the code easier. """ param_type_name = "parameter" def __init__( self, param_decls: t.Optional[t.Sequence[str]] = None, type: t.Optional[t.Union[types.ParamType, t.Any]] = None, required: bool = False, default: t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]] = None, callback: t.Optional[t.Callable[[Context, "Parameter", t.Any], t.Any]] = None, nargs: t.Optional[int] = None, multiple: bool = False, metavar: t.Optional[str] = None, expose_value: bool = True, is_eager: bool = False, envvar: t.Optional[t.Union[str, t.Sequence[str]]] = None, shell_complete: t.Optional[ t.Callable[ [Context, "Parameter", str], t.Union[t.List["CompletionItem"], t.List[str]], ] ] = None, ) -> None: self.name: t.Optional[str] self.opts: t.List[str] self.secondary_opts: t.List[str] self.name, self.opts, self.secondary_opts = self._parse_decls( param_decls or (), expose_value ) self.type: types.ParamType = types.convert_type(type, default) # Default nargs to what the type tells us if we have that # information available. if nargs is None: if self.type.is_composite: nargs = self.type.arity else: nargs = 1 self.required = required self.callback = callback self.nargs = nargs self.multiple = multiple self.expose_value = expose_value self.default = default self.is_eager = is_eager self.metavar = metavar self.envvar = envvar self._custom_shell_complete = shell_complete if __debug__: if self.type.is_composite and nargs != self.type.arity: raise ValueError( f"'nargs' must be {self.type.arity} (or None) for" f" type {self.type!r}, but it was {nargs}." ) # Skip no default or callable default. check_default = default if not callable(default) else None if check_default is not None: if multiple: try: # Only check the first value against nargs. check_default = next(_check_iter(check_default), None) except TypeError: raise ValueError( "'default' must be a list when 'multiple' is true." ) from None # Can be None for multiple with empty default. if nargs != 1 and check_default is not None: try: _check_iter(check_default) except TypeError: if multiple: message = ( "'default' must be a list of lists when 'multiple' is" " true and 'nargs' != 1." ) else: message = "'default' must be a list when 'nargs' != 1." raise ValueError(message) from None if nargs > 1 and len(check_default) != nargs: subject = "item length" if multiple else "length" raise ValueError( f"'default' {subject} must match nargs={nargs}." ) async def to_info_dict(self) -> t.Dict[str, t.Any]: """Gather information that could be useful for a tool generating user-facing documentation. Use :meth:`click.Context.to_info_dict` to traverse the entire CLI structure. .. versionadded:: 8.0 """ return { "name": self.name, "param_type_name": self.param_type_name, "opts": self.opts, "secondary_opts": self.secondary_opts, "type": await self.type.to_info_dict(), "required": self.required, "nargs": self.nargs, "multiple": self.multiple, "default": self.default, "envvar": self.envvar, } def __repr__(self) -> str: return f"<{self.__class__.__name__} {self.name}>" def _parse_decls( self, decls: t.Sequence[str], expose_value: bool ) -> t.Tuple[t.Optional[str], t.List[str], t.List[str]]: raise NotImplementedError() @property def human_readable_name(self) -> str: """Returns the human readable name of this parameter. This is the same as the name for options, but the metavar for arguments. """ return self.name # type: ignore def make_metavar(self) -> str: if self.metavar is not None: return self.metavar metavar = self.type.get_metavar(self) if metavar is None: metavar = self.type.name.upper() if self.nargs != 1: metavar += "..." return metavar @t.overload def get_default( self, ctx: Context, call: "te.Literal[True]" = True ) -> t.Optional[t.Any]: ... @t.overload def get_default( self, ctx: Context, call: bool = ... ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]: ... def get_default( self, ctx: Context, call: bool = True ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]: """Get the default for the parameter. Tries :meth:`Context.lookup_default` first, then the local default. :param ctx: Current context. :param call: If the default is a callable, call it. Disable to return the callable instead. .. versionchanged:: 8.0.2 Type casting is no longer performed when getting a default. .. versionchanged:: 8.0.1 Type casting can fail in resilient parsing mode. Invalid defaults will not prevent showing help text. .. versionchanged:: 8.0 Looks at ``ctx.default_map`` first. .. versionchanged:: 8.0 Added the ``call`` parameter. """ value = ctx.lookup_default(self.name, call=False) # type: ignore if value is None: value = self.default if call and callable(value): value = value() return value def add_to_parser(self, parser: OptionParser, ctx: Context) -> None: raise NotImplementedError() def consume_value( self, ctx: Context, opts: t.Mapping[str, t.Any] ) -> t.Tuple[t.Any, ParameterSource]: value = opts.get(self.name) # type: ignore source = ParameterSource.COMMANDLINE if value is None: value = self.value_from_envvar(ctx) source = ParameterSource.ENVIRONMENT if value is None: value = ctx.lookup_default(self.name) # type: ignore source = ParameterSource.DEFAULT_MAP if value is None: value = self.get_default(ctx) source = ParameterSource.DEFAULT return value, source def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any: """Convert and validate a value against the option's :attr:`type`, :attr:`multiple`, and :attr:`nargs`. """ if value is None: return () if self.multiple or self.nargs == -1 else None def check_iter(value: t.Any) -> t.Iterator[t.Any]: try: return _check_iter(value) except TypeError: # This should only happen when passing in args manually, # the parser should construct an iterable when parsing # the command line. raise BadParameter( _("Value must be an iterable."), ctx=ctx, param=self ) from None if self.nargs == 1 or self.type.is_composite: def convert(value: t.Any) -> t.Any: return self.type(value, param=self, ctx=ctx) elif self.nargs == -1: def convert(value: t.Any) -> t.Any: # t.Tuple[t.Any, ...] return tuple(self.type(x, self, ctx) for x in check_iter(value)) else: # nargs > 1 def convert(value: t.Any) -> t.Any: # t.Tuple[t.Any, ...] value = tuple(check_iter(value)) if len(value) != self.nargs: raise BadParameter( ngettext( "Takes {nargs} values but 1 was given.", "Takes {nargs} values but {len} were given.", len(value), ).format(nargs=self.nargs, len=len(value)), ctx=ctx, param=self, ) return tuple(self.type(x, self, ctx) for x in value) if self.multiple: return tuple(convert(x) for x in check_iter(value)) return convert(value) def value_is_missing(self, value: t.Any) -> bool: if value is None: return True if (self.nargs != 1 or self.multiple) and value == (): return True return False def process_value(self, ctx: Context, value: t.Any) -> t.Any: value = self.type_cast_value(ctx, value) if self.required and self.value_is_missing(value): raise MissingParameter(ctx=ctx, param=self) if self.callback is not None: value = self.callback(ctx, self, value) return value def resolve_envvar_value(self, ctx: Context) -> t.Optional[str]: if self.envvar is None: return None if isinstance(self.envvar, str): rv = os.environ.get(self.envvar) if rv: return rv else: for envvar in self.envvar: rv = os.environ.get(envvar) if rv: return rv return None def value_from_envvar(self, ctx: Context) -> t.Optional[t.Any]: rv: t.Optional[t.Any] = self.resolve_envvar_value(ctx) if rv is not None and self.nargs != 1: rv = self.type.split_envvar_value(rv) return rv async def handle_parse_result( self, ctx: Context, opts: t.Mapping[str, t.Any], args: t.List[str] ) -> t.Tuple[t.Any, t.List[str]]: with augment_usage_errors(ctx, param=self): value, source = self.consume_value(ctx, opts) ctx.set_parameter_source(self.name, source) # type: ignore try: value = self.process_value(ctx, value) except Exception: if not ctx.resilient_parsing: raise value = None if self.expose_value: ctx.params[self.name] = value # type: ignore return value, args def get_help_record(self, ctx: Context) -> t.Optional[t.Tuple[str, str]]: pass def get_usage_pieces(self, ctx: Context) -> t.List[str]: return [] def get_error_hint(self, ctx: Context) -> str: """Get a stringified version of the param for use in error messages to indicate which param caused the error. """ hint_list = self.opts or [self.human_readable_name] return " / ".join(f"'{x}'" for x in hint_list) def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]: """Return a list of completions for the incomplete value. If a ``shell_complete`` function was given during init, it is used. Otherwise, the :attr:`type` :meth:`~click.types.ParamType.shell_complete` function is used. :param ctx: Invocation context for this command. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0 """ if self._custom_shell_complete is not None: results = self._custom_shell_complete(ctx, self, incomplete) if results and isinstance(results[0], str): from .shell_completion import CompletionItem results = [CompletionItem(c) for c in results] return t.cast(t.List["CompletionItem"], results) return self.type.shell_complete(ctx, self, incomplete)
(param_decls: Optional[Sequence[str]] = None, type: Union[asyncclick.types.ParamType, Any, NoneType] = None, required: bool = False, default: Union[Any, Callable[[], Any], NoneType] = None, callback: Optional[Callable[[asyncclick.core.Context, ForwardRef('Parameter'), Any], Any]] = None, nargs: Optional[int] = None, multiple: bool = False, metavar: Optional[str] = None, expose_value: bool = True, is_eager: bool = False, envvar: Union[Sequence[str], str, NoneType] = None, shell_complete: Optional[Callable[[asyncclick.core.Context, ForwardRef('Parameter'), str], Union[List[ForwardRef('CompletionItem')], List[str]]]] = None) -> None
9,580
asyncclick.core
__init__
null
def __init__( self, param_decls: t.Optional[t.Sequence[str]] = None, type: t.Optional[t.Union[types.ParamType, t.Any]] = None, required: bool = False, default: t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]] = None, callback: t.Optional[t.Callable[[Context, "Parameter", t.Any], t.Any]] = None, nargs: t.Optional[int] = None, multiple: bool = False, metavar: t.Optional[str] = None, expose_value: bool = True, is_eager: bool = False, envvar: t.Optional[t.Union[str, t.Sequence[str]]] = None, shell_complete: t.Optional[ t.Callable[ [Context, "Parameter", str], t.Union[t.List["CompletionItem"], t.List[str]], ] ] = None, ) -> None: self.name: t.Optional[str] self.opts: t.List[str] self.secondary_opts: t.List[str] self.name, self.opts, self.secondary_opts = self._parse_decls( param_decls or (), expose_value ) self.type: types.ParamType = types.convert_type(type, default) # Default nargs to what the type tells us if we have that # information available. if nargs is None: if self.type.is_composite: nargs = self.type.arity else: nargs = 1 self.required = required self.callback = callback self.nargs = nargs self.multiple = multiple self.expose_value = expose_value self.default = default self.is_eager = is_eager self.metavar = metavar self.envvar = envvar self._custom_shell_complete = shell_complete if __debug__: if self.type.is_composite and nargs != self.type.arity: raise ValueError( f"'nargs' must be {self.type.arity} (or None) for" f" type {self.type!r}, but it was {nargs}." ) # Skip no default or callable default. check_default = default if not callable(default) else None if check_default is not None: if multiple: try: # Only check the first value against nargs. check_default = next(_check_iter(check_default), None) except TypeError: raise ValueError( "'default' must be a list when 'multiple' is true." ) from None # Can be None for multiple with empty default. if nargs != 1 and check_default is not None: try: _check_iter(check_default) except TypeError: if multiple: message = ( "'default' must be a list of lists when 'multiple' is" " true and 'nargs' != 1." ) else: message = "'default' must be a list when 'nargs' != 1." raise ValueError(message) from None if nargs > 1 and len(check_default) != nargs: subject = "item length" if multiple else "length" raise ValueError( f"'default' {subject} must match nargs={nargs}." )
(self, param_decls: Optional[Sequence[str]] = None, type: Union[asyncclick.types.ParamType, Any, NoneType] = None, required: bool = False, default: Union[Any, Callable[[], Any], NoneType] = None, callback: Optional[Callable[[asyncclick.core.Context, ForwardRef('Parameter'), Any], Any]] = None, nargs: Optional[int] = None, multiple: bool = False, metavar: Optional[str] = None, expose_value: bool = True, is_eager: bool = False, envvar: Union[Sequence[str], str, NoneType] = None, shell_complete: Optional[Callable[[asyncclick.core.Context, ForwardRef('Parameter'), str], Union[List[ForwardRef('CompletionItem')], List[str]]]] = None) -> None
9,582
asyncclick.core
_parse_decls
null
def _parse_decls( self, decls: t.Sequence[str], expose_value: bool ) -> t.Tuple[t.Optional[str], t.List[str], t.List[str]]: raise NotImplementedError()
(self, decls: Sequence[str], expose_value: bool) -> Tuple[Optional[str], List[str], List[str]]
9,583
asyncclick.core
add_to_parser
null
def add_to_parser(self, parser: OptionParser, ctx: Context) -> None: raise NotImplementedError()
(self, parser: asyncclick.parser.OptionParser, ctx: asyncclick.core.Context) -> NoneType
9,598
asyncclick.types
Path
The ``Path`` type is similar to the :class:`File` type, but returns the filename instead of an open file. Various checks can be enabled to validate the type of file and permissions. :param exists: The file or directory needs to exist for the value to be valid. If this is not set to ``True``, and the file does not exist, then all further checks are silently skipped. :param file_okay: Allow a file as a value. :param dir_okay: Allow a directory as a value. :param readable: if true, a readable check is performed. :param writable: if true, a writable check is performed. :param executable: if true, an executable check is performed. :param resolve_path: Make the value absolute and resolve any symlinks. A ``~`` is not expanded, as this is supposed to be done by the shell only. :param allow_dash: Allow a single dash as a value, which indicates a standard stream (but does not open it). Use :func:`~click.open_file` to handle opening this value. :param path_type: Convert the incoming path value to this type. If ``None``, keep Python's default, which is ``str``. Useful to convert to :class:`pathlib.Path`. .. versionchanged:: 8.1 Added the ``executable`` parameter. .. versionchanged:: 8.0 Allow passing ``path_type=pathlib.Path``. .. versionchanged:: 6.0 Added the ``allow_dash`` parameter.
class Path(ParamType): """The ``Path`` type is similar to the :class:`File` type, but returns the filename instead of an open file. Various checks can be enabled to validate the type of file and permissions. :param exists: The file or directory needs to exist for the value to be valid. If this is not set to ``True``, and the file does not exist, then all further checks are silently skipped. :param file_okay: Allow a file as a value. :param dir_okay: Allow a directory as a value. :param readable: if true, a readable check is performed. :param writable: if true, a writable check is performed. :param executable: if true, an executable check is performed. :param resolve_path: Make the value absolute and resolve any symlinks. A ``~`` is not expanded, as this is supposed to be done by the shell only. :param allow_dash: Allow a single dash as a value, which indicates a standard stream (but does not open it). Use :func:`~click.open_file` to handle opening this value. :param path_type: Convert the incoming path value to this type. If ``None``, keep Python's default, which is ``str``. Useful to convert to :class:`pathlib.Path`. .. versionchanged:: 8.1 Added the ``executable`` parameter. .. versionchanged:: 8.0 Allow passing ``path_type=pathlib.Path``. .. versionchanged:: 6.0 Added the ``allow_dash`` parameter. """ envvar_list_splitter: t.ClassVar[str] = os.path.pathsep def __init__( self, exists: bool = False, file_okay: bool = True, dir_okay: bool = True, writable: bool = False, readable: bool = True, resolve_path: bool = False, allow_dash: bool = False, path_type: t.Optional[t.Type[t.Any]] = None, executable: bool = False, ): self.exists = exists self.file_okay = file_okay self.dir_okay = dir_okay self.readable = readable self.writable = writable self.executable = executable self.resolve_path = resolve_path self.allow_dash = allow_dash self.type = path_type if self.file_okay and not self.dir_okay: self.name: str = _("file") elif self.dir_okay and not self.file_okay: self.name = _("directory") else: self.name = _("path") async def to_info_dict(self) -> t.Dict[str, t.Any]: info_dict = await super().to_info_dict() info_dict.update( exists=self.exists, file_okay=self.file_okay, dir_okay=self.dir_okay, writable=self.writable, readable=self.readable, allow_dash=self.allow_dash, ) return info_dict def coerce_path_result( self, value: "t.Union[str, os.PathLike[str]]" ) -> "t.Union[str, bytes, os.PathLike[str]]": if self.type is not None and not isinstance(value, self.type): if self.type is str: return os.fsdecode(value) elif self.type is bytes: return os.fsencode(value) else: return t.cast("os.PathLike[str]", self.type(value)) return value def convert( self, value: "t.Union[str, os.PathLike[str]]", param: t.Optional["Parameter"], ctx: t.Optional["Context"], ) -> "t.Union[str, bytes, os.PathLike[str]]": rv = value is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-") if not is_dash: if self.resolve_path: # os.path.realpath doesn't resolve symlinks on Windows # until Python 3.8. Use pathlib for now. import pathlib rv = os.fsdecode(pathlib.Path(rv).resolve()) try: st = os.stat(rv) except OSError: if not self.exists: return self.coerce_path_result(rv) self.fail( _("{name} {filename!r} does not exist.").format( name=self.name.title(), filename=format_filename(value) ), param, ctx, ) if not self.file_okay and stat.S_ISREG(st.st_mode): self.fail( _("{name} {filename!r} is a file.").format( name=self.name.title(), filename=format_filename(value) ), param, ctx, ) if not self.dir_okay and stat.S_ISDIR(st.st_mode): self.fail( _("{name} '{filename}' is a directory.").format( name=self.name.title(), filename=format_filename(value) ), param, ctx, ) if self.readable and not os.access(rv, os.R_OK): self.fail( _("{name} {filename!r} is not readable.").format( name=self.name.title(), filename=format_filename(value) ), param, ctx, ) if self.writable and not os.access(rv, os.W_OK): self.fail( _("{name} {filename!r} is not writable.").format( name=self.name.title(), filename=format_filename(value) ), param, ctx, ) if self.executable and not os.access(value, os.X_OK): self.fail( _("{name} {filename!r} is not executable.").format( name=self.name.title(), filename=format_filename(value) ), param, ctx, ) return self.coerce_path_result(rv) def shell_complete( self, ctx: "Context", param: "Parameter", incomplete: str ) -> t.List["CompletionItem"]: """Return a special completion marker that tells the completion system to use the shell to provide path completions for only directories or any paths. :param ctx: Invocation context for this command. :param param: The parameter that is requesting completion. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0 """ from .shell_completion import CompletionItem type = "dir" if self.dir_okay and not self.file_okay else "file" return [CompletionItem(incomplete, type=type)]
(exists: bool = False, file_okay: bool = True, dir_okay: bool = True, writable: bool = False, readable: bool = True, resolve_path: bool = False, allow_dash: bool = False, path_type: Optional[Type[Any]] = None, executable: bool = False)
9,600
asyncclick.types
__init__
null
def __init__( self, exists: bool = False, file_okay: bool = True, dir_okay: bool = True, writable: bool = False, readable: bool = True, resolve_path: bool = False, allow_dash: bool = False, path_type: t.Optional[t.Type[t.Any]] = None, executable: bool = False, ): self.exists = exists self.file_okay = file_okay self.dir_okay = dir_okay self.readable = readable self.writable = writable self.executable = executable self.resolve_path = resolve_path self.allow_dash = allow_dash self.type = path_type if self.file_okay and not self.dir_okay: self.name: str = _("file") elif self.dir_okay and not self.file_okay: self.name = _("directory") else: self.name = _("path")
(self, exists: bool = False, file_okay: bool = True, dir_okay: bool = True, writable: bool = False, readable: bool = True, resolve_path: bool = False, allow_dash: bool = False, path_type: Optional[Type[Any]] = None, executable: bool = False)
9,601
asyncclick.types
coerce_path_result
null
def coerce_path_result( self, value: "t.Union[str, os.PathLike[str]]" ) -> "t.Union[str, bytes, os.PathLike[str]]": if self.type is not None and not isinstance(value, self.type): if self.type is str: return os.fsdecode(value) elif self.type is bytes: return os.fsencode(value) else: return t.cast("os.PathLike[str]", self.type(value)) return value
(self, value: Union[str, os.PathLike[str]]) -> Union[str, bytes, os.PathLike[str]]
9,602
asyncclick.types
convert
null
def convert( self, value: "t.Union[str, os.PathLike[str]]", param: t.Optional["Parameter"], ctx: t.Optional["Context"], ) -> "t.Union[str, bytes, os.PathLike[str]]": rv = value is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-") if not is_dash: if self.resolve_path: # os.path.realpath doesn't resolve symlinks on Windows # until Python 3.8. Use pathlib for now. import pathlib rv = os.fsdecode(pathlib.Path(rv).resolve()) try: st = os.stat(rv) except OSError: if not self.exists: return self.coerce_path_result(rv) self.fail( _("{name} {filename!r} does not exist.").format( name=self.name.title(), filename=format_filename(value) ), param, ctx, ) if not self.file_okay and stat.S_ISREG(st.st_mode): self.fail( _("{name} {filename!r} is a file.").format( name=self.name.title(), filename=format_filename(value) ), param, ctx, ) if not self.dir_okay and stat.S_ISDIR(st.st_mode): self.fail( _("{name} '{filename}' is a directory.").format( name=self.name.title(), filename=format_filename(value) ), param, ctx, ) if self.readable and not os.access(rv, os.R_OK): self.fail( _("{name} {filename!r} is not readable.").format( name=self.name.title(), filename=format_filename(value) ), param, ctx, ) if self.writable and not os.access(rv, os.W_OK): self.fail( _("{name} {filename!r} is not writable.").format( name=self.name.title(), filename=format_filename(value) ), param, ctx, ) if self.executable and not os.access(value, os.X_OK): self.fail( _("{name} {filename!r} is not executable.").format( name=self.name.title(), filename=format_filename(value) ), param, ctx, ) return self.coerce_path_result(rv)
(self, value: 't.Union[str, os.PathLike[str]]', param: Optional[ForwardRef('Parameter')], ctx: Optional[ForwardRef('Context')]) -> 't.Union[str, bytes, os.PathLike[str]]'
9,606
asyncclick.types
shell_complete
Return a special completion marker that tells the completion system to use the shell to provide path completions for only directories or any paths. :param ctx: Invocation context for this command. :param param: The parameter that is requesting completion. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0
def shell_complete( self, ctx: "Context", param: "Parameter", incomplete: str ) -> t.List["CompletionItem"]: """Return a special completion marker that tells the completion system to use the shell to provide path completions for only directories or any paths. :param ctx: Invocation context for this command. :param param: The parameter that is requesting completion. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0 """ from .shell_completion import CompletionItem type = "dir" if self.dir_okay and not self.file_okay else "file" return [CompletionItem(incomplete, type=type)]
(self, ctx: 'Context', param: 'Parameter', incomplete: str) -> List[ForwardRef('CompletionItem')]
9,609
asyncclick.types
Tuple
The default behavior of Click is to apply a type on a value directly. This works well in most cases, except for when `nargs` is set to a fixed count and different types should be used for different items. In this case the :class:`Tuple` type can be used. This type can only be used if `nargs` is set to a fixed number. For more information see :ref:`tuple-type`. This can be selected by using a Python tuple literal as a type. :param types: a list of types that should be used for the tuple items.
class Tuple(CompositeParamType): """The default behavior of Click is to apply a type on a value directly. This works well in most cases, except for when `nargs` is set to a fixed count and different types should be used for different items. In this case the :class:`Tuple` type can be used. This type can only be used if `nargs` is set to a fixed number. For more information see :ref:`tuple-type`. This can be selected by using a Python tuple literal as a type. :param types: a list of types that should be used for the tuple items. """ def __init__(self, types: t.Sequence[t.Union[t.Type[t.Any], ParamType]]) -> None: self.types: t.Sequence[ParamType] = [convert_type(ty) for ty in types] async def to_info_dict(self) -> t.Dict[str, t.Any]: info_dict = await super().to_info_dict() info_dict["types"] = [await t.to_info_dict() for t in self.types] return info_dict @property def name(self) -> str: # type: ignore return f"<{' '.join(ty.name for ty in self.types)}>" @property def arity(self) -> int: # type: ignore return len(self.types) def convert( self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"] ) -> t.Any: len_type = len(self.types) len_value = len(value) if len_value != len_type: self.fail( ngettext( "{len_type} values are required, but {len_value} was given.", "{len_type} values are required, but {len_value} were given.", len_value, ).format(len_type=len_type, len_value=len_value), param=param, ctx=ctx, ) return tuple(ty(x, param, ctx) for ty, x in zip(self.types, value))
(types: Sequence[Union[Type[Any], asyncclick.types.ParamType]]) -> None
9,611
asyncclick.types
__init__
null
def __init__(self, types: t.Sequence[t.Union[t.Type[t.Any], ParamType]]) -> None: self.types: t.Sequence[ParamType] = [convert_type(ty) for ty in types]
(self, types: Sequence[Union[Type[Any], asyncclick.types.ParamType]]) -> NoneType
9,612
asyncclick.types
convert
null
def convert( self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"] ) -> t.Any: len_type = len(self.types) len_value = len(value) if len_value != len_type: self.fail( ngettext( "{len_type} values are required, but {len_value} was given.", "{len_type} values are required, but {len_value} were given.", len_value, ).format(len_type=len_type, len_value=len_value), param=param, ctx=ctx, ) return tuple(ty(x, param, ctx) for ty, x in zip(self.types, value))
(self, value: Any, param: Optional[ForwardRef('Parameter')], ctx: Optional[ForwardRef('Context')]) -> Any
9,619
asyncclick.exceptions
UsageError
An internal exception that signals a usage error. This typically aborts any further handling. :param message: the error message to display. :param ctx: optionally the context that caused this error. Click will fill in the context automatically in some situations.
class UsageError(ClickException): """An internal exception that signals a usage error. This typically aborts any further handling. :param message: the error message to display. :param ctx: optionally the context that caused this error. Click will fill in the context automatically in some situations. """ exit_code = 2 def __init__(self, message: str, ctx: t.Optional["Context"] = None) -> None: super().__init__(message) self.ctx = ctx self.cmd: t.Optional["Command"] = self.ctx.command if self.ctx else None def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None: if file is None: file = get_text_stderr() color = None hint = "" if ( self.ctx is not None and self.ctx.command.get_help_option(self.ctx) is not None ): hint = _("Try '{command} {option}' for help.").format( command=self.ctx.command_path, option=self.ctx.help_option_names[0] ) hint = f"{hint}\n" if self.ctx is not None: color = self.ctx.color echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color) echo( _("Error: {message}").format(message=self.format_message()), file=file, color=color, )
(message: str, ctx: Optional[ForwardRef('Context')] = None) -> None
9,625
asyncclick.decorators
argument
Attaches an argument to the command. All positional arguments are passed as parameter declarations to :class:`Argument`; all keyword arguments are forwarded unchanged (except ``cls``). This is equivalent to creating an :class:`Argument` instance manually and attaching it to the :attr:`Command.params` list. For the default argument class, refer to :class:`Argument` and :class:`Parameter` for descriptions of parameters. :param cls: the argument class to instantiate. This defaults to :class:`Argument`. :param param_decls: Passed as positional arguments to the constructor of ``cls``. :param attrs: Passed as keyword arguments to the constructor of ``cls``.
def argument( *param_decls: str, cls: t.Optional[t.Type[Argument]] = None, **attrs: t.Any ) -> t.Callable[[FC], FC]: """Attaches an argument to the command. All positional arguments are passed as parameter declarations to :class:`Argument`; all keyword arguments are forwarded unchanged (except ``cls``). This is equivalent to creating an :class:`Argument` instance manually and attaching it to the :attr:`Command.params` list. For the default argument class, refer to :class:`Argument` and :class:`Parameter` for descriptions of parameters. :param cls: the argument class to instantiate. This defaults to :class:`Argument`. :param param_decls: Passed as positional arguments to the constructor of ``cls``. :param attrs: Passed as keyword arguments to the constructor of ``cls``. """ if cls is None: cls = Argument def decorator(f: FC) -> FC: _param_memo(f, cls(param_decls, **attrs)) return f return decorator
(*param_decls: str, cls: Optional[Type[asyncclick.core.Argument]] = None, **attrs: Any) -> Callable[[~FC], ~FC]
9,626
asyncclick.termui
clear
Clears the terminal screen. This will have the effect of clearing the whole visible space of the terminal and moving the cursor to the top left. This does not do anything if not connected to a terminal. .. versionadded:: 2.0
def clear() -> None: """Clears the terminal screen. This will have the effect of clearing the whole visible space of the terminal and moving the cursor to the top left. This does not do anything if not connected to a terminal. .. versionadded:: 2.0 """ if not isatty(sys.stdout): return # ANSI escape \033[2J clears the screen, \033[1;1H moves the cursor echo("\033[2J\033[1;1H", nl=False)
() -> NoneType
9,627
asyncclick.decorators
command
Creates a new :class:`Command` and uses the decorated function as callback. This will also automatically attach all decorated :func:`option`\s and :func:`argument`\s as parameters to the command. The name of the command defaults to the name of the function with underscores replaced by dashes. If you want to change that, you can pass the intended name as the first argument. All keyword arguments are forwarded to the underlying command class. For the ``params`` argument, any decorated params are appended to the end of the list. Once decorated the function turns into a :class:`Command` instance that can be invoked as a command line utility or be attached to a command :class:`Group`. :param name: the name of the command. This defaults to the function name with underscores replaced by dashes. :param cls: the command class to instantiate. This defaults to :class:`Command`. .. versionchanged:: 8.1 This decorator can be applied without parentheses. .. versionchanged:: 8.1 The ``params`` argument can be used. Decorated params are appended to the end of the list.
def command( name: t.Union[t.Optional[str], _AnyCallable] = None, cls: t.Optional[t.Type[CmdType]] = None, **attrs: t.Any, ) -> t.Union[Command, t.Callable[[_AnyCallable], t.Union[Command, CmdType]]]: r"""Creates a new :class:`Command` and uses the decorated function as callback. This will also automatically attach all decorated :func:`option`\s and :func:`argument`\s as parameters to the command. The name of the command defaults to the name of the function with underscores replaced by dashes. If you want to change that, you can pass the intended name as the first argument. All keyword arguments are forwarded to the underlying command class. For the ``params`` argument, any decorated params are appended to the end of the list. Once decorated the function turns into a :class:`Command` instance that can be invoked as a command line utility or be attached to a command :class:`Group`. :param name: the name of the command. This defaults to the function name with underscores replaced by dashes. :param cls: the command class to instantiate. This defaults to :class:`Command`. .. versionchanged:: 8.1 This decorator can be applied without parentheses. .. versionchanged:: 8.1 The ``params`` argument can be used. Decorated params are appended to the end of the list. """ func: t.Optional[t.Callable[[_AnyCallable], t.Any]] = None if callable(name): func = name name = None assert cls is None, "Use 'command(cls=cls)(callable)' to specify a class." assert not attrs, "Use 'command(**kwargs)(callable)' to provide arguments." if cls is None: cls = t.cast(t.Type[CmdType], Command) def decorator(f: _AnyCallable) -> CmdType: if isinstance(f, Command): raise TypeError("Attempted to convert a callback into a command twice.") attr_params = attrs.pop("params", None) params = attr_params if attr_params is not None else [] try: decorator_params = f.__click_params__ # type: ignore except AttributeError: pass else: del f.__click_params__ # type: ignore params.extend(reversed(decorator_params)) if attrs.get("help") is None: attrs["help"] = f.__doc__ if t.TYPE_CHECKING: assert cls is not None assert not callable(name) cmd = cls( name=name or f.__name__.lower().replace("_", "-"), callback=f, params=params, **attrs, ) cmd.__doc__ = f.__doc__ return cmd if func is not None: return decorator(func) return decorator
(name: Union[str, NoneType, Callable[..., Any]] = None, cls: Optional[Type[~CmdType]] = None, **attrs: Any) -> Union[asyncclick.core.Command, Callable[[Callable[..., Any]], Union[asyncclick.core.Command, ~CmdType]]]
9,628
asyncclick.termui
confirm
Prompts for confirmation (yes/no question). If the user aborts the input by sending a interrupt signal this function will catch it and raise a :exc:`Abort` exception. :param text: the question to ask. :param default: The default value to use when no input is given. If ``None``, repeat until input is given. :param abort: if this is set to `True` a negative answer aborts the exception by raising :exc:`Abort`. :param prompt_suffix: a suffix that should be added to the prompt. :param show_default: shows or hides the default value in the prompt. :param err: if set to true the file defaults to ``stderr`` instead of ``stdout``, the same as with echo. .. versionchanged:: 8.0 Repeat until input is given if ``default`` is ``None``. .. versionadded:: 4.0 Added the ``err`` parameter.
def confirm( text: str, default: t.Optional[bool] = False, abort: bool = False, prompt_suffix: str = ": ", show_default: bool = True, err: bool = False, ) -> bool: """Prompts for confirmation (yes/no question). If the user aborts the input by sending a interrupt signal this function will catch it and raise a :exc:`Abort` exception. :param text: the question to ask. :param default: The default value to use when no input is given. If ``None``, repeat until input is given. :param abort: if this is set to `True` a negative answer aborts the exception by raising :exc:`Abort`. :param prompt_suffix: a suffix that should be added to the prompt. :param show_default: shows or hides the default value in the prompt. :param err: if set to true the file defaults to ``stderr`` instead of ``stdout``, the same as with echo. .. versionchanged:: 8.0 Repeat until input is given if ``default`` is ``None``. .. versionadded:: 4.0 Added the ``err`` parameter. """ prompt = _build_prompt( text, prompt_suffix, show_default, "y/n" if default is None else ("Y/n" if default else "y/N"), ) while True: try: # Write the prompt separately so that we get nice # coloring through colorama on Windows echo(prompt.rstrip(" "), nl=False, err=err) # Echo a space to stdout to work around an issue where # readline causes backspace to clear the whole line. value = visible_prompt_func(" ").lower().strip() except (KeyboardInterrupt, EOFError): raise Abort() from None if value in ("y", "yes"): rv = True elif value in ("n", "no"): rv = False elif default is not None and value == "": rv = default else: echo(_("Error: invalid input"), err=err) continue break if abort and not rv: raise Abort() return rv
(text: str, default: Optional[bool] = False, abort: bool = False, prompt_suffix: str = ': ', show_default: bool = True, err: bool = False) -> bool
9,629
asyncclick.decorators
confirmation_option
Add a ``--yes`` option which shows a prompt before continuing if not passed. If the prompt is declined, the program will exit. :param param_decls: One or more option names. Defaults to the single value ``"--yes"``. :param kwargs: Extra arguments are passed to :func:`option`.
def confirmation_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]: """Add a ``--yes`` option which shows a prompt before continuing if not passed. If the prompt is declined, the program will exit. :param param_decls: One or more option names. Defaults to the single value ``"--yes"``. :param kwargs: Extra arguments are passed to :func:`option`. """ def callback(ctx: Context, param: Parameter, value: bool) -> None: if not value: ctx.abort() if not param_decls: param_decls = ("--yes",) kwargs.setdefault("is_flag", True) kwargs.setdefault("callback", callback) kwargs.setdefault("expose_value", False) kwargs.setdefault("prompt", "Do you want to continue?") kwargs.setdefault("help", "Confirm the action without prompting.") return option(*param_decls, **kwargs)
(*param_decls: str, **kwargs: Any) -> Callable[[~FC], ~FC]
9,632
asyncclick.utils
echo
Print a message and newline to stdout or a file. This should be used instead of :func:`print` because it provides better support for different data, files, and environments. Compared to :func:`print`, this does the following: - Ensures that the output encoding is not misconfigured on Linux. - Supports Unicode in the Windows console. - Supports writing to binary outputs, and supports writing bytes to text outputs. - Supports colors and styles on Windows. - Removes ANSI color and style codes if the output does not look like an interactive terminal. - Always flushes the output. :param message: The string or bytes to output. Other objects are converted to strings. :param file: The file to write to. Defaults to ``stdout``. :param err: Write to ``stderr`` instead of ``stdout``. :param nl: Print a newline after the message. Enabled by default. :param color: Force showing or hiding colors and other styles. By default Click will remove color if the output does not look like an interactive terminal. .. versionchanged:: 6.0 Support Unicode output on the Windows console. Click does not modify ``sys.stdout``, so ``sys.stdout.write()`` and ``print()`` will still not support Unicode. .. versionchanged:: 4.0 Added the ``color`` parameter. .. versionadded:: 3.0 Added the ``err`` parameter. .. versionchanged:: 2.0 Support colors on Windows if colorama is installed.
def echo( message: t.Optional[t.Any] = None, file: t.Optional[t.IO[t.Any]] = None, nl: bool = True, err: bool = False, color: t.Optional[bool] = None, ) -> None: """Print a message and newline to stdout or a file. This should be used instead of :func:`print` because it provides better support for different data, files, and environments. Compared to :func:`print`, this does the following: - Ensures that the output encoding is not misconfigured on Linux. - Supports Unicode in the Windows console. - Supports writing to binary outputs, and supports writing bytes to text outputs. - Supports colors and styles on Windows. - Removes ANSI color and style codes if the output does not look like an interactive terminal. - Always flushes the output. :param message: The string or bytes to output. Other objects are converted to strings. :param file: The file to write to. Defaults to ``stdout``. :param err: Write to ``stderr`` instead of ``stdout``. :param nl: Print a newline after the message. Enabled by default. :param color: Force showing or hiding colors and other styles. By default Click will remove color if the output does not look like an interactive terminal. .. versionchanged:: 6.0 Support Unicode output on the Windows console. Click does not modify ``sys.stdout``, so ``sys.stdout.write()`` and ``print()`` will still not support Unicode. .. versionchanged:: 4.0 Added the ``color`` parameter. .. versionadded:: 3.0 Added the ``err`` parameter. .. versionchanged:: 2.0 Support colors on Windows if colorama is installed. """ if file is None: if err: file = _default_text_stderr() else: file = _default_text_stdout() # There are no standard streams attached to write to. For example, # pythonw on Windows. if file is None: return # Convert non bytes/text into the native string type. if message is not None and not isinstance(message, (str, bytes, bytearray)): out: t.Optional[t.Union[str, bytes]] = str(message) else: out = message if nl: out = out or "" if isinstance(out, str): out += "\n" else: out += b"\n" if not out: file.flush() return # If there is a message and the value looks like bytes, we manually # need to find the binary stream and write the message in there. # This is done separately so that most stream types will work as you # would expect. Eg: you can write to StringIO for other cases. if isinstance(out, (bytes, bytearray)): binary_file = _find_binary_writer(file) if binary_file is not None: file.flush() binary_file.write(out) binary_file.flush() return # ANSI style code support. For no message or bytes, nothing happens. # When outputting to a file instead of a terminal, strip codes. else: color = resolve_color_default(color) if should_strip_ansi(file, color): out = strip_ansi(out) elif WIN: if auto_wrap_for_ansi is not None: file = auto_wrap_for_ansi(file) # type: ignore elif not color: out = strip_ansi(out) file.write(out) # type: ignore file.flush()
(message: Optional[Any] = None, file: Optional[IO[Any]] = None, nl: bool = True, err: bool = False, color: Optional[bool] = None) -> NoneType
9,633
asyncclick.termui
echo_via_pager
This function takes a text and shows it via an environment specific pager on stdout. .. versionchanged:: 3.0 Added the `color` flag. :param text_or_generator: the text to page, or alternatively, a generator emitting the text to page. :param color: controls if the pager supports ANSI colors or not. The default is autodetection.
def echo_via_pager( text_or_generator: t.Union[t.Iterable[str], t.Callable[[], t.Iterable[str]], str], color: t.Optional[bool] = None, ) -> None: """This function takes a text and shows it via an environment specific pager on stdout. .. versionchanged:: 3.0 Added the `color` flag. :param text_or_generator: the text to page, or alternatively, a generator emitting the text to page. :param color: controls if the pager supports ANSI colors or not. The default is autodetection. """ color = resolve_color_default(color) if inspect.isgeneratorfunction(text_or_generator): i = t.cast(t.Callable[[], t.Iterable[str]], text_or_generator)() elif isinstance(text_or_generator, str): i = [text_or_generator] else: i = iter(t.cast(t.Iterable[str], text_or_generator)) # convert every element of i to a text type if necessary text_generator = (el if isinstance(el, str) else str(el) for el in i) from ._termui_impl import pager return pager(itertools.chain(text_generator, "\n"), color)
(text_or_generator: Union[Iterable[str], Callable[[], Iterable[str]], str], color: Optional[bool] = None) -> NoneType
9,634
asyncclick.termui
edit
Edits the given text in the defined editor. If an editor is given (should be the full path to the executable but the regular operating system search path is used for finding the executable) it overrides the detected editor. Optionally, some environment variables can be used. If the editor is closed without changes, `None` is returned. In case a file is edited directly the return value is always `None` and `require_save` and `extension` are ignored. If the editor cannot be opened a :exc:`UsageError` is raised. Note for Windows: to simplify cross-platform usage, the newlines are automatically converted from POSIX to Windows and vice versa. As such, the message here will have ``\n`` as newline markers. :param text: the text to edit. :param editor: optionally the editor to use. Defaults to automatic detection. :param env: environment variables to forward to the editor. :param require_save: if this is true, then not saving in the editor will make the return value become `None`. :param extension: the extension to tell the editor about. This defaults to `.txt` but changing this might change syntax highlighting. :param filename: if provided it will edit this file instead of the provided text contents. It will not use a temporary file as an indirection in that case.
def edit( text: t.Optional[t.AnyStr] = None, editor: t.Optional[str] = None, env: t.Optional[t.Mapping[str, str]] = None, require_save: bool = True, extension: str = ".txt", filename: t.Optional[str] = None, ) -> t.Optional[t.AnyStr]: r"""Edits the given text in the defined editor. If an editor is given (should be the full path to the executable but the regular operating system search path is used for finding the executable) it overrides the detected editor. Optionally, some environment variables can be used. If the editor is closed without changes, `None` is returned. In case a file is edited directly the return value is always `None` and `require_save` and `extension` are ignored. If the editor cannot be opened a :exc:`UsageError` is raised. Note for Windows: to simplify cross-platform usage, the newlines are automatically converted from POSIX to Windows and vice versa. As such, the message here will have ``\n`` as newline markers. :param text: the text to edit. :param editor: optionally the editor to use. Defaults to automatic detection. :param env: environment variables to forward to the editor. :param require_save: if this is true, then not saving in the editor will make the return value become `None`. :param extension: the extension to tell the editor about. This defaults to `.txt` but changing this might change syntax highlighting. :param filename: if provided it will edit this file instead of the provided text contents. It will not use a temporary file as an indirection in that case. """ from ._termui_impl import Editor ed = Editor(editor=editor, env=env, require_save=require_save, extension=extension) if filename is None: return ed.edit(text) ed.edit_file(filename) return None
(text: Optional[~AnyStr] = None, editor: Optional[str] = None, env: Optional[Mapping[str, str]] = None, require_save: bool = True, extension: str = '.txt', filename: Optional[str] = None) -> Optional[~AnyStr]
9,636
asyncclick.utils
format_filename
Format a filename as a string for display. Ensures the filename can be displayed by replacing any invalid bytes or surrogate escapes in the name with the replacement character ``�``. Invalid bytes or surrogate escapes will raise an error when written to a stream with ``errors="strict". This will typically happen with ``stdout`` when the locale is something like ``en_GB.UTF-8``. Many scenarios *are* safe to write surrogates though, due to PEP 538 and PEP 540, including: - Writing to ``stderr``, which uses ``errors="backslashreplace"``. - The system has ``LANG=C.UTF-8``, ``C``, or ``POSIX``. Python opens stdout and stderr with ``errors="surrogateescape"``. - None of ``LANG/LC_*`` are set. Python assumes ``LANG=C.UTF-8``. - Python is started in UTF-8 mode with ``PYTHONUTF8=1`` or ``-X utf8``. Python opens stdout and stderr with ``errors="surrogateescape"``. :param filename: formats a filename for UI display. This will also convert the filename into unicode without failing. :param shorten: this optionally shortens the filename to strip of the path that leads up to it.
def format_filename( filename: "t.Union[str, bytes, os.PathLike[str], os.PathLike[bytes]]", shorten: bool = False, ) -> str: """Format a filename as a string for display. Ensures the filename can be displayed by replacing any invalid bytes or surrogate escapes in the name with the replacement character ``�``. Invalid bytes or surrogate escapes will raise an error when written to a stream with ``errors="strict". This will typically happen with ``stdout`` when the locale is something like ``en_GB.UTF-8``. Many scenarios *are* safe to write surrogates though, due to PEP 538 and PEP 540, including: - Writing to ``stderr``, which uses ``errors="backslashreplace"``. - The system has ``LANG=C.UTF-8``, ``C``, or ``POSIX``. Python opens stdout and stderr with ``errors="surrogateescape"``. - None of ``LANG/LC_*`` are set. Python assumes ``LANG=C.UTF-8``. - Python is started in UTF-8 mode with ``PYTHONUTF8=1`` or ``-X utf8``. Python opens stdout and stderr with ``errors="surrogateescape"``. :param filename: formats a filename for UI display. This will also convert the filename into unicode without failing. :param shorten: this optionally shortens the filename to strip of the path that leads up to it. """ if shorten: filename = os.path.basename(filename) else: filename = os.fspath(filename) if isinstance(filename, bytes): filename = filename.decode(sys.getfilesystemencoding(), "replace") else: filename = filename.encode("utf-8", "surrogateescape").decode( "utf-8", "replace" ) return filename
(filename: Union[str, bytes, os.PathLike[str], os.PathLike[bytes]], shorten: bool = False) -> str
9,638
asyncclick.utils
get_app_dir
Returns the config folder for the application. The default behavior is to return whatever is most appropriate for the operating system. To give you an idea, for an app called ``"Foo Bar"``, something like the following folders could be returned: Mac OS X: ``~/Library/Application Support/Foo Bar`` Mac OS X (POSIX): ``~/.foo-bar`` Unix: ``~/.config/foo-bar`` Unix (POSIX): ``~/.foo-bar`` Windows (roaming): ``C:\Users\<user>\AppData\Roaming\Foo Bar`` Windows (not roaming): ``C:\Users\<user>\AppData\Local\Foo Bar`` .. versionadded:: 2.0 :param app_name: the application name. This should be properly capitalized and can contain whitespace. :param roaming: controls if the folder should be roaming or not on Windows. Has no effect otherwise. :param force_posix: if this is set to `True` then on any POSIX system the folder will be stored in the home folder with a leading dot instead of the XDG config home or darwin's application support folder.
def get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str: r"""Returns the config folder for the application. The default behavior is to return whatever is most appropriate for the operating system. To give you an idea, for an app called ``"Foo Bar"``, something like the following folders could be returned: Mac OS X: ``~/Library/Application Support/Foo Bar`` Mac OS X (POSIX): ``~/.foo-bar`` Unix: ``~/.config/foo-bar`` Unix (POSIX): ``~/.foo-bar`` Windows (roaming): ``C:\Users\<user>\AppData\Roaming\Foo Bar`` Windows (not roaming): ``C:\Users\<user>\AppData\Local\Foo Bar`` .. versionadded:: 2.0 :param app_name: the application name. This should be properly capitalized and can contain whitespace. :param roaming: controls if the folder should be roaming or not on Windows. Has no effect otherwise. :param force_posix: if this is set to `True` then on any POSIX system the folder will be stored in the home folder with a leading dot instead of the XDG config home or darwin's application support folder. """ if WIN: key = "APPDATA" if roaming else "LOCALAPPDATA" folder = os.environ.get(key) if folder is None: folder = os.path.expanduser("~") return os.path.join(folder, app_name) if force_posix: return os.path.join(os.path.expanduser(f"~/.{_posixify(app_name)}")) if sys.platform == "darwin": return os.path.join( os.path.expanduser("~/Library/Application Support"), app_name ) return os.path.join( os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config")), _posixify(app_name), )
(app_name: str, roaming: bool = True, force_posix: bool = False) -> str
9,639
asyncclick.utils
get_binary_stream
Returns a system stream for byte processing. :param name: the name of the stream to open. Valid names are ``'stdin'``, ``'stdout'`` and ``'stderr'``
def get_binary_stream(name: "te.Literal['stdin', 'stdout', 'stderr']") -> t.BinaryIO: """Returns a system stream for byte processing. :param name: the name of the stream to open. Valid names are ``'stdin'``, ``'stdout'`` and ``'stderr'`` """ opener = binary_streams.get(name) if opener is None: raise TypeError(f"Unknown standard stream '{name}'") return opener()
(name: "te.Literal['stdin', 'stdout', 'stderr']") -> <class 'BinaryIO'>
9,640
asyncclick.globals
get_current_context
Returns the current click context. This can be used as a way to access the current context object from anywhere. This is a more implicit alternative to the :func:`pass_context` decorator. This function is primarily useful for helpers such as :func:`echo` which might be interested in changing its behavior based on the current context. To push the current context, :meth:`Context.scope` can be used. .. versionadded:: 5.0 :param silent: if set to `True` the return value is `None` if no context is available. The default behavior is to raise a :exc:`RuntimeError`.
def get_current_context(silent: bool = False) -> t.Optional["Context"]: """Returns the current click context. This can be used as a way to access the current context object from anywhere. This is a more implicit alternative to the :func:`pass_context` decorator. This function is primarily useful for helpers such as :func:`echo` which might be interested in changing its behavior based on the current context. To push the current context, :meth:`Context.scope` can be used. .. versionadded:: 5.0 :param silent: if set to `True` the return value is `None` if no context is available. The default behavior is to raise a :exc:`RuntimeError`. """ try: return t.cast("Context", _local.stack[-1]) except (AttributeError, IndexError) as e: if not silent: raise RuntimeError("There is no active click context.") from e return None
(silent: bool = False) -> Optional[ForwardRef('Context')]
9,641
asyncclick.utils
get_text_stream
Returns a system stream for text processing. This usually returns a wrapped stream around a binary stream returned from :func:`get_binary_stream` but it also can take shortcuts for already correctly configured streams. :param name: the name of the stream to open. Valid names are ``'stdin'``, ``'stdout'`` and ``'stderr'`` :param encoding: overrides the detected default encoding. :param errors: overrides the default error mode.
def get_text_stream( name: "te.Literal['stdin', 'stdout', 'stderr']", encoding: t.Optional[str] = None, errors: t.Optional[str] = "strict", ) -> t.TextIO: """Returns a system stream for text processing. This usually returns a wrapped stream around a binary stream returned from :func:`get_binary_stream` but it also can take shortcuts for already correctly configured streams. :param name: the name of the stream to open. Valid names are ``'stdin'``, ``'stdout'`` and ``'stderr'`` :param encoding: overrides the detected default encoding. :param errors: overrides the default error mode. """ opener = text_streams.get(name) if opener is None: raise TypeError(f"Unknown standard stream '{name}'") return opener(encoding, errors)
(name: "te.Literal['stdin', 'stdout', 'stderr']", encoding: Optional[str] = None, errors: Optional[str] = 'strict') -> <class 'TextIO'>
9,642
asyncclick.termui
getchar
Fetches a single character from the terminal and returns it. This will always return a unicode character and under certain rare circumstances this might return more than one character. The situations which more than one character is returned is when for whatever reason multiple characters end up in the terminal buffer or standard input was not actually a terminal. Note that this will always read from the terminal, even if something is piped into the standard input. Note for Windows: in rare cases when typing non-ASCII characters, this function might wait for a second character and then return both at once. This is because certain Unicode characters look like special-key markers. .. versionadded:: 2.0 :param echo: if set to `True`, the character read will also show up on the terminal. The default is to not show it.
def getchar(echo: bool = False) -> str: """Fetches a single character from the terminal and returns it. This will always return a unicode character and under certain rare circumstances this might return more than one character. The situations which more than one character is returned is when for whatever reason multiple characters end up in the terminal buffer or standard input was not actually a terminal. Note that this will always read from the terminal, even if something is piped into the standard input. Note for Windows: in rare cases when typing non-ASCII characters, this function might wait for a second character and then return both at once. This is because certain Unicode characters look like special-key markers. .. versionadded:: 2.0 :param echo: if set to `True`, the character read will also show up on the terminal. The default is to not show it. """ global _getchar if _getchar is None: from ._termui_impl import getchar as f _getchar = f return _getchar(echo)
(echo: bool = False) -> str
9,644
asyncclick.decorators
group
Creates a new :class:`Group` with a function as callback. This works otherwise the same as :func:`command` just that the `cls` parameter is set to :class:`Group`. .. versionchanged:: 8.1 This decorator can be applied without parentheses.
def group( name: t.Union[str, _AnyCallable, None] = None, cls: t.Optional[t.Type[GrpType]] = None, **attrs: t.Any, ) -> t.Union[Group, t.Callable[[_AnyCallable], t.Union[Group, GrpType]]]: """Creates a new :class:`Group` with a function as callback. This works otherwise the same as :func:`command` just that the `cls` parameter is set to :class:`Group`. .. versionchanged:: 8.1 This decorator can be applied without parentheses. """ if cls is None: cls = t.cast(t.Type[GrpType], Group) if callable(name): return command(cls=cls, **attrs)(name) return command(name, cls, **attrs)
(name: Union[str, NoneType, Callable[..., Any]] = None, cls: Optional[Type[~GrpType]] = None, **attrs: Any) -> Union[asyncclick.core.Group, Callable[[Callable[..., Any]], Union[asyncclick.core.Group, ~GrpType]]]
9,645
asyncclick.decorators
help_option
Add a ``--help`` option which immediately prints the help page and exits the program. This is usually unnecessary, as the ``--help`` option is added to each command automatically unless ``add_help_option=False`` is passed. :param param_decls: One or more option names. Defaults to the single value ``"--help"``. :param kwargs: Extra arguments are passed to :func:`option`.
def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]: """Add a ``--help`` option which immediately prints the help page and exits the program. This is usually unnecessary, as the ``--help`` option is added to each command automatically unless ``add_help_option=False`` is passed. :param param_decls: One or more option names. Defaults to the single value ``"--help"``. :param kwargs: Extra arguments are passed to :func:`option`. """ def callback(ctx: Context, param: Parameter, value: bool) -> None: if not value or ctx.resilient_parsing: return echo(ctx.get_help(), color=ctx.color) ctx.exit() if not param_decls: param_decls = ("--help",) kwargs.setdefault("is_flag", True) kwargs.setdefault("expose_value", False) kwargs.setdefault("is_eager", True) kwargs.setdefault("help", _("Show this message and exit.")) kwargs["callback"] = callback return option(*param_decls, **kwargs)
(*param_decls: str, **kwargs: Any) -> Callable[[~FC], ~FC]
9,646
asyncclick.termui
launch
This function launches the given URL (or filename) in the default viewer application for this file type. If this is an executable, it might launch the executable in a new session. The return value is the exit code of the launched application. Usually, ``0`` indicates success. Examples:: click.launch('https://click.palletsprojects.com/') click.launch('/my/downloaded/file', locate=True) .. versionadded:: 2.0 :param url: URL or filename of the thing to launch. :param wait: Wait for the program to exit before returning. This only works if the launched program blocks. In particular, ``xdg-open`` on Linux does not block. :param locate: if this is set to `True` then instead of launching the application associated with the URL it will attempt to launch a file manager with the file located. This might have weird effects if the URL does not point to the filesystem.
def launch(url: str, wait: bool = False, locate: bool = False) -> int: """This function launches the given URL (or filename) in the default viewer application for this file type. If this is an executable, it might launch the executable in a new session. The return value is the exit code of the launched application. Usually, ``0`` indicates success. Examples:: click.launch('https://click.palletsprojects.com/') click.launch('/my/downloaded/file', locate=True) .. versionadded:: 2.0 :param url: URL or filename of the thing to launch. :param wait: Wait for the program to exit before returning. This only works if the launched program blocks. In particular, ``xdg-open`` on Linux does not block. :param locate: if this is set to `True` then instead of launching the application associated with the URL it will attempt to launch a file manager with the file located. This might have weird effects if the URL does not point to the filesystem. """ from ._termui_impl import open_url return open_url(url, wait=wait, locate=locate)
(url: str, wait: bool = False, locate: bool = False) -> int
9,647
asyncclick.decorators
make_pass_decorator
Given an object type this creates a decorator that will work similar to :func:`pass_obj` but instead of passing the object of the current context, it will find the innermost context of type :func:`object_type`. This generates a decorator that works roughly like this:: from functools import update_wrapper def decorator(f): @pass_context def new_func(ctx, *args, **kwargs): obj = ctx.find_object(object_type) return ctx.invoke(f, obj, *args, **kwargs) return update_wrapper(new_func, f) return decorator :param object_type: the type of the object to pass. :param ensure: if set to `True`, a new object will be created and remembered on the context if it's not there yet.
def make_pass_decorator( object_type: t.Type[T], ensure: bool = False ) -> t.Callable[["t.Callable[te.Concatenate[T, P], R]"], "t.Callable[P, R]"]: """Given an object type this creates a decorator that will work similar to :func:`pass_obj` but instead of passing the object of the current context, it will find the innermost context of type :func:`object_type`. This generates a decorator that works roughly like this:: from functools import update_wrapper def decorator(f): @pass_context def new_func(ctx, *args, **kwargs): obj = ctx.find_object(object_type) return ctx.invoke(f, obj, *args, **kwargs) return update_wrapper(new_func, f) return decorator :param object_type: the type of the object to pass. :param ensure: if set to `True`, a new object will be created and remembered on the context if it's not there yet. """ def decorator(f: "t.Callable[te.Concatenate[T, P], R]") -> "t.Callable[P, t.Coroutine[t.Any, t.Any, R]]": def new_func(*args: "P.args", **kwargs: "P.kwargs") -> "t.Coroutine[t.Any, t.Any, R]": ctx = get_current_context() obj: t.Optional[T] if ensure: obj = ctx.ensure_object(object_type) else: obj = ctx.find_object(object_type) if obj is None: raise RuntimeError( "Managed to invoke callback without a context" f" object of type {object_type.__name__!r}" " existing." ) return ctx.invoke(f, obj, *args, **kwargs) return update_wrapper(new_func, f) return decorator # type: ignore[return-value]
(object_type: Type[~T], ensure: bool = False) -> Callable[[ForwardRef('t.Callable[te.Concatenate[T, P], R]')], ForwardRef('t.Callable[P, R]')]
9,648
asyncclick.utils
open_file
Open a file, with extra behavior to handle ``'-'`` to indicate a standard stream, lazy open on write, and atomic write. Similar to the behavior of the :class:`~click.File` param type. If ``'-'`` is given to open ``stdout`` or ``stdin``, the stream is wrapped so that using it in a context manager will not close it. This makes it possible to use the function without accidentally closing a standard stream: .. code-block:: python with open_file(filename) as f: ... :param filename: The name of the file to open, or ``'-'`` for ``stdin``/``stdout``. :param mode: The mode in which to open the file. :param encoding: The encoding to decode or encode a file opened in text mode. :param errors: The error handling mode. :param lazy: Wait to open the file until it is accessed. For read mode, the file is temporarily opened to raise access errors early, then closed until it is read again. :param atomic: Write to a temporary file and replace the given file on close. .. versionadded:: 3.0
def open_file( filename: str, mode: str = "r", encoding: t.Optional[str] = None, errors: t.Optional[str] = "strict", lazy: bool = False, atomic: bool = False, ) -> t.IO[t.Any]: """Open a file, with extra behavior to handle ``'-'`` to indicate a standard stream, lazy open on write, and atomic write. Similar to the behavior of the :class:`~click.File` param type. If ``'-'`` is given to open ``stdout`` or ``stdin``, the stream is wrapped so that using it in a context manager will not close it. This makes it possible to use the function without accidentally closing a standard stream: .. code-block:: python with open_file(filename) as f: ... :param filename: The name of the file to open, or ``'-'`` for ``stdin``/``stdout``. :param mode: The mode in which to open the file. :param encoding: The encoding to decode or encode a file opened in text mode. :param errors: The error handling mode. :param lazy: Wait to open the file until it is accessed. For read mode, the file is temporarily opened to raise access errors early, then closed until it is read again. :param atomic: Write to a temporary file and replace the given file on close. .. versionadded:: 3.0 """ if lazy: return t.cast( t.IO[t.Any], LazyFile(filename, mode, encoding, errors, atomic=atomic) ) f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic) if not should_close: f = t.cast(t.IO[t.Any], KeepOpenFile(f)) return f
(filename: str, mode: str = 'r', encoding: Optional[str] = None, errors: Optional[str] = 'strict', lazy: bool = False, atomic: bool = False) -> IO[Any]
9,649
asyncclick.decorators
option
Attaches an option to the command. All positional arguments are passed as parameter declarations to :class:`Option`; all keyword arguments are forwarded unchanged (except ``cls``). This is equivalent to creating an :class:`Option` instance manually and attaching it to the :attr:`Command.params` list. For the default option class, refer to :class:`Option` and :class:`Parameter` for descriptions of parameters. :param cls: the option class to instantiate. This defaults to :class:`Option`. :param param_decls: Passed as positional arguments to the constructor of ``cls``. :param attrs: Passed as keyword arguments to the constructor of ``cls``.
def option( *param_decls: str, cls: t.Optional[t.Type[Option]] = None, **attrs: t.Any ) -> t.Callable[[FC], FC]: """Attaches an option to the command. All positional arguments are passed as parameter declarations to :class:`Option`; all keyword arguments are forwarded unchanged (except ``cls``). This is equivalent to creating an :class:`Option` instance manually and attaching it to the :attr:`Command.params` list. For the default option class, refer to :class:`Option` and :class:`Parameter` for descriptions of parameters. :param cls: the option class to instantiate. This defaults to :class:`Option`. :param param_decls: Passed as positional arguments to the constructor of ``cls``. :param attrs: Passed as keyword arguments to the constructor of ``cls``. """ if cls is None: cls = Option def decorator(f: FC) -> FC: _param_memo(f, cls(param_decls, **attrs)) return f return decorator
(*param_decls: str, cls: Optional[Type[asyncclick.core.Option]] = None, **attrs: Any) -> Callable[[~FC], ~FC]
9,651
asyncclick.decorators
pass_context
Marks a callback as wanting to receive the current context object as first argument.
def pass_context(f: "t.Callable[te.Concatenate[Context, P], R]") -> "t.Callable[P, R]": """Marks a callback as wanting to receive the current context object as first argument. """ def new_func(*args: "P.args", **kwargs: "P.kwargs") -> "R": return f(get_current_context(), *args, **kwargs) return update_wrapper(new_func, f)
(f: 't.Callable[te.Concatenate[Context, P], R]') -> 't.Callable[P, R]'
9,652
asyncclick.decorators
pass_obj
Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). This is useful if that object represents the state of a nested system.
def pass_obj(f: "t.Callable[te.Concatenate[t.Any, P], R]") -> "t.Callable[P, R]": """Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). This is useful if that object represents the state of a nested system. """ def new_func(*args: "P.args", **kwargs: "P.kwargs") -> "R": return f(get_current_context().obj, *args, **kwargs) return update_wrapper(new_func, f)
(f: 't.Callable[te.Concatenate[t.Any, P], R]') -> 't.Callable[P, R]'
9,653
asyncclick.decorators
password_option
Add a ``--password`` option which prompts for a password, hiding input and asking to enter the value again for confirmation. :param param_decls: One or more option names. Defaults to the single value ``"--password"``. :param kwargs: Extra arguments are passed to :func:`option`.
def password_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]: """Add a ``--password`` option which prompts for a password, hiding input and asking to enter the value again for confirmation. :param param_decls: One or more option names. Defaults to the single value ``"--password"``. :param kwargs: Extra arguments are passed to :func:`option`. """ if not param_decls: param_decls = ("--password",) kwargs.setdefault("prompt", True) kwargs.setdefault("confirmation_prompt", True) kwargs.setdefault("hide_input", True) return option(*param_decls, **kwargs)
(*param_decls: str, **kwargs: Any) -> Callable[[~FC], ~FC]
9,654
asyncclick.termui
pause
This command stops execution and waits for the user to press any key to continue. This is similar to the Windows batch "pause" command. If the program is not run through a terminal, this command will instead do nothing. .. versionadded:: 2.0 .. versionadded:: 4.0 Added the `err` parameter. :param info: The message to print before pausing. Defaults to ``"Press any key to continue..."``. :param err: if set to message goes to ``stderr`` instead of ``stdout``, the same as with echo.
def pause(info: t.Optional[str] = None, err: bool = False) -> None: """This command stops execution and waits for the user to press any key to continue. This is similar to the Windows batch "pause" command. If the program is not run through a terminal, this command will instead do nothing. .. versionadded:: 2.0 .. versionadded:: 4.0 Added the `err` parameter. :param info: The message to print before pausing. Defaults to ``"Press any key to continue..."``. :param err: if set to message goes to ``stderr`` instead of ``stdout``, the same as with echo. """ if not isatty(sys.stdin) or not isatty(sys.stdout): return if info is None: info = _("Press any key to continue...") try: if info: echo(info, nl=False, err=err) try: getchar() except (KeyboardInterrupt, EOFError): pass finally: if info: echo(err=err)
(info: Optional[str] = None, err: bool = False) -> NoneType
9,655
asyncclick.termui
progressbar
This function creates an iterable context manager that can be used to iterate over something while showing a progress bar. It will either iterate over the `iterable` or `length` items (that are counted up). While iteration happens, this function will print a rendered progress bar to the given `file` (defaults to stdout) and will attempt to calculate remaining time and more. By default, this progress bar will not be rendered if the file is not a terminal. The context manager creates the progress bar. When the context manager is entered the progress bar is already created. With every iteration over the progress bar, the iterable passed to the bar is advanced and the bar is updated. When the context manager exits, a newline is printed and the progress bar is finalized on screen. Note: The progress bar is currently designed for use cases where the total progress can be expected to take at least several seconds. Because of this, the ProgressBar class object won't display progress that is considered too fast, and progress where the time between steps is less than a second. No printing must happen or the progress bar will be unintentionally destroyed. Example usage:: with progressbar(items) as bar: for item in bar: do_something_with(item) Alternatively, if no iterable is specified, one can manually update the progress bar through the `update()` method instead of directly iterating over the progress bar. The update method accepts the number of steps to increment the bar with:: with progressbar(length=chunks.total_bytes) as bar: for chunk in chunks: process_chunk(chunk) bar.update(chunks.bytes) The ``update()`` method also takes an optional value specifying the ``current_item`` at the new position. This is useful when used together with ``item_show_func`` to customize the output for each manual step:: with click.progressbar( length=total_size, label='Unzipping archive', item_show_func=lambda a: a.filename ) as bar: for archive in zip_file: archive.extract() bar.update(archive.size, archive) :param iterable: an iterable to iterate over. If not provided the length is required. :param length: the number of items to iterate over. By default the progressbar will attempt to ask the iterator about its length, which might or might not work. If an iterable is also provided this parameter can be used to override the length. If an iterable is not provided the progress bar will iterate over a range of that length. :param label: the label to show next to the progress bar. :param show_eta: enables or disables the estimated time display. This is automatically disabled if the length cannot be determined. :param show_percent: enables or disables the percentage display. The default is `True` if the iterable has a length or `False` if not. :param show_pos: enables or disables the absolute position display. The default is `False`. :param item_show_func: A function called with the current item which can return a string to show next to the progress bar. If the function returns ``None`` nothing is shown. The current item can be ``None``, such as when entering and exiting the bar. :param fill_char: the character to use to show the filled part of the progress bar. :param empty_char: the character to use to show the non-filled part of the progress bar. :param bar_template: the format string to use as template for the bar. The parameters in it are ``label`` for the label, ``bar`` for the progress bar and ``info`` for the info section. :param info_sep: the separator between multiple info items (eta etc.) :param width: the width of the progress bar in characters, 0 means full terminal width :param file: The file to write to. If this is not a terminal then only the label is printed. :param color: controls if the terminal supports ANSI colors or not. The default is autodetection. This is only needed if ANSI codes are included anywhere in the progress bar output which is not the case by default. :param update_min_steps: Render only when this many updates have completed. This allows tuning for very fast iterators. .. versionchanged:: 8.0 Output is shown even if execution time is less than 0.5 seconds. .. versionchanged:: 8.0 ``item_show_func`` shows the current item, not the previous one. .. versionchanged:: 8.0 Labels are echoed if the output is not a TTY. Reverts a change in 7.0 that removed all output. .. versionadded:: 8.0 Added the ``update_min_steps`` parameter. .. versionchanged:: 4.0 Added the ``color`` parameter. Added the ``update`` method to the object. .. versionadded:: 2.0
def progressbar( iterable: t.Optional[t.Iterable[V]] = None, length: t.Optional[int] = None, label: t.Optional[str] = None, show_eta: bool = True, show_percent: t.Optional[bool] = None, show_pos: bool = False, item_show_func: t.Optional[t.Callable[[t.Optional[V]], t.Optional[str]]] = None, fill_char: str = "#", empty_char: str = "-", bar_template: str = "%(label)s [%(bar)s] %(info)s", info_sep: str = " ", width: int = 36, file: t.Optional[t.TextIO] = None, color: t.Optional[bool] = None, update_min_steps: int = 1, ) -> "ProgressBar[V]": """This function creates an iterable context manager that can be used to iterate over something while showing a progress bar. It will either iterate over the `iterable` or `length` items (that are counted up). While iteration happens, this function will print a rendered progress bar to the given `file` (defaults to stdout) and will attempt to calculate remaining time and more. By default, this progress bar will not be rendered if the file is not a terminal. The context manager creates the progress bar. When the context manager is entered the progress bar is already created. With every iteration over the progress bar, the iterable passed to the bar is advanced and the bar is updated. When the context manager exits, a newline is printed and the progress bar is finalized on screen. Note: The progress bar is currently designed for use cases where the total progress can be expected to take at least several seconds. Because of this, the ProgressBar class object won't display progress that is considered too fast, and progress where the time between steps is less than a second. No printing must happen or the progress bar will be unintentionally destroyed. Example usage:: with progressbar(items) as bar: for item in bar: do_something_with(item) Alternatively, if no iterable is specified, one can manually update the progress bar through the `update()` method instead of directly iterating over the progress bar. The update method accepts the number of steps to increment the bar with:: with progressbar(length=chunks.total_bytes) as bar: for chunk in chunks: process_chunk(chunk) bar.update(chunks.bytes) The ``update()`` method also takes an optional value specifying the ``current_item`` at the new position. This is useful when used together with ``item_show_func`` to customize the output for each manual step:: with click.progressbar( length=total_size, label='Unzipping archive', item_show_func=lambda a: a.filename ) as bar: for archive in zip_file: archive.extract() bar.update(archive.size, archive) :param iterable: an iterable to iterate over. If not provided the length is required. :param length: the number of items to iterate over. By default the progressbar will attempt to ask the iterator about its length, which might or might not work. If an iterable is also provided this parameter can be used to override the length. If an iterable is not provided the progress bar will iterate over a range of that length. :param label: the label to show next to the progress bar. :param show_eta: enables or disables the estimated time display. This is automatically disabled if the length cannot be determined. :param show_percent: enables or disables the percentage display. The default is `True` if the iterable has a length or `False` if not. :param show_pos: enables or disables the absolute position display. The default is `False`. :param item_show_func: A function called with the current item which can return a string to show next to the progress bar. If the function returns ``None`` nothing is shown. The current item can be ``None``, such as when entering and exiting the bar. :param fill_char: the character to use to show the filled part of the progress bar. :param empty_char: the character to use to show the non-filled part of the progress bar. :param bar_template: the format string to use as template for the bar. The parameters in it are ``label`` for the label, ``bar`` for the progress bar and ``info`` for the info section. :param info_sep: the separator between multiple info items (eta etc.) :param width: the width of the progress bar in characters, 0 means full terminal width :param file: The file to write to. If this is not a terminal then only the label is printed. :param color: controls if the terminal supports ANSI colors or not. The default is autodetection. This is only needed if ANSI codes are included anywhere in the progress bar output which is not the case by default. :param update_min_steps: Render only when this many updates have completed. This allows tuning for very fast iterators. .. versionchanged:: 8.0 Output is shown even if execution time is less than 0.5 seconds. .. versionchanged:: 8.0 ``item_show_func`` shows the current item, not the previous one. .. versionchanged:: 8.0 Labels are echoed if the output is not a TTY. Reverts a change in 7.0 that removed all output. .. versionadded:: 8.0 Added the ``update_min_steps`` parameter. .. versionchanged:: 4.0 Added the ``color`` parameter. Added the ``update`` method to the object. .. versionadded:: 2.0 """ from ._termui_impl import ProgressBar color = resolve_color_default(color) return ProgressBar( iterable=iterable, length=length, show_eta=show_eta, show_percent=show_percent, show_pos=show_pos, item_show_func=item_show_func, fill_char=fill_char, empty_char=empty_char, bar_template=bar_template, info_sep=info_sep, file=file, label=label, width=width, color=color, update_min_steps=update_min_steps, )
(iterable: Optional[Iterable[~V]] = None, length: Optional[int] = None, label: Optional[str] = None, show_eta: bool = True, show_percent: Optional[bool] = None, show_pos: bool = False, item_show_func: Optional[Callable[[Optional[~V]], Optional[str]]] = None, fill_char: str = '#', empty_char: str = '-', bar_template: str = '%(label)s [%(bar)s] %(info)s', info_sep: str = ' ', width: int = 36, file: Optional[TextIO] = None, color: Optional[bool] = None, update_min_steps: int = 1) -> 'ProgressBar[V]'
9,656
asyncclick.termui
prompt
Prompts a user for input. This is a convenience function that can be used to prompt a user for input later. If the user aborts the input by sending an interrupt signal, this function will catch it and raise a :exc:`Abort` exception. :param text: the text to show for the prompt. :param default: the default value to use if no input happens. If this is not given it will prompt until it's aborted. :param hide_input: if this is set to true then the input value will be hidden. :param confirmation_prompt: Prompt a second time to confirm the value. Can be set to a string instead of ``True`` to customize the message. :param type: the type to use to check the value against. :param value_proc: if this parameter is provided it's a function that is invoked instead of the type conversion to convert a value. :param prompt_suffix: a suffix that should be added to the prompt. :param show_default: shows or hides the default value in the prompt. :param err: if set to true the file defaults to ``stderr`` instead of ``stdout``, the same as with echo. :param show_choices: Show or hide choices if the passed type is a Choice. For example if type is a Choice of either day or week, show_choices is true and text is "Group by" then the prompt will be "Group by (day, week): ". .. versionadded:: 8.0 ``confirmation_prompt`` can be a custom string. .. versionadded:: 7.0 Added the ``show_choices`` parameter. .. versionadded:: 6.0 Added unicode support for cmd.exe on Windows. .. versionadded:: 4.0 Added the `err` parameter.
def prompt( text: str, default: t.Optional[t.Any] = None, hide_input: bool = False, confirmation_prompt: t.Union[bool, str] = False, type: t.Optional[t.Union[ParamType, t.Any]] = None, value_proc: t.Optional[t.Callable[[str], t.Any]] = None, prompt_suffix: str = ": ", show_default: bool = True, err: bool = False, show_choices: bool = True, ) -> t.Any: """Prompts a user for input. This is a convenience function that can be used to prompt a user for input later. If the user aborts the input by sending an interrupt signal, this function will catch it and raise a :exc:`Abort` exception. :param text: the text to show for the prompt. :param default: the default value to use if no input happens. If this is not given it will prompt until it's aborted. :param hide_input: if this is set to true then the input value will be hidden. :param confirmation_prompt: Prompt a second time to confirm the value. Can be set to a string instead of ``True`` to customize the message. :param type: the type to use to check the value against. :param value_proc: if this parameter is provided it's a function that is invoked instead of the type conversion to convert a value. :param prompt_suffix: a suffix that should be added to the prompt. :param show_default: shows or hides the default value in the prompt. :param err: if set to true the file defaults to ``stderr`` instead of ``stdout``, the same as with echo. :param show_choices: Show or hide choices if the passed type is a Choice. For example if type is a Choice of either day or week, show_choices is true and text is "Group by" then the prompt will be "Group by (day, week): ". .. versionadded:: 8.0 ``confirmation_prompt`` can be a custom string. .. versionadded:: 7.0 Added the ``show_choices`` parameter. .. versionadded:: 6.0 Added unicode support for cmd.exe on Windows. .. versionadded:: 4.0 Added the `err` parameter. """ def prompt_func(text: str) -> str: f = hidden_prompt_func if hide_input else visible_prompt_func try: # Write the prompt separately so that we get nice # coloring through colorama on Windows echo(text.rstrip(" "), nl=False, err=err) # Echo a space to stdout to work around an issue where # readline causes backspace to clear the whole line. return f(" ") except (KeyboardInterrupt, EOFError): # getpass doesn't print a newline if the user aborts input with ^C. # Allegedly this behavior is inherited from getpass(3). # A doc bug has been filed at https://bugs.python.org/issue24711 if hide_input: echo(None, err=err) raise Abort() from None if value_proc is None: value_proc = convert_type(type, default) prompt = _build_prompt( text, prompt_suffix, show_default, default, show_choices, type ) if confirmation_prompt: if confirmation_prompt is True: confirmation_prompt = _("Repeat for confirmation") confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix) while True: while True: value = prompt_func(prompt) if value: break elif default is not None: value = default break try: result = value_proc(value) except UsageError as e: if hide_input: echo(_("Error: The value you entered was invalid."), err=err) else: echo(_("Error: {e.message}").format(e=e), err=err) # noqa: B306 continue if not confirmation_prompt: return result while True: value2 = prompt_func(confirmation_prompt) is_empty = not value and not value2 if value2 or is_empty: break if value == value2: return result echo(_("Error: The two entered values do not match."), err=err)
(text: str, default: Optional[Any] = None, hide_input: bool = False, confirmation_prompt: Union[bool, str] = False, type: Union[asyncclick.types.ParamType, Any, NoneType] = None, value_proc: Optional[Callable[[str], Any]] = None, prompt_suffix: str = ': ', show_default: bool = True, err: bool = False, show_choices: bool = True) -> Any
9,657
asyncclick.termui
secho
This function combines :func:`echo` and :func:`style` into one call. As such the following two calls are the same:: click.secho('Hello World!', fg='green') click.echo(click.style('Hello World!', fg='green')) All keyword arguments are forwarded to the underlying functions depending on which one they go with. Non-string types will be converted to :class:`str`. However, :class:`bytes` are passed directly to :meth:`echo` without applying style. If you want to style bytes that represent text, call :meth:`bytes.decode` first. .. versionchanged:: 8.0 A non-string ``message`` is converted to a string. Bytes are passed through without style applied. .. versionadded:: 2.0
def secho( message: t.Optional[t.Any] = None, file: t.Optional[t.IO[t.AnyStr]] = None, nl: bool = True, err: bool = False, color: t.Optional[bool] = None, **styles: t.Any, ) -> None: """This function combines :func:`echo` and :func:`style` into one call. As such the following two calls are the same:: click.secho('Hello World!', fg='green') click.echo(click.style('Hello World!', fg='green')) All keyword arguments are forwarded to the underlying functions depending on which one they go with. Non-string types will be converted to :class:`str`. However, :class:`bytes` are passed directly to :meth:`echo` without applying style. If you want to style bytes that represent text, call :meth:`bytes.decode` first. .. versionchanged:: 8.0 A non-string ``message`` is converted to a string. Bytes are passed through without style applied. .. versionadded:: 2.0 """ if message is not None and not isinstance(message, (bytes, bytearray)): message = style(message, **styles) return echo(message, file=file, nl=nl, err=err, color=color)
(message: Optional[Any] = None, file: Optional[IO[~AnyStr]] = None, nl: bool = True, err: bool = False, color: Optional[bool] = None, **styles: Any) -> NoneType
9,658
asyncclick.termui
style
Styles a text with ANSI styles and returns the new string. By default the styling is self contained which means that at the end of the string a reset code is issued. This can be prevented by passing ``reset=False``. Examples:: click.echo(click.style('Hello World!', fg='green')) click.echo(click.style('ATTENTION!', blink=True)) click.echo(click.style('Some things', reverse=True, fg='cyan')) click.echo(click.style('More colors', fg=(255, 12, 128), bg=117)) Supported color names: * ``black`` (might be a gray) * ``red`` * ``green`` * ``yellow`` (might be an orange) * ``blue`` * ``magenta`` * ``cyan`` * ``white`` (might be light gray) * ``bright_black`` * ``bright_red`` * ``bright_green`` * ``bright_yellow`` * ``bright_blue`` * ``bright_magenta`` * ``bright_cyan`` * ``bright_white`` * ``reset`` (reset the color code only) If the terminal supports it, color may also be specified as: - An integer in the interval [0, 255]. The terminal must support 8-bit/256-color mode. - An RGB tuple of three integers in [0, 255]. The terminal must support 24-bit/true-color mode. See https://en.wikipedia.org/wiki/ANSI_color and https://gist.github.com/XVilka/8346728 for more information. :param text: the string to style with ansi codes. :param fg: if provided this will become the foreground color. :param bg: if provided this will become the background color. :param bold: if provided this will enable or disable bold mode. :param dim: if provided this will enable or disable dim mode. This is badly supported. :param underline: if provided this will enable or disable underline. :param overline: if provided this will enable or disable overline. :param italic: if provided this will enable or disable italic. :param blink: if provided this will enable or disable blinking. :param reverse: if provided this will enable or disable inverse rendering (foreground becomes background and the other way round). :param strikethrough: if provided this will enable or disable striking through text. :param reset: by default a reset-all code is added at the end of the string which means that styles do not carry over. This can be disabled to compose styles. .. versionchanged:: 8.0 A non-string ``message`` is converted to a string. .. versionchanged:: 8.0 Added support for 256 and RGB color codes. .. versionchanged:: 8.0 Added the ``strikethrough``, ``italic``, and ``overline`` parameters. .. versionchanged:: 7.0 Added support for bright colors. .. versionadded:: 2.0
def style( text: t.Any, fg: t.Optional[t.Union[int, t.Tuple[int, int, int], str]] = None, bg: t.Optional[t.Union[int, t.Tuple[int, int, int], str]] = None, bold: t.Optional[bool] = None, dim: t.Optional[bool] = None, underline: t.Optional[bool] = None, overline: t.Optional[bool] = None, italic: t.Optional[bool] = None, blink: t.Optional[bool] = None, reverse: t.Optional[bool] = None, strikethrough: t.Optional[bool] = None, reset: bool = True, ) -> str: """Styles a text with ANSI styles and returns the new string. By default the styling is self contained which means that at the end of the string a reset code is issued. This can be prevented by passing ``reset=False``. Examples:: click.echo(click.style('Hello World!', fg='green')) click.echo(click.style('ATTENTION!', blink=True)) click.echo(click.style('Some things', reverse=True, fg='cyan')) click.echo(click.style('More colors', fg=(255, 12, 128), bg=117)) Supported color names: * ``black`` (might be a gray) * ``red`` * ``green`` * ``yellow`` (might be an orange) * ``blue`` * ``magenta`` * ``cyan`` * ``white`` (might be light gray) * ``bright_black`` * ``bright_red`` * ``bright_green`` * ``bright_yellow`` * ``bright_blue`` * ``bright_magenta`` * ``bright_cyan`` * ``bright_white`` * ``reset`` (reset the color code only) If the terminal supports it, color may also be specified as: - An integer in the interval [0, 255]. The terminal must support 8-bit/256-color mode. - An RGB tuple of three integers in [0, 255]. The terminal must support 24-bit/true-color mode. See https://en.wikipedia.org/wiki/ANSI_color and https://gist.github.com/XVilka/8346728 for more information. :param text: the string to style with ansi codes. :param fg: if provided this will become the foreground color. :param bg: if provided this will become the background color. :param bold: if provided this will enable or disable bold mode. :param dim: if provided this will enable or disable dim mode. This is badly supported. :param underline: if provided this will enable or disable underline. :param overline: if provided this will enable or disable overline. :param italic: if provided this will enable or disable italic. :param blink: if provided this will enable or disable blinking. :param reverse: if provided this will enable or disable inverse rendering (foreground becomes background and the other way round). :param strikethrough: if provided this will enable or disable striking through text. :param reset: by default a reset-all code is added at the end of the string which means that styles do not carry over. This can be disabled to compose styles. .. versionchanged:: 8.0 A non-string ``message`` is converted to a string. .. versionchanged:: 8.0 Added support for 256 and RGB color codes. .. versionchanged:: 8.0 Added the ``strikethrough``, ``italic``, and ``overline`` parameters. .. versionchanged:: 7.0 Added support for bright colors. .. versionadded:: 2.0 """ if not isinstance(text, str): text = str(text) bits = [] if fg: try: bits.append(f"\033[{_interpret_color(fg)}m") except KeyError: raise TypeError(f"Unknown color {fg!r}") from None if bg: try: bits.append(f"\033[{_interpret_color(bg, 10)}m") except KeyError: raise TypeError(f"Unknown color {bg!r}") from None if bold is not None: bits.append(f"\033[{1 if bold else 22}m") if dim is not None: bits.append(f"\033[{2 if dim else 22}m") if underline is not None: bits.append(f"\033[{4 if underline else 24}m") if overline is not None: bits.append(f"\033[{53 if overline else 55}m") if italic is not None: bits.append(f"\033[{3 if italic else 23}m") if blink is not None: bits.append(f"\033[{5 if blink else 25}m") if reverse is not None: bits.append(f"\033[{7 if reverse else 27}m") if strikethrough is not None: bits.append(f"\033[{9 if strikethrough else 29}m") bits.append(text) if reset: bits.append(_ansi_reset_all) return "".join(bits)
(text: Any, fg: Union[int, Tuple[int, int, int], str, NoneType] = None, bg: Union[int, Tuple[int, int, int], str, NoneType] = None, bold: Optional[bool] = None, dim: Optional[bool] = None, underline: Optional[bool] = None, overline: Optional[bool] = None, italic: Optional[bool] = None, blink: Optional[bool] = None, reverse: Optional[bool] = None, strikethrough: Optional[bool] = None, reset: bool = True) -> str
9,661
asyncclick.termui
unstyle
Removes ANSI styling information from a string. Usually it's not necessary to use this function as Click's echo function will automatically remove styling if necessary. .. versionadded:: 2.0 :param text: the text to remove style information from.
def unstyle(text: str) -> str: """Removes ANSI styling information from a string. Usually it's not necessary to use this function as Click's echo function will automatically remove styling if necessary. .. versionadded:: 2.0 :param text: the text to remove style information from. """ return strip_ansi(text)
(text: str) -> str
9,663
asyncclick.decorators
version_option
Add a ``--version`` option which immediately prints the version number and exits the program. If ``version`` is not provided, Click will try to detect it using :func:`importlib.metadata.version` to get the version for the ``package_name``. On Python < 3.8, the ``importlib_metadata`` backport must be installed. If ``package_name`` is not provided, Click will try to detect it by inspecting the stack frames. This will be used to detect the version, so it must match the name of the installed package. :param version: The version number to show. If not provided, Click will try to detect it. :param param_decls: One or more option names. Defaults to the single value ``"--version"``. :param package_name: The package name to detect the version from. If not provided, Click will try to detect it. :param prog_name: The name of the CLI to show in the message. If not provided, it will be detected from the command. :param message: The message to show. The values ``%(prog)s``, ``%(package)s``, and ``%(version)s`` are available. Defaults to ``"%(prog)s, version %(version)s"``. :param kwargs: Extra arguments are passed to :func:`option`. :raise RuntimeError: ``version`` could not be detected. .. versionchanged:: 8.0 Add the ``package_name`` parameter, and the ``%(package)s`` value for messages. .. versionchanged:: 8.0 Use :mod:`importlib.metadata` instead of ``pkg_resources``. The version is detected based on the package name, not the entry point name. The Python package name must match the installed package name, or be passed with ``package_name=``.
def version_option( version: t.Optional[str] = None, *param_decls: str, package_name: t.Optional[str] = None, prog_name: t.Optional[str] = None, message: t.Optional[str] = None, **kwargs: t.Any, ) -> t.Callable[[FC], FC]: """Add a ``--version`` option which immediately prints the version number and exits the program. If ``version`` is not provided, Click will try to detect it using :func:`importlib.metadata.version` to get the version for the ``package_name``. On Python < 3.8, the ``importlib_metadata`` backport must be installed. If ``package_name`` is not provided, Click will try to detect it by inspecting the stack frames. This will be used to detect the version, so it must match the name of the installed package. :param version: The version number to show. If not provided, Click will try to detect it. :param param_decls: One or more option names. Defaults to the single value ``"--version"``. :param package_name: The package name to detect the version from. If not provided, Click will try to detect it. :param prog_name: The name of the CLI to show in the message. If not provided, it will be detected from the command. :param message: The message to show. The values ``%(prog)s``, ``%(package)s``, and ``%(version)s`` are available. Defaults to ``"%(prog)s, version %(version)s"``. :param kwargs: Extra arguments are passed to :func:`option`. :raise RuntimeError: ``version`` could not be detected. .. versionchanged:: 8.0 Add the ``package_name`` parameter, and the ``%(package)s`` value for messages. .. versionchanged:: 8.0 Use :mod:`importlib.metadata` instead of ``pkg_resources``. The version is detected based on the package name, not the entry point name. The Python package name must match the installed package name, or be passed with ``package_name=``. """ if message is None: message = _("%(prog)s, version %(version)s") if version is None and package_name is None: frame = inspect.currentframe() f_back = frame.f_back if frame is not None else None f_globals = f_back.f_globals if f_back is not None else None # break reference cycle # https://docs.python.org/3/library/inspect.html#the-interpreter-stack del frame if f_globals is not None: package_name = f_globals.get("__name__") if package_name == "__main__": package_name = f_globals.get("__package__") if package_name: package_name = package_name.partition(".")[0] def callback(ctx: Context, param: Parameter, value: bool) -> None: if not value or ctx.resilient_parsing: return nonlocal prog_name nonlocal version if prog_name is None: prog_name = ctx.find_root().info_name if version is None and package_name is not None: metadata: t.Optional[types.ModuleType] try: from importlib import metadata # type: ignore except ImportError: # Python < 3.8 import importlib_metadata as metadata # type: ignore try: version = metadata.version(package_name) # type: ignore except metadata.PackageNotFoundError: # type: ignore raise RuntimeError( f"{package_name!r} is not installed. Try passing" " 'package_name' instead." ) from None if version is None: raise RuntimeError( f"Could not determine the version for {package_name!r} automatically." ) echo( message % {"prog": prog_name, "package": package_name, "version": version}, color=ctx.color, ) ctx.exit() if not param_decls: param_decls = ("--version",) kwargs.setdefault("is_flag", True) kwargs.setdefault("expose_value", False) kwargs.setdefault("is_eager", True) kwargs.setdefault("help", _("Show the version and exit.")) kwargs["callback"] = callback return option(*param_decls, **kwargs)
(version: Optional[str] = None, *param_decls: str, package_name: Optional[str] = None, prog_name: Optional[str] = None, message: Optional[str] = None, **kwargs: Any) -> Callable[[~FC], ~FC]
9,664
asyncclick.formatting
wrap_text
A helper function that intelligently wraps text. By default, it assumes that it operates on a single paragraph of text but if the `preserve_paragraphs` parameter is provided it will intelligently handle paragraphs (defined by two empty lines). If paragraphs are handled, a paragraph can be prefixed with an empty line containing the ``\b`` character (``\x08``) to indicate that no rewrapping should happen in that block. :param text: the text that should be rewrapped. :param width: the maximum width for the text. :param initial_indent: the initial indent that should be placed on the first line as a string. :param subsequent_indent: the indent string that should be placed on each consecutive line. :param preserve_paragraphs: if this flag is set then the wrapping will intelligently handle paragraphs.
def wrap_text( text: str, width: int = 78, initial_indent: str = "", subsequent_indent: str = "", preserve_paragraphs: bool = False, ) -> str: """A helper function that intelligently wraps text. By default, it assumes that it operates on a single paragraph of text but if the `preserve_paragraphs` parameter is provided it will intelligently handle paragraphs (defined by two empty lines). If paragraphs are handled, a paragraph can be prefixed with an empty line containing the ``\\b`` character (``\\x08``) to indicate that no rewrapping should happen in that block. :param text: the text that should be rewrapped. :param width: the maximum width for the text. :param initial_indent: the initial indent that should be placed on the first line as a string. :param subsequent_indent: the indent string that should be placed on each consecutive line. :param preserve_paragraphs: if this flag is set then the wrapping will intelligently handle paragraphs. """ from ._textwrap import TextWrapper text = text.expandtabs() wrapper = TextWrapper( width, initial_indent=initial_indent, subsequent_indent=subsequent_indent, replace_whitespace=False, ) if not preserve_paragraphs: return wrapper.fill(text) p: t.List[t.Tuple[int, bool, str]] = [] buf: t.List[str] = [] indent = None def _flush_par() -> None: if not buf: return if buf[0].strip() == "\b": p.append((indent or 0, True, "\n".join(buf[1:]))) else: p.append((indent or 0, False, " ".join(buf))) del buf[:] for line in text.splitlines(): if not line: _flush_par() indent = None else: if indent is None: orig_len = term_len(line) line = line.lstrip() indent = orig_len - term_len(line) buf.append(line) _flush_par() rv = [] for indent, raw, text in p: with wrapper.extra_indent(" " * indent): if raw: rv.append(wrapper.indent_only(text)) else: rv.append(wrapper.fill(text)) return "\n\n".join(rv)
(text: str, width: int = 78, initial_indent: str = '', subsequent_indent: str = '', preserve_paragraphs: bool = False) -> str
9,665
unicodedata2
UCD
null
from unicodedata2 import UCD
()
9,666
bettersql.sqldf
sqldf
sql : str The SQL command or commands you want to run. You can pass in multiple statements separated by a ; in order to do UPDATE, INSERT, DELETE, but the last query must be a SELECT without a ; index : bool (Default: False) When a DataFrame is pushed into the memory table, should the index col be included output : str {'dataframe', 'dict', 'list', 'series', 'split', 'records', 'index'} Determines the type of the values of the dictionary. - 'dict' (default) : dict like {column -> {index -> value}} - 'list' : dict like {column -> [values]} - 'series' : dict like {column -> Series(values)} - 'split' : dict like {'index' -> [index], 'columns' -> [columns], 'data' -> [values]} - 'records' : list like [{column -> value}, ... , {column -> value}] - 'csv' : simple CSV format params : dict KV parameters to pass in Python functions to the memory database, or to specify specific tables with aliases rather than the default of searching for FROM and JOIN key is a string which is the function name SQL will use, value is a pointer to the function or table source There is no real error checking so make sure any list or dicts you pass in to automatically convert to a DataFrame are in the correct format and that you don't send any bad SQL. This module relies on the errors thrown by the functions it calls.
def sqldf(sql:str, *, index:bool = False, output:str = 'dataframe', **params): ''' sql : str The SQL command or commands you want to run. You can pass in multiple statements separated by a ; in order to do UPDATE, INSERT, DELETE, but the last query must be a SELECT without a ; index : bool (Default: False) When a DataFrame is pushed into the memory table, should the index col be included output : str {'dataframe', 'dict', 'list', 'series', 'split', 'records', 'index'} Determines the type of the values of the dictionary. - 'dict' (default) : dict like {column -> {index -> value}} - 'list' : dict like {column -> [values]} - 'series' : dict like {column -> Series(values)} - 'split' : dict like {'index' -> [index], 'columns' -> [columns], 'data' -> [values]} - 'records' : list like [{column -> value}, ... , {column -> value}] - 'csv' : simple CSV format params : dict KV parameters to pass in Python functions to the memory database, or to specify specific tables with aliases rather than the default of searching for FROM and JOIN key is a string which is the function name SQL will use, value is a pointer to the function or table source There is no real error checking so make sure any list or dicts you pass in to automatically convert to a DataFrame are in the correct format and that you don't send any bad SQL. This module relies on the errors thrown by the functions it calls. ''' from pandas import read_sql_query, DataFrame import sqlite3 import types from inspect import signature, stack # get globals and locals from the caller level in order to find objects that refer to virtual tables in the SQL statement # env = stack()[1][0] env = stack()[1][0].f_globals env2 = stack()[1][0].f_locals env.update(env2) with sqlite3.connect(':memory:') as cn: addedtables = set() # go through the list of KV parameters to push any UDF's or named tables into the memory database for k, v in params.items(): if type(v) in (types.FunctionType, types.LambdaType): # If it's a function add it cn.create_function(k, len(signature(v).parameters), v) elif isinstance(v, DataFrame): # if it's a DataFrame add it as is addedtables.add(k) v.to_sql(k, cn, index = index) elif isinstance(v, dict) or isinstance(v, list): # if it's a list of dict automatically convert it to a DataFrame addedtables.add(k) df = DataFrame(v) df.to_sql(k, cn, index = index) # search through the environment to see if any tables mentioned in FROM or JOIN clause # that are not specified in the params and push them into the memory database # the table can be a DataFrame or a list or dict that is convertible to a DataFrame for k in get_table_names(sql): if k in env and k not in addedtables: o = env[k] if isinstance(o, DataFrame): o.to_sql(k, cn, index = index) elif isinstance(o, dict) or isinstance(o, list): df = DataFrame(o) df.to_sql(k, cn, index = index) # you can pass in multiple statements separated by a ; in order to do CREATE TABLE, UPDATE, INSERT, DELETE, # but the last query must be a SELECT to return a result if ';' in sql: commands = [x.strip() for x in sql.split(';')] for c in commands[:-1]: cn.execute(c) r = read_sql_query(commands[-1], cn) else: r = read_sql_query(sql, cn) # if the output flag is passed it calls the DataFrame to_dict with that option if output: if output.lower() == 'csv': x = r.to_dict('record') return ( ','.join(map(str, e.values())) for e in x) elif output.lower() != 'dataframe': return r.to_dict(output) return r
(sql: str, *, index: bool = False, output: str = 'dataframe', **params)
9,667
cloudscraper
CipherSuiteAdapter
null
class CipherSuiteAdapter(HTTPAdapter): __attrs__ = [ 'ssl_context', 'max_retries', 'config', '_pool_connections', '_pool_maxsize', '_pool_block', 'source_address' ] def __init__(self, *args, **kwargs): self.ssl_context = kwargs.pop('ssl_context', None) self.cipherSuite = kwargs.pop('cipherSuite', None) self.source_address = kwargs.pop('source_address', None) self.server_hostname = kwargs.pop('server_hostname', None) self.ecdhCurve = kwargs.pop('ecdhCurve', 'prime256v1') if self.source_address: if isinstance(self.source_address, str): self.source_address = (self.source_address, 0) if not isinstance(self.source_address, tuple): raise TypeError( "source_address must be IP address string or (ip, port) tuple" ) if not self.ssl_context: self.ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) self.ssl_context.orig_wrap_socket = self.ssl_context.wrap_socket self.ssl_context.wrap_socket = self.wrap_socket if self.server_hostname: self.ssl_context.server_hostname = self.server_hostname self.ssl_context.set_ciphers(self.cipherSuite) self.ssl_context.set_ecdh_curve(self.ecdhCurve) self.ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2 self.ssl_context.maximum_version = ssl.TLSVersion.TLSv1_3 super(CipherSuiteAdapter, self).__init__(**kwargs) # ------------------------------------------------------------------------------- # def wrap_socket(self, *args, **kwargs): if hasattr(self.ssl_context, 'server_hostname') and self.ssl_context.server_hostname: kwargs['server_hostname'] = self.ssl_context.server_hostname self.ssl_context.check_hostname = False else: self.ssl_context.check_hostname = True return self.ssl_context.orig_wrap_socket(*args, **kwargs) # ------------------------------------------------------------------------------- # def init_poolmanager(self, *args, **kwargs): kwargs['ssl_context'] = self.ssl_context kwargs['source_address'] = self.source_address return super(CipherSuiteAdapter, self).init_poolmanager(*args, **kwargs) # ------------------------------------------------------------------------------- # def proxy_manager_for(self, *args, **kwargs): kwargs['ssl_context'] = self.ssl_context kwargs['source_address'] = self.source_address return super(CipherSuiteAdapter, self).proxy_manager_for(*args, **kwargs)
(*args, **kwargs)
9,668
requests.adapters
__getstate__
null
def __getstate__(self): return {attr: getattr(self, attr, None) for attr in self.__attrs__}
(self)
9,669
cloudscraper
__init__
null
def __init__(self, *args, **kwargs): self.ssl_context = kwargs.pop('ssl_context', None) self.cipherSuite = kwargs.pop('cipherSuite', None) self.source_address = kwargs.pop('source_address', None) self.server_hostname = kwargs.pop('server_hostname', None) self.ecdhCurve = kwargs.pop('ecdhCurve', 'prime256v1') if self.source_address: if isinstance(self.source_address, str): self.source_address = (self.source_address, 0) if not isinstance(self.source_address, tuple): raise TypeError( "source_address must be IP address string or (ip, port) tuple" ) if not self.ssl_context: self.ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) self.ssl_context.orig_wrap_socket = self.ssl_context.wrap_socket self.ssl_context.wrap_socket = self.wrap_socket if self.server_hostname: self.ssl_context.server_hostname = self.server_hostname self.ssl_context.set_ciphers(self.cipherSuite) self.ssl_context.set_ecdh_curve(self.ecdhCurve) self.ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2 self.ssl_context.maximum_version = ssl.TLSVersion.TLSv1_3 super(CipherSuiteAdapter, self).__init__(**kwargs)
(self, *args, **kwargs)
9,670
requests.adapters
__setstate__
null
def __setstate__(self, state): # Can't handle by adding 'proxy_manager' to self.__attrs__ because # self.poolmanager uses a lambda function, which isn't pickleable. self.proxy_manager = {} self.config = {} for attr, value in state.items(): setattr(self, attr, value) self.init_poolmanager( self._pool_connections, self._pool_maxsize, block=self._pool_block )
(self, state)
9,671
requests.adapters
add_headers
Add any headers needed by the connection. As of v2.0 this does nothing by default, but is left for overriding by users that subclass the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to. :param kwargs: The keyword arguments from the call to send().
def add_headers(self, request, **kwargs): """Add any headers needed by the connection. As of v2.0 this does nothing by default, but is left for overriding by users that subclass the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to. :param kwargs: The keyword arguments from the call to send(). """ pass
(self, request, **kwargs)
9,672
requests.adapters
build_response
Builds a :class:`Response <requests.Response>` object from a urllib3 response. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>` :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response. :param resp: The urllib3 response object. :rtype: requests.Response
def build_response(self, req, resp): """Builds a :class:`Response <requests.Response>` object from a urllib3 response. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>` :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response. :param resp: The urllib3 response object. :rtype: requests.Response """ response = Response() # Fallback to None if there's no status_code, for whatever reason. response.status_code = getattr(resp, "status", None) # Make headers case-insensitive. response.headers = CaseInsensitiveDict(getattr(resp, "headers", {})) # Set encoding. response.encoding = get_encoding_from_headers(response.headers) response.raw = resp response.reason = response.raw.reason if isinstance(req.url, bytes): response.url = req.url.decode("utf-8") else: response.url = req.url # Add new cookies from the server. extract_cookies_to_jar(response.cookies, req, resp) # Give the Response some context. response.request = req response.connection = self return response
(self, req, resp)
9,673
requests.adapters
cert_verify
Verify a SSL certificate. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param conn: The urllib3 connection object associated with the cert. :param url: The requested URL. :param verify: Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: The SSL certificate to verify.
def cert_verify(self, conn, url, verify, cert): """Verify a SSL certificate. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param conn: The urllib3 connection object associated with the cert. :param url: The requested URL. :param verify: Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: The SSL certificate to verify. """ if url.lower().startswith("https") and verify: cert_loc = None # Allow self-specified cert location. if verify is not True: cert_loc = verify if not cert_loc: cert_loc = extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH) if not cert_loc or not os.path.exists(cert_loc): raise OSError( f"Could not find a suitable TLS CA certificate bundle, " f"invalid path: {cert_loc}" ) conn.cert_reqs = "CERT_REQUIRED" if not os.path.isdir(cert_loc): conn.ca_certs = cert_loc else: conn.ca_cert_dir = cert_loc else: conn.cert_reqs = "CERT_NONE" conn.ca_certs = None conn.ca_cert_dir = None if cert: if not isinstance(cert, basestring): conn.cert_file = cert[0] conn.key_file = cert[1] else: conn.cert_file = cert conn.key_file = None if conn.cert_file and not os.path.exists(conn.cert_file): raise OSError( f"Could not find the TLS certificate file, " f"invalid path: {conn.cert_file}" ) if conn.key_file and not os.path.exists(conn.key_file): raise OSError( f"Could not find the TLS key file, invalid path: {conn.key_file}" )
(self, conn, url, verify, cert)
9,674
requests.adapters
close
Disposes of any internal state. Currently, this closes the PoolManager and any active ProxyManager, which closes any pooled connections.
def close(self): """Disposes of any internal state. Currently, this closes the PoolManager and any active ProxyManager, which closes any pooled connections. """ self.poolmanager.clear() for proxy in self.proxy_manager.values(): proxy.clear()
(self)
9,675
requests.adapters
get_connection
Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param url: The URL to connect to. :param proxies: (optional) A Requests-style dictionary of proxies used on this request. :rtype: urllib3.ConnectionPool
def get_connection(self, url, proxies=None): """Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param url: The URL to connect to. :param proxies: (optional) A Requests-style dictionary of proxies used on this request. :rtype: urllib3.ConnectionPool """ proxy = select_proxy(url, proxies) if proxy: proxy = prepend_scheme_if_needed(proxy, "http") proxy_url = parse_url(proxy) if not proxy_url.host: raise InvalidProxyURL( "Please check proxy URL. It is malformed " "and could be missing the host." ) proxy_manager = self.proxy_manager_for(proxy) conn = proxy_manager.connection_from_url(url) else: # Only scheme should be lower case parsed = urlparse(url) url = parsed.geturl() conn = self.poolmanager.connection_from_url(url) return conn
(self, url, proxies=None)
9,676
cloudscraper
init_poolmanager
null
def init_poolmanager(self, *args, **kwargs): kwargs['ssl_context'] = self.ssl_context kwargs['source_address'] = self.source_address return super(CipherSuiteAdapter, self).init_poolmanager(*args, **kwargs)
(self, *args, **kwargs)
9,677
requests.adapters
proxy_headers
Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxy: The url of the proxy being used for this request. :rtype: dict
def proxy_headers(self, proxy): """Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxy: The url of the proxy being used for this request. :rtype: dict """ headers = {} username, password = get_auth_from_url(proxy) if username: headers["Proxy-Authorization"] = _basic_auth_str(username, password) return headers
(self, proxy)
9,678
cloudscraper
proxy_manager_for
null
def proxy_manager_for(self, *args, **kwargs): kwargs['ssl_context'] = self.ssl_context kwargs['source_address'] = self.source_address return super(CipherSuiteAdapter, self).proxy_manager_for(*args, **kwargs)
(self, *args, **kwargs)
9,679
requests.adapters
request_url
Obtain the url to use when making the final request. If the message is being sent through a HTTP proxy, the full URL has to be used. Otherwise, we should only use the path portion of the URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs. :rtype: str
def request_url(self, request, proxies): """Obtain the url to use when making the final request. If the message is being sent through a HTTP proxy, the full URL has to be used. Otherwise, we should only use the path portion of the URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs. :rtype: str """ proxy = select_proxy(request.url, proxies) scheme = urlparse(request.url).scheme is_proxied_http_request = proxy and scheme != "https" using_socks_proxy = False if proxy: proxy_scheme = urlparse(proxy).scheme.lower() using_socks_proxy = proxy_scheme.startswith("socks") url = request.path_url if is_proxied_http_request and not using_socks_proxy: url = urldefragauth(request.url) return url
(self, request, proxies)
9,680
requests.adapters
send
Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request content. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple or urllib3 Timeout object :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: (optional) Any user-provided SSL certificate to be trusted. :param proxies: (optional) The proxies dictionary to apply to the request. :rtype: requests.Response
def send( self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None ): """Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request content. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple or urllib3 Timeout object :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: (optional) Any user-provided SSL certificate to be trusted. :param proxies: (optional) The proxies dictionary to apply to the request. :rtype: requests.Response """ try: conn = self.get_connection(request.url, proxies) except LocationValueError as e: raise InvalidURL(e, request=request) self.cert_verify(conn, request.url, verify, cert) url = self.request_url(request, proxies) self.add_headers( request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies, ) chunked = not (request.body is None or "Content-Length" in request.headers) if isinstance(timeout, tuple): try: connect, read = timeout timeout = TimeoutSauce(connect=connect, read=read) except ValueError: raise ValueError( f"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, " f"or a single float to set both timeouts to the same value." ) elif isinstance(timeout, TimeoutSauce): pass else: timeout = TimeoutSauce(connect=timeout, read=timeout) try: resp = conn.urlopen( method=request.method, url=url, body=request.body, headers=request.headers, redirect=False, assert_same_host=False, preload_content=False, decode_content=False, retries=self.max_retries, timeout=timeout, chunked=chunked, ) except (ProtocolError, OSError) as err: raise ConnectionError(err, request=request) except MaxRetryError as e: if isinstance(e.reason, ConnectTimeoutError): # TODO: Remove this in 3.0.0: see #2811 if not isinstance(e.reason, NewConnectionError): raise ConnectTimeout(e, request=request) if isinstance(e.reason, ResponseError): raise RetryError(e, request=request) if isinstance(e.reason, _ProxyError): raise ProxyError(e, request=request) if isinstance(e.reason, _SSLError): # This branch is for urllib3 v1.22 and later. raise SSLError(e, request=request) raise ConnectionError(e, request=request) except ClosedPoolError as e: raise ConnectionError(e, request=request) except _ProxyError as e: raise ProxyError(e) except (_SSLError, _HTTPError) as e: if isinstance(e, _SSLError): # This branch is for urllib3 versions earlier than v1.22 raise SSLError(e, request=request) elif isinstance(e, ReadTimeoutError): raise ReadTimeout(e, request=request) elif isinstance(e, _InvalidHeader): raise InvalidHeader(e, request=request) else: raise return self.build_response(request, resp)
(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None)
9,681
cloudscraper
wrap_socket
null
def wrap_socket(self, *args, **kwargs): if hasattr(self.ssl_context, 'server_hostname') and self.ssl_context.server_hostname: kwargs['server_hostname'] = self.ssl_context.server_hostname self.ssl_context.check_hostname = False else: self.ssl_context.check_hostname = True return self.ssl_context.orig_wrap_socket(*args, **kwargs)
(self, *args, **kwargs)
9,682
cloudscraper
CloudScraper
null
class CloudScraper(Session): def __init__(self, *args, **kwargs): self.debug = kwargs.pop('debug', False) self.disableCloudflareV1 = kwargs.pop('disableCloudflareV1', False) self.delay = kwargs.pop('delay', None) self.captcha = kwargs.pop('captcha', {}) self.doubleDown = kwargs.pop('doubleDown', True) self.interpreter = kwargs.pop('interpreter', 'native') self.requestPreHook = kwargs.pop('requestPreHook', None) self.requestPostHook = kwargs.pop('requestPostHook', None) self.cipherSuite = kwargs.pop('cipherSuite', None) self.ecdhCurve = kwargs.pop('ecdhCurve', 'prime256v1') self.source_address = kwargs.pop('source_address', None) self.server_hostname = kwargs.pop('server_hostname', None) self.ssl_context = kwargs.pop('ssl_context', None) self.allow_brotli = kwargs.pop( 'allow_brotli', True if 'brotli' in sys.modules.keys() else False ) self.user_agent = User_Agent( allow_brotli=self.allow_brotli, browser=kwargs.pop('browser', None) ) self._solveDepthCnt = 0 self.solveDepth = kwargs.pop('solveDepth', 3) super(CloudScraper, self).__init__(*args, **kwargs) # pylint: disable=E0203 if 'requests' in self.headers['User-Agent']: # ------------------------------------------------------------------------------- # # Set a random User-Agent if no custom User-Agent has been set # ------------------------------------------------------------------------------- # self.headers = self.user_agent.headers if not self.cipherSuite: self.cipherSuite = self.user_agent.cipherSuite if isinstance(self.cipherSuite, list): self.cipherSuite = ':'.join(self.cipherSuite) self.mount( 'https://', CipherSuiteAdapter( cipherSuite=self.cipherSuite, ecdhCurve=self.ecdhCurve, server_hostname=self.server_hostname, source_address=self.source_address, ssl_context=self.ssl_context ) ) # purely to allow us to pickle dump copyreg.pickle(ssl.SSLContext, lambda obj: (obj.__class__, (obj.protocol,))) # ------------------------------------------------------------------------------- # # Allow us to pickle our session back with all variables # ------------------------------------------------------------------------------- # def __getstate__(self): return self.__dict__ # ------------------------------------------------------------------------------- # # Allow replacing actual web request call via subclassing # ------------------------------------------------------------------------------- # def perform_request(self, method, url, *args, **kwargs): return super(CloudScraper, self).request(method, url, *args, **kwargs) # ------------------------------------------------------------------------------- # # Raise an Exception with no stacktrace and reset depth counter. # ------------------------------------------------------------------------------- # def simpleException(self, exception, msg): self._solveDepthCnt = 0 sys.tracebacklimit = 0 raise exception(msg) # ------------------------------------------------------------------------------- # # debug the request via the response # ------------------------------------------------------------------------------- # @staticmethod def debugRequest(req): try: print(dump.dump_all(req).decode('utf-8', errors='backslashreplace')) except ValueError as e: print(f"Debug Error: {getattr(e, 'message', e)}") # ------------------------------------------------------------------------------- # # Decode Brotli on older versions of urllib3 manually # ------------------------------------------------------------------------------- # def decodeBrotli(self, resp): if requests.packages.urllib3.__version__ < '1.25.1' and resp.headers.get('Content-Encoding') == 'br': if self.allow_brotli and resp._content: resp._content = brotli.decompress(resp.content) else: logging.warning( f'You\'re running urllib3 {requests.packages.urllib3.__version__}, Brotli content detected, ' 'Which requires manual decompression, ' 'But option allow_brotli is set to False, ' 'We will not continue to decompress.' ) return resp # ------------------------------------------------------------------------------- # # Our hijacker request function # ------------------------------------------------------------------------------- # def request(self, method, url, *args, **kwargs): # pylint: disable=E0203 if kwargs.get('proxies') and kwargs.get('proxies') != self.proxies: self.proxies = kwargs.get('proxies') # ------------------------------------------------------------------------------- # # Pre-Hook the request via user defined function. # ------------------------------------------------------------------------------- # if self.requestPreHook: (method, url, args, kwargs) = self.requestPreHook( self, method, url, *args, **kwargs ) # ------------------------------------------------------------------------------- # # Make the request via requests. # ------------------------------------------------------------------------------- # response = self.decodeBrotli( self.perform_request(method, url, *args, **kwargs) ) # ------------------------------------------------------------------------------- # # Debug the request via the Response object. # ------------------------------------------------------------------------------- # if self.debug: self.debugRequest(response) # ------------------------------------------------------------------------------- # # Post-Hook the request aka Post-Hook the response via user defined function. # ------------------------------------------------------------------------------- # if self.requestPostHook: newResponse = self.requestPostHook(self, response) if response != newResponse: # Give me walrus in 3.7!!! response = newResponse if self.debug: print('==== requestPostHook Debug ====') self.debugRequest(response) # ------------------------------------------------------------------------------- # if not self.disableCloudflareV1: cloudflareV1 = Cloudflare(self) # ------------------------------------------------------------------------------- # # Check if Cloudflare v1 anti-bot is on # ------------------------------------------------------------------------------- # if cloudflareV1.is_Challenge_Request(response): # ------------------------------------------------------------------------------- # # Try to solve the challenge and send it back # ------------------------------------------------------------------------------- # if self._solveDepthCnt >= self.solveDepth: _ = self._solveDepthCnt self.simpleException( CloudflareLoopProtection, f"!!Loop Protection!! We have tried to solve {_} time(s) in a row." ) self._solveDepthCnt += 1 response = cloudflareV1.Challenge_Response(response, **kwargs) else: if not response.is_redirect and response.status_code not in [429, 503]: self._solveDepthCnt = 0 return response # ------------------------------------------------------------------------------- # @classmethod def create_scraper(cls, sess=None, **kwargs): """ Convenience function for creating a ready-to-go CloudScraper object. """ scraper = cls(**kwargs) if sess: for attr in ['auth', 'cert', 'cookies', 'headers', 'hooks', 'params', 'proxies', 'data']: val = getattr(sess, attr, None) if val is not None: setattr(scraper, attr, val) return scraper # ------------------------------------------------------------------------------- # # Functions for integrating cloudscraper with other applications and scripts # ------------------------------------------------------------------------------- # @classmethod def get_tokens(cls, url, **kwargs): scraper = cls.create_scraper( **{ field: kwargs.pop(field, None) for field in [ 'allow_brotli', 'browser', 'debug', 'delay', 'doubleDown', 'captcha', 'interpreter', 'source_address', 'requestPreHook', 'requestPostHook' ] if field in kwargs } ) try: resp = scraper.get(url, **kwargs) resp.raise_for_status() except Exception: logging.error(f'"{url}" returned an error. Could not collect tokens.') raise domain = urlparse(resp.url).netloc # noinspection PyUnusedLocal cookie_domain = None for d in scraper.cookies.list_domains(): if d.startswith('.') and d in (f'.{domain}'): cookie_domain = d break else: cls.simpleException( cls, CloudflareIUAMError, "Unable to find Cloudflare cookies. Does the site actually " "have Cloudflare IUAM (I'm Under Attack Mode) enabled?" ) return ( { 'cf_clearance': scraper.cookies.get('cf_clearance', '', domain=cookie_domain) }, scraper.headers['User-Agent'] ) # ------------------------------------------------------------------------------- # @classmethod def get_cookie_string(cls, url, **kwargs): """ Convenience function for building a Cookie HTTP header value. """ tokens, user_agent = cls.get_tokens(url, **kwargs) return '; '.join('='.join(pair) for pair in tokens.items()), user_agent
(*args, **kwargs)
9,685
cloudscraper
__getstate__
null
def __getstate__(self): return self.__dict__
(self)
9,686
cloudscraper
__init__
null
def __init__(self, *args, **kwargs): self.debug = kwargs.pop('debug', False) self.disableCloudflareV1 = kwargs.pop('disableCloudflareV1', False) self.delay = kwargs.pop('delay', None) self.captcha = kwargs.pop('captcha', {}) self.doubleDown = kwargs.pop('doubleDown', True) self.interpreter = kwargs.pop('interpreter', 'native') self.requestPreHook = kwargs.pop('requestPreHook', None) self.requestPostHook = kwargs.pop('requestPostHook', None) self.cipherSuite = kwargs.pop('cipherSuite', None) self.ecdhCurve = kwargs.pop('ecdhCurve', 'prime256v1') self.source_address = kwargs.pop('source_address', None) self.server_hostname = kwargs.pop('server_hostname', None) self.ssl_context = kwargs.pop('ssl_context', None) self.allow_brotli = kwargs.pop( 'allow_brotli', True if 'brotli' in sys.modules.keys() else False ) self.user_agent = User_Agent( allow_brotli=self.allow_brotli, browser=kwargs.pop('browser', None) ) self._solveDepthCnt = 0 self.solveDepth = kwargs.pop('solveDepth', 3) super(CloudScraper, self).__init__(*args, **kwargs) # pylint: disable=E0203 if 'requests' in self.headers['User-Agent']: # ------------------------------------------------------------------------------- # # Set a random User-Agent if no custom User-Agent has been set # ------------------------------------------------------------------------------- # self.headers = self.user_agent.headers if not self.cipherSuite: self.cipherSuite = self.user_agent.cipherSuite if isinstance(self.cipherSuite, list): self.cipherSuite = ':'.join(self.cipherSuite) self.mount( 'https://', CipherSuiteAdapter( cipherSuite=self.cipherSuite, ecdhCurve=self.ecdhCurve, server_hostname=self.server_hostname, source_address=self.source_address, ssl_context=self.ssl_context ) ) # purely to allow us to pickle dump copyreg.pickle(ssl.SSLContext, lambda obj: (obj.__class__, (obj.protocol,)))
(self, *args, **kwargs)
9,687
requests.sessions
__setstate__
null
def __setstate__(self, state): for attr, value in state.items(): setattr(self, attr, value)
(self, state)
9,688
requests.sessions
close
Closes all adapters and as such the session
def close(self): """Closes all adapters and as such the session""" for v in self.adapters.values(): v.close()
(self)
9,689
cloudscraper
debugRequest
null
@staticmethod def debugRequest(req): try: print(dump.dump_all(req).decode('utf-8', errors='backslashreplace')) except ValueError as e: print(f"Debug Error: {getattr(e, 'message', e)}")
(req)
9,690
cloudscraper
decodeBrotli
null
def decodeBrotli(self, resp): if requests.packages.urllib3.__version__ < '1.25.1' and resp.headers.get('Content-Encoding') == 'br': if self.allow_brotli and resp._content: resp._content = brotli.decompress(resp.content) else: logging.warning( f'You\'re running urllib3 {requests.packages.urllib3.__version__}, Brotli content detected, ' 'Which requires manual decompression, ' 'But option allow_brotli is set to False, ' 'We will not continue to decompress.' ) return resp
(self, resp)
9,691
requests.sessions
delete
Sends a DELETE request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
def delete(self, url, **kwargs): r"""Sends a DELETE request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ return self.request("DELETE", url, **kwargs)
(self, url, **kwargs)
9,692
requests.sessions
get
Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
def get(self, url, **kwargs): r"""Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault("allow_redirects", True) return self.request("GET", url, **kwargs)
(self, url, **kwargs)
9,693
requests.sessions
get_adapter
Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter
def get_adapter(self, url): """ Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter """ for (prefix, adapter) in self.adapters.items(): if url.lower().startswith(prefix.lower()): return adapter # Nothing matches :-/ raise InvalidSchema(f"No connection adapters were found for {url!r}")
(self, url)
9,694
requests.sessions
get_redirect_target
Receives a Response. Returns a redirect URI or ``None``
def get_redirect_target(self, resp): """Receives a Response. Returns a redirect URI or ``None``""" # Due to the nature of how requests processes redirects this method will # be called at least once upon the original response and at least twice # on each subsequent redirect response (if any). # If a custom mixin is used to handle this logic, it may be advantageous # to cache the redirect location onto the response object as a private # attribute. if resp.is_redirect: location = resp.headers["location"] # Currently the underlying http module on py3 decode headers # in latin1, but empirical evidence suggests that latin1 is very # rarely used with non-ASCII characters in HTTP headers. # It is more likely to get UTF8 header rather than latin1. # This causes incorrect handling of UTF8 encoded location headers. # To solve this, we re-encode the location in latin1. location = location.encode("latin1") return to_native_string(location, "utf8") return None
(self, resp)
9,695
requests.sessions
head
Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
def head(self, url, **kwargs): r"""Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault("allow_redirects", False) return self.request("HEAD", url, **kwargs)
(self, url, **kwargs)
9,696
requests.sessions
merge_environment_settings
Check the environment and merge it with some settings. :rtype: dict
def merge_environment_settings(self, url, proxies, stream, verify, cert): """ Check the environment and merge it with some settings. :rtype: dict """ # Gather clues from the surrounding environment. if self.trust_env: # Set environment's proxies. no_proxy = proxies.get("no_proxy") if proxies is not None else None env_proxies = get_environ_proxies(url, no_proxy=no_proxy) for (k, v) in env_proxies.items(): proxies.setdefault(k, v) # Look for requests environment configuration # and be compatible with cURL. if verify is True or verify is None: verify = ( os.environ.get("REQUESTS_CA_BUNDLE") or os.environ.get("CURL_CA_BUNDLE") or verify ) # Merge all the kwargs. proxies = merge_setting(proxies, self.proxies) stream = merge_setting(stream, self.stream) verify = merge_setting(verify, self.verify) cert = merge_setting(cert, self.cert) return {"proxies": proxies, "stream": stream, "verify": verify, "cert": cert}
(self, url, proxies, stream, verify, cert)
9,697
requests.sessions
mount
Registers a connection adapter to a prefix. Adapters are sorted in descending order by prefix length.
def mount(self, prefix, adapter): """Registers a connection adapter to a prefix. Adapters are sorted in descending order by prefix length. """ self.adapters[prefix] = adapter keys_to_move = [k for k in self.adapters if len(k) < len(prefix)] for key in keys_to_move: self.adapters[key] = self.adapters.pop(key)
(self, prefix, adapter)
9,698
requests.sessions
options
Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
def options(self, url, **kwargs): r"""Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault("allow_redirects", True) return self.request("OPTIONS", url, **kwargs)
(self, url, **kwargs)
9,699
requests.sessions
patch
Sends a PATCH request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
def patch(self, url, data=None, **kwargs): r"""Sends a PATCH request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ return self.request("PATCH", url, data=data, **kwargs)
(self, url, data=None, **kwargs)
9,700
cloudscraper
perform_request
null
def perform_request(self, method, url, *args, **kwargs): return super(CloudScraper, self).request(method, url, *args, **kwargs)
(self, method, url, *args, **kwargs)
9,701
requests.sessions
post
Sends a POST request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
def post(self, url, data=None, json=None, **kwargs): r"""Sends a POST request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ return self.request("POST", url, data=data, json=json, **kwargs)
(self, url, data=None, json=None, **kwargs)
9,702
requests.sessions
prepare_request
Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this session's settings. :rtype: requests.PreparedRequest
def prepare_request(self, request): """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this session's settings. :rtype: requests.PreparedRequest """ cookies = request.cookies or {} # Bootstrap CookieJar. if not isinstance(cookies, cookielib.CookieJar): cookies = cookiejar_from_dict(cookies) # Merge with session cookies merged_cookies = merge_cookies( merge_cookies(RequestsCookieJar(), self.cookies), cookies ) # Set environment's basic authentication if not explicitly set. auth = request.auth if self.trust_env and not auth and not self.auth: auth = get_netrc_auth(request.url) p = PreparedRequest() p.prepare( method=request.method.upper(), url=request.url, files=request.files, data=request.data, json=request.json, headers=merge_setting( request.headers, self.headers, dict_class=CaseInsensitiveDict ), params=merge_setting(request.params, self.params), auth=merge_setting(auth, self.auth), cookies=merged_cookies, hooks=merge_hooks(request.hooks, self.hooks), ) return p
(self, request)
9,703
requests.sessions
put
Sends a PUT request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
def put(self, url, data=None, **kwargs): r"""Sends a PUT request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ return self.request("PUT", url, data=data, **kwargs)
(self, url, data=None, **kwargs)
9,704
requests.sessions
rebuild_auth
When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss.
def rebuild_auth(self, prepared_request, response): """When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss. """ headers = prepared_request.headers url = prepared_request.url if "Authorization" in headers and self.should_strip_auth( response.request.url, url ): # If we get redirected to a new host, we should strip out any # authentication headers. del headers["Authorization"] # .netrc might have more auth for us on our new host. new_auth = get_netrc_auth(url) if self.trust_env else None if new_auth is not None: prepared_request.prepare_auth(new_auth)
(self, prepared_request, response)
9,705
requests.sessions
rebuild_method
When being redirected we may want to change the method of the request based on certain specs or browser behavior.
def rebuild_method(self, prepared_request, response): """When being redirected we may want to change the method of the request based on certain specs or browser behavior. """ method = prepared_request.method # https://tools.ietf.org/html/rfc7231#section-6.4.4 if response.status_code == codes.see_other and method != "HEAD": method = "GET" # Do what the browsers do, despite standards... # First, turn 302s into GETs. if response.status_code == codes.found and method != "HEAD": method = "GET" # Second, if a POST is responded to with a 301, turn it into a GET. # This bizarre behaviour is explained in Issue 1704. if response.status_code == codes.moved and method == "POST": method = "GET" prepared_request.method = method
(self, prepared_request, response)
9,706
requests.sessions
rebuild_proxies
This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect). This method also replaces the Proxy-Authorization header where necessary. :rtype: dict
def rebuild_proxies(self, prepared_request, proxies): """This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect). This method also replaces the Proxy-Authorization header where necessary. :rtype: dict """ headers = prepared_request.headers scheme = urlparse(prepared_request.url).scheme new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env) if "Proxy-Authorization" in headers: del headers["Proxy-Authorization"] try: username, password = get_auth_from_url(new_proxies[scheme]) except KeyError: username, password = None, None # urllib3 handles proxy authorization for us in the standard adapter. # Avoid appending this to TLS tunneled requests where it may be leaked. if not scheme.startswith('https') and username and password: headers["Proxy-Authorization"] = _basic_auth_str(username, password) return new_proxies
(self, prepared_request, proxies)
9,707
cloudscraper
request
null
def request(self, method, url, *args, **kwargs): # pylint: disable=E0203 if kwargs.get('proxies') and kwargs.get('proxies') != self.proxies: self.proxies = kwargs.get('proxies') # ------------------------------------------------------------------------------- # # Pre-Hook the request via user defined function. # ------------------------------------------------------------------------------- # if self.requestPreHook: (method, url, args, kwargs) = self.requestPreHook( self, method, url, *args, **kwargs ) # ------------------------------------------------------------------------------- # # Make the request via requests. # ------------------------------------------------------------------------------- # response = self.decodeBrotli( self.perform_request(method, url, *args, **kwargs) ) # ------------------------------------------------------------------------------- # # Debug the request via the Response object. # ------------------------------------------------------------------------------- # if self.debug: self.debugRequest(response) # ------------------------------------------------------------------------------- # # Post-Hook the request aka Post-Hook the response via user defined function. # ------------------------------------------------------------------------------- # if self.requestPostHook: newResponse = self.requestPostHook(self, response) if response != newResponse: # Give me walrus in 3.7!!! response = newResponse if self.debug: print('==== requestPostHook Debug ====') self.debugRequest(response) # ------------------------------------------------------------------------------- # if not self.disableCloudflareV1: cloudflareV1 = Cloudflare(self) # ------------------------------------------------------------------------------- # # Check if Cloudflare v1 anti-bot is on # ------------------------------------------------------------------------------- # if cloudflareV1.is_Challenge_Request(response): # ------------------------------------------------------------------------------- # # Try to solve the challenge and send it back # ------------------------------------------------------------------------------- # if self._solveDepthCnt >= self.solveDepth: _ = self._solveDepthCnt self.simpleException( CloudflareLoopProtection, f"!!Loop Protection!! We have tried to solve {_} time(s) in a row." ) self._solveDepthCnt += 1 response = cloudflareV1.Challenge_Response(response, **kwargs) else: if not response.is_redirect and response.status_code not in [429, 503]: self._solveDepthCnt = 0 return response
(self, method, url, *args, **kwargs)
9,708
requests.sessions
resolve_redirects
Receives a Response. Returns a generator of Responses or Requests.
def resolve_redirects( self, resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs, ): """Receives a Response. Returns a generator of Responses or Requests.""" hist = [] # keep track of history url = self.get_redirect_target(resp) previous_fragment = urlparse(req.url).fragment while url: prepared_request = req.copy() # Update history and keep track of redirects. # resp.history must ignore the original request in this loop hist.append(resp) resp.history = hist[1:] try: resp.content # Consume socket so it can be released except (ChunkedEncodingError, ContentDecodingError, RuntimeError): resp.raw.read(decode_content=False) if len(resp.history) >= self.max_redirects: raise TooManyRedirects( f"Exceeded {self.max_redirects} redirects.", response=resp ) # Release the connection back into the pool. resp.close() # Handle redirection without scheme (see: RFC 1808 Section 4) if url.startswith("//"): parsed_rurl = urlparse(resp.url) url = ":".join([to_native_string(parsed_rurl.scheme), url]) # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2) parsed = urlparse(url) if parsed.fragment == "" and previous_fragment: parsed = parsed._replace(fragment=previous_fragment) elif parsed.fragment: previous_fragment = parsed.fragment url = parsed.geturl() # Facilitate relative 'location' headers, as allowed by RFC 7231. # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') # Compliant with RFC3986, we percent encode the url. if not parsed.netloc: url = urljoin(resp.url, requote_uri(url)) else: url = requote_uri(url) prepared_request.url = to_native_string(url) self.rebuild_method(prepared_request, resp) # https://github.com/psf/requests/issues/1084 if resp.status_code not in ( codes.temporary_redirect, codes.permanent_redirect, ): # https://github.com/psf/requests/issues/3490 purged_headers = ("Content-Length", "Content-Type", "Transfer-Encoding") for header in purged_headers: prepared_request.headers.pop(header, None) prepared_request.body = None headers = prepared_request.headers headers.pop("Cookie", None) # Extract any cookies sent on the response to the cookiejar # in the new request. Because we've mutated our copied prepared # request, use the old one that we haven't yet touched. extract_cookies_to_jar(prepared_request._cookies, req, resp.raw) merge_cookies(prepared_request._cookies, self.cookies) prepared_request.prepare_cookies(prepared_request._cookies) # Rebuild auth and proxy information. proxies = self.rebuild_proxies(prepared_request, proxies) self.rebuild_auth(prepared_request, resp) # A failed tell() sets `_body_position` to `object()`. This non-None # value ensures `rewindable` will be True, allowing us to raise an # UnrewindableBodyError, instead of hanging the connection. rewindable = prepared_request._body_position is not None and ( "Content-Length" in headers or "Transfer-Encoding" in headers ) # Attempt to rewind consumed file-like object. if rewindable: rewind_body(prepared_request) # Override the original request. req = prepared_request if yield_requests: yield req else: resp = self.send( req, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies, allow_redirects=False, **adapter_kwargs, ) extract_cookies_to_jar(self.cookies, prepared_request, resp.raw) # extract redirect url, if any, for the next loop url = self.get_redirect_target(resp) yield resp
(self, resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs)
9,709
requests.sessions
send
Send a given PreparedRequest. :rtype: requests.Response
def send(self, request, **kwargs): """Send a given PreparedRequest. :rtype: requests.Response """ # Set defaults that the hooks can utilize to ensure they always have # the correct parameters to reproduce the previous request. kwargs.setdefault("stream", self.stream) kwargs.setdefault("verify", self.verify) kwargs.setdefault("cert", self.cert) if "proxies" not in kwargs: kwargs["proxies"] = resolve_proxies(request, self.proxies, self.trust_env) # It's possible that users might accidentally send a Request object. # Guard against that specific failure case. if isinstance(request, Request): raise ValueError("You can only send PreparedRequests.") # Set up variables needed for resolve_redirects and dispatching of hooks allow_redirects = kwargs.pop("allow_redirects", True) stream = kwargs.get("stream") hooks = request.hooks # Get the appropriate adapter to use adapter = self.get_adapter(url=request.url) # Start time (approximately) of the request start = preferred_clock() # Send the request r = adapter.send(request, **kwargs) # Total elapsed time of the request (approximately) elapsed = preferred_clock() - start r.elapsed = timedelta(seconds=elapsed) # Response manipulation hooks r = dispatch_hook("response", hooks, r, **kwargs) # Persist cookies if r.history: # If the hooks create history then we want those cookies too for resp in r.history: extract_cookies_to_jar(self.cookies, resp.request, resp.raw) extract_cookies_to_jar(self.cookies, request, r.raw) # Resolve redirects if allowed. if allow_redirects: # Redirect resolving generator. gen = self.resolve_redirects(r, request, **kwargs) history = [resp for resp in gen] else: history = [] # Shuffle things around if there's history. if history: # Insert the first (original) request at the start history.insert(0, r) # Get the last request made r = history.pop() r.history = history # If redirects aren't being followed, store the response on the Request for Response.next(). if not allow_redirects: try: r._next = next( self.resolve_redirects(r, request, yield_requests=True, **kwargs) ) except StopIteration: pass if not stream: r.content return r
(self, request, **kwargs)
9,710
requests.sessions
should_strip_auth
Decide whether Authorization header should be removed when redirecting
def should_strip_auth(self, old_url, new_url): """Decide whether Authorization header should be removed when redirecting""" old_parsed = urlparse(old_url) new_parsed = urlparse(new_url) if old_parsed.hostname != new_parsed.hostname: return True # Special case: allow http -> https redirect when using the standard # ports. This isn't specified by RFC 7235, but is kept to avoid # breaking backwards compatibility with older versions of requests # that allowed any redirects on the same host. if ( old_parsed.scheme == "http" and old_parsed.port in (80, None) and new_parsed.scheme == "https" and new_parsed.port in (443, None) ): return False # Handle default port usage corresponding to scheme. changed_port = old_parsed.port != new_parsed.port changed_scheme = old_parsed.scheme != new_parsed.scheme default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None) if ( not changed_scheme and old_parsed.port in default_port and new_parsed.port in default_port ): return False # Standard case: root URI must match return changed_port or changed_scheme
(self, old_url, new_url)
9,711
cloudscraper
simpleException
null
def simpleException(self, exception, msg): self._solveDepthCnt = 0 sys.tracebacklimit = 0 raise exception(msg)
(self, exception, msg)
9,712
cloudscraper.cloudflare
Cloudflare
null
class Cloudflare(): def __init__(self, cloudscraper): self.cloudscraper = cloudscraper # ------------------------------------------------------------------------------- # # Unescape / decode html entities # ------------------------------------------------------------------------------- # @staticmethod def unescape(html_text): if sys.version_info >= (3, 0): if sys.version_info >= (3, 4): return html.unescape(html_text) return HTMLParser().unescape(html_text) return HTMLParser().unescape(html_text) # ------------------------------------------------------------------------------- # # check if the response contains a valid Cloudflare challenge # ------------------------------------------------------------------------------- # @staticmethod def is_IUAM_Challenge(resp): try: return ( resp.headers.get('Server', '').startswith('cloudflare') and resp.status_code in [429, 503] and re.search(r'/cdn-cgi/images/trace/jsch/', resp.text, re.M | re.S) and re.search( r'''<form .*?="challenge-form" action="/\S+__cf_chl_f_tk=''', resp.text, re.M | re.S ) ) except AttributeError: pass return False # ------------------------------------------------------------------------------- # # check if the response contains new Cloudflare challenge # ------------------------------------------------------------------------------- # def is_New_IUAM_Challenge(self, resp): try: return ( self.is_IUAM_Challenge(resp) and re.search( r'''cpo.src\s*=\s*['"]/cdn-cgi/challenge-platform/\S+orchestrate/jsch/v1''', resp.text, re.M | re.S ) ) except AttributeError: pass return False # ------------------------------------------------------------------------------- # # check if the response contains a v2 hCaptcha Cloudflare challenge # ------------------------------------------------------------------------------- # def is_New_Captcha_Challenge(self, resp): try: return ( self.is_Captcha_Challenge(resp) and re.search( r'''cpo.src\s*=\s*['"]/cdn-cgi/challenge-platform/\S+orchestrate/(captcha|managed)/v1''', resp.text, re.M | re.S ) ) except AttributeError: pass return False # ------------------------------------------------------------------------------- # # check if the response contains a Cloudflare hCaptcha challenge # ------------------------------------------------------------------------------- # @staticmethod def is_Captcha_Challenge(resp): try: return ( resp.headers.get('Server', '').startswith('cloudflare') and resp.status_code == 403 and re.search(r'/cdn-cgi/images/trace/(captcha|managed)/', resp.text, re.M | re.S) and re.search( r'''<form .*?="challenge-form" action="/\S+__cf_chl_f_tk=''', resp.text, re.M | re.S ) ) except AttributeError: pass return False # ------------------------------------------------------------------------------- # # check if the response contains Firewall 1020 Error # ------------------------------------------------------------------------------- # @staticmethod def is_Firewall_Blocked(resp): try: return ( resp.headers.get('Server', '').startswith('cloudflare') and resp.status_code == 403 and re.search( r'<span class="cf-error-code">1020</span>', resp.text, re.M | re.DOTALL ) ) except AttributeError: pass return False # ------------------------------------------------------------------------------- # # Wrapper for is_Captcha_Challenge, is_IUAM_Challenge, is_Firewall_Blocked # ------------------------------------------------------------------------------- # def is_Challenge_Request(self, resp): if self.is_Firewall_Blocked(resp): self.cloudscraper.simpleException( CloudflareCode1020, 'Cloudflare has blocked this request (Code 1020 Detected).' ) if self.is_New_Captcha_Challenge(resp): self.cloudscraper.simpleException( CloudflareChallengeError, 'Detected a Cloudflare version 2 Captcha challenge, This feature is not available in the opensource (free) version.' ) if self.is_New_IUAM_Challenge(resp): self.cloudscraper.simpleException( CloudflareChallengeError, 'Detected a Cloudflare version 2 challenge, This feature is not available in the opensource (free) version.' ) if self.is_Captcha_Challenge(resp) or self.is_IUAM_Challenge(resp): if self.cloudscraper.debug: print('Detected a Cloudflare version 1 challenge.') return True return False # ------------------------------------------------------------------------------- # # Try to solve cloudflare javascript challenge. # ------------------------------------------------------------------------------- # def IUAM_Challenge_Response(self, body, url, interpreter): try: formPayload = re.search( r'<form (?P<form>.*?="challenge-form" ' r'action="(?P<challengeUUID>.*?' r'__cf_chl_f_tk=\S+)"(.*?)</form>)', body, re.M | re.DOTALL ).groupdict() if not all(key in formPayload for key in ['form', 'challengeUUID']): self.cloudscraper.simpleException( CloudflareIUAMError, "Cloudflare IUAM detected, unfortunately we can't extract the parameters correctly." ) payload = OrderedDict() for challengeParam in re.findall(r'^\s*<input\s(.*?)/>', formPayload['form'], re.M | re.S): inputPayload = dict(re.findall(r'(\S+)="(\S+)"', challengeParam)) if inputPayload.get('name') in ['r', 'jschl_vc', 'pass']: payload.update({inputPayload['name']: inputPayload['value']}) except AttributeError: self.cloudscraper.simpleException( CloudflareIUAMError, "Cloudflare IUAM detected, unfortunately we can't extract the parameters correctly." ) hostParsed = urlparse(url) try: payload['jschl_answer'] = JavaScriptInterpreter.dynamicImport( interpreter ).solveChallenge(body, hostParsed.netloc) except Exception as e: self.cloudscraper.simpleException( CloudflareIUAMError, f"Unable to parse Cloudflare anti-bots page: {getattr(e, 'message', e)}" ) return { 'url': f"{hostParsed.scheme}://{hostParsed.netloc}{self.unescape(formPayload['challengeUUID'])}", 'data': payload } # ------------------------------------------------------------------------------- # # Try to solve the Captcha challenge via 3rd party. # ------------------------------------------------------------------------------- # def captcha_Challenge_Response(self, provider, provider_params, body, url): try: formPayload = re.search( r'<form (?P<form>.*?="challenge-form" ' r'action="(?P<challengeUUID>.*?__cf_chl_captcha_tk__=\S+)"(.*?)</form>)', body, re.M | re.DOTALL ).groupdict() if not all(key in formPayload for key in ['form', 'challengeUUID']): self.cloudscraper.simpleException( CloudflareCaptchaError, "Cloudflare Captcha detected, unfortunately we can't extract the parameters correctly." ) payload = OrderedDict( re.findall( r'(name="r"\svalue|data-ray|data-sitekey|name="cf_captcha_kind"\svalue)="(.*?)"', formPayload['form'] ) ) captchaType = 'reCaptcha' if payload['name="cf_captcha_kind" value'] == 're' else 'hCaptcha' except (AttributeError, KeyError): self.cloudscraper.simpleException( CloudflareCaptchaError, "Cloudflare Captcha detected, unfortunately we can't extract the parameters correctly." ) # ------------------------------------------------------------------------------- # # Pass proxy parameter to provider to solve captcha. # ------------------------------------------------------------------------------- # if self.cloudscraper.proxies and self.cloudscraper.proxies != self.cloudscraper.captcha.get('proxy'): self.cloudscraper.captcha['proxy'] = self.proxies # ------------------------------------------------------------------------------- # # Pass User-Agent if provider supports it to solve captcha. # ------------------------------------------------------------------------------- # self.cloudscraper.captcha['User-Agent'] = self.cloudscraper.headers['User-Agent'] # ------------------------------------------------------------------------------- # # Submit job to provider to request captcha solve. # ------------------------------------------------------------------------------- # captchaResponse = Captcha.dynamicImport( provider.lower() ).solveCaptcha( captchaType, url, payload['data-sitekey'], provider_params ) # ------------------------------------------------------------------------------- # # Parse and handle the response of solved captcha. # ------------------------------------------------------------------------------- # dataPayload = OrderedDict([ ('r', payload.get('name="r" value', '')), ('cf_captcha_kind', payload['name="cf_captcha_kind" value']), ('id', payload.get('data-ray')), ('g-recaptcha-response', captchaResponse) ]) if captchaType == 'hCaptcha': dataPayload.update({'h-captcha-response': captchaResponse}) hostParsed = urlparse(url) return { 'url': f"{hostParsed.scheme}://{hostParsed.netloc}{self.unescape(formPayload['challengeUUID'])}", 'data': dataPayload } # ------------------------------------------------------------------------------- # # Attempt to handle and send the challenge response back to cloudflare # ------------------------------------------------------------------------------- # def Challenge_Response(self, resp, **kwargs): if self.is_Captcha_Challenge(resp): # ------------------------------------------------------------------------------- # # double down on the request as some websites are only checking # if cfuid is populated before issuing Captcha. # ------------------------------------------------------------------------------- # if self.cloudscraper.doubleDown: resp = self.cloudscraper.decodeBrotli( self.cloudscraper.perform_request(resp.request.method, resp.url, **kwargs) ) if not self.is_Captcha_Challenge(resp): return resp # ------------------------------------------------------------------------------- # # if no captcha provider raise a runtime error. # ------------------------------------------------------------------------------- # if ( not self.cloudscraper.captcha or not isinstance(self.cloudscraper.captcha, dict) or not self.cloudscraper.captcha.get('provider') ): self.cloudscraper.simpleException( CloudflareCaptchaProvider, "Cloudflare Captcha detected, unfortunately you haven't loaded an anti Captcha provider " "correctly via the 'captcha' parameter." ) # ------------------------------------------------------------------------------- # # if provider is return_response, return the response without doing anything. # ------------------------------------------------------------------------------- # if self.cloudscraper.captcha.get('provider') == 'return_response': return resp # ------------------------------------------------------------------------------- # # Submit request to parser wrapper to solve captcha # ------------------------------------------------------------------------------- # submit_url = self.captcha_Challenge_Response( self.cloudscraper.captcha.get('provider'), self.cloudscraper.captcha, resp.text, resp.url ) else: # ------------------------------------------------------------------------------- # # Cloudflare requires a delay before solving the challenge # ------------------------------------------------------------------------------- # if not self.cloudscraper.delay: try: delay = float( re.search( r'submit\(\);\r?\n\s*},\s*([0-9]+)', resp.text ).group(1) ) / float(1000) if isinstance(delay, (int, float)): self.cloudscraper.delay = delay except (AttributeError, ValueError): self.cloudscraper.simpleException( CloudflareIUAMError, "Cloudflare IUAM possibility malformed, issue extracing delay value." ) time.sleep(self.cloudscraper.delay) # ------------------------------------------------------------------------------- # submit_url = self.IUAM_Challenge_Response( resp.text, resp.url, self.cloudscraper.interpreter ) # ------------------------------------------------------------------------------- # # Send the Challenge Response back to Cloudflare # ------------------------------------------------------------------------------- # if submit_url: def updateAttr(obj, name, newValue): try: obj[name].update(newValue) return obj[name] except (AttributeError, KeyError): obj[name] = {} obj[name].update(newValue) return obj[name] cloudflare_kwargs = deepcopy(kwargs) cloudflare_kwargs['allow_redirects'] = False cloudflare_kwargs['data'] = updateAttr( cloudflare_kwargs, 'data', submit_url['data'] ) urlParsed = urlparse(resp.url) cloudflare_kwargs['headers'] = updateAttr( cloudflare_kwargs, 'headers', { 'Origin': f'{urlParsed.scheme}://{urlParsed.netloc}', 'Referer': resp.url } ) challengeSubmitResponse = self.cloudscraper.request( 'POST', submit_url['url'], **cloudflare_kwargs ) if challengeSubmitResponse.status_code == 400: self.cloudscraper.simpleException( CloudflareSolveError, 'Invalid challenge answer detected, Cloudflare broken?' ) # ------------------------------------------------------------------------------- # # Return response if Cloudflare is doing content pass through instead of 3xx # else request with redirect URL also handle protocol scheme change http -> https # ------------------------------------------------------------------------------- # if not challengeSubmitResponse.is_redirect: return challengeSubmitResponse else: cloudflare_kwargs = deepcopy(kwargs) cloudflare_kwargs['headers'] = updateAttr( cloudflare_kwargs, 'headers', {'Referer': challengeSubmitResponse.url} ) if not urlparse(challengeSubmitResponse.headers['Location']).netloc: redirect_location = urljoin( challengeSubmitResponse.url, challengeSubmitResponse.headers['Location'] ) else: redirect_location = challengeSubmitResponse.headers['Location'] return self.cloudscraper.request( resp.request.method, redirect_location, **cloudflare_kwargs ) # ------------------------------------------------------------------------------- # # We shouldn't be here... # Re-request the original query and/or process again.... # ------------------------------------------------------------------------------- # return self.cloudscraper.request(resp.request.method, resp.url, **kwargs) # ------------------------------------------------------------------------------- #
(cloudscraper)
9,713
cloudscraper.cloudflare
Challenge_Response
null
def Challenge_Response(self, resp, **kwargs): if self.is_Captcha_Challenge(resp): # ------------------------------------------------------------------------------- # # double down on the request as some websites are only checking # if cfuid is populated before issuing Captcha. # ------------------------------------------------------------------------------- # if self.cloudscraper.doubleDown: resp = self.cloudscraper.decodeBrotli( self.cloudscraper.perform_request(resp.request.method, resp.url, **kwargs) ) if not self.is_Captcha_Challenge(resp): return resp # ------------------------------------------------------------------------------- # # if no captcha provider raise a runtime error. # ------------------------------------------------------------------------------- # if ( not self.cloudscraper.captcha or not isinstance(self.cloudscraper.captcha, dict) or not self.cloudscraper.captcha.get('provider') ): self.cloudscraper.simpleException( CloudflareCaptchaProvider, "Cloudflare Captcha detected, unfortunately you haven't loaded an anti Captcha provider " "correctly via the 'captcha' parameter." ) # ------------------------------------------------------------------------------- # # if provider is return_response, return the response without doing anything. # ------------------------------------------------------------------------------- # if self.cloudscraper.captcha.get('provider') == 'return_response': return resp # ------------------------------------------------------------------------------- # # Submit request to parser wrapper to solve captcha # ------------------------------------------------------------------------------- # submit_url = self.captcha_Challenge_Response( self.cloudscraper.captcha.get('provider'), self.cloudscraper.captcha, resp.text, resp.url ) else: # ------------------------------------------------------------------------------- # # Cloudflare requires a delay before solving the challenge # ------------------------------------------------------------------------------- # if not self.cloudscraper.delay: try: delay = float( re.search( r'submit\(\);\r?\n\s*},\s*([0-9]+)', resp.text ).group(1) ) / float(1000) if isinstance(delay, (int, float)): self.cloudscraper.delay = delay except (AttributeError, ValueError): self.cloudscraper.simpleException( CloudflareIUAMError, "Cloudflare IUAM possibility malformed, issue extracing delay value." ) time.sleep(self.cloudscraper.delay) # ------------------------------------------------------------------------------- # submit_url = self.IUAM_Challenge_Response( resp.text, resp.url, self.cloudscraper.interpreter ) # ------------------------------------------------------------------------------- # # Send the Challenge Response back to Cloudflare # ------------------------------------------------------------------------------- # if submit_url: def updateAttr(obj, name, newValue): try: obj[name].update(newValue) return obj[name] except (AttributeError, KeyError): obj[name] = {} obj[name].update(newValue) return obj[name] cloudflare_kwargs = deepcopy(kwargs) cloudflare_kwargs['allow_redirects'] = False cloudflare_kwargs['data'] = updateAttr( cloudflare_kwargs, 'data', submit_url['data'] ) urlParsed = urlparse(resp.url) cloudflare_kwargs['headers'] = updateAttr( cloudflare_kwargs, 'headers', { 'Origin': f'{urlParsed.scheme}://{urlParsed.netloc}', 'Referer': resp.url } ) challengeSubmitResponse = self.cloudscraper.request( 'POST', submit_url['url'], **cloudflare_kwargs ) if challengeSubmitResponse.status_code == 400: self.cloudscraper.simpleException( CloudflareSolveError, 'Invalid challenge answer detected, Cloudflare broken?' ) # ------------------------------------------------------------------------------- # # Return response if Cloudflare is doing content pass through instead of 3xx # else request with redirect URL also handle protocol scheme change http -> https # ------------------------------------------------------------------------------- # if not challengeSubmitResponse.is_redirect: return challengeSubmitResponse else: cloudflare_kwargs = deepcopy(kwargs) cloudflare_kwargs['headers'] = updateAttr( cloudflare_kwargs, 'headers', {'Referer': challengeSubmitResponse.url} ) if not urlparse(challengeSubmitResponse.headers['Location']).netloc: redirect_location = urljoin( challengeSubmitResponse.url, challengeSubmitResponse.headers['Location'] ) else: redirect_location = challengeSubmitResponse.headers['Location'] return self.cloudscraper.request( resp.request.method, redirect_location, **cloudflare_kwargs ) # ------------------------------------------------------------------------------- # # We shouldn't be here... # Re-request the original query and/or process again.... # ------------------------------------------------------------------------------- # return self.cloudscraper.request(resp.request.method, resp.url, **kwargs)
(self, resp, **kwargs)
9,714
cloudscraper.cloudflare
IUAM_Challenge_Response
null
def IUAM_Challenge_Response(self, body, url, interpreter): try: formPayload = re.search( r'<form (?P<form>.*?="challenge-form" ' r'action="(?P<challengeUUID>.*?' r'__cf_chl_f_tk=\S+)"(.*?)</form>)', body, re.M | re.DOTALL ).groupdict() if not all(key in formPayload for key in ['form', 'challengeUUID']): self.cloudscraper.simpleException( CloudflareIUAMError, "Cloudflare IUAM detected, unfortunately we can't extract the parameters correctly." ) payload = OrderedDict() for challengeParam in re.findall(r'^\s*<input\s(.*?)/>', formPayload['form'], re.M | re.S): inputPayload = dict(re.findall(r'(\S+)="(\S+)"', challengeParam)) if inputPayload.get('name') in ['r', 'jschl_vc', 'pass']: payload.update({inputPayload['name']: inputPayload['value']}) except AttributeError: self.cloudscraper.simpleException( CloudflareIUAMError, "Cloudflare IUAM detected, unfortunately we can't extract the parameters correctly." ) hostParsed = urlparse(url) try: payload['jschl_answer'] = JavaScriptInterpreter.dynamicImport( interpreter ).solveChallenge(body, hostParsed.netloc) except Exception as e: self.cloudscraper.simpleException( CloudflareIUAMError, f"Unable to parse Cloudflare anti-bots page: {getattr(e, 'message', e)}" ) return { 'url': f"{hostParsed.scheme}://{hostParsed.netloc}{self.unescape(formPayload['challengeUUID'])}", 'data': payload }
(self, body, url, interpreter)
9,715
cloudscraper.cloudflare
__init__
null
def __init__(self, cloudscraper): self.cloudscraper = cloudscraper
(self, cloudscraper)
9,716
cloudscraper.cloudflare
captcha_Challenge_Response
null
def captcha_Challenge_Response(self, provider, provider_params, body, url): try: formPayload = re.search( r'<form (?P<form>.*?="challenge-form" ' r'action="(?P<challengeUUID>.*?__cf_chl_captcha_tk__=\S+)"(.*?)</form>)', body, re.M | re.DOTALL ).groupdict() if not all(key in formPayload for key in ['form', 'challengeUUID']): self.cloudscraper.simpleException( CloudflareCaptchaError, "Cloudflare Captcha detected, unfortunately we can't extract the parameters correctly." ) payload = OrderedDict( re.findall( r'(name="r"\svalue|data-ray|data-sitekey|name="cf_captcha_kind"\svalue)="(.*?)"', formPayload['form'] ) ) captchaType = 'reCaptcha' if payload['name="cf_captcha_kind" value'] == 're' else 'hCaptcha' except (AttributeError, KeyError): self.cloudscraper.simpleException( CloudflareCaptchaError, "Cloudflare Captcha detected, unfortunately we can't extract the parameters correctly." ) # ------------------------------------------------------------------------------- # # Pass proxy parameter to provider to solve captcha. # ------------------------------------------------------------------------------- # if self.cloudscraper.proxies and self.cloudscraper.proxies != self.cloudscraper.captcha.get('proxy'): self.cloudscraper.captcha['proxy'] = self.proxies # ------------------------------------------------------------------------------- # # Pass User-Agent if provider supports it to solve captcha. # ------------------------------------------------------------------------------- # self.cloudscraper.captcha['User-Agent'] = self.cloudscraper.headers['User-Agent'] # ------------------------------------------------------------------------------- # # Submit job to provider to request captcha solve. # ------------------------------------------------------------------------------- # captchaResponse = Captcha.dynamicImport( provider.lower() ).solveCaptcha( captchaType, url, payload['data-sitekey'], provider_params ) # ------------------------------------------------------------------------------- # # Parse and handle the response of solved captcha. # ------------------------------------------------------------------------------- # dataPayload = OrderedDict([ ('r', payload.get('name="r" value', '')), ('cf_captcha_kind', payload['name="cf_captcha_kind" value']), ('id', payload.get('data-ray')), ('g-recaptcha-response', captchaResponse) ]) if captchaType == 'hCaptcha': dataPayload.update({'h-captcha-response': captchaResponse}) hostParsed = urlparse(url) return { 'url': f"{hostParsed.scheme}://{hostParsed.netloc}{self.unescape(formPayload['challengeUUID'])}", 'data': dataPayload }
(self, provider, provider_params, body, url)
9,717
cloudscraper.cloudflare
is_Captcha_Challenge
null
@staticmethod def is_Captcha_Challenge(resp): try: return ( resp.headers.get('Server', '').startswith('cloudflare') and resp.status_code == 403 and re.search(r'/cdn-cgi/images/trace/(captcha|managed)/', resp.text, re.M | re.S) and re.search( r'''<form .*?="challenge-form" action="/\S+__cf_chl_f_tk=''', resp.text, re.M | re.S ) ) except AttributeError: pass return False
(resp)
9,718
cloudscraper.cloudflare
is_Challenge_Request
null
def is_Challenge_Request(self, resp): if self.is_Firewall_Blocked(resp): self.cloudscraper.simpleException( CloudflareCode1020, 'Cloudflare has blocked this request (Code 1020 Detected).' ) if self.is_New_Captcha_Challenge(resp): self.cloudscraper.simpleException( CloudflareChallengeError, 'Detected a Cloudflare version 2 Captcha challenge, This feature is not available in the opensource (free) version.' ) if self.is_New_IUAM_Challenge(resp): self.cloudscraper.simpleException( CloudflareChallengeError, 'Detected a Cloudflare version 2 challenge, This feature is not available in the opensource (free) version.' ) if self.is_Captcha_Challenge(resp) or self.is_IUAM_Challenge(resp): if self.cloudscraper.debug: print('Detected a Cloudflare version 1 challenge.') return True return False
(self, resp)
9,719
cloudscraper.cloudflare
is_Firewall_Blocked
null
@staticmethod def is_Firewall_Blocked(resp): try: return ( resp.headers.get('Server', '').startswith('cloudflare') and resp.status_code == 403 and re.search( r'<span class="cf-error-code">1020</span>', resp.text, re.M | re.DOTALL ) ) except AttributeError: pass return False
(resp)
9,720
cloudscraper.cloudflare
is_IUAM_Challenge
null
@staticmethod def is_IUAM_Challenge(resp): try: return ( resp.headers.get('Server', '').startswith('cloudflare') and resp.status_code in [429, 503] and re.search(r'/cdn-cgi/images/trace/jsch/', resp.text, re.M | re.S) and re.search( r'''<form .*?="challenge-form" action="/\S+__cf_chl_f_tk=''', resp.text, re.M | re.S ) ) except AttributeError: pass return False
(resp)