Python http.client.CannotSendRequest() Examples

The following are 9 code examples of http.client.CannotSendRequest(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module http.client , or try the search function .
Example #1
Source File: connection.py    From neo4jdb-python with MIT License 6 votes vote down vote up
def _http_req(self, method, path, payload=None, retries=2):
        serialized_payload = json.dumps(payload) if payload is not None else None

        try:
            self._http.request(method, path, serialized_payload, self._COMMON_HEADERS)
            http_response = self._http.getresponse()
        except (http.BadStatusLine, http.CannotSendRequest):
            self._http = http.HTTPConnection(self._host)
            if retries > 0:
                return self._http_req(method, path, payload, retries-1)
            self._handle_error(self, None, Connection.OperationalError, "Connection has expired.")

        if not http_response.status in [200, 201]:
            message = "Server returned unexpected response: " + ustr(http_response.status) + ustr(http_response.read())
            self._handle_error(self, None, Connection.OperationalError, message)

        return http_response 
Example #2
Source File: datastore.py    From oslo.vmware with Apache License 2.0 6 votes vote down vote up
def connect(self, method, content_length, cookie):
        try:
            if self._scheme == 'http':
                conn = httplib.HTTPConnection(self._server)
            elif self._scheme == 'https':
                # TODO(browne): This needs to be changed to use python requests
                conn = httplib.HTTPSConnection(self._server)  # nosec
            else:
                excep_msg = _("Invalid scheme: %s.") % self._scheme
                LOG.error(excep_msg)
                raise ValueError(excep_msg)
            conn.putrequest(method, '/folder/%s?%s' % (self.path, self._query))
            conn.putheader('User-Agent', constants.USER_AGENT)
            conn.putheader('Content-Length', content_length)
            conn.putheader('Cookie', cookie)
            conn.endheaders()
            LOG.debug("Created HTTP connection to transfer the file with "
                      "URL = %s.", str(self))
            return conn
        except (httplib.InvalidURL, httplib.CannotSendRequest,
                httplib.CannotSendHeader) as excep:
            excep_msg = _("Error occurred while creating HTTP connection "
                          "to write to file with URL = %s.") % str(self)
            LOG.exception(excep_msg)
            raise exceptions.VimConnectionException(excep_msg, excep) 
Example #3
Source File: uploadrobot.py    From youtube-video-maker with GNU General Public License v3.0 5 votes vote down vote up
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)) 
Example #4
Source File: node.py    From simcoin with MIT License 5 votes vote down vote up
def execute_rpc(self, *args):
        retry = 30
        while retry > 0:
            try:
                return self._rpc_connection.call(args[0], *args[1:])
            except (IOError, CannotSendRequest) as error:
                logging.exception('Could not execute RPC-call={} on node={} because of error={}.'
                                  ' Reconnecting and retrying, {} retries left'
                                  .format(args[0], self._name,  error, retry))
                retry -= 1
                self.connect_to_rpc()
        raise Exception('Could not execute RPC-call={} on node {}'.format(args[0], self._name)) 
Example #5
Source File: tasks.py    From django-cc with MIT License 5 votes vote down vote up
def refill_addresses_queue():
    for currency in Currency.objects.all():
        coin = AuthServiceProxy(currency.api_url)
        count = Address.objects.filter(currency=currency, active=True, wallet=None).count()

        if count < settings.CC_ADDRESS_QUEUE:
            for i in range(count, settings.CC_ADDRESS_QUEUE):
                try:
                    Address.objects.create(address=coin.getnewaddress(settings.CC_ACCOUNT), currency=currency)
                except (socket_error, CannotSendRequest) :
                    pass 
Example #6
Source File: test_service.py    From oslo.vmware with Apache License 2.0 5 votes vote down vote up
def test_request_handler_with_http_cannot_send_error(self):
        managed_object = 'VirtualMachine'

        def side_effect(mo, **kwargs):
            self.assertEqual(managed_object, mo._type)
            self.assertEqual(managed_object, mo.value)
            raise httplib.CannotSendRequest()

        svc_obj = service.Service()
        attr_name = 'powerOn'
        service_mock = svc_obj.client.service
        setattr(service_mock, attr_name, side_effect)
        self.assertRaises(exceptions.VimSessionOverLoadException,
                          svc_obj.powerOn,
                          managed_object) 
