當前位置: 首頁>>代碼示例>>Python>>正文


Python exceptions.RequestException方法代碼示例

本文整理匯總了Python中requests.exceptions.RequestException方法的典型用法代碼示例。如果您正苦於以下問題:Python exceptions.RequestException方法的具體用法?Python exceptions.RequestException怎麽用?Python exceptions.RequestException使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在requests.exceptions的用法示例。


在下文中一共展示了exceptions.RequestException方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: start_suite

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import RequestException [as 別名]
def start_suite(self, suite: TestSuite) -> None:
        """Form list of tests for the Robot Framework test suite that are included in the TestRail test run.

        If analysis depth of the run results is greater than zero, when first suite is launched
        a list of 'testrailid' tags of stable test cases is obtained.
        After that the list of tags is written to the class attribute and for subsequent suites the obtaining is not happening.

        If analysis depth of the run results is zero, when the first suite is launched
        a list of 'testrailid' tags of all test cases in the given status is obtained.
        After that the list of tags is written to the class attribute and for subsequent suites the obtaining is not happening.

        *Args:*\n
            _suite_ - Robot Framework test suite object.
        """
        tests = suite.tests
        suite.tests = None
        try:
            if self.results_depth > 0:
                suite.tests = [t for t in tests if (set(t.tags) & set(self.tr_stable_tags_list))]
            else:
                suite.tests = [t for t in tests if (set(t.tags) & set(self.tr_tags_list))]
        except (RequestException, TimeoutError) as error:
            self._log_to_parent_suite(suite, str(error)) 
開發者ID:peterservice-rnd,項目名稱:robotframework-testrail,代碼行數:25,代碼來源:TestRailPreRunModifier.py

示例2: find_bad_items

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import RequestException [as 別名]
def find_bad_items(self, batch: Mapping[str, DatabaseMedia]):
        """
        a batch get failed. Now do all of its contents as individual
        gets so we can work out which ID(s) cause the failure
        """
        for item_id, media_item in batch.items():
            try:
                log.debug("BAD ID Retry on %s (%s)", item_id, media_item.relative_path)
                response = self._api.mediaItems.get.execute(mediaItemId=item_id)
                media_item_json = response.json()
                self.download_file(media_item, media_item_json)
            except RequestException as e:
                self.bad_ids.add_id(
                    str(media_item.relative_path), media_item.id, media_item.url, e
                )
                self.files_download_failed += 1
                log.error(
                    "FAILURE %d in get of %s BAD ID",
                    self.files_download_failed,
                    media_item.relative_path,
                ) 
開發者ID:gilesknap,項目名稱:gphotos-sync,代碼行數:23,代碼來源:GooglePhotosDownload.py

示例3: job_exists

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import RequestException [as 別名]
def job_exists(self, job_id):
        try:
            endpoint = "job/{}".format(job_id)
            url = self.bulk_url.format(self.sf.instance_url, endpoint)
            headers = self._get_bulk_headers()

            with metrics.http_request_timer("get_job"):
                self.sf._make_request('GET', url, headers=headers)

            return True # requests will raise for a 400 InvalidJob

        except RequestException as ex:
            if ex.response.headers["Content-Type"] == 'application/json':
                exception_code = ex.response.json()['exceptionCode']
                if exception_code == 'InvalidJob':
                    return False
            raise 
開發者ID:singer-io,項目名稱:tap-salesforce,代碼行數:19,代碼來源:bulk.py

示例4: _make_request

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import RequestException [as 別名]
def _make_request(self, http_method, url, headers=None, body=None, stream=False, params=None):
        if http_method == "GET":
            LOGGER.info("Making %s request to %s with params: %s", http_method, url, params)
            resp = self.session.get(url, headers=headers, stream=stream, params=params)
        elif http_method == "POST":
            LOGGER.info("Making %s request to %s with body %s", http_method, url, body)
            resp = self.session.post(url, headers=headers, data=body)
        else:
            raise TapSalesforceException("Unsupported HTTP method")

        try:
            resp.raise_for_status()
        except RequestException as ex:
            raise ex

        if resp.headers.get('Sforce-Limit-Info') is not None:
            self.rest_requests_attempted += 1
            self.check_rest_quota_usage(resp.headers)

        return resp 
開發者ID:singer-io,項目名稱:tap-salesforce,代碼行數:22,代碼來源:__init__.py

