我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用http.client.BadStatusLine()。
def quit(self): """Quits the driver and close every associated window.""" try: RemoteWebDriver.quit(self) except (http_client.BadStatusLine, socket.error): # Happens if Firefox shutsdown before we've read the response from # the socket. pass if "specificationLevel" in self.capabilities: self.service.stop() else: self.binary.kill() try: shutil.rmtree(self.profile.path) if self.profile.tempfolder is not None: shutil.rmtree(self.profile.tempfolder) except Exception as e: print(str(e))
def read_headers(self): status_line = yield from self.getline() if self.verbose: print('<', status_line, file=sys.stderr) status_parts = status_line.split(None, 2) if len(status_parts) != 3: raise BadStatusLine(status_line) self.http_version, status, self.reason = status_parts self.status = int(status) while True: header_line = yield from self.getline() if not header_line: break if self.verbose: print('<', header_line, file=sys.stderr) # TODO: Continuation lines. key, value = header_line.split(':', 1) self.headers.append((key, value.strip())) if self.verbose: print(file=sys.stderr)
def read_headers(self): """Read the response status and the request headers.""" status_line = yield from self.getline() status_parts = status_line.split(None, 2) if len(status_parts) != 3: self.log(0, 'bad status_line', repr(status_line)) raise BadStatusLine(status_line) self.http_version, status, self.reason = status_parts self.status = int(status) while True: header_line = yield from self.getline() if not header_line: break # TODO: Continuation lines. key, value = header_line.split(':', 1) self.headers.append((key, value.strip()))
def quit(self): """Quits the driver and close every associated window.""" try: RemoteWebDriver.quit(self) except (http_client.BadStatusLine, socket.error): # Happens if Firefox shutsdown before we've read the response from # the socket. pass if self.w3c: self.service.stop() else: self.binary.kill() if self.profile is not None: try: shutil.rmtree(self.profile.path) if self.profile.tempfolder is not None: shutil.rmtree(self.profile.tempfolder) except Exception as e: print(str(e))
def pcl_put(options, source, target): """ ?????????? ?????????? ??????? ???????? ????? ? ????????? (pcl_put_retry) """ pcl_verbose("Transfer: {0} ({1}) -> {2}".format(source, pcl_human(os.path.getsize(source)), target), options.verbose) retry = 0 while True: try: pcl_put_retry(options, source, target) break except (pclURLError, pclBadStatusLine, pclCannotSendRequest, ssl.SSLError, socket.error, pclError) as e: pcl_can_query_retry(e) retry += 1 pcl_debug("Retry {0}/{1}: {2}".format(retry, options.retries, e), options.debug) if retry >= options.retries: raise pclError(1, e) time.sleep(options.delay)
def pcl_get(options, source, target): """ ?????????? ?????????? ??????? ????????? ????? ?? ????????? (pcl_get_retry) """ pcl_verbose("Transfer: {0} -> {1}".format(source, target), options.verbose) retry = 0 while True: try: pcl_get_retry(options, source, target) break except (pclURLError, pclBadStatusLine, pclCannotSendRequest, ssl.SSLError, socket.error, pclError) as e: pcl_can_query_retry(e) retry += 1 pcl_debug("Retry {0}/{1}: {2}".format(retry, options.retries, e), options.debug) if retry >= options.retries: raise pclError(1, e) time.sleep(options.delay)
def test_status_lines(self): # Test HTTP status lines body = "HTTP/1.1 200 Ok\r\n\r\nText" sock = FakeSocket(body) resp = client.HTTPResponse(sock) resp.begin() self.assertEqual(resp.read(), b"Text") self.assertTrue(resp.isclosed()) self.assertFalse(resp.closed) resp.close() self.assertTrue(resp.closed) body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText" sock = FakeSocket(body) resp = client.HTTPResponse(sock) self.assertRaises(client.BadStatusLine, resp.begin)
def _request(self, method, path, postdata): ''' Do a HTTP request, with retry if we get disconnected (e.g. due to a timeout). This is a workaround for https://bugs.python.org/issue3566 which is fixed in Python 3.5. ''' headers = {'Host': self.__url.hostname, 'User-Agent': USER_AGENT, 'Authorization': self.__auth_header, 'Content-type': 'application/json'} try: self.__conn.request(method, path, postdata, headers) return self._get_response() except httplib.BadStatusLine as e: if e.line == "''": # if connection was closed, try again self.__conn.close() self.__conn.request(method, path, postdata, headers) return self._get_response() else: raise
def test_status_lines(self): # Test HTTP status lines body = "HTTP/1.1 200 Ok\r\n\r\nText" sock = FakeSocket(body) resp = client.HTTPResponse(sock) resp.begin() self.assertEqual(resp.read(0), b'') # Issue #20007 self.assertFalse(resp.isclosed()) self.assertFalse(resp.closed) self.assertEqual(resp.read(), b"Text") self.assertTrue(resp.isclosed()) self.assertFalse(resp.closed) resp.close() self.assertTrue(resp.closed) body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText" sock = FakeSocket(body) resp = client.HTTPResponse(sock) self.assertRaises(client.BadStatusLine, resp.begin)
def request(self, url, query, headers, timeout): request = Request(url, query.encode('utf-8'), headers) try: if (sys.version_info[0] == 2 and sys.version_info[1] > 5) or sys.version_info[0] > 2: response = self.http_opener.open(request, timeout=timeout) else: response = self.http_opener.open(request) except HTTPError as error: if error.fp is None: raise HTTPHandlerError(error.filename, error.code, error.msg, dict(error.hdrs)) else: raise HTTPHandlerError(error.filename, error.code, error.msg, dict(error.hdrs), error.read()) except URLError as error: # urllib2.URLError documentation is horrendous! # Try to get the tuple arguments of URLError if hasattr(error.reason, 'args') and isinstance(error.reason.args, tuple) and len(error.reason.args) == 2: raise HTTPHandlerError(httpcode=error.reason.args[0], httpmsg=error.reason.args[1]) else: raise HTTPHandlerError(httpmsg='urllib2.URLError: %s' % (error.reason)) except BadStatusLine as error: raise HTTPHandlerError(httpmsg='httplib.BadStatusLine: %s' % (error.line)) return response.read().decode('utf-8')
def quit(self): """ Closes the browser and shuts down the SafariDriver executable that is started when starting the SafariDriver """ try: RemoteWebDriver.quit(self) except http_client.BadStatusLine: pass finally: self.service.stop()
def read_headers(self): status_line = yield from self.getline() status_parts = status_line.split(None, 2) if len(status_parts) != 3: raise BadStatusLine(status_line) self.http_version, status, self.reason = status_parts self.status = int(status) while True: header_line = yield from self.getline() if not header_line: break # TODO: Continuation lines. key, value = header_line.split(':', 1) self.headers.append((key, value.strip()))
def request(self, host, handler, request_body, verbose=0): """Send XMLRPC request""" uri = '{scheme}://{host}{handler}'.format(scheme=self._scheme, host=host, handler=handler) if self._passmgr: self._passmgr.add_password(None, uri, self._username, self._password) if self.verbose: _LOGGER.debug("FabricTransport: {0}".format(uri)) opener = urllib2.build_opener(*self._handlers) headers = { 'Content-Type': 'text/xml', 'User-Agent': self.user_agent, } req = urllib2.Request(uri, request_body, headers=headers) try: return self.parse_response(opener.open(req)) except (urllib2.URLError, urllib2.HTTPError) as exc: try: code = -1 if exc.code == 400: reason = 'Permission denied' code = exc.code else: reason = exc.reason msg = "{reason} ({code})".format(reason=reason, code=code) except AttributeError: if 'SSL' in str(exc): msg = "SSL error" else: msg = str(exc) raise InterfaceError("Connection with Fabric failed: " + msg) except BadStatusLine: raise InterfaceError("Connection with Fabric failed: check SSL")
def quit(self): """ Closes the browser and shuts down the OperaDriver executable that is started when starting the OperaDriver """ try: RemoteWebDriver.quit(self) except http_client.BadStatusLine: pass finally: self.service.stop()
def quit(self): """Quits the driver and close every associated window.""" try: RemoteWebDriver.quit(self) except (http_client.BadStatusLine, socket.error): # Happens if Firefox shutsdown before we've read the response from # the socket. pass self.binary.kill() try: shutil.rmtree(self.profile.path) if self.profile.tempfolder is not None: shutil.rmtree(self.profile.tempfolder) except Exception as e: print(str(e))
def request(self, url: str, query: str, headers: Dict[Any, Any], timeout: int) -> str: headers = {**self.auth, **headers} request = Request(url, query.encode('utf-8'), headers) try: if (sys.version_info[0] == 2 and sys.version_info[1] > 5) or sys.version_info[0] > 2: response = self.http_opener.open(request, timeout=timeout) else: response = self.http_opener.open(request) except HTTPError as http_error: if http_error.fp is None: # type: ignore raise HTTPHandlerError( http_error.filename, http_error.code, http_error.msg, dict(http_error.hdrs)) # type: ignore else: raise HTTPHandlerError( http_error.filename, http_error.code, http_error.msg, # type: ignore dict(http_error.hdrs), http_error.read()) # type: ignore except URLError as url_error: # urllib2.URLError documentation is horrendous! # Try to get the tuple arguments of URLError if hasattr(url_error.reason, 'args') and isinstance(url_error.reason.args, tuple) and len(url_error.reason.args) == 2: # type: ignore raise HTTPHandlerError( httpcode=url_error.reason.args[0], httpmsg=url_error.reason.args[1]) # type: ignore else: raise HTTPHandlerError( httpmsg='urllib2.URLError: %s' % url_error.reason) # type: ignore except BadStatusLine as line_error: raise HTTPHandlerError( httpmsg='httplib.BadStatusLine: %s' % line_error.line) # type: ignore return response.read().decode('utf-8')
def validate_default(self, parts, verify_exists=False): """ Validation for FTP, FTPS, HTTP, and HTTPS scehems. When `verify_exists` is set to True, this validator will make HEAD requests for the URL and will return False if the URL returns a status outside of the range of 200 >= «status» > 400. :param parts: :param verify_exists: :return: """ validator = URLValidator() if not parts['netloc']: # If there is no host/port, then this may be a link to a local # resource (media or static asset, etc.) Use the provided default. parts['netloc'] = self.netloc url = urlunparse(parts.values()) try: validator(url) except ValidationError: return False else: if verify_exists: try: response = urlopen(HeadRequest(url)) # NOTE: urllib should have already resolved any 301/302s return 200 <= response.code < 400 # pragma: no cover except (HTTPError, URLError, BadStatusLine, UnicodeEncodeError): return False else: return True
def quit(self): """ Closes the browser and shuts down the """ try: RemoteWebDriver.quit(self) except http_client.BadStatusLine: pass
def test_status_lines(self): # Test HTTP status lines body = "HTTP/1.1 200 Ok\r\n\r\nText" sock = FakeSocket(body) resp = client.HTTPResponse(sock) resp.begin() self.assertEqual(resp.read(), b"Text") self.assertTrue(resp.isclosed()) body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText" sock = FakeSocket(body) resp = client.HTTPResponse(sock) self.assertRaises(client.BadStatusLine, resp.begin)
def test_bad_status_repr(self): exc = client.BadStatusLine('') self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
def test_overflowing_status_line(self): body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n" resp = client.HTTPResponse(FakeSocket(body)) self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
def send_request(self, req_inter): try: if self.logger: self.logger.debug("SendRequest %s" % req_inter) self.conn.request(req_inter.method, req_inter.uri, req_inter.data, req_inter.header) self.conn.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) try: http_resp = self.conn.getresponse() except BadStatusLine: #open another connection when keep-alive timeout #httplib will not handle keep-alive timeout, so we must handle it ourself self.conn.close() self.conn.request(req_inter.method, req_inter.uri, req_inter.data, req_inter.header) self.conn.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) http_resp = self.conn.getresponse() headers = dict(http_resp.getheaders()) resp_inter = ResponseInternal(status = http_resp.status, header = headers, data = http_resp.read()) self.request_size = self.conn.request_length self.response_size = len(resp_inter.data) if not self.is_keep_alive(): self.conn.close() if self.logger: self.logger.debug("GetResponse %s" % resp_inter) return resp_inter except Exception as e: self.conn.close() raise MNSClientNetworkException("NetWorkException", str(e), req_inter.get_req_id()) #raise netException
def pcl_query(options, method, url, args, headers = None, filename = None): """ ?????????? ?????????? ??????? ??????? ? API (pcl_query_retry) """ retry = 0 while True: try: return pcl_query_retry(options, method, url, args, headers, filename) except (pclURLError, pclBadStatusLine, pclCannotSendRequest, ssl.SSLError, socket.error, pclError) as e: pcl_can_query_retry(e) retry += 1 pcl_debug("Retry {0}/{1}: {2}".format(retry, options.retries, e), options.debug) if retry >= options.retries: raise pclError(1, e) time.sleep(options.delay)
def test_error_leak(self): # Test that the socket is not leaked if getresponse() fails conn = client.HTTPConnection('example.com') response = None class Response(client.HTTPResponse): def __init__(self, *pos, **kw): nonlocal response response = self # Avoid garbage collector closing the socket client.HTTPResponse.__init__(self, *pos, **kw) conn.response_class = Response conn.sock = FakeSocket('') # Emulate server dropping connection conn.request('GET', '/') self.assertRaises(client.BadStatusLine, conn.getresponse) self.assertTrue(response.closed) self.assertTrue(conn.sock.file_closed)
def sync_check(self): url = '%s/synccheck' % self.loginInfo.get('syncUrl', self.loginInfo['url']) params = { 'r' : int(time.time() * 1000), 'skey' : self.loginInfo['skey'], 'sid' : self.loginInfo['wxsid'], 'uin' : self.loginInfo['wxuin'], 'deviceid' : self.loginInfo['deviceid'], 'synckey' : self.loginInfo['synckey'], '_' : int(time.time() * 1000),} headers = { 'User-Agent' : config.USER_AGENT } try: r = self.s.get(url, params=params, headers=headers, timeout=config.TIMEOUT) except requests.exceptions.ConnectionError as e: try: if not isinstance(e.args[0].args[1], BadStatusLine): raise # will return a package with status '0 -' # and value like: # 6f:00:8a:9c:09:74:e4:d8:e0:14:bf:96:3a:56:a0:64:1b:a4:25:5d:12:f4:31:a5:30:f1:c6:48:5f:c3:75:6a:99:93 # seems like status of typing, but before I make further achievement code will remain like this return '2' except: raise r.raise_for_status() regx = r'window.synccheck={retcode:"(\d+)",selector:"(\d+)"}' pm = re.search(regx, r.text) if pm is None or pm.group(1) != '0': logger.debug('Unexpected sync check result: %s' % r.text) return None return pm.group(2)
def bucket(self, name): for _repeat in range(6): try: return Bucket(self.connection.get_bucket(name)) except (IOError, BadStatusLine) as e: sleep(_repeat * 2 + 1) if e.errno == errno.EPIPE: self.connection = storage.Client()
def list(self): for _repeat in range(6): buckets = [] try: for bucket in self.connection.list_buckets(): buckets.append(bucket.name) break except (IOError, BadStatusLine) as e: sleep(_repeat * 2 + 1) if e.errno == errno.EPIPE: self.connection = storage.Client() return buckets
def put(self, source, target): for _repeat in range(6): try: key = self.handle.blob(target, chunk_size=self.CHUNK_SIZE) key.upload_from_filename(source) break except (IOError, BadStatusLine) as e: sleep(_repeat * 2 + 1) self._reconnect(self.name) except: pass
def get(self, source, target): key = self.handle.get_blob(source) if key is None: raise Exception("Object {} not exists in bucket {}.".format( source, self.handle.id)) key.chunk_size = self.CHUNK_SIZE for _repeat in range(6): try: key.download_to_filename(target) except (IOError, BadStatusLine) as e: sleep(_repeat * 2 + 1) self._reconnect(self.name) key = self.handle.get_blob(source) except: pass
def is_public(self, source): for _repeat in range(6): try: key = self.handle.get_blob(source) if key is None: return False return 'READER' in key.acl.all().get_roles() except (IOError, BadStatusLine) as e: sleep(_repeat * 2 + 1) self._reconnect(self.name) except: pass
def get_elev(x, units='Meters'): """Uses USGS elevation service to retrieve elevation :param x: longitude and latitude of point where elevation is desired :type x: list :param units: units for returned value; defaults to Meters; options are 'Meters' or 'Feet' :type units: str :returns: ned float elevation of location in meters :Example: >>> get_elev([-111.21,41.4]) 1951.99 """ values = { 'x': x[0], 'y': x[1], 'units': units, 'output': 'json' } elev_url = 'http://ned.usgs.gov/epqs/pqs.php?' attempts = 0 while attempts < 4: try: response = requests.get(elev_url, params=values).json() g = float(response['USGS_Elevation_Point_Query_Service']['Elevation_Query']['Elevation']) break except(BadStatusLine): print("Connection attempt {:} of 3 failed.".format(attempts)) attempts += 1 g = 0 return g