当前位置: 首页>>代码示例>>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;未经允许,请勿转载。