• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python treq.content函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中treq.content函数的典型用法代码示例。如果您正苦于以下问题:Python content函数的具体用法?Python content怎么用?Python content使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: main

def main(reactor):
    print 'List of tuples'
    resp = yield treq.get('http://httpbin.org/get',
                          params=[('foo', 'bar'), ('baz', 'bax')])
    content = yield treq.content(resp)
    print content

    print 'Single value dictionary'
    resp = yield treq.get('http://httpbin.org/get',
                          params={'foo': 'bar', 'baz': 'bax'})
    content = yield treq.content(resp)
    print content

    print 'Multi value dictionary'
    resp = yield treq.get('http://httpbin.org/get',
                          params={'foo': ['bar', 'baz', 'bax']})
    content = yield treq.content(resp)
    print content

    print 'Mixed value dictionary'
    resp = yield treq.get('http://httpbin.org/get',
                          params={'foo': ['bar', 'baz'], 'bax': 'quux'})
    content = yield treq.content(resp)
    print content

    print 'Preserved query parameters'
    resp = yield treq.get('http://httpbin.org/get?foo=bar',
                          params={'baz': 'bax'})
    content = yield treq.content(resp)
    print content
开发者ID:FxIII,项目名称:treq,代码行数:30,代码来源:query_params.py


示例2: login

 def login(self, email, password, accountType = ACCOUNT_TYPE_HOSTED_OR_GOOGLE):
     params = {"Email": email, "Passwd": password, "service": self.SERVICE,
               "accountType": accountType, "has_permission": "1",
               "source": "android", "androidId": self.androidId,
               "app": "com.android.vending", "sdk_version": "16" }
     resp = yield treq.post(self.URL_LOGIN, params)
     if resp.code == http.OK:
         data = yield treq.content(resp)
         data = data.split()
         params = {}
         for d in data:
             k, v = d.split("=")
             params[k.strip()] = v.strip()
         if "Auth" in params:
             self.setAuthSubToken(params["Auth"])
             self.loggedIn = True
         else:
             raise LoginError("Auth token not found.")
     else:
         if resp.code == http.FORBIDDEN:
             data = yield treq.content(resp)
             params = {}
             for d in data.split('\n'):
                 d = d.strip()
                 if d:
                     k, v = d.split("=", 1)
                     params[k.strip()] = v.strip()
             if "error" in params:
                 raise LoginError(params["error"])
             else:
                 raise LoginError("Login failed.")
         else:
             data = yield treq.content(resp)
             raise LoginError("Login failed: error %d <%s>" % (resp.code, data.rstrip(),))
开发者ID:3cky,项目名称:google-play-review-notify,代码行数:34,代码来源:market.py


示例3: test_content_multiple_waiters

    def test_content_multiple_waiters(self):
        d1 = content(self.response)
        d2 = content(self.response)

        self.protocol.dataReceived('foo')
        self.protocol.connectionLost(Failure(ResponseDone()))

        self.assertEqual(self.successResultOf(d1), 'foo')
        self.assertEqual(self.successResultOf(d2), 'foo')

        self.assertNotIdentical(d1, d2)
开发者ID:FxIII,项目名称:treq,代码行数:11,代码来源:test_content.py


示例4: handleArchivePage

def handleArchivePage(response):
        global CURRENTIP
	log.msg( "Archive page code is %s" % response.code)
	if response.code ==403:
		log.msg("Oh oh - looks like we're in the doghouse")
		CURRENTIP=next(IPADDRS)
		log.msg("Switching IP to %s" % str(CURRENTIP))
#		raise DoghouseException("Couldn't get archive - code was %i" % response.code)
                # treq seems to "block" if you don't fetch the content
                return treq.content(response)
#                return defer.succeed(False)
	else:
                d=treq.content(response).addCallback(parseArchiveResults)
	return d
开发者ID:truekonrads,项目名称:pastespy,代码行数:14,代码来源:pastespy.py


示例5: make_request

        def make_request():
            if ssl:
                response = yield treq.post(url, agent=self.agent, **kwargs)
            else:
                response = yield treq.post(url, **kwargs)

            try:
                content = yield treq.content(response)
            except:
                log.msg("Error while reading body in HTTP response",
                        level=logger.WARN)
                self.stats_client.incr('http.requests.errors.read_body_error')
                err = RuntimeError("Error while reading body in HTTP response (Response code: %d)." % response.code)
                err.status_code = response.code
                raise err
            else:
                if response.code == 200:
                    defer.returnValue(content)
                else:
                    log.msg("Error: Bad status code in HTTP response",
                            http_response_code=response.code,
                            http_content=content,
                            level=logger.WARN)
                    self.stats_client.incr('http.requests.errors.bad_status_code.%d' % response.code)
                    err = RuntimeError('Error: Bad status code in HTTP response: %d' % response.code)
                    err.status_code = response.code
                    raise err
开发者ID:Seekscale,项目名称:smbproxy,代码行数:27,代码来源:fs_cache.py


