try: # RFC 2617 HTTP Authentication # https://www.ietf.org/rfc/rfc2617.txt # the colon must be present, but the username and password may be # otherwise blank.
username, password = decoded.split(":", 1) except ValueError: raise ValueError("Invalid credentials.")
return cls(username, password, encoding=encoding)
@classmethod def from_url(cls, url: URL, *, encoding: str = "latin1") -> Optional["BasicAuth"]: """Create BasicAuth from url.""" ifnot isinstance(url, URL): raise TypeError("url should be yarl.URL instance") # Check raw_user and raw_password first as yarl is likely # to already have these values parsed from the netloc in the cache. if url.raw_user isNoneand url.raw_password isNone: returnNone return cls(url.user or"", url.password or"", encoding=encoding)
def strip_auth_from_url(url: URL) -> Tuple[URL, Optional[BasicAuth]]: """Remove user and password from URL if present and return BasicAuth object.""" # Check raw_user and raw_password first as yarl is likely # to already have these values parsed from the netloc in the cache. if url.raw_user isNoneand url.raw_password isNone: return url, None return url.with_user(None), BasicAuth(url.user or"", url.password or"")
def netrc_from_env() -> Optional[netrc.netrc]: """Load netrc from file.
Attempt to load it from the path specified by the env-var
NETRC orin the default location in the user's home directory.
Returns Noneif it couldn't be found or fails to parse. """
netrc_env = os.environ.get("NETRC")
if netrc_env isnotNone:
netrc_path = Path(netrc_env) else: try:
home_dir = Path.home() except RuntimeError as e: # pragma: no cover # if pathlib can't resolve home, it may raise a RuntimeError
client_logger.debug( "Could not resolve home directory when " "trying to look for .netrc file: %s",
e,
) returnNone
try: return netrc.netrc(str(netrc_path)) except netrc.NetrcParseError as e:
client_logger.warning("Could not parse .netrc file: %s", e) except OSError as e:
netrc_exists = False with contextlib.suppress(OSError):
netrc_exists = netrc_path.is_file() # we couldn't read the file (doesn't exist, permissions, etc.) if netrc_env or netrc_exists: # only warn if the environment wanted us to load it, # or it appears like the default file does actually exist
client_logger.warning("Could not read .netrc file: %s", e)
returnNone
@attr.s(auto_attribs=True, frozen=True, slots=True) class ProxyInfo:
proxy: URL
proxy_auth: Optional[BasicAuth]
def basicauth_from_netrc(netrc_obj: Optional[netrc.netrc], host: str) -> BasicAuth: """ Return :py:class:`~aiohttp.BasicAuth` credentials for ``host`` from ``netrc_obj``.
:raises LookupError: if ``netrc_obj`` is :py:data:`None` orif no
entry is found for the ``host``. """ if netrc_obj isNone: raise LookupError("No .netrc file found")
auth_from_netrc = netrc_obj.authenticators(host)
if auth_from_netrc isNone: raise LookupError(f"No entry for {host!s} found in the `.netrc` file.")
login, account, password = auth_from_netrc
# TODO(PY311): username = login or account # Up to python 3.10, account could be None if not specified, # and login will be empty string if not specified. From 3.11, # login and account will be empty string if not specified.
username = login if (login or account isNone) else account
# TODO(PY311): Remove this, as password will be empty string # if not specified if password isNone:
password = ""
return BasicAuth(username, password)
def proxies_from_env() -> Dict[str, ProxyInfo]:
proxy_urls = {
k: URL(v) for k, v in getproxies().items() if k in ("http", "https", "ws", "wss")
}
netrc_obj = netrc_from_env()
stripped = {k: strip_auth_from_url(v) for k, v in proxy_urls.items()}
ret = {} for proto, val in stripped.items():
proxy, auth = val if proxy.scheme in ("https", "wss"):
client_logger.warning( "%s proxies %s are not supported, ignoring", proxy.scheme.upper(), proxy
) continue if netrc_obj and auth isNone: if proxy.host isnotNone: try:
auth = basicauth_from_netrc(netrc_obj, proxy.host) except LookupError:
auth = None
ret[proto] = ProxyInfo(proxy, auth) return ret
def get_env_proxy_for_url(url: URL) -> Tuple[URL, Optional[BasicAuth]]: """Get a permitted proxy for the given URL from the env.""" if url.host isnotNoneand proxy_bypass(url.host): raise LookupError(f"Proxying is disallowed for `{url.host!r}`")
proxies_in_env = proxies_from_env() try:
proxy_info = proxies_in_env[url.scheme] except KeyError: raise LookupError(f"No proxies found for `{url!s}` in the env") else: return proxy_info.proxy, proxy_info.proxy_auth
def guess_filename(obj: Any, default: Optional[str] = None) -> Optional[str]:
name = getattr(obj, "name", None) if name and isinstance(name, str) and name[0] != "<"and name[-1] != ">": return Path(name).name return default
not_qtext_re = re.compile(r"[^\041\043-\133\135-\176]")
QCONTENT = {chr(i) for i in range(0x20, 0x7F)} | {"\t"}
def quoted_string(content: str) -> str: """Return 7-bit content as quoted-string.
Format content into a quoted-string as defined in RFC5322 for
Internet Message Format. Notice that this isnot the 8-bit HTTP
format, but the 7-bit email format. Content must be in usascii or
a ValueError is raised. """ ifnot (QCONTENT > set(content)): raise ValueError(f"bad content for quoted-string {content!r}") return not_qtext_re.sub(lambda x: "\\" + x.group(0), content)
This is the MIME payload Content-Disposition header from RFC 2183 and RFC 7579 section 4.2, not the HTTP Content-Disposition from
RFC 6266.
disptype is a disposition type: inline, attachment, form-data.
Should be valid extension token (see RFC 2183)
quote_fields performs value quoting to 7-bit MIME headers
according to RFC 7578. Set to quote_fields to Falseif recipient
can take 8-bit file names and field values.
_charset specifies the charset to use when quote_fields isTrue.
params is a dict with disposition params. """ ifnot disptype ornot (TOKEN > set(disptype)): raise ValueError("bad content disposition type {!r}""".format(disptype))
value = disptype if params:
lparams = [] for key, val in params.items(): ifnot key ornot (TOKEN > set(key)): raise ValueError( "bad content disposition parameter"" {!r}={!r}".format(key, val)
) if quote_fields: if key.lower() == "filename":
qval = quote(val, "", encoding=_charset)
lparams.append((key, '"%s"' % qval)) else: try:
qval = quoted_string(val) except ValueError:
qval = "".join(
(_charset, "''", quote(val, "", encoding=_charset))
)
lparams.append((key + "*", qval)) else:
lparams.append((key, '"%s"' % qval)) else:
qval = val.replace("\\", "\\\\").replace('"', '\\"')
lparams.append((key, '"%s"' % qval))
sparams = "; ".join("=".join(pair) for pair in lparams)
value = "; ".join((value, sparams)) return value
class _TSelf(Protocol, Generic[_T]):
_cache: Dict[str, _T]
class reify(Generic[_T]): """Use as a class method decorator.
It operates almost exactly like
the Python `@property` decorator, but it puts the result of the
method it decorates into the instance dict after the first call,
effectively replacing the function it decorates with an instance
variable. It is, in Python parlance, a data descriptor. """
def is_ipv4_address(host: Optional[Union[str, bytes]]) -> bool: """Check if host looks like an IPv4 address.
This function does not validate that the format is correct, only that
the host is a str or bytes, and its all numeric.
This check is only meant as a heuristic to ensure that
a host isnot a domain name. """ ifnot host: returnFalse # For a host to be an ipv4 address, it must be all numeric. if isinstance(host, str): return host.replace(".", "").isdigit() if isinstance(host, (bytes, bytearray, memoryview)): return host.decode("ascii").replace(".", "").isdigit() raise TypeError(f"{host} [{type(host)}] is not a str or bytes")
def is_ipv6_address(host: Optional[Union[str, bytes]]) -> bool: """Check if host looks like an IPv6 address.
This function does not validate that the format is correct, only that
the host contains a colon and that it is a str or bytes.
This check is only meant as a heuristic to ensure that
a host isnot a domain name. """ ifnot host: returnFalse # The host must contain a colon to be an IPv6 address. if isinstance(host, str): return":"in host if isinstance(host, (bytes, bytearray, memoryview)): return b":"in host raise TypeError(f"{host} [{type(host)}] is not a str or bytes")
def is_ip_address(host: Optional[Union[str, bytes, bytearray, memoryview]]) -> bool: """Check if host looks like an IP Address.
This check is only meant as a heuristic to ensure that
a host isnot a domain name. """ return is_ipv4_address(host) or is_ipv6_address(host)
def _weakref_handle(info: "Tuple[weakref.ref[object], str]") -> None:
ref, name = info
ob = ref() if ob isnotNone: with suppress(Exception):
getattr(ob, name)()
def weakref_handle(
ob: object,
name: str,
timeout: float,
loop: asyncio.AbstractEventLoop,
timeout_ceil_threshold: float = 5,
) -> Optional[asyncio.TimerHandle]: if timeout isnotNoneand timeout > 0:
when = loop.time() + timeout if timeout >= timeout_ceil_threshold:
when = ceil(when)
def calculate_timeout_when(
loop_time: float,
timeout: float,
timeout_ceiling_threshold: float,
) -> float: """Calculate when to execute a timeout."""
when = loop_time + timeout if timeout > timeout_ceiling_threshold: return ceil(when) return when
def assert_timeout(self) -> None: """Raise TimeoutError if timer has already been cancelled.""" if self._cancelled: raise asyncio.TimeoutError fromNone
def __enter__(self) -> BaseTimerContext:
task = asyncio.current_task(loop=self._loop) if task isNone: raise RuntimeError( "Timeout context manager should be used ""inside a task"
)
if sys.version_info >= (3, 11): # Remember if the task was already cancelling # so when we __exit__ we can decide if we should # raise asyncio.TimeoutError or let the cancellation propagate
self._cancelling = task.cancelling()
if self._cancelled: raise asyncio.TimeoutError fromNone
if exc_type is asyncio.CancelledError and self._cancelled: assert enter_task isnotNone # The timeout was hit, and the task was cancelled # so we need to uncancel the last task that entered the context manager # since the cancellation should not leak out of the context manager if sys.version_info >= (3, 11): # If the task was already cancelling don't raise # asyncio.TimeoutError and instead return None # to allow the cancellation to propagate if enter_task.uncancel() > self._cancelling: returnNone raise asyncio.TimeoutError from exc_val returnNone
def timeout(self) -> None: ifnot self._cancelled: for task in set(self._tasks):
task.cancel()
loop = asyncio.get_running_loop()
now = loop.time()
when = now + delay if delay > ceil_threshold:
when = ceil(when) return async_timeout.timeout_at(when)
class HeadersMixin:
ATTRS = frozenset(["_content_type", "_content_dict", "_stored_content_type"])
def _parse_content_type(self, raw: Optional[str]) -> None:
self._stored_content_type = raw if raw isNone: # default value according to RFC 2616
self._content_type = "application/octet-stream"
self._content_dict = {} else:
msg = HeaderParser().parsestr("Content-Type: " + raw)
self._content_type = msg.get_content_type()
params = msg.get_params(())
self._content_dict = dict(params[1:]) # First element is content type again
@property def content_type(self) -> str: """The value of content part for Content-Type HTTP header."""
raw = self._headers.get(hdrs.CONTENT_TYPE) if self._stored_content_type != raw:
self._parse_content_type(raw) assert self._content_type isnotNone return self._content_type
@property def charset(self) -> Optional[str]: """The value of charset part for Content-Type HTTP header."""
raw = self._headers.get(hdrs.CONTENT_TYPE) if self._stored_content_type != raw:
self._parse_content_type(raw) assert self._content_dict isnotNone return self._content_dict.get("charset")
@property def content_length(self) -> Optional[int]: """The value of Content-Length HTTP header."""
content_length = self._headers.get(hdrs.CONTENT_LENGTH) returnNoneif content_length isNoneelse int(content_length)
If the future is marked as complete, this function is a no-op.
:param exc_cause: An exception that is a direct cause of ``exc``.
Only set if provided. """ if asyncio.isfuture(fut) and fut.done(): return
exc_is_sentinel = exc_cause is _EXC_SENTINEL
exc_causes_itself = exc is exc_cause ifnot exc_is_sentinel andnot exc_causes_itself:
exc.__cause__ = exc_cause
fut.set_exception(exc)
@functools.total_ordering class AppKey(Generic[_T]): """Keys for static typing support in Application."""
__slots__ = ("_name", "_t", "__orig_class__")
# This may be set by Python when instantiating with a generic type. We need to # support this, in order to support types that are not concrete classes, # like Iterable, which can't be passed as the second parameter to __init__.
__orig_class__: Type[object]
def __init__(self, name: str, t: Optional[Type[_T]] = None): # Prefix with module name to help deduplicate key names.
frame = inspect.currentframe() while frame: if frame.f_code.co_name == "":
module: str = frame.f_globals["__name__"] break
frame = frame.f_back
self._name = module + "." + name
self._t = t
def __lt__(self, other: object) -> bool: if isinstance(other, AppKey): return self._name < other._name returnTrue# Order AppKey above other types.
def __repr__(self) -> str:
t = self._t if t isNone: with suppress(AttributeError): # Set to type arg.
t = get_args(self.__orig_class__)[0]
if t isNone:
t_repr = "<>" elif isinstance(t, type): if t.__module__ == "builtins":
t_repr = t.__qualname__ else:
t_repr = f"{t.__module__}.{t.__qualname__}" else:
t_repr = repr(t) return f""
class ChainMapProxy(Mapping[Union[str, AppKey[Any]], Any]):
__slots__ = ("_maps",)
def validate_etag_value(value: str) -> None: if value != ETAG_ANY andnot _ETAGC_RE.fullmatch(value): raise ValueError(
f"Value {value!r} is not a valid etag. Maybe it contains '\"'?"
)
def parse_http_date(date_str: Optional[str]) -> Optional[datetime.datetime]: """Process a date string, return a datetime object""" if date_str isnotNone:
timetuple = parsedate(date_str) if timetuple isnotNone: with suppress(ValueError): return datetime.datetime(*timetuple[:6], tzinfo=datetime.timezone.utc) returnNone
@functools.lru_cache def must_be_empty_body(method: str, code: int) -> bool: """Check if a request must return an empty body.""" return (
status_code_must_be_empty_body(code) or method_must_be_empty_body(method) or (200 <= code < 300 and method.upper() == hdrs.METH_CONNECT)
)
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung ist noch experimentell.