annotate CSP2/CSP2_env/env-d9b9114564458d9d-741b3de822f2aaca6c6caa4325c4afce/lib/python3.8/site-packages/urllib3/exceptions.py @ 68:5028fdace37b

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