当前位置: 首页>>代码示例>>Python>>正文


Python requests.Timeout方法代码示例

本文整理汇总了Python中requests.Timeout方法的典型用法代码示例。如果您正苦于以下问题:Python requests.Timeout方法的具体用法?Python requests.Timeout怎么用?Python requests.Timeout使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在requests的用法示例。


在下文中一共展示了requests.Timeout方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_authentication

# 需要导入模块: import requests [as 别名]
# 或者: from requests import Timeout [as 别名]
def test_authentication(self):
        try:
            resp = self.get('account/', op='list_authorisation_tokens')
        except requests.Timeout:
            raise errors.TransientDriverError("Timeout connection to MaaS")
        except Exception as ex:
            raise errors.PersistentDriverError(
                "Error accessing MaaS: %s" % str(ex))

        if resp.status_code in [401, 403]:
            raise errors.PersistentDriverError(
                "MaaS API Authentication Failed")

        if resp.status_code in [500, 503]:
            raise errors.TransientDriverError("Received 50x error from MaaS")

        if resp.status_code != 200:
            raise errors.PersistentDriverError(
                "Received unexpected error from MaaS")

        return True 
开发者ID:airshipit,项目名称:drydock,代码行数:23,代码来源:api_client.py

示例2: _request

# 需要导入模块: import requests [as 别名]
# 或者: from requests import Timeout [as 别名]
def _request(self, url, refresh=False, **params):
        if self.using_cache and refresh is False:  # refresh=True forces a request instead of using cache
            cache = self._resolve_cache(url, **params)
            if cache is not None:
                return cache
        method = params.get('method', 'GET')
        json_data = params.get('json', {})
        timeout = params.pop('timeout', None) or self.timeout
        if self.is_async:  # return a coroutine
            return self._arequest(url, **params)
        try:
            with self.session.request(
                method, url, timeout=timeout, headers=self.headers, params=params, json=json_data
            ) as resp:
                return self._raise_for_status(resp, resp.text, method=method)
        except requests.Timeout:
            raise NotResponding
        except requests.ConnectionError:
            raise NetworkError 
开发者ID:cgrok,项目名称:clashroyale,代码行数:21,代码来源:client.py

示例3: _request

# 需要导入模块: import requests [as 别名]
# 或者: from requests import Timeout [as 别名]
def _request(self, url, refresh=False, **params):
        if self.using_cache and refresh is False:  # refresh=True forces a request instead of using cache
            cache = self._resolve_cache(url, **params)
            if cache is not None:
                return cache
        if self.ratelimit[1] == 0 and time() < self.ratelimit[2] / 1000:
            if not url.endswith('/auth/stats'):
                raise RatelimitErrorDetected(self.ratelimit[2] / 1000 - time())
        if self.is_async:  # return a coroutine
            return self._arequest(url, **params)
        timeout = params.pop('timeout', None) or self.timeout
        try:
            with self.session.get(url, timeout=timeout, headers=self.headers, params=params) as resp:
                return self._raise_for_status(resp, resp.text, method='GET')
        except requests.Timeout:
            raise NotResponding
        except requests.ConnectionError:
            raise NetworkError 
开发者ID:cgrok,项目名称:clashroyale,代码行数:20,代码来源:client.py

示例4: test_location_google_breaks

# 需要导入模块: import requests [as 别名]
# 或者: from requests import Timeout [as 别名]
def test_location_google_breaks(self):
        """User passed location arg but google api gave error"""
        caught_exceptions = [
            requests.ConnectionError, requests.HTTPError, requests.Timeout]
        with mock.patch('requests.get') as mock_get:
            for exception in caught_exceptions:
                mock_get.side_effect = exception
                with capture_sys_output():
                    with self.assertRaises(RipeAtlasToolsException):
                        cmd = Command()
                        cmd.init_args(["--location", "blaaaa"])
                        cmd.run()
            mock_get.side_effect = Exception()
            with self.assertRaises(Exception):
                cmd = Command()
                cmd.init_args(["--location", "blaaaa"])
                cmd.run() 
开发者ID:RIPE-NCC,项目名称:ripe-atlas-tools,代码行数:19,代码来源:probe_search.py

示例5: check_http_page

# 需要导入模块: import requests [as 别名]
# 或者: from requests import Timeout [as 别名]
def check_http_page(info):
    http_redirect = info.new_check()
    try:
        resp, tree = fetch_through_redirects("http://{}".format(info.domain))
        info.http_redirects_to_https = resp.url.startswith("https://")
        if info.http_redirects_to_https:
            http_redirect.succeed("HTTP site redirects to HTTPS.")
        else:
            http_redirect.fail("HTTP site doesn&rsquo;t redirect to HTTPS.")
    except requests.Timeout:
        http_redirect.fail("The HTTP site times out.")
        return
    except requests.ConnectionError:
        http_redirect.fail("Nothing is listening on port 80")
        return
    except Not200 as e:
        http_redirect.fail("The HTTP site returns an error status ({}) on request.".format(e.status))
        return 
