我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用httplib.ResponseNotReady()。
def HTTPResponse__getheaders(self): """Return list of (header, value) tuples.""" if self.msg is None: raise httplib.ResponseNotReady() return self.msg.items()
def getAPIversionHttpService(api): hasLocalJSON = API.hasLocalJSON(api) api, version, api_version, cred_family = API.getVersion(api) httpObj = httplib2.Http(disable_ssl_certificate_validation=GC.Values[GC.NO_VERIFY_SSL], cache=GM.Globals[GM.CACHE_DIR]) if not hasLocalJSON: retries = 3 for n in range(1, retries+1): try: service = googleapiclient.discovery.build(api, version, http=httpObj, cache_discovery=False) if GM.Globals[GM.CACHE_DISCOVERY_ONLY]: httpObj.cache = None return (api_version, httpObj, service, cred_family) except httplib2.ServerNotFoundError as e: systemErrorExit(NETWORK_ERROR_RC, str(e)) except googleapiclient.errors.UnknownApiNameOrVersion as e: systemErrorExit(GOOGLE_API_ERROR_RC, Msg.UNKNOWN_API_OR_VERSION.format(str(e), __author__)) except (googleapiclient.errors.InvalidJsonError, KeyError, ValueError): httpObj.cache = None if n != retries: waitOnFailure(n, retries, INVALID_JSON_RC, Msg.INVALID_JSON_INFORMATION) continue systemErrorExit(INVALID_JSON_RC, Msg.INVALID_JSON_INFORMATION) except (http_client.ResponseNotReady, httplib2.SSLHandshakeError, socket.error) as e: errMsg = u'Connection error: {0}'.format(str(e) or repr(e)) if n != retries: waitOnFailure(n, retries, SOCKET_ERROR_RC, errMsg) continue systemErrorExit(SOCKET_ERROR_RC, errMsg) disc_file, discovery = readDiscoveryFile(api_version) try: service = googleapiclient.discovery.build_from_document(discovery, http=httpObj) if GM.Globals[GM.CACHE_DISCOVERY_ONLY]: httpObj.cache = None return (api_version, httpObj, service, cred_family) except (KeyError, ValueError): invalidDiscoveryJsonExit(disc_file)
def selenium_login(self): try: self.pydriver.get(self.config_dict[TABLEAU_SERVER_URL]) time.sleep(2) self.pydriver.page_source.encode('utf-8') logins = self.pydriver.find_elements(By.XPATH, '//input') if logins is None or len(logins) == 0: ACLogger().get_logger().error('selenium_login error 1') return False the_login = logins[0] password = logins[1] the_login.send_keys(self.config_dict[TABLEAU_SERVER_USERNAME]) password.send_keys(self.config_dict[TABLEAU_SERVER_PASSWORD]) buttons = self.pydriver.find_elements(By.XPATH, '//button') button = None for b in buttons: if str(b.text) == 'Sign In': button = b if button is None: ACLogger().get_logger().error('selenium_login error 2') return False button.click() time.sleep(2) if 'Workbooks' not in self.pydriver.title: ACLogger().get_logger().error('selenium_login error 3') return False except (WebDriverException, StaleElementReferenceException, HTTPException, ResponseNotReady) , e: ACLogger().get_logger().error('selenium_login error: %s' % str(e)) return False ACLogger().get_logger().info( 'Logged in %s successfully, next page title: %s' % (self.config_dict[TABLEAU_SERVER_URL], self.pydriver.title)) return True
def postForm(self, path): params = urllib.urlencode(self.postData) self.setReqHeader() self.conn.request("POST", path, params, headers=self.headers) #log.debug("POST:{} {} with {}".format(path, params, self.headers)) self.res = None cnt = 0 while True: #if cnt > 10: # log.error("Max Redo Post") # exit(1) try: self.res = self.conn.getresponse() if self.res : break except httplib.ResponseNotReady: if self.res is not None: break cnt+=1 sys.stdout.write("retry {}\r".format(cnt)) sys.stdout.flush() self.conn.request("POST", path, params, headers=self.headers) continue except Exception as e: cnt+=1 log.error("\tRedo All {} {}\r".format(cnt, type(e).__name__)) self.resolveImg() self.setPostData(\ self.postData['publicAuditVO.invoiceNumber'], self.postData['publicAuditVO.invoiceDate']) params = urllib.urlencode(self.postData) self.setReqHeader() self.conn.request("POST", path, params, headers=self.headers) time.sleep(cnt*0.5) continue self.body = self.res.read() return self.res.status
def callGData(service, function, soft_errors=False, throw_errors=None, retry_errors=None, **kwargs): import gdata.apps.service if throw_errors is None: throw_errors = [] if retry_errors is None: retry_errors = [] all_retry_errors = GDATA.NON_TERMINATING_ERRORS+retry_errors method = getattr(service, function) retries = 10 for n in range(1, retries+1): try: return method(**kwargs) except gdata.apps.service.AppsForYourDomainException as e: error_code, error_message = checkGDataError(e, service) if (n != retries) and (error_code in all_retry_errors): waitOnFailure(n, retries, error_code, error_message) continue if error_code in throw_errors: if error_code in GDATA.ERROR_CODE_EXCEPTION_MAP: raise GDATA.ERROR_CODE_EXCEPTION_MAP[error_code](error_message) raise if soft_errors: stderrErrorMsg(u'{0} - {1}{2}'.format(error_code, error_message, [u'', u': Giving up.'][n > 1])) return None if error_code == GDATA.INSUFFICIENT_PERMISSIONS: APIAccessDeniedExit() systemErrorExit(GOOGLE_API_ERROR_RC, u'{0} - {1}'.format(error_code, error_message)) except oauth2client.client.AccessTokenRefreshError as e: handleOAuthTokenError(str(e), GDATA.SERVICE_NOT_APPLICABLE in throw_errors) raise GDATA.ERROR_CODE_EXCEPTION_MAP[GDATA.SERVICE_NOT_APPLICABLE](str(e)) except (http_client.ResponseNotReady, httplib2.SSLHandshakeError, socket.error) as e: errMsg = u'Connection error: {0}'.format(str(e) or repr(e)) if n != retries: waitOnFailure(n, retries, SOCKET_ERROR_RC, errMsg) continue if soft_errors: writeStderr(convertUTF8(u'\n{0}{1} - Giving up.\n'.format(ERROR_PREFIX, errMsg))) return None systemErrorExit(SOCKET_ERROR_RC, errMsg) except httplib2.ServerNotFoundError as e: systemErrorExit(NETWORK_ERROR_RC, str(e))
def callGAPI(service, function, silent_errors=False, soft_errors=False, throw_reasons=None, retry_reasons=None, **kwargs): if throw_reasons is None: throw_reasons = [] if retry_reasons is None: retry_reasons = [] all_retry_reasons = GAPI.DEFAULT_RETRY_REASONS+retry_reasons method = getattr(service, function) retries = 10 svcparms = dict(kwargs.items()+GM.Globals[GM.EXTRA_ARGS_LIST]) for n in range(1, retries+1): try: return method(**svcparms).execute() except googleapiclient.errors.HttpError as e: http_status, reason, message = checkGAPIError(e, soft_errors=soft_errors, silent_errors=silent_errors, retryOnHttpError=n < 3, service=service) if http_status == -1: continue if http_status == 0: return None if (n != retries) and (reason in all_retry_reasons): waitOnFailure(n, retries, reason, message) continue if reason in throw_reasons: if reason in GAPI.REASON_EXCEPTION_MAP: raise GAPI.REASON_EXCEPTION_MAP[reason](message) raise e if soft_errors: stderrErrorMsg(u'{0}: {1} - {2}{3}'.format(http_status, reason, message, [u'', u': Giving up.'][n > 1])) return None if reason == GAPI.INSUFFICIENT_PERMISSIONS: APIAccessDeniedExit() systemErrorExit(HTTP_ERROR_RC, formatHTTPError(http_status, reason, message)) except oauth2client.client.AccessTokenRefreshError as e: handleOAuthTokenError(str(e), GAPI.SERVICE_NOT_AVAILABLE in throw_reasons) raise GAPI.REASON_EXCEPTION_MAP[GAPI.SERVICE_NOT_AVAILABLE](str(e)) except httplib2.CertificateValidationUnsupported: noPythonSSLExit() except (http_client.ResponseNotReady, httplib2.SSLHandshakeError, socket.error) as e: errMsg = u'Connection error: {0}'.format(str(e) or repr(e)) if n != retries: waitOnFailure(n, retries, SOCKET_ERROR_RC, errMsg) continue if soft_errors: writeStderr(convertUTF8(u'\n{0}{1} - Giving up.\n'.format(ERROR_PREFIX, errMsg))) return None systemErrorExit(SOCKET_ERROR_RC, errMsg) except ValueError as e: if service._http.cache is not None: service._http.cache = None continue systemErrorExit(GOOGLE_API_ERROR_RC, str(e)) except TypeError as e: systemErrorExit(GOOGLE_API_ERROR_RC, str(e)) except httplib2.ServerNotFoundError as e: systemErrorExit(NETWORK_ERROR_RC, str(e))
def do_open(self, http_class, req): h = None host = req.get_host() if not host: raise urllib2.URLError('no host given') try: need_new_connection = 1 key = self._get_connection_key(host) h = self._connections.get(key) if not h is None: try: self._start_connection(h, req) except: r = None else: try: r = h.getresponse() except httplib.ResponseNotReady, e: r = None except httplib.BadStatusLine, e: r = None if r is None or r.version == 9: # httplib falls back to assuming HTTP 0.9 if it gets a # bad header back. This is most likely to happen if # the socket has been closed by the server since we # last used the connection. if DEBUG: print "failed to re-use connection to %s" % host h.close() else: if DEBUG: print "re-using connection to %s" % host need_new_connection = 0 if need_new_connection: if DEBUG: print "creating new connection to %s" % host h = http_class(host) self._connections[key] = h self._start_connection(h, req) r = h.getresponse() except socket.error, err: if h: h.close() raise urllib2.URLError(err) # if not a persistent connection, don't try to reuse it if r.will_close: self._remove_connection(host) if DEBUG: print "STATUS: %s, %s" % (r.status, r.reason) r._handler = self r._host = host r._url = req.get_full_url() #if r.status == 200 or not HANDLE_ERRORS: #return r if r.status == 200 or not HANDLE_ERRORS: # [speedplane] Must return an adinfourl object resp = urllib2.addinfourl(r, r.msg, req.get_full_url()) resp.code = r.status resp.msg = r.reason return resp; else: r.code = r.status return self.parent.error('http', req, r, r.status, r.reason, r.msg)