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


Python ClientSession.get方法代码示例

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


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

示例1: test_http_methods

# 需要导入模块: from aiohttp.client import ClientSession [as 别名]
# 或者: from aiohttp.client.ClientSession import get [as 别名]
 def test_http_methods(self, patched):
     session = ClientSession(loop=self.loop)
     add_params = dict(
         headers={"Authorization": "Basic ..."},
         max_redirects=2,
         encoding="latin1",
         version=aiohttp.HttpVersion10,
         compress="deflate",
         chunked=True,
         expect100=True,
         read_until_eof=False)
     run = self.loop.run_until_complete
     # Check GET
     run(session.get(
         "http://test.example.com",
         params={"x": 1},
         **add_params))
     self.assertEqual(
         patched.call_count, 1, "`ClientSession.request` not called")
     self.assertEqual(
         list(patched.call_args),
         [("GET", "http://test.example.com",),
          dict(
             params={"x": 1},
             allow_redirects=True,
             **add_params)])
     # Check OPTIONS
     run(session.options(
         "http://opt.example.com",
         params={"x": 2},
         **add_params))
     self.assertEqual(
         patched.call_count, 2, "`ClientSession.request` not called")
     self.assertEqual(
         list(patched.call_args),
         [("OPTIONS", "http://opt.example.com",),
          dict(
             params={"x": 2},
             allow_redirects=True,
             **add_params)])
     # Check HEAD
     run(session.head(
         "http://head.example.com",
         params={"x": 2},
         **add_params))
     self.assertEqual(
         patched.call_count, 3, "`ClientSession.request` not called")
     self.assertEqual(
         list(patched.call_args),
         [("HEAD", "http://head.example.com",),
          dict(
             params={"x": 2},
             allow_redirects=False,
             **add_params)])
     # Check POST
     run(session.post(
         "http://post.example.com",
         params={"x": 2},
         data="Some_data",
         files={"x": '1'},
         **add_params))
     self.assertEqual(
         patched.call_count, 4, "`ClientSession.request` not called")
     self.assertEqual(
         list(patched.call_args),
         [("POST", "http://post.example.com",),
          dict(
             params={"x": 2},
             data="Some_data",
             files={"x": '1'},
             **add_params)])
     # Check PUT
     run(session.put(
         "http://put.example.com",
         params={"x": 2},
         data="Some_data",
         files={"x": '1'},
         **add_params))
     self.assertEqual(
         patched.call_count, 5, "`ClientSession.request` not called")
     self.assertEqual(
         list(patched.call_args),
         [("PUT", "http://put.example.com",),
          dict(
             params={"x": 2},
             data="Some_data",
             files={"x": '1'},
             **add_params)])
     # Check PATCH
     run(session.patch(
         "http://patch.example.com",
         params={"x": 2},
         data="Some_data",
         files={"x": '1'},
         **add_params))
     self.assertEqual(
         patched.call_count, 6, "`ClientSession.request` not called")
     self.assertEqual(
         list(patched.call_args),
         [("PATCH", "http://patch.example.com",),
#.........这里部分代码省略.........
开发者ID:ttezel,项目名称:aiohttp,代码行数:103,代码来源:test_client_session.py

示例2: AIOResponsesTestCase

# 需要导入模块: from aiohttp.client import ClientSession [as 别名]
# 或者: from aiohttp.client.ClientSession import get [as 别名]
class AIOResponsesTestCase(TestCase):
    use_default_loop = False

    @asyncio.coroutine
    def setUp(self):
        self.url = 'http://example.com/api'
        self.session = ClientSession()
        super().setUp()

    @asyncio.coroutine
    def tearDown(self):
        self.session.close()
        super().tearDown()

    @data(
        hdrs.METH_HEAD,
        hdrs.METH_GET,
        hdrs.METH_POST,
        hdrs.METH_PUT,
        hdrs.METH_PATCH,
        hdrs.METH_DELETE,
        hdrs.METH_OPTIONS,
    )
    @patch('aioresponses.aioresponses.add')
    @fail_on(unused_loop=False)
    def test_shortcut_method(self, http_method, mocked):
        with aioresponses() as m:
            getattr(m, http_method.lower())(self.url)
            mocked.assert_called_once_with(self.url, method=http_method)

    @aioresponses()
    def test_returned_instance(self, m):
        m.get(self.url)
        response = self.loop.run_until_complete(self.session.get(self.url))
        self.assertIsInstance(response, ClientResponse)

    @aioresponses()
    @asyncio.coroutine
    def test_returned_instance_and_status_code(self, m):
        m.get(self.url, status=204)
        response = yield from self.session.get(self.url)
        self.assertIsInstance(response, ClientResponse)
        self.assertEqual(response.status, 204)

    @aioresponses()
    @asyncio.coroutine
    def test_returned_response_headers(self, m):
        m.get(self.url,
              content_type='text/html',
              headers={'Connection': 'keep-alive'})
        response = yield from self.session.get(self.url)

        self.assertEqual(response.headers['Connection'], 'keep-alive')
        self.assertEqual(response.headers[hdrs.CONTENT_TYPE], 'text/html')

    @aioresponses()
    def test_method_dont_match(self, m):
        m.get(self.url)
        with self.assertRaises(ClientConnectionError):
            self.loop.run_until_complete(self.session.post(self.url))

    @aioresponses()
    @asyncio.coroutine
    def test_streaming(self, m):
        m.get(self.url, body='Test')
        resp = yield from self.session.get(self.url)
        content = yield from resp.content.read()
        self.assertEqual(content, b'Test')

    @aioresponses()
    @asyncio.coroutine
    def test_streaming_up_to(self, m):
        m.get(self.url, body='Test')
        resp = yield from self.session.get(self.url)
        content = yield from resp.content.read(2)
        self.assertEqual(content, b'Te')
        content = yield from resp.content.read(2)
        self.assertEqual(content, b'st')

    @asyncio.coroutine
    def test_mocking_as_context_manager(self):
        with aioresponses() as aiomock:
            aiomock.add(self.url, payload={'foo': 'bar'})
            resp = yield from self.session.get(self.url)
            self.assertEqual(resp.status, 200)
            payload = yield from resp.json()
            self.assertDictEqual(payload, {'foo': 'bar'})

    def test_mocking_as_decorator(self):
        @aioresponses()
        def foo(loop, m):
            m.add(self.url, payload={'foo': 'bar'})

            resp = loop.run_until_complete(self.session.get(self.url))
            self.assertEqual(resp.status, 200)
            payload = loop.run_until_complete(resp.json())
            self.assertDictEqual(payload, {'foo': 'bar'})

        foo(self.loop)

#.........这里部分代码省略.........
开发者ID:Hellowlol,项目名称:aioresponses,代码行数:103,代码来源:test_aioresponses.py

示例3: GraphitePlugin

# 需要导入模块: from aiohttp.client import ClientSession [as 别名]
# 或者: from aiohttp.client.ClientSession import get [as 别名]
class GraphitePlugin(BasePlugin):
    _type = 'graphite'
    condition_map = {
        '>': operator.gt,
        '>=': operator.ge,
        '<': operator.lt,
        '<=': operator.le,
        '==': operator.eq
    }

    def __init__(self):
        super().__init__()
        self.session = ClientSession()

    def supported_types(self):
        return settings.GRAPHITE_TYPES

    def init(self, *args):
        super().init(*args)

    def get_graphite_url(self, env):
        return 'http://{}/render'.format(
            settings.ENVIRONMENTS[env]['metrics_service']['host']
        )

    def get_graph_url(self, env: str):
        """Returns a formatted URL for a graph."""
        return settings.ENVIRONMENTS[env]['metrics_service'].get(
            'graph_url',
            self.get_graphite_url(env)
        )

    @asyncio.coroutine
    @stats.increment(metric_name='graphite.execute')
    @stats.timer(metric_name='graphite.execute')
    def execute(self, check):
        logger.info(
            'Processing check: id="{}", metric="{}"'.format(
                check['id'], check['fields']['metric']
            )
        )
        fields = check['fields']
        check['target'] = fields['metric']

        env = check.get('environment', 'test')
        url = self.get_graphite_url(env)

        try:
            metric = fields['metric']
            with Timeout(settings.GRAPHITE_TIMEOUT):
                response = yield from self.session.get(
                    url,
                    params={
                        'target': metric,
                        'from': settings.GRAPHITE_TIME_RANGE,
                        'format': 'json'
                    }
                )

                response.raise_for_status()
                data = yield from response.json()
            self.process(check, data, env)

        except (ValueError, HttpProcessingError,
                TimeoutError, ClientOSError) as e:
            message = self.exception_repr(e, pattern='{}: {}')
            logger.error('Could not execute plugin for check `%s`, %s',
                         check['id'], message)
            self.set_check_status(check, RESULT_UNKNOWN, message)

    def add_meta(self, check, trigger, env, threshold=None):
        threshold = threshold or 0.0
        now = datetime.now()
        # - 1 hour
        from_date = now - timedelta(0, 3600)
        params = [
            ('width', settings.GRAPHITE_CHART_WIDTH),
            ('height', settings.GRAPHITE_CHART_HEIGHT),
            ('tz', settings.GRAPHITE_TIME_ZONE),
            ('from', from_date.strftime('%H:%M_%Y%m%d')),
            ('until', now.strftime('%H:%M_%Y%m%d')),
            ('target', check['fields']['metric']),
            ('target', 'threshold({}, \"{}\", red)'.format(
                threshold, 'threshold = {}'.format(threshold),
            )),
        ]
        graphite_url = "{}?{}".format(
            self.get_graph_url(env), urlencode(params)
        )
        trigger['meta']['links']['graphite_url'] = dict(
            type='link', href=graphite_url
        )

    @stats.increment(metric_name='graphite.process')
    @stats.timer(metric_name='graphite.process')
    def process(self, check, data, env):
        frequency = int(check['fields']['frequency'])
        expected_num_hosts = check['fields'].get('expected_num_hosts', 0)

        ret = Result()
#.........这里部分代码省略.........
开发者ID:RulersOfAsgard,项目名称:ALAMO-worker,代码行数:103,代码来源:graphite.py


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