示例5: test

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import RequestException [as 別名]
def test(self):
        # list UDSO's
        json_payload = ''
        api_path = "/WebApp/api/SuspiciousObjects/UserDefinedSO/"
        request_url = self.url + api_path
        self.create_jwt_token(api_path, 'GET', json_payload)

        response = None

        try:
            response = requests.get(request_url, headers=self.header_dict, data=json_payload, verify=False)
            response.raise_for_status()
            if response.status_code != 200:
                raise ConnectionTestException(f'{response.text} (HTTP status: {response.status_code})')

            return {"success": True}
        except RequestException as rex:
            if response:
                self.logger.error(f"Received status code: {response.status_code}")
                self.logger.error(f"Response was: {response.text}")
            raise ConnectionTestException(assistance="Please verify the connection details and input data.",
                                          cause=f"Error processing the Apex request: {rex}") 
開發者ID:rapid7,項目名稱:insightconnect-plugins,代碼行數:24,代碼來源:connection.py

示例6: dispatch_event

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import RequestException [as 別名]
def dispatch_event(event):
        """ Dispatch the event being represented by the Event object.

    Args:
      event: Object holding information about the request to be dispatched to the Optimizely backend.
    """

        try:
            if event.http_verb == enums.HTTPVerbs.GET:
                requests.get(event.url, params=event.params, timeout=REQUEST_TIMEOUT).raise_for_status()
            elif event.http_verb == enums.HTTPVerbs.POST:
                requests.post(
                    event.url, data=json.dumps(event.params), headers=event.headers, timeout=REQUEST_TIMEOUT,
                ).raise_for_status()

        except request_exception.RequestException as error:
            logging.error('Dispatch event failed. Error: %s' % str(error)) 
開發者ID:optimizely,項目名稱:python-sdk,代碼行數:19,代碼來源:event_dispatcher.py

示例7: test_dispatch_event__handle_request_exception

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import RequestException [as 別名]
def test_dispatch_event__handle_request_exception(self):
        """ Test that dispatch event handles exceptions and logs error. """

        url = 'https://www.optimizely.com'
        params = {
            'accountId': '111001',
            'eventName': 'test_event',
            'eventEntityId': '111028',
            'visitorId': 'oeutest_user',
        }
        event = event_builder.Event(url, params, http_verb='POST', headers={'Content-Type': 'application/json'})

        with mock.patch(
            'requests.post', side_effect=request_exception.RequestException('Failed Request'),
        ) as mock_request_post, mock.patch('logging.error') as mock_log_error:
            event_dispatcher.EventDispatcher.dispatch_event(event)

        mock_request_post.assert_called_once_with(
            url,
            data=json.dumps(params),
            headers={'Content-Type': 'application/json'},
            timeout=event_dispatcher.REQUEST_TIMEOUT,
        )
        mock_log_error.assert_called_once_with('Dispatch event failed. Error: Failed Request') 
開發者ID:optimizely,項目名稱:python-sdk,代碼行數:26,代碼來源:test_event_dispatcher.py

示例8: complete_experiment

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import RequestException [as 別名]
def complete_experiment(self, status):
        """Record worker completion status to the experiment server.

        This is done using a GET request to the /worker_complete
        or /worker_failed endpoints.
        """
        self.log("Bot player completing experiment. Status: {}".format(status))
        while True:
            url = "{host}/{status}?participant_id={participant_id}".format(
                host=self.host, participant_id=self.participant_id, status=status
            )
            try:
                result = requests.get(url)
                result.raise_for_status()
            except RequestException:
                self.stochastic_sleep()
                continue
            return result 
開發者ID:Dallinger,項目名稱:Dallinger,代碼行數:20,代碼來源:bots.py

示例9: complete_questionnaire

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import RequestException [as 別名]
def complete_questionnaire(self):
        """Complete the standard debriefing form.

        Answers the questions in the base questionnaire.
        """
        while True:
            data = {
                "question": "questionnaire",
                "number": 1,
                "response": json.dumps(self.question_responses),
            }
            url = "{host}/question/{self.participant_id}".format(
                host=self.host, self=self
            )
            try:
                result = requests.post(url, data=data)
                result.raise_for_status()
            except RequestException:
                self.stochastic_sleep()
                continue
            return True 
開發者ID:Dallinger,項目名稱:Dallinger,代碼行數:23,代碼來源:bots.py

示例10: prefetch_login

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import RequestException [as 別名]
def prefetch_login(self):
        """Check if we have stored credentials.
        If so, do the login before the user requests it"""
        from requests import exceptions
        try:
            common.get_credentials()
            if not self.is_logged_in():
                self._login()
            self.is_prefetch_login = True
        except exceptions.RequestException as exc:
            # It was not possible to connect to the web service, no connection, network problem, etc
            import traceback
            common.error('Login prefetch: request exception {}', exc)
            common.debug(g.py2_decode(traceback.format_exc(), 'latin-1'))
        except MissingCredentialsError:
            common.info('Login prefetch: No stored credentials are available')
        except (LoginFailedError, LoginValidateError):
            ui.show_notification(common.get_local_string(30009))
        except (InvalidMembershipStatusError, InvalidMembershipStatusAnonymous):
            ui.show_notification(common.get_local_string(30180), time=10000) 
