本文整理汇总了Python中http.client.IncompleteRead方法的典型用法代码示例。如果您正苦于以下问题:Python client.IncompleteRead方法的具体用法?Python client.IncompleteRead怎么用?Python client.IncompleteRead使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类http.client
的用法示例。
在下文中一共展示了client.IncompleteRead方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _update_chunk_length
# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import IncompleteRead [as 别名]
def _update_chunk_length(self):
# First, we'll figure out length of a chunk and then
# we'll try to read it from socket.
if self.chunk_left is not None:
return
line = self._fp.fp.readline()
line = line.split(b';', 1)[0]
try:
self.chunk_left = int(line, 16)
except ValueError:
# Invalid chunked protocol response, abort.
self.close()
raise httplib.IncompleteRead(line)
示例2: content
# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import IncompleteRead [as 别名]
def content(self) -> str:
"""HTML source code of the web-page as str"""
if self._is_empty:
return ""
try:
return self._response.text
except (ConnectionError, OSError, IncompleteRead):
return ""
示例3: bytes
# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import IncompleteRead [as 别名]
def bytes(self) -> bytes:
"""HTTP body response as raw bytes"""
if self._is_empty:
return b""
try:
return self._response.content
except (ConnectionError, OSError, IncompleteRead):
return b""
示例4: test_chunked
# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import IncompleteRead [as 别名]
def test_chunked(self):
expected = chunked_expected
sock = FakeSocket(chunked_start + last_chunk + chunked_end)
resp = client.HTTPResponse(sock, method="GET")
resp.begin()
self.assertEqual(resp.read(), expected)
resp.close()
# Various read sizes
for n in range(1, 12):
sock = FakeSocket(chunked_start + last_chunk + chunked_end)
resp = client.HTTPResponse(sock, method="GET")
resp.begin()
self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
resp.close()
for x in ('', 'foo\r\n'):
sock = FakeSocket(chunked_start + x)
resp = client.HTTPResponse(sock, method="GET")
resp.begin()
try:
resp.read()
except client.IncompleteRead as i:
self.assertEqual(i.partial, expected)
expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
self.assertEqual(repr(i), expected_message)
self.assertEqual(str(i), expected_message)
else:
self.fail('IncompleteRead expected')
finally:
resp.close()
示例5: test_incomplete_read
# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import IncompleteRead [as 别名]
def test_incomplete_read(self):
sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
resp = client.HTTPResponse(sock, method="GET")
resp.begin()
try:
resp.read()
except client.IncompleteRead as i:
self.assertEqual(i.partial, b'Hello\r\n')
self.assertEqual(repr(i),
"IncompleteRead(7 bytes read, 3 more expected)")
self.assertEqual(str(i),
"IncompleteRead(7 bytes read, 3 more expected)")
self.assertTrue(resp.isclosed())
else:
self.fail('IncompleteRead expected')
示例6: __init__
# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import IncompleteRead [as 别名]
def __init__(self):
httplib2.RETRIES = 1
self.MAX_RETRIES = 10
self.RETRIABLE_EXCEPTIONS = (httplib2.HttpLib2Error, IOError, httplib.NotConnected,
httplib.IncompleteRead, httplib.ImproperConnectionState,
httplib.CannotSendRequest, httplib.CannotSendHeader,
httplib.ResponseNotReady, httplib.BadStatusLine)
self.RETRIABLE_STATUS_CODES = [500, 502, 503, 504]
self.CLIENT_SECRETS_FILE = "client_secrets.json"
self.YOUTUBE_UPLOAD_SCOPE = "https://www.googleapis.com/auth/youtube.upload"
self.YOUTUBE_API_SERVICE_NAME = "youtube"
self.YOUTUBE_API_VERSION = "v3"
self.MISSING_CLIENT_SECRETS_MESSAGE = """
WARNING: Please configure OAuth 2.0
To make this sample run you will need to populate the client_secrets.json file
found at:
%s
with information from the Developers Console
https://console.developers.google.com/
For more information about the client_secrets.json file format, please visit:
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),
self.CLIENT_SECRETS_FILE))
示例7: test_mixed_reads
# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import IncompleteRead [as 别名]
def test_mixed_reads(self):
# readline() should update the remaining length, so that read() knows
# how much data is left and does not raise IncompleteRead
body = "HTTP/1.1 200 Ok\r\nContent-Length: 13\r\n\r\nText\r\nAnother"
sock = FakeSocket(body)
resp = client.HTTPResponse(sock)
resp.begin()
self.assertEqual(resp.readline(), b'Text\r\n')
self.assertFalse(resp.isclosed())
self.assertEqual(resp.read(), b'Another')
self.assertTrue(resp.isclosed())
self.assertFalse(resp.closed)
resp.close()
self.assertTrue(resp.closed)
示例8: restore_command
# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import IncompleteRead [as 别名]
def restore_command(site, xlog, output, host=PGHOARD_HOST, port=PGHOARD_PORT, retry_interval=5, retry_count=3):
if not output:
headers = {}
method = "HEAD"
else:
# Construct absolute path for output - postgres calls this command with a relative path to its xlog
# directory. Note that os.path.join strips preceding components if a new components starts with a
# slash so it's still possible to use this with absolute paths.
output_path = os.path.join(os.getcwd(), output)
headers = {"x-pghoard-target-path": output_path}
method = "GET"
path = "/{}/archive/{}".format(site, xlog)
for retries in range(retry_count - 1, -1, -1):
try:
status = http_request(host, port, method, path, headers)
break
except (socket.error, BadStatusLine, IncompleteRead) as ex:
err = "HTTP connection to {0}:{1} failed: {2.__class__.__name__}: {2}".format(host, port, ex)
if not retries:
raise PGCError(err, exit_code=EXIT_ABORT)
print("{}; {} retries left, sleeping {} seconds and retrying".format(err, retries, retry_interval))
time.sleep(retry_interval)
if status == 201 and method == "GET":
return
if status == 200 and method == "HEAD":
return
# NOTE: PostgreSQL interprets exit codes 1..125 as "file not found errors" signalling that there's no
# such wal file from which PostgreSQL assumes that we've completed recovery so we never want to return
# such an error code unless we actually got confirmation that the file isn't in the backend.
if status == 404:
raise PGCError("{!r} not found from archive".format(xlog), exit_code=EXIT_NOT_FOUND)
raise PGCError("Restore failed with HTTP status {}".format(status), exit_code=EXIT_ABORT)
示例9: _retry_on_reset
# 需要导入模块: from http import client [as 别名]
# 或者: from http.client import IncompleteRead [as 别名]
def _retry_on_reset(self, request, action):
retries = 60
retry_wait = 2
while True:
try:
return action()
except (IncompleteRead, HttpError, ssl.SSLEOFError, socket.timeout, OSError, socket.gaierror) as ex:
# Note that socket.timeout and ssl.SSLEOFError inherit from OSError
# and the order of handling the errors here needs to be correct
if not retries:
raise
elif isinstance(ex, (IncompleteRead, socket.timeout, ssl.SSLEOFError, BrokenPipeError)):
pass # just retry with the same sleep amount
elif isinstance(ex, HttpError):
# https://cloud.google.com/storage/docs/json_api/v1/status-codes
# https://cloud.google.com/storage/docs/exponential-backoff
if ex.resp["status"] not in ("429", "500", "502", "503", "504"): # pylint: disable=no-member
raise
retry_wait = min(10.0, max(1.0, retry_wait * 2) + random.random())
# httplib2 commonly fails with Bad File Descriptor and Connection Reset
elif isinstance(ex, OSError) and ex.errno not in [errno.EAGAIN, errno.EBADF, errno.ECONNRESET]:
raise
# getaddrinfo sometimes fails with "Name or service not known"
elif isinstance(ex, socket.gaierror) and ex.errno != socket.EAI_NONAME:
raise
self.log.warning("%s failed: %s (%s), retrying in %.2fs",
action, ex.__class__.__name__, ex, retry_wait)
# we want to reset the http connection state in case of error
if request and hasattr(request, "http"):
request.http.connections.clear() # reset connection cache
retries -= 1
time.sleep(retry_wait)