Example #7
Source File: client64.py    From msl-loadlib with MIT License 4 votes vote down vote up
def shutdown_server32(self, kill_timeout=10):
        """Shutdown the 32-bit server.

        This method shuts down the 32-bit server, closes the client connection
        and it deletes the temporary file that is used to save the serialized
        :mod:`pickle`\'d data.

        .. versionchanged:: 0.6
           Added the `kill_timeout` parameter

        Parameters
        ----------
        kill_timeout : :class:`float`, optional
            If the 32-bit server is still running after `kill_timeout` seconds then
            the server will be killed using brute force. A warning will be issued
            if the server is killed in this manner.

        Note
        ----
        This method gets called automatically when the reference count to the
        :class:`~.client64.Client64` object reaches 0.
        """
        if self._conn is None:
            return

        # send the shutdown request
        try:
            self._conn.request('POST', SHUTDOWN)
        except CannotSendRequest:
            # can occur if the previous request raised ResponseTimeoutError
            # send the shutdown request again
            self._conn.close()
            self._conn = HTTPConnection(self.host, port=self.port)
            self._conn.request('POST', SHUTDOWN)

        # give the server a chance to shut down gracefully
        t0 = time.time()
        while self._proc.poll() is None:
            time.sleep(0.1)
            if time.time() - t0 > kill_timeout:
                self._proc.terminate()
                self._proc.returncode = -1
                warnings.warn('killed the 32-bit server using brute force', stacklevel=2)
                break

        # the frozen 32-bit server can still block the process from terminating
        # the <signal.SIGKILL 9> constant is not available on Windows
        if self._meta32:
            try:
                os.kill(self._meta32['pid'], 9)
            except OSError:
                pass  # the server has already stopped

        if os.path.isfile(self._pickle_path):
            os.remove(self._pickle_path)

        self._conn.close()
        self._conn = None 
Example #8
Source File: __init__.py    From magnitude with MIT License 4 votes vote down vote up
def _prefetch_in_background(self, n, amount, offset):
            headers = {
                'Range': "bytes=" + str(max(offset, 0)) + "-" + str(
                    min((offset + amount) - 1, self.length)  # noqa
                ),
            }

            self._wait_on_prefetch_connection(n)
            while not self.pconn_terminated[n]:
                try:
                    self.pconn[n].request(
                        "GET", self.parsed_url.path, headers=headers)
                    break
                except CannotSendRequest:
                    sleep(1)
            while not self.pconn_terminated[n]:
                try:
                    res = self.pconn[n].getresponse()
                    break
                except ResponseNotReady:
                    # Since we are sharing the connection wait for this to be
                    # ready
                    sleep(1)
            if self.pconn_terminated[n]:
                self._unwait_on_prefetch_connection(n)
                return
            else:
                self._unwait_on_prefetch_connection(n)

            if not(res.status >= 200 and res.status <= 299):
                # Check for a valid status from the server
                return
            data = bytearray(res.length)
            i = 0
            for piece in iter(lambda: res.read(1024), bytes('')):
                if not getattr(threading.currentThread(), "do_run", True):
                    break
                data[i:i + len(piece)] = piece
                i = i + len(piece)
            else:
                return bytes(data)

            # Leaving the thread early, without
            # reading all of the data this will
            # make the connection unusable, refresh it
            self._prepare_prefetch_connection(n) 
Example #9
Source File: __init__.py    From supersqlite with MIT License 4 votes vote down vote up
def _prefetch_in_background(self, n, amount, offset):
            headers = {
                'Range': "bytes=" + str(max(offset, 0)) + "-" + str(
                    min((offset + amount) - 1, self.length)  # noqa
                ),
            }

            self._wait_on_prefetch_connection(n)
            while not self.pconn_terminated[n]:
                try:
                    self.pconn[n].request(
                        "GET", self.parsed_url.path, headers=headers)
                    break
                except CannotSendRequest:
                    sleep(1)
            while not self.pconn_terminated[n]:
                try:
                    res = self.pconn[n].getresponse()
                    break
                except ResponseNotReady:
                    # Since we are sharing the connection wait for this to be
                    # ready
                    sleep(1)
            if self.pconn_terminated[n]:
                self._unwait_on_prefetch_connection(n)
                return
            else:
                self._unwait_on_prefetch_connection(n)

            if not(res.status >= 200 and res.status <= 299):
                # Check for a valid status from the server
                return
            data = bytearray(res.length)
            i = 0
            for piece in iter(lambda: res.read(1024), bytes('')):
                if not getattr(threading.currentThread(), "do_run", True):
                    break
                data[i:i + len(piece)] = piece
                i = i + len(piece)
            else:
                return bytes(data)

            # Leaving the thread early, without
            # reading all of the data this will
            # make the connection unusable, refresh it
            self._prepare_prefetch_connection(n)