开发者ID:benjaminp,项目名称:httpswatch,代码行数:20,代码来源:check_https.py

示例6: scrape_page_for_open_location

# 需要导入模块: import requests [as 别名]
# 或者: from requests import Timeout [as 别名]
def scrape_page_for_open_location(self, my_webpage):
        # logger.info(u"scraping", url)
        try:
            find_pdf_link = self.should_look_for_publisher_pdf()
            if not find_pdf_link:
                logger.info('skipping pdf search')

            my_webpage.scrape_for_fulltext_link(find_pdf_link=find_pdf_link)

            if my_webpage.error:
                self.error += my_webpage.error

            if my_webpage.is_open:
                my_open_location = my_webpage.mint_open_location()
                self.open_locations.append(my_open_location)
                # logger.info(u"found open version at", webpage.url)
            else:
                # logger.info(u"didn't find open version at", webpage.url)
                pass

        except requests.Timeout, e:
            self.error += "Timeout in scrape_page_for_open_location on {}: {}".format(
                my_webpage, unicode(e.message).encode("utf-8"))
            logger.info(self.error) 
开发者ID:ourresearch,项目名称:oadoi,代码行数:26,代码来源:pub.py

示例7: _generate_signature

# 需要导入模块: import requests [as 别名]
# 或者: from requests import Timeout [as 别名]
def _generate_signature(self, stream, timestamp_url, gnupghome):  # pragma: no cover
        # generate the signature
        gpg = gnupg.GPG(gnupghome=gnupghome)
        signature = gpg.sign_file(stream, detach=True)

        # have the signature remotely timestamped
        try:
            response = requests.post(
                timestamp_url, files={"file": signature.data}, timeout=2
            )
        except requests.Timeout:
            raise SPKSignError("Timestamp server did not respond in time")

        # check the response status
        if response.status_code != 200:
            raise SPKSignError(
                "Timestamp server returned with status code %d" % response.status_code
            )

        # verify the timestamp
        if not gpg.verify(response.content):
            raise SPKSignError("Cannot verify timestamp")

        response.encoding = "ascii"
        return response.text 
开发者ID:SynoCommunity,项目名称:spkrepo,代码行数:27,代码来源:utils.py

示例8: http_request_wrapper

# 需要导入模块: import requests [as 别名]
# 或者: from requests import Timeout [as 别名]
def http_request_wrapper(func, *args, timeout=None, max_execution_time=300, **kwargs):
    start_time = time.clock()
    while True:
        try:
            response = func(*args, timeout=timeout, **kwargs)
            response.raise_for_status()
            return response
        except requests.Timeout:
            pass

        if (time.clock() - start_time > max_execution_time):
            raise error.AztkError("Waited {} seconds for request {}, exceeded max_execution_time={}".format(
                time.clock() - start_time,
                func.__name__,
                max_execution_time,
            )) 
开发者ID:Azure,项目名称:aztk,代码行数:18,代码来源:scheduling_target.py

示例9: _get_data

# 需要导入模块: import requests [as 别名]
# 或者: from requests import Timeout [as 别名]
def _get_data(self, path):
        """Getting the required information using metadata service."""
        try:
            response = self._http_request(path)
        except requests.HTTPError as exc:
            if exc.response.status_code == 404:
                raise NotExistingMetadataException(
                    getattr(exc, "message", str(exc)))
            raise
        except requests.exceptions.SSLError as exc:
            LOG.exception(exc)
            raise exception.CertificateVerifyFailed(
                "HTTPS certificate validation failed.")
        except (requests.ConnectionError, requests.Timeout) as exc:
            LOG.exception(exc)
            raise

        return response 
开发者ID:cloudbase,项目名称:cloudbase-init,代码行数:20,代码来源:base.py

示例10: request

# 需要导入模块: import requests [as 别名]
# 或者: from requests import Timeout [as 别名]
def request(self, url, params=None, data=None, method='GET'):
        """Make a `method` request on `url` with the given parameters

        :param string url: part of the URL to reach with the leading slash
        :param dict params: params of the request
        :param dict data: data of the request
        :param string method: method of the request
        :return: the response
        :rtype: :class:`bs4.BeautifulSoup`
        :raise: :class:`~subliminal.exceptions.ProviderNotAvailable`

        """
        try:
            r = self.session.request(method, self.server + url, params=params, data=data, timeout=10)
        except requests.Timeout:
            raise ProviderNotAvailable('Timeout after 10 seconds')
        if r.status_code != 200:
            raise ProviderNotAvailable('Request failed with status code %d' % r.status_code)
        return bs4.BeautifulSoup(r.content, ['permissive']) 
开发者ID:caronc,项目名称:nzb-subliminal,代码行数:21,代码来源:tvsubtitles.py

示例11: download_subtitle

