annotate CSP2/CSP2_env/env-d9b9114564458d9d-741b3de822f2aaca6c6caa4325c4afce/lib/python3.8/site-packages/urllib3/exceptions.py @ 69:33d812a61356

planemo upload commit 2e9511a184a1ca667c7be0c6321a36dc4e3d116d
author jpayne
date Tue, 18 Mar 2025 17:55:14 -0400
parents
children
rev   line source
jpayne@69 1 from __future__ import annotations
jpayne@69 2
jpayne@69 3 import socket
jpayne@69 4 import typing
jpayne@69 5 import warnings
jpayne@69 6 from email.errors import MessageDefect
jpayne@69 7 from http.client import IncompleteRead as httplib_IncompleteRead
jpayne@69 8
jpayne@69 9 if typing.TYPE_CHECKING:
jpayne@69 10 from .connection import HTTPConnection
jpayne@69 11 from .connectionpool import ConnectionPool
jpayne@69 12 from .response import HTTPResponse
jpayne@69 13 from .util.retry import Retry
jpayne@69 14
jpayne@69 15 # Base Exceptions
jpayne@69 16
jpayne@69 17
jpayne@69 18 class HTTPError(Exception):
jpayne@69 19 """Base exception used by this module."""
jpayne@69 20
jpayne@69 21
jpayne@69 22 class HTTPWarning(Warning):
jpayne@69 23 """Base warning used by this module."""
jpayne@69 24
jpayne@69 25
jpayne@69 26 _TYPE_REDUCE_RESULT = typing.Tuple[
jpayne@69 27 typing.Callable[..., object], typing.Tuple[object, ...]
jpayne@69 28 ]
jpayne@69 29
jpayne@69 30
jpayne@69 31 class PoolError(HTTPError):
jpayne@69 32 """Base exception for errors caused within a pool."""
jpayne@69 33
jpayne@69 34 def __init__(self, pool: ConnectionPool, message: str) -> None:
jpayne@69 35 self.pool = pool
jpayne@69 36 super().__init__(f"{pool}: {message}")
jpayne@69 37
jpayne@69 38 def __reduce__(self) -> _TYPE_REDUCE_RESULT:
jpayne@69 39 # For pickling purposes.
jpayne@69 40 return self.__class__, (None, None)
jpayne@69 41
jpayne@69 42
jpayne@69 43 class RequestError(PoolError):
jpayne@69 44 """Base exception for PoolErrors that have associated URLs."""
jpayne@69 45
jpayne@69 46 def __init__(self, pool: ConnectionPool, url: str, message: str) -> None:
jpayne@69 47 self.url = url
jpayne@69 48 super().__init__(pool, message)
jpayne@69 49
jpayne@69 50 def __reduce__(self) -> _TYPE_REDUCE_RESULT:
jpayne@69 51 # For pickling purposes.
jpayne@69 52 return self.__class__, (None, self.url, None)
jpayne@69 53
jpayne@69 54
jpayne@69 55 class SSLError(HTTPError):
jpayne@69 56 """Raised when SSL certificate fails in an HTTPS connection."""
jpayne@69 57
jpayne@69 58
jpayne@69 59 class ProxyError(HTTPError):
jpayne@69 60 """Raised when the connection to a proxy fails."""
jpayne@69 61
jpayne@69 62 # The original error is also available as __cause__.
jpayne@69 63 original_error: Exception
jpayne@69 64
jpayne@69 65 def __init__(self, message: str, error: Exception) -> None:
jpayne@69 66 super().__init__(message, error)
jpayne@69 67 self.original_error = error
jpayne@69 68
jpayne@69 69
jpayne@69 70 class DecodeError(HTTPError):
jpayne@69 71 """Raised when automatic decoding based on Content-Type fails."""
jpayne@69 72
jpayne@69 73
jpayne@69 74 class ProtocolError(HTTPError):
jpayne@69 75 """Raised when something unexpected happens mid-request/response."""
jpayne@69 76
jpayne@69 77
jpayne@69 78 #: Renamed to ProtocolError but aliased for backwards compatibility.
jpayne@69 79 ConnectionError = ProtocolError
jpayne@69 80
jpayne@69 81
jpayne@69 82 # Leaf Exceptions
jpayne@69 83
jpayne@69 84
jpayne@69 85 class MaxRetryError(RequestError):
jpayne@69 86 """Raised when the maximum number of retries is exceeded.
jpayne@69 87
jpayne@69 88 :param pool: The connection pool
jpayne@69 89 :type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool`
jpayne@69 90 :param str url: The requested Url
jpayne@69 91 :param reason: The underlying error
jpayne@69 92 :type reason: :class:`Exception`
jpayne@69 93
jpayne@69 94 """
jpayne@69 95
jpayne@69 96 def __init__(
jpayne@69 97 self, pool: ConnectionPool, url: str, reason: Exception | None = None
jpayne@69 98 ) -> None:
jpayne@69 99 self.reason = reason
jpayne@69 100
jpayne@69 101 message = f"Max retries exceeded with url: {url} (Caused by {reason!r})"
jpayne@69 102
jpayne@69 103 super().__init__(pool, url, message)
jpayne@69 104
jpayne@69 105
jpayne@69 106 class HostChangedError(RequestError):
jpayne@69 107 """Raised when an existing pool gets a request for a foreign host."""
jpayne@69 108
jpayne@69 109 def __init__(
jpayne@69 110 self, pool: ConnectionPool, url: str, retries: Retry | int = 3
jpayne@69 111 ) -> None:
jpayne@69 112 message = f"Tried to open a foreign host with url: {url}"
jpayne@69 113 super().__init__(pool, url, message)
jpayne@69 114 self.retries = retries
jpayne@69 115
jpayne@69 116
jpayne@69 117 class TimeoutStateError(HTTPError):
jpayne@69 118 """Raised when passing an invalid state to a timeout"""
jpayne@69 119
jpayne@69 120
jpayne@69 121 class TimeoutError(HTTPError):
jpayne@69 122 """Raised when a socket timeout error occurs.
jpayne@69 123
jpayne@69 124 Catching this error will catch both :exc:`ReadTimeoutErrors
jpayne@69 125 <ReadTimeoutError>` and :exc:`ConnectTimeoutErrors <ConnectTimeoutError>`.
jpayne@69 126 """
jpayne@69 127
jpayne@69 128
jpayne@69 129 class ReadTimeoutError(TimeoutError, RequestError):
jpayne@69 130 """Raised when a socket timeout occurs while receiving data from a server"""
jpayne@69 131
jpayne@69 132
jpayne@69 133 # This timeout error does not have a URL attached and needs to inherit from the
jpayne@69 134 # base HTTPError
jpayne@69 135 class ConnectTimeoutError(TimeoutError):
jpayne@69 136 """Raised when a socket timeout occurs while connecting to a server"""
jpayne@69 137
jpayne@69 138
jpayne@69 139 class NewConnectionError(ConnectTimeoutError, HTTPError):
jpayne@69 140 """Raised when we fail to establish a new connection. Usually ECONNREFUSED."""
jpayne@69 141
jpayne@69 142 def __init__(self, conn: HTTPConnection, message: str) -> None:
jpayne@69 143 self.conn = conn
jpayne@69 144 super().__init__(f"{conn}: {message}")
jpayne@69 145
jpayne@69 146 @property
jpayne@69 147 def pool(self) -> HTTPConnection:
jpayne@69 148 warnings.warn(
jpayne@69 149 "The 'pool' property is deprecated and will be removed "
jpayne@69 150 "in urllib3 v2.1.0. Use 'conn' instead.",
jpayne@69 151 DeprecationWarning,
jpayne@69 152 stacklevel=2,
jpayne@69 153 )
jpayne@69 154
jpayne@69 155 return self.conn
jpayne@69 156
jpayne@69 157
jpayne@69 158 class NameResolutionError(NewConnectionError):
jpayne@69 159 """Raised when host name resolution fails."""
jpayne@69 160
jpayne@69 161 def __init__(self, host: str, conn: HTTPConnection, reason: socket.gaierror):
jpayne@69 162 message = f"Failed to resolve '{host}' ({reason})"
jpayne@69 163 super().__init__(conn, message)
jpayne@69 164
jpayne@69 165
jpayne@69 166 class EmptyPoolError(PoolError):
jpayne@69 167 """Raised when a pool runs out of connections and no more are allowed."""
jpayne@69 168
jpayne@69 169
jpayne@69 170 class FullPoolError(PoolError):
jpayne@69 171 """Raised when we try to add a connection to a full pool in blocking mode."""
jpayne@69 172
jpayne@69 173
jpayne@69 174 class ClosedPoolError(PoolError):
jpayne@69 175 """Raised when a request enters a pool after the pool has been closed."""
jpayne@69 176
jpayne@69 177
jpayne@69 178 class LocationValueError(ValueError, HTTPError):
jpayne@69 179 """Raised when there is something wrong with a given URL input."""
jpayne@69 180
jpayne@69 181
jpayne@69 182 class LocationParseError(LocationValueError):
jpayne@69 183 """Raised when get_host or similar fails to parse the URL input."""
jpayne@69 184
jpayne@69 185 def __init__(self, location: str) -> None:
jpayne@69 186 message = f"Failed to parse: {location}"
jpayne@69 187 super().__init__(message)
jpayne@69 188
jpayne@69 189 self.location = location
jpayne@69 190
jpayne@69 191
jpayne@69 192 class URLSchemeUnknown(LocationValueError):
jpayne@69 193 """Raised when a URL input has an unsupported scheme."""
jpayne@69 194
jpayne@69 195 def __init__(self, scheme: str):
jpayne@69 196 message = f"Not supported URL scheme {scheme}"
jpayne@69 197 super().__init__(message)
jpayne@69 198
jpayne@69 199 self.scheme = scheme
jpayne@69 200
jpayne@69 201
jpayne@69 202 class ResponseError(HTTPError):
jpayne@69 203 """Used as a container for an error reason supplied in a MaxRetryError."""
jpayne@69 204
jpayne@69 205 GENERIC_ERROR = "too many error responses"
jpayne@69 206 SPECIFIC_ERROR = "too many {status_code} error responses"
jpayne@69 207
jpayne@69 208
jpayne@69 209 class SecurityWarning(HTTPWarning):
jpayne@69 210 """Warned when performing security reducing actions"""
jpayne@69 211
jpayne@69 212
jpayne@69 213 class InsecureRequestWarning(SecurityWarning):
jpayne@69 214 """Warned when making an unverified HTTPS request."""
jpayne@69 215
jpayne@69 216
jpayne@69 217 class NotOpenSSLWarning(SecurityWarning):
jpayne@69 218 """Warned when using unsupported SSL library"""
jpayne@69 219
jpayne@69 220
jpayne@69 221 class SystemTimeWarning(SecurityWarning):
jpayne@69 222 """Warned when system time is suspected to be wrong"""
jpayne@69 223
jpayne@69 224
jpayne@69 225 class InsecurePlatformWarning(SecurityWarning):
jpayne@69 226 """Warned when certain TLS/SSL configuration is not available on a platform."""
jpayne@69 227
jpayne@69 228
jpayne@69 229 class DependencyWarning(HTTPWarning):
jpayne@69 230 """
jpayne@69 231 Warned when an attempt is made to import a module with missing optional
jpayne@69 232 dependencies.
jpayne@69 233 """
jpayne@69 234
jpayne@69 235
jpayne@69 236 class ResponseNotChunked(ProtocolError, ValueError):
jpayne@69 237 """Response needs to be chunked in order to read it as chunks."""
jpayne@69 238
jpayne@69 239
jpayne@69 240 class BodyNotHttplibCompatible(HTTPError):
jpayne@69 241 """
jpayne@69 242 Body should be :class:`http.client.HTTPResponse` like
jpayne@69 243 (have an fp attribute which returns raw chunks) for read_chunked().
jpayne@69 244 """
jpayne@69 245
jpayne@69 246
jpayne@69 247 class IncompleteRead(HTTPError, httplib_IncompleteRead):
jpayne@69 248 """
jpayne@69 249 Response length doesn't match expected Content-Length
jpayne@69 250
jpayne@69 251 Subclass of :class:`http.client.IncompleteRead` to allow int value
jpayne@69 252 for ``partial`` to avoid creating large objects on streamed reads.
jpayne@69 253 """
jpayne@69 254
jpayne@69 255 partial: int # type: ignore[assignment]
jpayne@69 256 expected: int
jpayne@69 257
jpayne@69 258 def __init__(self, partial: int, expected: int) -> None:
jpayne@69 259 self.partial = partial
jpayne@69 260 self.expected = expected
jpayne@69 261
jpayne@69 262 def __repr__(self) -> str:
jpayne@69 263 return "IncompleteRead(%i bytes read, %i more expected)" % (
jpayne@69 264 self.partial,
jpayne@69 265 self.expected,
jpayne@69 266 )
jpayne@69 267
jpayne@69 268
jpayne@69 269 class InvalidChunkLength(HTTPError, httplib_IncompleteRead):
jpayne@69 270 """Invalid chunk length in a chunked response."""
jpayne@69 271
jpayne@69 272 def __init__(self, response: HTTPResponse, length: bytes) -> None:
jpayne@69 273 self.partial: int = response.tell() # type: ignore[assignment]
jpayne@69 274 self.expected: int | None = response.length_remaining
jpayne@69 275 self.response = response
jpayne@69 276 self.length = length
jpayne@69 277
jpayne@69 278 def __repr__(self) -> str:
jpayne@69 279 return "InvalidChunkLength(got length %r, %i bytes read)" % (
jpayne@69 280 self.length,
jpayne@69 281 self.partial,
jpayne@69 282 )
jpayne@69 283
jpayne@69 284
jpayne@69 285 class InvalidHeader(HTTPError):
jpayne@69 286 """The header provided was somehow invalid."""
jpayne@69 287
jpayne@69 288
jpayne@69 289 class ProxySchemeUnknown(AssertionError, URLSchemeUnknown):
jpayne@69 290 """ProxyManager does not support the supplied scheme"""
jpayne@69 291
jpayne@69 292 # TODO(t-8ch): Stop inheriting from AssertionError in v2.0.
jpayne@69 293
jpayne@69 294 def __init__(self, scheme: str | None) -> None:
jpayne@69 295 # 'localhost' is here because our URL parser parses
jpayne@69 296 # localhost:8080 -> scheme=localhost, remove if we fix this.
jpayne@69 297 if scheme == "localhost":
jpayne@69 298 scheme = None
jpayne@69 299 if scheme is None:
jpayne@69 300 message = "Proxy URL had no scheme, should start with http:// or https://"
jpayne@69 301 else:
jpayne@69 302 message = f"Proxy URL had unsupported scheme {scheme}, should use http:// or https://"
jpayne@69 303 super().__init__(message)
jpayne@69 304
jpayne@69 305
jpayne@69 306 class ProxySchemeUnsupported(ValueError):
jpayne@69 307 """Fetching HTTPS resources through HTTPS proxies is unsupported"""
jpayne@69 308
jpayne@69 309
jpayne@69 310 class HeaderParsingError(HTTPError):
jpayne@69 311 """Raised by assert_header_parsing, but we convert it to a log.warning statement."""
jpayne@69 312
jpayne@69 313 def __init__(
jpayne@69 314 self, defects: list[MessageDefect], unparsed_data: bytes | str | None
jpayne@69 315 ) -> None:
jpayne@69 316 message = f"{defects or 'Unknown'}, unparsed data: {unparsed_data!r}"
jpayne@69 317 super().__init__(message)
jpayne@69 318
jpayne@69 319
jpayne@69 320 class UnrewindableBodyError(HTTPError):
jpayne@69 321 """urllib3 encountered an error when trying to rewind a body"""