我们从Python开源项目中,提取了以下12个代码示例,用于说明如何使用httplib.CannotSendRequest()。
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 deposit(): printMsg("Loading bitcoin address...") # connect to node and get new wallet address try: addr = rpc_connection.getnewaddress() except (socket.error, httplib.CannotSendRequest): printMsg("getnewaddress http error", COLOR_RED) time.sleep(2) return False # show off the new address! printMsg(addr, COLOR_GREEN, 1) showQR(addr, 'M') # called by withdraw() to display segment of a list as a menu
def poli_request(self, endpoint, data, method="POST"): """ @arg : endpoint The API target endpoint @arg : data dictionary @return : dict issued from JSON """ if not self.is_online: g_logger.error("Cannot send requests while not connected") raise IOError headers = {"Accept-encoding": "gzip, deflate", "Content-type": "application/json", "Accept": "*/*;q=0.8", "Accept-Language": "en-US,en;q=0.5", "Connection": "Keep-Alive", "X-API-Key": self.api_key} json_data = json.dumps(data) try: self.h_conn.request(method, endpoint, json_data, headers) except httplib.CannotSendRequest as e: g_logger.error("Error during request, retrying") self.close_connection() self.get_online() self.h_conn.request(method, endpoint, json_data, headers) res = self.h_conn.getresponse() if res.status != 200: g_logger.error("The %s request didn't go as expected", method) g_logger.debug("Status code was %d and content was %s", res.status, res.read()) return None content_type = res.getheader("Content-Encoding") if content_type == "gzip": buf = StringIO(res.read()) res = gzip.GzipFile(fileobj=buf) data = res.read() try: result = json.loads(data) except BaseException: raise IOError return result
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 showQR(): global rpc_connection print "Loading 2nd bitcoin address..." # connect to node and get new wallet address try: addr = rpc_connection.getnewaddress() except (socket.error, httplib.CannotSendRequest): print "showQR Timeout" initRPC() return False # bypass rpc for testing #addr = '1CepbXDXPeJTsk9PUUKkXwfqcyDgmo1qoE' # generate QR code and display on LED grid code = pyqrcode.create(addr, error='M', version=3) t = code.text(1) print addr # print the actual QR code to terminal with 1's and 0's print t row = 31 col = 0 matrix.Clear() for i in t: if i != '\n': matrix.SetPixel(row, col, 255-int(i)*255, 255-int(i)*255, 255-int(i)*255) col += 1 else: row -= 1 col = 0 time.sleep(0.001) # give us a chance to scan it time.sleep(5) return True
def withdraw(): printMsg("Loading unspent coins...") # connect to node and get all unspent outputs try: list = rpc_connection.listunspent(0) except (socket.error, httplib.CannotSendRequest): printMsg("listunspent http error", COLOR_RED) time.sleep(2) return False # no coins if len(list) == 0: printMsg("No unspent outputs!", COLOR_RED) time.sleep(2) return False # calculate balances of each spendable key in wallet coins = {} for addr in list: if addr['address'] in coins: coins[addr['address']] += addr['amount'] else: coins[addr['address']] = addr['amount'] # send unspent coins list to the recursive paging menu function withdrawMenu(coins) # display bitcoin address QR code for tipping
def quit(self): """ Overrides the base class method cleaning the timestamped profile. """ self.is_running = False try: wl_log.info("Quit: Removing profile dir") shutil.rmtree(self.prof_dir_path) super(TorBrowserDriver, self).quit() except CannotSendRequest: wl_log.error("CannotSendRequest while quitting TorBrowserDriver", exc_info=False) # following is copied from webdriver.firefox.webdriver.quit() which # was interrupted due to an unhandled CannotSendRequest exception. # kill the browser self.binary.kill() # remove the profile folder 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)) except Exception: wl_log.error("Exception while quitting TorBrowserDriver", exc_info=True)
def getSuggestions(self, queryString): self.prepareQuery() if queryString is not "": query = self.prepQuerry + quote(queryString) self.conn = HTTPConnection("google.com") try: self.conn = HTTPConnection("google.com") self.conn.request("GET", query, "", {"Accept-Encoding": "UTF-8"}) except (CannotSendRequest, gaierror, error): self.conn.close() print "[MyTube - GoogleSuggestions] Can not send request for suggestions" return None else: try: response = self.conn.getresponse() except BadStatusLine: self.conn.close() print "[MyTube - GoogleSuggestions] Can not get a response from google" return None else: if response.status == 200: data = response.read() header = response.getheader("Content-Type", "text/xml; charset=ISO-8859-1") charset = "ISO-8859-1" try: charset = header.split(";")[1].split("=")[1] print "[MyTube - GoogleSuggestions] Got charset %s" %charset except: print "[MyTube - GoogleSuggestions] No charset in Header, falling back to %s" %charset data = data.decode(charset).encode("utf-8") self.conn.close() return data else: self.conn.close() return None else: return None
def getnewaddr(self, _user = None): """ Generate a new address for _user Returns (string) address """ user = self.verify_user(_user=_user) addr = "" counter = 0 while True: try: # Unlock wallet for keypoolrefill if hasattr(self.conf, 'walletpassphrase'): self.conn.walletpassphrase(self.conf.walletpassphrase, 1) # Generate new address addr = self.conn.getnewaddress(user) # Lock wallet if hasattr(self.conf, 'walletpassphrase'): self.conn.walletlock() if not addr: raise Exception("CtbCoin::getnewaddr(%s): empty addr", user) time.sleep(0.1) return str(addr) except BitcoindException as e: lg.error("CtbCoin::getnewaddr(%s): BitcoindException: %s", user, e) raise except CannotSendRequest as e: if counter < 3: lg.warning("CtbCoin::getnewaddr(%s): CannotSendRequest, retrying") counter += 1 time.sleep(10) continue else: raise except Exception as e: if str(e) == "timed out" and counter < 3: lg.warning("CtbCoin::getnewaddr(%s): timed out, retrying") counter += 1 time.sleep(10) continue else: lg.error("CtbCoin::getnewaddr(%s): Exception: %s", user, e) raise
def getPath(self, path="/"): self.body = None self.__initConnections__( path ) try: self.conn.request("GET", path, headers=self.headers) except httplib.CannotSendRequest as e: log.error("CannotSendRequest") pass except Exception as e: log.error("{}".format(type(e).__name__)) exit(1) #log.debug("GET:{} with {}".format(path, self.headers)) self.res = None cnt = 0 while True: try: self.res = self.conn.getresponse() if self.res is not None: self.body = self.res.read() break except Exception, e: if self.res is not None: self.body = self.res.read() break sys.stdout.write("\tretry {}\r".format(cnt)) sys.stdout.flush() self.conn = None self.__initConnections__( path ) self.conn.request("GET", path, headers=self.headers) time.sleep(cnt*0.5) #if cnt > 10: # log.error("Reaching Max Fail") # exit(1) continue for header in self.res.getheaders(): if header[0] == 'set-cookie': self.cookie_str = header[1] break return self.res.status