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


Python requests.exceptions方法代码示例

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


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

示例1: _must_post

# 需要导入模块: import requests [as 别名]
# 或者: from requests import exceptions [as 别名]
def _must_post(self, api, data=None, json=None, timeout=10, **kwargs):
        if data is not None:
            kwargs['data'] = data
        elif json is not None:
            kwargs['json'] = json
        else:
            kwargs['data'] = {}
        kwargs['timeout'] = timeout

        try:
            r = requests.post(api, **kwargs)
            return r
        except requests.exceptions.Timeout:
            logger.error("Timeout requesting Gitter")
        except KeyboardInterrupt:
            raise
        except:
            logger.exception("Unknown error requesting Gitter")
        return None 
开发者ID:tuna,项目名称:fishroom,代码行数:21,代码来源:gitter.py

示例2: upload_image

# 需要导入模块: import requests [as 别名]
# 或者: from requests import exceptions [as 别名]
def upload_image(self, filename=None, filedata=None, **kwargs) -> str:
        if filedata is None:
            files = {"image": open(filename, 'rb')}
        else:
            files = {"image": filedata}

        try:
            r = requests.post(self.url, files=files, timeout=5)
        except requests.exceptions.Timeout:
            logger.error("Timeout uploading to VimCN")
            return None
        except:
            logger.exception("Unknown errror uploading to VimCN")
            return None
        if not r.ok:
            return None
        return r.text.strip() 
开发者ID:tuna,项目名称:fishroom,代码行数:19,代码来源:photostore.py

示例3: http_head

# 需要导入模块: import requests [as 别名]
# 或者: from requests import exceptions [as 别名]
def http_head(self, path, **kwargs):
        """
        Make a HEAD request to the k8s server.
        """
        try:

            url = urljoin(self.url, path)
            response = self.session.head(url, **kwargs)
        except requests.exceptions.ConnectionError as err:
            # reraise as KubeException, but log stacktrace.
            message = "There was a problem retrieving headers from " \
                "the Kubernetes API server. URL: {}".format(url)
            logger.error(message)
            raise KubeException(message) from err

        return response 
开发者ID:deis,项目名称:controller,代码行数:18,代码来源:__init__.py

示例4: http_post

# 需要导入模块: import requests [as 别名]
# 或者: from requests import exceptions [as 别名]
def http_post(self, path, data=None, json=None, **kwargs):
        """
        Make a POST request to the k8s server.
        """
        try:
            url = urljoin(self.url, path)
            response = self.session.post(url, data=data, json=json, **kwargs)
        except requests.exceptions.ConnectionError as err:
            # reraise as KubeException, but log stacktrace.
            message = "There was a problem posting data to " \
                      "the Kubernetes API server. URL: {}, " \
                      "data: {}, json: {}".format(url, data, json)
            logger.error(message)
            raise KubeException(message) from err

        return response 
开发者ID:deis,项目名称:controller,代码行数:18,代码来源:__init__.py

示例5: http_put

# 需要导入模块: import requests [as 别名]
# 或者: from requests import exceptions [as 别名]
def http_put(self, path, data=None, **kwargs):
        """
        Make a PUT request to the k8s server.
        """
        try:
            url = urljoin(self.url, path)
            response = self.session.put(url, data=data, **kwargs)
        except requests.exceptions.ConnectionError as err:
            # reraise as KubeException, but log stacktrace.
            message = "There was a problem putting data to " \
                      "the Kubernetes API server. URL: {}, " \
                      "data: {}".format(url, data)
            logger.error(message)
            raise KubeException(message) from err

        return response 
开发者ID:deis,项目名称:controller,代码行数:18,代码来源:__init__.py

示例6: checkout_branch

# 需要导入模块: import requests [as 别名]
# 或者: from requests import exceptions [as 别名]
def checkout_branch(self, project: str, branch: str) -> None:
        """Checks out a new git branch. Only works in dev workspace.

        Args:
            project: Name of the Looker project to use.
            branch: Name of the Git branch to check out.
        """
        logger.debug(f"Setting Git branch to '{branch}'")
        url = utils.compose_url(self.api_url, path=["projects", project, "git_branch"])
        body = {"name": branch}
        response = self.put(url=url, json=body, timeout=TIMEOUT_SEC)
        try:
            response.raise_for_status()
        except requests.exceptions.HTTPError:
            raise LookerApiError(
                name="unable-to-checkout-branch",
                title="Couldn't checkout Git branch.",
                status=response.status_code,
                detail=(
                    f"Unable to checkout Git branch '{branch}'. "
                    "If you have uncommitted changes on the current branch, "
                    "please commit or revert them, then try again."
                ),
                response=response,
            ) 
开发者ID:spectacles-ci,项目名称:spectacles,代码行数:27,代码来源:client.py

示例7: get_lookml_models

# 需要导入模块: import requests [as 别名]
# 或者: from requests import exceptions [as 别名]
def get_lookml_models(self) -> List[JsonDict]:
        """Gets all models and explores from the LookmlModel endpoint.

        Returns:
            List[JsonDict]: JSON response containing LookML models and explores.

        """
        logger.debug(f"Getting all models and explores from {self.base_url}")
        url = utils.compose_url(self.api_url, path=["lookml_models"])
        response = self.get(url=url, timeout=TIMEOUT_SEC)
        try:
            response.raise_for_status()
        except requests.exceptions.HTTPError:
            raise LookerApiError(
                name="unable-to-get-lookml",
                title="Couldn't retrieve models and explores.",
                status=response.status_code,
                detail="Unable to retrieve LookML details. Please try again.",
                response=response,
            )

        return response.json() 
开发者ID:spectacles-ci,项目名称:spectacles,代码行数:24,代码来源:client.py

示例8: content_validation

# 需要导入模块: import requests [as 别名]
# 或者: from requests import exceptions [as 别名]
def content_validation(self) -> JsonDict:
        logger.debug("Validating all content in Looker")
        url = utils.compose_url(self.api_url, path=["content_validation"])
        response = self.get(url=url, timeout=TIMEOUT_SEC)

        try:
            response.raise_for_status()
        except requests.exceptions.HTTPError:
            raise LookerApiError(
                name="unable-to-validate-content",
                title="Couldn't validate Looks and Dashboards.",
                status=response.status_code,
                detail=("Failed to run the content validator. Please try again."),
                response=response,
            )

        result = response.json()
        return result 
开发者ID:spectacles-ci,项目名称:spectacles,代码行数:20,代码来源:client.py

示例9: all_folders

# 需要导入模块: import requests [as 别名]
# 或者: from requests import exceptions [as 别名]
def all_folders(self, project: str) -> List[JsonDict]:
        logger.debug("Getting information about all folders")
        url = utils.compose_url(self.api_url, path=["folders"])
        response = self.get(url=url, timeout=TIMEOUT_SEC)

        try:
            response.raise_for_status()
        except requests.exceptions.HTTPError:
            raise LookerApiError(
                name="unable-to-get-folders",
                title="Couldn't obtain project folders.",
                status=response.status_code,
                detail=(f"Failed to get all folders for project '{project}'."),
                response=response,
            )

        result = response.json()
        return result 
开发者ID:spectacles-ci,项目名称:spectacles,代码行数:20,代码来源:client.py

示例10: execute

# 需要导入模块: import requests [as 别名]
# 或者: from requests import exceptions [as 别名]
def execute(self, method: str, url: str, payload: dict) -> dict:
        self.connection.create_jwt_token(url, method.upper(), json.dumps(payload))
        request_url = self.connection.url + url

        response = None
        try:
            response = requests.request(method, request_url,
                                        json=payload,
                                        headers=self.connection.header_dict)

            if response.status_code == 403:
                raise PluginException(preset=PluginException.Preset.API_KEY)
            if response.status_code >= 400:
                raise PluginException(preset=PluginException.Preset.UNKNOWN, data=response.json())
            if 200 <= response.status_code < 300:
                return komand.helper.clean(response.json())

            raise PluginException(preset=PluginException.Preset.UNKNOWN, data=response.text)
        except json.decoder.JSONDecodeError as e:
            self.logger.info(f"Invalid json: {e}")
            raise PluginException(preset=PluginException.Preset.INVALID_JSON, data=response.text)
        except requests.exceptions.HTTPError as e:
            self.logger.info(f"Call to Trend Micro Apex failed: {e}")
            raise PluginException(preset=PluginException.Preset.UNKNOWN, data=response.text) 
开发者ID:rapid7,项目名称:insightconnect-plugins,代码行数:26,代码来源:api.py

示例11: _set_response_ins_

# 需要导入模块: import requests [as 别名]
# 或者: from requests import exceptions [as 别名]
def _set_response_ins_(self, pageurl):
        """
        Sets the response for the GET request of pageurl and stores it in self.resp

        :param pageurl: url for which we store the response.
        """
        try:
            s = requests.Session()
            a = requests.adapters.HTTPAdapter(max_retries=5)
            s.mount('http://', a)
            resp = s.get(pageurl, timeout=30)
            self.__resp_obj__ = resp
            resp.close()
        except requests.exceptions.Timeout:
            logging.error("\tVery Slow Internet Connection.")
        except requests.exceptions.ConnectionError:
            logging.error("\tNetwork Unavailable. Check your connection.")
        except requests.exceptions.MissingSchema:
            logging.error("\t503 Service Unavailable. Retrying download ... ") 
开发者ID:AnimeshShaw,项目名称:MangaScrapper,代码行数:21,代码来源:mangascrapper.py

示例12: is_registry_running

# 需要导入模块: import requests [as 别名]
# 或者: from requests import exceptions [as 别名]
def is_registry_running():
    """
    is docker registry running (at {docker0,lo}:5000)?
    """
    try:
        lo_response = requests.get(LOCALHOST_REGISTRY_HTTP)
    except requests.exceptions.ConnectionError:
        return False
    if not lo_response.ok:
        return False
    try:
        lo_response = requests.get(DOCKER0_REGISTRY_HTTP)  # leap of faith
    except requests.exceptions.ConnectionError:
        return False
    if not lo_response.ok:
        return False
    return True 
开发者ID:containerbuildsystem,项目名称:atomic-reactor,代码行数:19,代码来源:conftest.py

示例13: get_cdas_url

# 需要导入模块: import requests [as 别名]
# 或者: from requests import exceptions [as 别名]
def get_cdas_url(starttime, endtime, vars, dataset, timeout=10):
    dataview = 'sp_phys'
    if vars is None:
        try:
            var_info = get_variables(dataset, timeout=timeout)
        except requests.exceptions.ReadTimeout:
            raise util.NoDataError(
                'Connection to CDAweb timed out when getting CDAS URL for '
                f'{dataset} data for interval {starttime} - {endtime}.')

        if not len(var_info):
            raise util.NoDataError(
                f'No {dataset} data available for {starttime} - {endtime}')

        vars = [v['Name'] for v in var_info['VariableDescription']]

    uri = '/'.join(['dataviews', dataview,
                    'datasets', dataset,
                    'data',
                    ','.join([starttime.strftime('%Y%m%dT%H%M%SZ'),
                              endtime.strftime('%Y%m%dT%H%M%SZ')]),
                    ','.join(vars)
                    ])
    url = '/'.join([CDAS_BASEURL, uri])
    return url 
开发者ID:heliopython,项目名称:heliopy,代码行数:27,代码来源:cdasrest.py

示例14: iter_lines

# 需要导入模块: import requests [as 别名]
# 或者: from requests import exceptions [as 别名]
def iter_lines(self):
        kwargs = {
            # OpenShift does not respond with any encoding value.
            # This causes requests module to guess it as ISO-8859-1.
            # Likely, the encoding is actually UTF-8, but we can't
            # guarantee it. Therefore, we take the approach of simply
            # passing through the encoded data with no effort to
            # attempt decoding it.
            'decode_unicode': False
        }
        if requests.__version__.startswith('2.6.'):
            kwargs['chunk_size'] = 1
        # if this fails for any reason other than ChunkedEncodingError
        # or IncompleteRead (either of which may happen when no bytes
        # are received), let someone else handle the exception
        try:
            for line in self.req.iter_lines(**kwargs):
                yield line
        except (requests.exceptions.ChunkedEncodingError,
                http_client.IncompleteRead):
            return 
开发者ID:containerbuildsystem,项目名称:osbs-client,代码行数:23,代码来源:http.py

示例15: __call__

# 需要导入模块: import requests [as 别名]
# 或者: from requests import exceptions [as 别名]
def __call__(self, f):
        """
        A decorator function to retry a function (ie API call, web query) a
        number of times, with optional exceptions under which to retry.

        Returns results of a cleanup function if all retries fail.
        :return: decorator function.
        """
        @wraps(f)
        def wrapped_f(*args, **kwargs):
            for i in range(self.times):
                # Exponential backoff if required and limit to a max pause time
                pause = min(self.pause * self.retreat ** i, self.max_pause)
                try:
                    return f(*args, **kwargs)
                except self.exceptions:
                    if self.pause is not None:
                        time.sleep(pause)
                    else:
                        pass
            if self.cleanup is not None:
                return self.cleanup(*args, **kwargs)
        return wrapped_f 
开发者ID:aseylys,项目名称:KStock,代码行数:25,代码来源:NASDAQ.py


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