# 需要导入模块: import requests [as 别名]
# 或者: from requests import Timeout [as 别名]
def download_subtitle(self, subtitle):
        try:
            r = self.session.get(self.server + '/download-{subtitle_id}.html'.format(subtitle_id=subtitle.id),
                                 timeout=10)
            logger.debug('Download URL: %s' % (
                self.server + '/download-{subtitle_id}.html'\
                .format(subtitle_id=subtitle.id)))
        except requests.Timeout:
            raise ProviderNotAvailable('Timeout after 10 seconds')
        if r.status_code != 200:
            raise ProviderNotAvailable('Request failed with status code %d' % r.status_code)
        with contextlib.closing(zipfile.ZipFile(io.BytesIO(r.content))) as zf:
            if len(zf.namelist()) > 1:
                raise ProviderError('More than one file to unzip')
            subtitle_bytes = zf.read(zf.namelist()[0])
        subtitle_text = subtitle_bytes.decode(
            detect(subtitle_bytes, subtitle.language.alpha2)['encoding'], 'replace')
        if not is_valid_subtitle(subtitle_text):
            raise InvalidSubtitle
        return subtitle_text 
开发者ID:caronc,项目名称:nzb-subliminal,代码行数:22,代码来源:tvsubtitles.py

示例12: terminate

# 需要导入模块: import requests [as 别名]
# 或者: from requests import Timeout [as 别名]
def terminate(self):
        # logout
        if self.logged_in:

            # Toggle our flag reguardless of our success
            self.logged_in = False
            try:
                r = self.session.get(self.server + '/logout.php', timeout=10)
                logger.debug('Successfully logged out of Addic7ed.')
            except requests.Timeout:
                # No problem... we're done anyway
                logger.warning('A timeout occured logging out of Addic7ed!')
                return

            if r.status_code != 200:
                logger.warning(
                    'Addic7ed returned the error code %d while logging out' %\
                    r.status_code,
                )
                return

        # Close our session
        self.session.close() 
开发者ID:caronc,项目名称:nzb-subliminal,代码行数:25,代码来源:addic7ed.py

示例13: download_subtitle

# 需要导入模块: import requests [as 别名]
# 或者: from requests import Timeout [as 别名]
def download_subtitle(self, subtitle):
        try:
            r = self.session.get(self.server + subtitle.download_link, timeout=10,
                                 headers={'Referer': self.server + subtitle.referer})
            logger.debug('Download URL: %s' % (self.server + subtitle.download_link))
        except requests.Timeout:
            raise ProviderNotAvailable('Timeout after 10 seconds')
        if r.status_code != 200:
            raise ProviderNotAvailable('Request failed with status code %d' % r.status_code)
        if r.headers['Content-Type'] == 'text/html':
            raise ProviderNotAvailable('Download limit exceeded')
        subtitle_text = r.content.decode(
            detect(r.content, subtitle.language.alpha2)['encoding'], 'replace')
        if not is_valid_subtitle(subtitle_text):
            raise InvalidSubtitle
        return subtitle_text 
开发者ID:caronc,项目名称:nzb-subliminal,代码行数:18,代码来源:addic7ed.py

示例14: download_subtitle

# 需要导入模块: import requests [as 别名]
# 或者: from requests import Timeout [as 别名]
def download_subtitle(self, subtitle):
        try:
            r = self.session.get(self.server + subtitle.link, timeout=10)
            logger.debug('Download URL: %s' % (self.server + subtitle.link))
        except requests.Timeout:
            raise ProviderNotAvailable('Timeout after 10 seconds')
        if r.status_code != 200:
            raise ProviderNotAvailable('Request failed with status code %d' % r.status_code)
        with contextlib.closing(zipfile.ZipFile(io.BytesIO(r.content))) as zf:
            if len(zf.namelist()) > 1:
                raise ProviderError('More than one file to unzip')
            subtitle_bytes = zf.read(zf.namelist()[0])
        subtitle_text = subtitle_bytes.decode(
            detect(subtitle_bytes, subtitle.language.alpha2)['encoding'], 'replace')
        if not is_valid_subtitle(subtitle_text):
            raise InvalidSubtitle
        return subtitle_text 
开发者ID:caronc,项目名称:nzb-subliminal,代码行数:19,代码来源:podnapisi.py

示例15: get_odlcs

# 需要导入模块: import requests [as 别名]
# 或者: from requests import Timeout [as 别名]
def get_odlcs(self, mission=None):
        """GET odlcs.

        Args:
            mission: Optional. ID of a mission to restrict by.
        Returns:
            List of Odlc objects which are viewable by user.
        Raises:
            InteropError: Error from server.
            requests.Timeout: Request timeout.
            ValueError or AttributeError: Malformed response from server.
        """
        url = '/api/odlcs'
        if mission:
            url += '?mission=%d' % mission
        r = self.get(url)
        odlcs = []
        for odlc_dict in r.json():
            odlc_proto = interop_api_pb2.Odlc()
            json_format.Parse(json.dumps(odlc_dict), odlc_proto)
            odlcs.append(odlc_proto)
        return odlcs 
开发者ID:auvsi-suas,项目名称:interop,代码行数:24,代码来源:client.py


注:本文中的requests.Timeout方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。