示例6: test_client_init

 def test_client_init(self):
     # FIXME: this test passes because stuff in the server is hard coded.
     #        revisit this when we're actually parsing stuff.
     syncml = self.syncml.build_request()
     response = yield self.request(syncml.build().toXml())
     body = yield content(response)
     self.assertTrue(str(constants.AUTHENTICATION_ACCEPTED) in body)
开发者ID:smn,项目名称:txsyncml,代码行数:7,代码来源:test_resource.py


示例7: test_delete_server_fails_specified_number_of_times

 def test_delete_server_fails_specified_number_of_times(self):
     """
     Test to verify :func: `delete_server` does not delete the server,
     and returns the given response code, the number of times specified
     in the metadata
     """
     deletefail = {"times": 1, "code": 500}
     metadata = {"delete_server_failure": json.dumps(deletefail)}
     # create server and verify it was successful
     create_server_response = self.create_server(metadata=metadata)
     self.assertEquals(create_server_response.code, 202)
     create_server_response_body = self.successResultOf(
         treq.json_content(create_server_response))
     # delete server and verify the response
     delete_server = request(self, self.root, "DELETE", self.uri + '/servers/'
                             + create_server_response_body["server"]["id"])
     delete_server_response = self.successResultOf(delete_server)
     self.assertEqual(delete_server_response.code, 500)
     # get server and verify the server was not deleted
     get_server = request(self, self.root, "GET", self.uri + '/servers/' +
                          create_server_response_body["server"]["id"])
     get_server_response = self.successResultOf(get_server)
     self.assertEquals(get_server_response.code, 200)
     # delete server again and verify the response
     delete_server = request(self, self.root, "DELETE", self.uri + '/servers/'
                             + create_server_response_body["server"]["id"])
     delete_server_response = self.successResultOf(delete_server)
     self.assertEqual(delete_server_response.code, 204)
     self.assertEqual(self.successResultOf(treq.content(delete_server_response)),
                      b"")
     # get server and verify the server was deleted this time
     get_server = request(self, self.root, "GET", self.uri + '/servers/' +
                          create_server_response_body["server"]["id"])
     get_server_response = self.successResultOf(get_server)
     self.assertEquals(get_server_response.code, 404)
开发者ID:lvh,项目名称:mimic,代码行数:35,代码来源:test_nova.py


示例8: got_result

 def got_result(result):
     if result.code == success_code:
         return json_content(result)
     else:
         d = content(result)
         d.addCallback(error, result.code)
         return d
开发者ID:jeromeshi,项目名称:flocker,代码行数:7,代码来源:_client.py


示例9: callRemote

    def callRemote(self, method, *args):
        scheme = "https://" if self.secure else "http://"
        netloc = self.host
        if self.port:
            netloc += ":%s" % self.port
        if self.user:
            auth = self.user
            if self.password:
                auth += ":%s" % self.password
            netloc = "%[email protected]%s" % (auth, netloc)

        url = scheme + netloc + self.path
        data = self.payloadTemplate % (
            method,
            xmlrpclib.dumps(args, allow_none=self.allowNone),
        )
        headers = {"User-Agent": "Twisted/XMLRPC", "Content-Type": "text/xml"}

        response = yield treq.post(
            url,
            data,
            headers=headers,
            timeout=self.connectTimeout,
            reactor=self._reactor,
        )
        body = yield treq.content(response)
        parsed = xmlrpclib.loads(body, use_datetime=self.useDateTime)[0][0]
        returnValue(parsed)
开发者ID:Fugiman,项目名称:Servrhe,代码行数:28,代码来源:blog.py


示例10: print_response

def print_response(r):
    print(r.code, r.phrase)
    print(r.headers)

    d = treq.content(r)
    d.addCallback(print)
    return d
开发者ID:jml,项目名称:treq,代码行数:7,代码来源:basic_get.py


示例11: message_scan_url

    def message_scan_url(self, url_info):
        # I'm still not sure whether I like inlineCallbacks. It made
        # this easier to test, though, because of implicit maybeDeferred.

        # TODO: limit size of retrieved content. it could be huge!
        try:

            queue_entry = util.queue_entry_parse(url_info)

            print "making request..."
            response = yield treq.get(queue_entry.url)
            content = yield treq.content(response)
            print "got content"

            base_url, urls = self.scan_page(queue_entry.url, content)
            urls = self.normalize_urls(base_url, urls)

            # TODO: would be cool to put some jitter in here. probably not needed
            # though, there will be natural jitter from the requests maybe possibly
            # hopefully... there will probably still be situations that it'd be
            # wanted though
        except:
            import traceback
            traceback.print_exc()
            print "offending url:", queue_entry.url
            self.command("url_completed", queue_entry.job_id)
            return

        self.command("url_completed", queue_entry.job_id)

        for url in urls:
            # blah, QueueEntry feels like java
            qe = util.QueueEntry(queue_entry.job_id, queue_entry.level + 1, url)
            self.command("found", util.queue_entry_format(qe))
开发者ID:johncosta,项目名称:distributed-crawler,代码行数:34,代码来源:drone.py


示例12: http_status_filter

