當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。