開發者ID:CastagnaIT,項目名稱:plugin.video.netflix,代碼行數:22,代碼來源:nfsession_access.py

示例11: test__requests_exception

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import RequestException [as 別名]
def test__requests_exception(self):
        """force a requests exception."""
        from requests.exceptions import RequestException
        import oandapyV20.endpoints.accounts as accounts
        setattr(sys.modules["oandapyV20.oandapyV20"],
                "TRADING_ENVIRONMENTS",
                {"practice": {
                 "stream": "ttps://test.com",
                 "api": "ttps://test.com",
                 }})
        api = API(environment=environment,
                  access_token=access_token,
                  headers={"Content-Type": "application/json"})
        text = "No connection " \
               "adapters were found for 'ttps://test.com/v3/accounts'"
        r = accounts.AccountList()
        with self.assertRaises(RequestException) as oErr:
            api.request(r)

        self.assertEqual("{}".format(oErr.exception), text) 
開發者ID:hootnot,項目名稱:oanda-api-v20,代碼行數:22,代碼來源:test_oandapyv20.py

示例12: fetch_description

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import RequestException [as 別名]
def fetch_description(url: str) -> list:
        """

        :param id: Id of the image whose description will be downloaded
        :return: Json
        """
        # Sometimes their site isn't responding well, and than an error occurs,
        # So we will retry 10 seconds later and repeat until it succeeds
        while True:
            try:
                # Download the description
                response_desc = requests.get(url, stream=True, timeout=20)
                # Validate the download status is ok
                response_desc.raise_for_status()
                # Parse the description
                parsed_description = response_desc.json()
                return parsed_description
            except (RequestException, ReadTimeoutError):
                time.sleep(5) 
開發者ID:GalAvineri,項目名稱:ISIC-Archive-Downloader,代碼行數:21,代碼來源:download_single_item.py

示例13: working_directory

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import RequestException [as 別名]
def working_directory():
    docker_client = utils.get_docker_client()
    volume_name = 'epicbox-' + str(uuid.uuid4())
    log = logger.bind(volume=volume_name)
    log.info("Creating new docker volume for working directory")
    try:
        volume = docker_client.volumes.create(volume_name)
    except (RequestException, DockerException) as e:
        log.exception("Failed to create a docker volume")
        raise exceptions.DockerError(str(e))
    log.info("New docker volume is created")
    try:
        yield _WorkingDirectory(volume=volume_name, node=None)
    finally:  # Ensure that volume cleanup takes place
        log.info("Removing the docker volume")
        try:
            volume.remove()
        except NotFound:
            log.warning("Failed to remove the docker volume, it doesn't exist")
        except (RequestException, DockerException):
            log.exception("Failed to remove the docker volume")
        else:
            log.info("Docker volume removed") 
開發者ID:StepicOrg,項目名稱:epicbox,代碼行數:25,代碼來源:sandboxes.py

示例14: inspect_exited_container_state

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import RequestException [as 別名]
def inspect_exited_container_state(container):
    try:
        container.reload()
    except (RequestException, DockerException) as e:
        logger.exception("Failed to load the container from the Docker engine",
                         container=container)
        raise exceptions.DockerError(str(e))
    started_at = dateutil.parser.parse(container.attrs['State']['StartedAt'])
    finished_at = dateutil.parser.parse(container.attrs['State']['FinishedAt'])
    duration = finished_at - started_at
    duration_seconds = duration.total_seconds()
    if duration_seconds < 0:
        duration_seconds = -1
    return {
        'exit_code': container.attrs['State']['ExitCode'],
        'duration': duration_seconds,
        'oom_killed': container.attrs['State'].get('OOMKilled', False),
    } 
開發者ID:StepicOrg,項目名稱:epicbox,代碼行數:20,代碼來源:utils.py

示例15: submit_bug

# 需要導入模塊: from requests import exceptions [as 別名]
# 或者: from requests.exceptions import RequestException [as 別名]
def submit_bug(filename, options):
    import requests  # only import when needed
    from requests.exceptions import RequestException

    try:
        opts = dict((k, v) for k, v in options.__dict__.items()
                    if v and k != 'submit_bug')

        r = requests.post('http://localhost:5000/bugs', {'filename': filename,
                                                         'version': __version__,
                                                         'options': str(opts)})
        if r.status_code == 200:
            print('Successfully submitted file: %s' % r.text)
        else:
            print('Could not submit bug at the moment, please try again later.')

    except RequestException as e:
        print('Could not submit bug at the moment, please try again later.') 
開發者ID:caronc,項目名稱:nzb-subliminal,代碼行數:20,代碼來源:__main__.py


注:本文中的requests.exceptions.RequestException方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。