def http_status_filter(response, allowed, ex, msg=None, include_resp_text=True):
    """
    Checks the response status and determines if it is in one of the
    allowed ranges.  If not, it raises `ex()`.

    `ex` is a callable that results in an Exception to be raised,
        (typically an exception class).
    `allowed` is a sequence of (start, end) valid status ranges.
    """
    code = response.code
    in_range = False
    for start_range, end_range in allowed:
        if code >= start_range and code <= end_range:
            in_range = True
            break
    if not in_range:

        def raise_error(body, ex):
            ex_msg = []
            if msg is not None:
                ex_msg.append(msg)
            if include_resp_text:
                ex_msg.append(body)
            text = '\n'.join(ex_msg)
            if text != "":
                raise ex(text)
            else:
                raise ex()

        # Need to still deliver the response body or Twisted make
        # hang.
        d = treq.content(response)
        d.addCallback(raise_error, ex)
        return d
    return response
开发者ID:cwaldbieser,项目名称:txcas,代码行数:35,代码来源:utils.py


示例13: do_http

def do_http(method, url, **kwargs):
    response = yield treq.request(method, url, persistent=False, **kwargs)
    body = yield treq.content(response)
    # TODO: replace this with response.fail_for_status when
    # https://github.com/twisted/treq/pull/159 has landed
    if 400 <= response.code < 600:
        raise Error(response.code, response=body)
    defer.returnValue(body)
开发者ID:LeastAuthority,项目名称:tahoe-lafs,代码行数:8,代码来源:common_web.py


示例14: test_delete_queue

 def test_delete_queue(self):
     """
     Test to verify :func:`del_queue` on ``DELETE /v2.0/<tenant_id>/servers/<queue_name>``
     """
     delete_queue = request(self, self.root, b"DELETE", self.uri + '/queues/' + self.queue_name)
     delete_queue_response = self.successResultOf(delete_queue)
     self.assertEqual(delete_queue_response.code, 204)
     self.assertEqual(self.successResultOf(treq.content(delete_queue_response)), b"")
开发者ID:BenjamenMeyer,项目名称:mimic,代码行数:8,代码来源:test_queue.py


示例15: test_invalid_content_type

 def test_invalid_content_type(self):
     response = yield self.request_with_fixture('client_sync_init.xml', {
         'Content-Type': ['foo'],
     })
     body = yield content(response)
     self.assertEqual(response.code, http.NOT_ACCEPTABLE)
     self.assertContentType(response, 'text/plain')
     self.assertEqual(body, 'Unsupported content-type.')
开发者ID:smn,项目名称:txsyncml,代码行数:8,代码来源:test_resource.py


示例16: test_content

    def test_content(self):
        d = content(self.response)

        self.protocol.dataReceived('foo')
        self.protocol.dataReceived('bar')
        self.protocol.connectionLost(Failure(ResponseDone()))

        self.assertEqual(self.successResultOf(d), 'foobar')
开发者ID:FxIII,项目名称:treq,代码行数:8,代码来源:test_content.py


示例17: got_result

 def got_result(result):
     if result.code in success_codes:
         action.addSuccessFields(response_code=result.code)
         return json_content(result)
     else:
         d = content(result)
         d.addCallback(error, result.code)
         return d
开发者ID:stmcginnis,项目名称:flocker,代码行数:8,代码来源:_client.py


示例18: test_delete_server

 def test_delete_server(self):
     """
     Test to verify :func:`delete_server` on ``DELETE /v2.0/<tenant_id>/servers/<server_id>``
     """
     delete_server = request(self, self.root, "DELETE", self.uri + '/servers/' + self.server_id)
     delete_server_response = self.successResultOf(delete_server)
     self.assertEqual(delete_server_response.code, 204)
     self.assertEqual(self.successResultOf(treq.content(delete_server_response)),
                      b"")
开发者ID:proverma,项目名称:mimic,代码行数:9,代码来源:test_nova.py


示例19: test_content_cached

    def test_content_cached(self):
        d1 = content(self.response)

        self.protocol.dataReceived('foo')
        self.protocol.dataReceived('bar')
        self.protocol.connectionLost(Failure(ResponseDone()))

        self.assertEqual(self.successResultOf(d1), 'foobar')

        def _fail_deliverBody(protocol):
            self.fail("deliverBody unexpectedly called.")

        self.response.original.deliverBody.side_effect = _fail_deliverBody

        d3 = content(self.response)

        self.assertEqual(self.successResultOf(d3), 'foobar')

        self.assertNotIdentical(d1, d3)
开发者ID:FxIII,项目名称:treq,代码行数:19,代码来源:test_content.py


示例20: got_response

 def got_response(response):
     if response.code in success_codes:
         action.addSuccessFields(response_code=response.code)
         d = json_content(response)
         d.addCallback(lambda decoded_body: (decoded_body, response.headers))
         return d
     else:
         d = content(response)
         d.addCallback(error, response.code)
         return d
开发者ID:wangbinxiang,项目名称:flocker,代码行数:10,代码来源:_client.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python treq.get函数代码示例发布时间:2022-05-27
下一篇:
Python mock.dbg_setup函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap