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


Python models.Response方法代码示例

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


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

示例1: __init__

# 需要导入模块: from requests import models [as 别名]
# 或者: from requests.models import Response [as 别名]
def __init__(self, response: Response, url: str, empty: bool = False):
        """Create a new Page object.

        @type response: Response
        @param response: a requests Response instance.

        @type url: str
        @param url: URL of the Page.

        @type empty: bool
        @param empty: whether the Page is empty (body length == 0)"""
        self._response = response
        self._url = url
        self._base = None
        self._soup = None
        self._is_empty = empty
        try:
            self._tld = get_tld(url)
        except TldDomainNotFound:
            self._tld = urlparse(url).netloc 
开发者ID:penetrate2hack,项目名称:ITWSV,代码行数:22,代码来源:crawler.py

示例2: _interpret_returned_request

# 需要导入模块: from requests import models [as 别名]
# 或者: from requests.models import Response [as 别名]
def _interpret_returned_request(self, res, frmt):
        # must be a Response
        if isinstance(res, Response) is False:
            return res
        # if a response, there is a status code that should be ok
        if not res.ok:
            reason = res.reason
            self.logging.warning("status is not ok with {0}".format(reason))
            return res.status_code
        if frmt == "json":
            try:
                return res.json()
            except:
                return res
        # finally
        return res.content 
开发者ID:cokelaer,项目名称:bioservices,代码行数:18,代码来源:services.py

示例3: test

# 需要导入模块: from requests import models [as 别名]
# 或者: from requests.models import Response [as 别名]
def test(self):
        patience = 100
        while True:
            try:
                response = requests.get("http://localhost:{}".format(self.port))
                break
            except ConnectionError:
                patience -= 1
                if not patience:
                    self.fail(
                        "Couldn't get response from app, (Python executable {})".format(
                            sys.executable
                        )
                    )
                else:
                    sleep(0.1)

        self.assertIsInstance(response, Response)
        self.assertIn("Hello There!", response.text) 
开发者ID:johnbywater,项目名称:eventsourcing,代码行数:21,代码来源:test_flask.py

示例4: _decode_response_as_text_lines

# 需要导入模块: from requests import models [as 别名]
# 或者: from requests.models import Response [as 别名]
def _decode_response_as_text_lines(file_uri: str, res: Response) -> Iterator[str]:
    """Decode requests response into utf8 lines

    Downloads remote files to disk, rather than streaming directly, to support compressed
    files. The python gzip module doesn't support streaming directly and implementing
    with zlib seemed more error prone than writing to disk.
    """
    suffix = os.path.splitext(file_uri)[1]
    if suffix == '.gz':
        with NamedTemporaryFile(suffix=suffix) as f_temp:
            shutil.copyfileobj(res.raw, f_temp)
            f_temp.flush()
            with gzip.open(f_temp.name, 'rt') as f_out:
                yield from f_out
    else:
        if res.encoding is None:
            res.encoding = 'utf-8'
        yield from res.iter_lines(decode_unicode=True)
    log.info('Finished download of %s', file_uri) 
开发者ID:wikimedia,项目名称:search-MjoLniR,代码行数:21,代码来源:bulk_daemon.py

示例5: on_file_available

# 需要导入模块: from requests import models [as 别名]
# 或者: from requests.models import Response [as 别名]
def on_file_available(self, uri: str, response: Response) -> None:
        # Metadata we aren't interested in
        if os.path.basename(uri)[0] == '_':
            return
        lines = Peekable(_decode_response_as_text_lines(uri, response))
        try:
            header = json.loads(lines.peek())
            action, meta = header.popitem()
            index_name = meta['_index']
        except (ValueError, KeyError):
            raise MalformedUploadException(
                "Loaded file is malformed and cannot be processed: {}".format(uri))

        # Ignoring errors, can't do anything useful with them. They still
        # get logged and counted.
        bulk_import(client=self.client_for_index(index_name),
                    actions=pair(line.strip() for line in lines),
                    expand_action_callback=expand_string_actions,
                    **self.bulk_kwargs) 
开发者ID:wikimedia,项目名称:search-MjoLniR,代码行数:21,代码来源:bulk_daemon.py

示例6: test_new_api_object

# 需要导入模块: from requests import models [as 别名]
# 或者: from requests.models import Response [as 别名]
def test_new_api_object(self):
        def api_client(x): return x
        obj = new_api_object(api_client, simple_data)
        self.assertIsInstance(obj, APIObject)
        self.assertIsNone(obj.response)
        self.assertIsNone(obj.pagination)
        self.assertIsNone(obj.warnings)

        response = Response()

        def pagination(x): return x

        def warnings(x): return x
        obj = new_api_object(
            api_client, simple_data, response=response, pagination=pagination,
            warnings=warnings)
        self.assertIs(obj.response, response)
        self.assertIs(obj.pagination, pagination)
        self.assertIs(obj.warnings, warnings) 
开发者ID:coinbase,项目名称:coinbase-python,代码行数:21,代码来源:test_api_object.py

示例7: send

# 需要导入模块: from requests import models [as 别名]
# 或者: from requests.models import Response [as 别名]
def send(self, request, **kwargs):
        response = Response()
        response.headers = {}
        response.encoding = 'utf-8'  # FIXME: this is a complete guess
        response.url = request.url
        response.request = request
        response.connection = self

        try:
            response.raw = open(request.url.replace('file://', ''), 'r')
        except IOError as e:
            response.status_code = 404
            return response

        response.status_code = 200
        return response 
开发者ID:heroku,项目名称:python-salesforce-client,代码行数:18,代码来源:base.py

示例8: test_from_response_404_with_detail

# 需要导入模块: from requests import models [as 别名]
# 或者: from requests.models import Response [as 别名]
def test_from_response_404_with_detail(self):
        r = models.Response()
        r.status_code = 404
        r.headers['Content-Type'] = "application/json"
        r._content = json.dumps({
            "code": 404,
            "description": {
                "cause": "Aggregation method does not exist for this metric",
                "detail": {
                    "aggregation_method": "rate:mean",
                    "metric": "a914dad6-b8f6-42f6-b090-6daa29725caf",
                }},
            "title": "Not Found"
        }).encode('utf-8')
        exc = exceptions.from_response(r)
        self.assertIsInstance(exc, exceptions.ClientException) 
开发者ID:gnocchixyz,项目名称:python-gnocchiclient,代码行数:18,代码来源:test_exceptions.py

示例9: hashivault_pki_ca_set

# 需要导入模块: from requests import models [as 别名]
# 或者: from requests.models import Response [as 别名]
def hashivault_pki_ca_set(module):
    params = module.params
    client = hashivault_auth_client(params)
    mount_point = params.get('mount_point').strip('/')
    pem_bundle = params.get('pem_bundle')

    # check if engine is enabled
    changed, err = check_secrets_engines(module, client)
    if err:
        return err

    result = {'changed': changed}
    if module.check_mode:
        return result

    data = client.secrets.pki.submit_ca_information(pem_bundle=pem_bundle, mount_point=mount_point)
    if data:
        from requests.models import Response
        if isinstance(data, Response):
            result['data'] = data.text
        else:
            result['data'] = data

    return result 
开发者ID:TerryHowe,项目名称:ansible-modules-hashivault,代码行数:26,代码来源:hashivault_pki_ca_set.py

示例10: get_objects

# 需要导入模块: from requests import models [as 别名]
# 或者: from requests.models import Response [as 别名]
def get_objects(self, **filter_kwargs):
        self._verify_can_read()
        query_params = _filter_kwargs_to_query_params(filter_kwargs)
        assert isinstance(query_params, dict)
        full_filter = BasicFilter(query_params)
        objs = full_filter.process_filter(
            self.objects,
            ("id", "type", "version"),
            self.manifests,
            100,
        )[0]
        if objs:
            return stix2.v21.Bundle(objects=objs)
        else:
            resp = Response()
            resp.status_code = 404
            resp.raise_for_status() 
开发者ID:oasis-open,项目名称:cti-python-stix2,代码行数:19,代码来源:test_datastore_taxii.py

示例11: get_object

# 需要导入模块: from requests import models [as 别名]
# 或者: from requests.models import Response [as 别名]
def get_object(self, id, **filter_kwargs):
        self._verify_can_read()
        query_params = _filter_kwargs_to_query_params(filter_kwargs)
        assert isinstance(query_params, dict)
        full_filter = BasicFilter(query_params)

        # In this endpoint we must first filter objects by id beforehand.
        objects = [x for x in self.objects if x["id"] == id]
        if objects:
            filtered_objects = full_filter.process_filter(
                objects,
                ("version",),
                self.manifests,
                100,
            )[0]
        else:
            filtered_objects = []
        if filtered_objects:
            return stix2.v21.Bundle(objects=filtered_objects)
        else:
            resp = Response()
            resp.status_code = 404
            resp.raise_for_status() 
开发者ID:oasis-open,项目名称:cti-python-stix2,代码行数:25,代码来源:test_datastore_taxii.py

示例12: test_get_404

# 需要导入模块: from requests import models [as 别名]
# 或者: from requests.models import Response [as 别名]
def test_get_404():
    """a TAXIICollectionSource.get() call that receives an HTTP 404 response
    code from the taxii2client should be be returned as None.

    TAXII spec states that a TAXII server can return a 404 for nonexistent
    resources or lack of access. Decided that None is acceptable reponse
    to imply that state of the TAXII endpoint.
    """

    class TAXIICollection404():
        can_read = True

        def get_object(self, id, version=None):
            resp = Response()
            resp.status_code = 404
            resp.raise_for_status()

    ds = stix2.TAXIICollectionSource(TAXIICollection404())

    # this will raise 404 from mock TAXII Client but TAXIICollectionStore
    # should handle gracefully and return None
    stix_obj = ds.get("indicator--1")
    assert stix_obj is None 
开发者ID:oasis-open,项目名称:cti-python-stix2,代码行数:25,代码来源:test_datastore_taxii.py

示例13: get_objects

# 需要导入模块: from requests import models [as 别名]
# 或者: from requests.models import Response [as 别名]
def get_objects(self, **filter_kwargs):
        self._verify_can_read()
        query_params = _filter_kwargs_to_query_params(filter_kwargs)
        assert isinstance(query_params, dict)
        full_filter = BasicFilter(query_params)
        objs = full_filter.process_filter(
            self.objects,
            ("id", "type", "version"),
            self.manifests,
            100,
        )[0]
        if objs:
            return stix2.v20.Bundle(objects=objs)
        else:
            resp = Response()
            resp.status_code = 404
            resp.raise_for_status() 
开发者ID:oasis-open,项目名称:cti-python-stix2,代码行数:19,代码来源:test_datastore_taxii.py

示例14: get_object

# 需要导入模块: from requests import models [as 别名]
# 或者: from requests.models import Response [as 别名]
def get_object(self, id, **filter_kwargs):
        self._verify_can_read()
        query_params = _filter_kwargs_to_query_params(filter_kwargs)
        assert isinstance(query_params, dict)
        full_filter = BasicFilter(query_params)

        # In this endpoint we must first filter objects by id beforehand.
        objects = [x for x in self.objects if x["id"] == id]
        if objects:
            filtered_objects = full_filter.process_filter(
                objects,
                ("version",),
                self.manifests,
                100,
            )[0]
        else:
            filtered_objects = []
        if filtered_objects:
            return stix2.v20.Bundle(objects=filtered_objects)
        else:
            resp = Response()
            resp.status_code = 404
            resp.raise_for_status() 
开发者ID:oasis-open,项目名称:cti-python-stix2,代码行数:25,代码来源:test_datastore_taxii.py

示例15: test_searchParamIsNoneAndResopnseCodeIs200_shouldReturnAllOrgCollections

# 需要导入模块: from requests import models [as 别名]
# 或者: from requests.models import Response [as 别名]
def test_searchParamIsNoneAndResopnseCodeIs200_shouldReturnAllOrgCollections(self, mock_api_get):
        org_id = "org_id"
        # self.search_response.
        result = ['col1','col2','col3']
        response_mock  = MagicMock(spec=Response, status_code=200, headers={'content-type': "application/json"}
                                   , text=json.dumps({'status': True,"facets": {
                "dates": {},
                "fields": {},
                "queries": {}
            },"results": result
            }))
        response_mock.json.return_value = result
        mock_api_get.return_value = response_mock
        orgReadBaseView = views.OrganizationReadBaseView()
        orgReadBaseView.request = FakeRequest()

        searcher = orgReadBaseView.get_org_collections(org_id, search_params={'resourceFilter':'col'})
        self.assertEquals(searcher.search_results, result) 
开发者ID:OpenConceptLab,项目名称:ocl_web,代码行数:20,代码来源:test_views.py


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