Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/ShExBy/shex_roo.../usr/lib64/python3..../http
File: client.py
r"""HTTP/1.1 client library
[0] Fix | Delete
[1] Fix | Delete
<intro stuff goes here>
[2] Fix | Delete
<other stuff, too>
[3] Fix | Delete
[4] Fix | Delete
HTTPConnection goes through a number of "states", which define when a client
[5] Fix | Delete
may legally make another request or fetch the response for a particular
[6] Fix | Delete
request. This diagram details these state transitions:
[7] Fix | Delete
[8] Fix | Delete
(null)
[9] Fix | Delete
|
[10] Fix | Delete
| HTTPConnection()
[11] Fix | Delete
v
[12] Fix | Delete
Idle
[13] Fix | Delete
|
[14] Fix | Delete
| putrequest()
[15] Fix | Delete
v
[16] Fix | Delete
Request-started
[17] Fix | Delete
|
[18] Fix | Delete
| ( putheader() )* endheaders()
[19] Fix | Delete
v
[20] Fix | Delete
Request-sent
[21] Fix | Delete
|\_____________________________
[22] Fix | Delete
| | getresponse() raises
[23] Fix | Delete
| response = getresponse() | ConnectionError
[24] Fix | Delete
v v
[25] Fix | Delete
Unread-response Idle
[26] Fix | Delete
[Response-headers-read]
[27] Fix | Delete
|\____________________
[28] Fix | Delete
| |
[29] Fix | Delete
| response.read() | putrequest()
[30] Fix | Delete
v v
[31] Fix | Delete
Idle Req-started-unread-response
[32] Fix | Delete
______/|
[33] Fix | Delete
/ |
[34] Fix | Delete
response.read() | | ( putheader() )* endheaders()
[35] Fix | Delete
v v
[36] Fix | Delete
Request-started Req-sent-unread-response
[37] Fix | Delete
|
[38] Fix | Delete
| response.read()
[39] Fix | Delete
v
[40] Fix | Delete
Request-sent
[41] Fix | Delete
[42] Fix | Delete
This diagram presents the following rules:
[43] Fix | Delete
-- a second request may not be started until {response-headers-read}
[44] Fix | Delete
-- a response [object] cannot be retrieved until {request-sent}
[45] Fix | Delete
-- there is no differentiation between an unread response body and a
[46] Fix | Delete
partially read response body
[47] Fix | Delete
[48] Fix | Delete
Note: this enforcement is applied by the HTTPConnection class. The
[49] Fix | Delete
HTTPResponse class does not enforce this state machine, which
[50] Fix | Delete
implies sophisticated clients may accelerate the request/response
[51] Fix | Delete
pipeline. Caution should be taken, though: accelerating the states
[52] Fix | Delete
beyond the above pattern may imply knowledge of the server's
[53] Fix | Delete
connection-close behavior for certain requests. For example, it
[54] Fix | Delete
is impossible to tell whether the server will close the connection
[55] Fix | Delete
UNTIL the response headers have been read; this means that further
[56] Fix | Delete
requests cannot be placed into the pipeline until it is known that
[57] Fix | Delete
the server will NOT be closing the connection.
[58] Fix | Delete
[59] Fix | Delete
Logical State __state __response
[60] Fix | Delete
------------- ------- ----------
[61] Fix | Delete
Idle _CS_IDLE None
[62] Fix | Delete
Request-started _CS_REQ_STARTED None
[63] Fix | Delete
Request-sent _CS_REQ_SENT None
[64] Fix | Delete
Unread-response _CS_IDLE <response_class>
[65] Fix | Delete
Req-started-unread-response _CS_REQ_STARTED <response_class>
[66] Fix | Delete
Req-sent-unread-response _CS_REQ_SENT <response_class>
[67] Fix | Delete
"""
[68] Fix | Delete
[69] Fix | Delete
import email.parser
[70] Fix | Delete
import email.message
[71] Fix | Delete
import http
[72] Fix | Delete
import io
[73] Fix | Delete
import re
[74] Fix | Delete
import socket
[75] Fix | Delete
import collections.abc
[76] Fix | Delete
from urllib.parse import urlsplit
[77] Fix | Delete
[78] Fix | Delete
# HTTPMessage, parse_headers(), and the HTTP status code constants are
[79] Fix | Delete
# intentionally omitted for simplicity
[80] Fix | Delete
__all__ = ["HTTPResponse", "HTTPConnection",
[81] Fix | Delete
"HTTPException", "NotConnected", "UnknownProtocol",
[82] Fix | Delete
"UnknownTransferEncoding", "UnimplementedFileMode",
[83] Fix | Delete
"IncompleteRead", "InvalidURL", "ImproperConnectionState",
[84] Fix | Delete
"CannotSendRequest", "CannotSendHeader", "ResponseNotReady",
[85] Fix | Delete
"BadStatusLine", "LineTooLong", "RemoteDisconnected", "error",
[86] Fix | Delete
"responses"]
[87] Fix | Delete
[88] Fix | Delete
HTTP_PORT = 80
[89] Fix | Delete
HTTPS_PORT = 443
[90] Fix | Delete
[91] Fix | Delete
_UNKNOWN = 'UNKNOWN'
[92] Fix | Delete
[93] Fix | Delete
# connection states
[94] Fix | Delete
_CS_IDLE = 'Idle'
[95] Fix | Delete
_CS_REQ_STARTED = 'Request-started'
[96] Fix | Delete
_CS_REQ_SENT = 'Request-sent'
[97] Fix | Delete
[98] Fix | Delete
[99] Fix | Delete
# hack to maintain backwards compatibility
[100] Fix | Delete
globals().update(http.HTTPStatus.__members__)
[101] Fix | Delete
[102] Fix | Delete
# another hack to maintain backwards compatibility
[103] Fix | Delete
# Mapping status codes to official W3C names
[104] Fix | Delete
responses = {v: v.phrase for v in http.HTTPStatus.__members__.values()}
[105] Fix | Delete
[106] Fix | Delete
# maximal line length when calling readline().
[107] Fix | Delete
_MAXLINE = 65536
[108] Fix | Delete
_MAXHEADERS = 100
[109] Fix | Delete
[110] Fix | Delete
# Header name/value ABNF (http://tools.ietf.org/html/rfc7230#section-3.2)
[111] Fix | Delete
#
[112] Fix | Delete
# VCHAR = %x21-7E
[113] Fix | Delete
# obs-text = %x80-FF
[114] Fix | Delete
# header-field = field-name ":" OWS field-value OWS
[115] Fix | Delete
# field-name = token
[116] Fix | Delete
# field-value = *( field-content / obs-fold )
[117] Fix | Delete
# field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
[118] Fix | Delete
# field-vchar = VCHAR / obs-text
[119] Fix | Delete
#
[120] Fix | Delete
# obs-fold = CRLF 1*( SP / HTAB )
[121] Fix | Delete
# ; obsolete line folding
[122] Fix | Delete
# ; see Section 3.2.4
[123] Fix | Delete
[124] Fix | Delete
# token = 1*tchar
[125] Fix | Delete
#
[126] Fix | Delete
# tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
[127] Fix | Delete
# / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
[128] Fix | Delete
# / DIGIT / ALPHA
[129] Fix | Delete
# ; any VCHAR, except delimiters
[130] Fix | Delete
#
[131] Fix | Delete
# VCHAR defined in http://tools.ietf.org/html/rfc5234#appendix-B.1
[132] Fix | Delete
[133] Fix | Delete
# the patterns for both name and value are more lenient than RFC
[134] Fix | Delete
# definitions to allow for backwards compatibility
[135] Fix | Delete
_is_legal_header_name = re.compile(rb'[^:\s][^:\r\n]*').fullmatch
[136] Fix | Delete
_is_illegal_header_value = re.compile(rb'\n(?![ \t])|\r(?![ \t\n])').search
[137] Fix | Delete
[138] Fix | Delete
# These characters are not allowed within HTTP URL paths.
[139] Fix | Delete
# See https://tools.ietf.org/html/rfc3986#section-3.3 and the
[140] Fix | Delete
# https://tools.ietf.org/html/rfc3986#appendix-A pchar definition.
[141] Fix | Delete
# Prevents CVE-2019-9740. Includes control characters such as \r\n.
[142] Fix | Delete
# We don't restrict chars above \x7f as putrequest() limits us to ASCII.
[143] Fix | Delete
_contains_disallowed_url_pchar_re = re.compile('[\x00-\x20\x7f]')
[144] Fix | Delete
# Arguably only these _should_ allowed:
[145] Fix | Delete
# _is_allowed_url_pchars_re = re.compile(r"^[/!$&'()*+,;=:@%a-zA-Z0-9._~-]+$")
[146] Fix | Delete
# We are more lenient for assumed real world compatibility purposes.
[147] Fix | Delete
[148] Fix | Delete
# These characters are not allowed within HTTP method names
[149] Fix | Delete
# to prevent http header injection.
[150] Fix | Delete
_contains_disallowed_method_pchar_re = re.compile('[\x00-\x1f]')
[151] Fix | Delete
[152] Fix | Delete
# We always set the Content-Length header for these methods because some
[153] Fix | Delete
# servers will otherwise respond with a 411
[154] Fix | Delete
_METHODS_EXPECTING_BODY = {'PATCH', 'POST', 'PUT'}
[155] Fix | Delete
[156] Fix | Delete
[157] Fix | Delete
def _encode(data, name='data'):
[158] Fix | Delete
"""Call data.encode("latin-1") but show a better error message."""
[159] Fix | Delete
try:
[160] Fix | Delete
return data.encode("latin-1")
[161] Fix | Delete
except UnicodeEncodeError as err:
[162] Fix | Delete
raise UnicodeEncodeError(
[163] Fix | Delete
err.encoding,
[164] Fix | Delete
err.object,
[165] Fix | Delete
err.start,
[166] Fix | Delete
err.end,
[167] Fix | Delete
"%s (%.20r) is not valid Latin-1. Use %s.encode('utf-8') "
[168] Fix | Delete
"if you want to send it encoded in UTF-8." %
[169] Fix | Delete
(name.title(), data[err.start:err.end], name)) from None
[170] Fix | Delete
[171] Fix | Delete
[172] Fix | Delete
class HTTPMessage(email.message.Message):
[173] Fix | Delete
# XXX The only usage of this method is in
[174] Fix | Delete
# http.server.CGIHTTPRequestHandler. Maybe move the code there so
[175] Fix | Delete
# that it doesn't need to be part of the public API. The API has
[176] Fix | Delete
# never been defined so this could cause backwards compatibility
[177] Fix | Delete
# issues.
[178] Fix | Delete
[179] Fix | Delete
def getallmatchingheaders(self, name):
[180] Fix | Delete
"""Find all header lines matching a given header name.
[181] Fix | Delete
[182] Fix | Delete
Look through the list of headers and find all lines matching a given
[183] Fix | Delete
header name (and their continuation lines). A list of the lines is
[184] Fix | Delete
returned, without interpretation. If the header does not occur, an
[185] Fix | Delete
empty list is returned. If the header occurs multiple times, all
[186] Fix | Delete
occurrences are returned. Case is not important in the header name.
[187] Fix | Delete
[188] Fix | Delete
"""
[189] Fix | Delete
name = name.lower() + ':'
[190] Fix | Delete
n = len(name)
[191] Fix | Delete
lst = []
[192] Fix | Delete
hit = 0
[193] Fix | Delete
for line in self.keys():
[194] Fix | Delete
if line[:n].lower() == name:
[195] Fix | Delete
hit = 1
[196] Fix | Delete
elif not line[:1].isspace():
[197] Fix | Delete
hit = 0
[198] Fix | Delete
if hit:
[199] Fix | Delete
lst.append(line)
[200] Fix | Delete
return lst
[201] Fix | Delete
[202] Fix | Delete
def _read_headers(fp):
[203] Fix | Delete
"""Reads potential header lines into a list from a file pointer.
[204] Fix | Delete
[205] Fix | Delete
Length of line is limited by _MAXLINE, and number of
[206] Fix | Delete
headers is limited by _MAXHEADERS.
[207] Fix | Delete
"""
[208] Fix | Delete
headers = []
[209] Fix | Delete
while True:
[210] Fix | Delete
line = fp.readline(_MAXLINE + 1)
[211] Fix | Delete
if len(line) > _MAXLINE:
[212] Fix | Delete
raise LineTooLong("header line")
[213] Fix | Delete
headers.append(line)
[214] Fix | Delete
if len(headers) > _MAXHEADERS:
[215] Fix | Delete
raise HTTPException("got more than %d headers" % _MAXHEADERS)
[216] Fix | Delete
if line in (b'\r\n', b'\n', b''):
[217] Fix | Delete
break
[218] Fix | Delete
return headers
[219] Fix | Delete
[220] Fix | Delete
def parse_headers(fp, _class=HTTPMessage):
[221] Fix | Delete
"""Parses only RFC2822 headers from a file pointer.
[222] Fix | Delete
[223] Fix | Delete
email Parser wants to see strings rather than bytes.
[224] Fix | Delete
But a TextIOWrapper around self.rfile would buffer too many bytes
[225] Fix | Delete
from the stream, bytes which we later need to read as bytes.
[226] Fix | Delete
So we read the correct bytes here, as bytes, for email Parser
[227] Fix | Delete
to parse.
[228] Fix | Delete
[229] Fix | Delete
"""
[230] Fix | Delete
headers = _read_headers(fp)
[231] Fix | Delete
hstring = b''.join(headers).decode('iso-8859-1')
[232] Fix | Delete
return email.parser.Parser(_class=_class).parsestr(hstring)
[233] Fix | Delete
[234] Fix | Delete
[235] Fix | Delete
class HTTPResponse(io.BufferedIOBase):
[236] Fix | Delete
[237] Fix | Delete
# See RFC 2616 sec 19.6 and RFC 1945 sec 6 for details.
[238] Fix | Delete
[239] Fix | Delete
# The bytes from the socket object are iso-8859-1 strings.
[240] Fix | Delete
# See RFC 2616 sec 2.2 which notes an exception for MIME-encoded
[241] Fix | Delete
# text following RFC 2047. The basic status line parsing only
[242] Fix | Delete
# accepts iso-8859-1.
[243] Fix | Delete
[244] Fix | Delete
def __init__(self, sock, debuglevel=0, method=None, url=None):
[245] Fix | Delete
# If the response includes a content-length header, we need to
[246] Fix | Delete
# make sure that the client doesn't read more than the
[247] Fix | Delete
# specified number of bytes. If it does, it will block until
[248] Fix | Delete
# the server times out and closes the connection. This will
[249] Fix | Delete
# happen if a self.fp.read() is done (without a size) whether
[250] Fix | Delete
# self.fp is buffered or not. So, no self.fp.read() by
[251] Fix | Delete
# clients unless they know what they are doing.
[252] Fix | Delete
self.fp = sock.makefile("rb")
[253] Fix | Delete
self.debuglevel = debuglevel
[254] Fix | Delete
self._method = method
[255] Fix | Delete
[256] Fix | Delete
# The HTTPResponse object is returned via urllib. The clients
[257] Fix | Delete
# of http and urllib expect different attributes for the
[258] Fix | Delete
# headers. headers is used here and supports urllib. msg is
[259] Fix | Delete
# provided as a backwards compatibility layer for http
[260] Fix | Delete
# clients.
[261] Fix | Delete
[262] Fix | Delete
self.headers = self.msg = None
[263] Fix | Delete
[264] Fix | Delete
# from the Status-Line of the response
[265] Fix | Delete
self.version = _UNKNOWN # HTTP-Version
[266] Fix | Delete
self.status = _UNKNOWN # Status-Code
[267] Fix | Delete
self.reason = _UNKNOWN # Reason-Phrase
[268] Fix | Delete
[269] Fix | Delete
self.chunked = _UNKNOWN # is "chunked" being used?
[270] Fix | Delete
self.chunk_left = _UNKNOWN # bytes left to read in current chunk
[271] Fix | Delete
self.length = _UNKNOWN # number of bytes left in response
[272] Fix | Delete
self.will_close = _UNKNOWN # conn will close at end of response
[273] Fix | Delete
[274] Fix | Delete
def _read_status(self):
[275] Fix | Delete
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
[276] Fix | Delete
if len(line) > _MAXLINE:
[277] Fix | Delete
raise LineTooLong("status line")
[278] Fix | Delete
if self.debuglevel > 0:
[279] Fix | Delete
print("reply:", repr(line))
[280] Fix | Delete
if not line:
[281] Fix | Delete
# Presumably, the server closed the connection before
[282] Fix | Delete
# sending a valid response.
[283] Fix | Delete
raise RemoteDisconnected("Remote end closed connection without"
[284] Fix | Delete
" response")
[285] Fix | Delete
try:
[286] Fix | Delete
version, status, reason = line.split(None, 2)
[287] Fix | Delete
except ValueError:
[288] Fix | Delete
try:
[289] Fix | Delete
version, status = line.split(None, 1)
[290] Fix | Delete
reason = ""
[291] Fix | Delete
except ValueError:
[292] Fix | Delete
# empty version will cause next test to fail.
[293] Fix | Delete
version = ""
[294] Fix | Delete
if not version.startswith("HTTP/"):
[295] Fix | Delete
self._close_conn()
[296] Fix | Delete
raise BadStatusLine(line)
[297] Fix | Delete
[298] Fix | Delete
# The status code is a three-digit number
[299] Fix | Delete
try:
[300] Fix | Delete
status = int(status)
[301] Fix | Delete
if status < 100 or status > 999:
[302] Fix | Delete
raise BadStatusLine(line)
[303] Fix | Delete
except ValueError:
[304] Fix | Delete
raise BadStatusLine(line)
[305] Fix | Delete
return version, status, reason
[306] Fix | Delete
[307] Fix | Delete
def begin(self):
[308] Fix | Delete
if self.headers is not None:
[309] Fix | Delete
# we've already started reading the response
[310] Fix | Delete
return
[311] Fix | Delete
[312] Fix | Delete
# read until we get a non-100 response
[313] Fix | Delete
while True:
[314] Fix | Delete
version, status, reason = self._read_status()
[315] Fix | Delete
if status != CONTINUE:
[316] Fix | Delete
break
[317] Fix | Delete
# skip the header from the 100 response
[318] Fix | Delete
skipped_headers = _read_headers(self.fp)
[319] Fix | Delete
if self.debuglevel > 0:
[320] Fix | Delete
print("headers:", skipped_headers)
[321] Fix | Delete
del skipped_headers
[322] Fix | Delete
[323] Fix | Delete
self.code = self.status = status
[324] Fix | Delete
self.reason = reason.strip()
[325] Fix | Delete
if version in ("HTTP/1.0", "HTTP/0.9"):
[326] Fix | Delete
# Some servers might still return "0.9", treat it as 1.0 anyway
[327] Fix | Delete
self.version = 10
[328] Fix | Delete
elif version.startswith("HTTP/1."):
[329] Fix | Delete
self.version = 11 # use HTTP/1.1 code for HTTP/1.x where x>=1
[330] Fix | Delete
else:
[331] Fix | Delete
raise UnknownProtocol(version)
[332] Fix | Delete
[333] Fix | Delete
self.headers = self.msg = parse_headers(self.fp)
[334] Fix | Delete
[335] Fix | Delete
if self.debuglevel > 0:
[336] Fix | Delete
for hdr, val in self.headers.items():
[337] Fix | Delete
print("header:", hdr + ":", val)
[338] Fix | Delete
[339] Fix | Delete
# are we using the chunked-style of transfer encoding?
[340] Fix | Delete
tr_enc = self.headers.get("transfer-encoding")
[341] Fix | Delete
if tr_enc and tr_enc.lower() == "chunked":
[342] Fix | Delete
self.chunked = True
[343] Fix | Delete
self.chunk_left = None
[344] Fix | Delete
else:
[345] Fix | Delete
self.chunked = False
[346] Fix | Delete
[347] Fix | Delete
# will the connection close at the end of the response?
[348] Fix | Delete
self.will_close = self._check_close()
[349] Fix | Delete
[350] Fix | Delete
# do we have a Content-Length?
[351] Fix | Delete
# NOTE: RFC 2616, S4.4, #3 says we ignore this if tr_enc is "chunked"
[352] Fix | Delete
self.length = None
[353] Fix | Delete
length = self.headers.get("content-length")
[354] Fix | Delete
if length and not self.chunked:
[355] Fix | Delete
try:
[356] Fix | Delete
self.length = int(length)
[357] Fix | Delete
except ValueError:
[358] Fix | Delete
self.length = None
[359] Fix | Delete
else:
[360] Fix | Delete
if self.length < 0: # ignore nonsensical negative lengths
[361] Fix | Delete
self.length = None
[362] Fix | Delete
else:
[363] Fix | Delete
self.length = None
[364] Fix | Delete
[365] Fix | Delete
# does the body have a fixed length? (of zero)
[366] Fix | Delete
if (status == NO_CONTENT or status == NOT_MODIFIED or
[367] Fix | Delete
100 <= status < 200 or # 1xx codes
[368] Fix | Delete
self._method == "HEAD"):
[369] Fix | Delete
self.length = 0
[370] Fix | Delete
[371] Fix | Delete
# if the connection remains open, and we aren't using chunked, and
[372] Fix | Delete
# a content-length was not provided, then assume that the connection
[373] Fix | Delete
# WILL close.
[374] Fix | Delete
if (not self.will_close and
[375] Fix | Delete
not self.chunked and
[376] Fix | Delete
self.length is None):
[377] Fix | Delete
self.will_close = True
[378] Fix | Delete
[379] Fix | Delete
def _check_close(self):
[380] Fix | Delete
conn = self.headers.get("connection")
[381] Fix | Delete
if self.version == 11:
[382] Fix | Delete
# An HTTP/1.1 proxy is assumed to stay open unless
[383] Fix | Delete
# explicitly closed.
[384] Fix | Delete
if conn and "close" in conn.lower():
[385] Fix | Delete
return True
[386] Fix | Delete
return False
[387] Fix | Delete
[388] Fix | Delete
# Some HTTP/1.0 implementations have support for persistent
[389] Fix | Delete
# connections, using rules different than HTTP/1.1.
[390] Fix | Delete
[391] Fix | Delete
# For older HTTP, Keep-Alive indicates persistent connection.
[392] Fix | Delete
if self.headers.get("keep-alive"):
[393] Fix | Delete
return False
[394] Fix | Delete
[395] Fix | Delete
# At least Akamai returns a "Connection: Keep-Alive" header,
[396] Fix | Delete
# which was supposed to be sent by the client.
[397] Fix | Delete
if conn and "keep-alive" in conn.lower():
[398] Fix | Delete
return False
[399] Fix | Delete
[400] Fix | Delete
# Proxy-Connection is a netscape hack.
[401] Fix | Delete
pconn = self.headers.get("proxy-connection")
[402] Fix | Delete
if pconn and "keep-alive" in pconn.lower():
[403] Fix | Delete
return False
[404] Fix | Delete
[405] Fix | Delete
# otherwise, assume it will close
[406] Fix | Delete
return True
[407] Fix | Delete
[408] Fix | Delete
def _close_conn(self):
[409] Fix | Delete
fp = self.fp
[410] Fix | Delete
self.fp = None
[411] Fix | Delete
fp.close()
[412] Fix | Delete
[413] Fix | Delete
def close(self):
[414] Fix | Delete
try:
[415] Fix | Delete
super().close() # set "closed" flag
[416] Fix | Delete
finally:
[417] Fix | Delete
if self.fp:
[418] Fix | Delete
self._close_conn()
[419] Fix | Delete
[420] Fix | Delete
# These implementations are for the benefit of io.BufferedReader.
[421] Fix | Delete
[422] Fix | Delete
# XXX This class should probably be revised to act more like
[423] Fix | Delete
# the "raw stream" that BufferedReader expects.
[424] Fix | Delete
[425] Fix | Delete
def flush(self):
[426] Fix | Delete
super().flush()
[427] Fix | Delete
if self.fp:
[428] Fix | Delete
self.fp.flush()
[429] Fix | Delete
[430] Fix | Delete
def readable(self):
[431] Fix | Delete
"""Always returns True"""
[432] Fix | Delete
return True
[433] Fix | Delete
[434] Fix | Delete
# End of "raw stream" methods
[435] Fix | Delete
[436] Fix | Delete
def isclosed(self):
[437] Fix | Delete
"""True if the connection is closed."""
[438] Fix | Delete
# NOTE: it is possible that we will not ever call self.close(). This
[439] Fix | Delete
# case occurs when will_close is TRUE, length is None, and we
[440] Fix | Delete
# read up to the last byte, but NOT past it.
[441] Fix | Delete
#
[442] Fix | Delete
# IMPLIES: if will_close is FALSE, then self.close() will ALWAYS be
[443] Fix | Delete
# called, meaning self.isclosed() is meaningful.
[444] Fix | Delete
return self.fp is None
[445] Fix | Delete
[446] Fix | Delete
def read(self, amt=None):
[447] Fix | Delete
if self.fp is None:
[448] Fix | Delete
return b""
[449] Fix | Delete
[450] Fix | Delete
if self._method == "HEAD":
[451] Fix | Delete
self._close_conn()
[452] Fix | Delete
return b""
[453] Fix | Delete
[454] Fix | Delete
if amt is not None:
[455] Fix | Delete
# Amount is given, implement using readinto
[456] Fix | Delete
b = bytearray(amt)
[457] Fix | Delete
n = self.readinto(b)
[458] Fix | Delete
return memoryview(b)[:n].tobytes()
[459] Fix | Delete
else:
[460] Fix | Delete
# Amount is not given (unbounded read) so we must check self.length
[461] Fix | Delete
# and self.chunked
[462] Fix | Delete
[463] Fix | Delete
if self.chunked:
[464] Fix | Delete
return self._readall_chunked()
[465] Fix | Delete
[466] Fix | Delete
if self.length is None:
[467] Fix | Delete
s = self.fp.read()
[468] Fix | Delete
else:
[469] Fix | Delete
try:
[470] Fix | Delete
s = self._safe_read(self.length)
[471] Fix | Delete
except IncompleteRead:
[472] Fix | Delete
self._close_conn()
[473] Fix | Delete
raise
[474] Fix | Delete
self.length = 0
[475] Fix | Delete
self._close_conn() # we read everything
[476] Fix | Delete
return s
[477] Fix | Delete
[478] Fix | Delete
def readinto(self, b):
[479] Fix | Delete
"""Read up to len(b) bytes into bytearray b and return the number
[480] Fix | Delete
of bytes read.
[481] Fix | Delete
"""
[482] Fix | Delete
[483] Fix | Delete
if self.fp is None:
[484] Fix | Delete
return 0
[485] Fix | Delete
[486] Fix | Delete
if self._method == "HEAD":
[487] Fix | Delete
self._close_conn()
[488] Fix | Delete
return 0
[489] Fix | Delete
[490] Fix | Delete
if self.chunked:
[491] Fix | Delete
return self._readinto_chunked(b)
[492] Fix | Delete
[493] Fix | Delete
if self.length is not None:
[494] Fix | Delete
if len(b) > self.length:
[495] Fix | Delete
# clip the read to the "end of response"
[496] Fix | Delete
b = memoryview(b)[0:self.length]
[497] Fix | Delete
[498] Fix | Delete
# we do not use _safe_read() here because this may be a .will_close
[499] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function