當前位置: 首頁>>代碼示例>>Python>>正文


Python aiohttp.ClientSession方法代碼示例

本文整理匯總了Python中aiohttp.ClientSession方法的典型用法代碼示例。如果您正苦於以下問題:Python aiohttp.ClientSession方法的具體用法?Python aiohttp.ClientSession怎麽用?Python aiohttp.ClientSession使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在aiohttp的用法示例。


在下文中一共展示了aiohttp.ClientSession方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: create_session

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientSession [as 別名]
def create_session(self, loop):
        conn = None

        if self.proxy and self.proxy_user:
            conn = aiohttp.ProxyConnector(
                loop=loop,
                limit=self.parallel,
                proxy=self.proxy,
                proxy_auth=aiohttp.BasicAuth(self.proxy_user, self.proxy_password)
            )
        elif self.proxy:
            conn = aiohttp.ProxyConnector(loop=loop, limit=self.parallel, proxy=self.proxy)
        else:
            conn = aiohttp.TCPConnector(loop=loop, limit=self.parallel)

        session = aiohttp.ClientSession(connector=conn)
        return session 
開發者ID:icoxfog417,項目名稱:mlimages,代碼行數:19,代碼來源:__init__.py

示例2: listen_message_stream

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientSession [as 別名]
def listen_message_stream(self, id_blacklist=None):
        id_blacklist = set(id_blacklist or [self.me, ])

        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        with aiohttp.ClientSession(loop=loop) as session:
            self.aioclient_session = session

            tasks = [
                asyncio.ensure_future(self.fetch(session, room, id_blacklist))
                for room in self.rooms
            ]
            done, _ = loop.run_until_complete(
                asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION)
            )
            for d in done:
                if d.exception():
                    raise d.exception() 
開發者ID:tuna,項目名稱:fishroom,代碼行數:20,代碼來源:gitter.py

示例3: get_launch_dict

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientSession [as 別名]
def get_launch_dict(launch_number: int = 0) -> Dict:
    """Get a launch information dictionary for the given launch.

    If launch_number <= 0 (the default), get the "next" launch.
    """

    route = launch_number if launch_number > 0 else "next"
    spacex_api_url = f"https://api.spacexdata.com/v3/launches/{route}"

    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(spacex_api_url) as response:
                if response.status != 200:
                    logging.error(f"Response status: {response.status}")
                    return {}
                return await response.json()

    except aiohttp.client_exceptions.ClientConnectorError:
        logging.error("Cannot connect to api.spacexdata.com")
        return {}

    except aiohttp.ContentTypeError:
        logging.error("JSON decode failed")
        return {} 
開發者ID:r-spacex,項目名稱:SpaceXLaunchBot,代碼行數:26,代碼來源:spacex.py

示例4: test_returns_answer_with_timeout

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientSession [as 別名]
def test_returns_answer_with_timeout(self):
        question: str = "how do I clean the stove?"
        options = QnAMakerOptions(timeout=999999)
        qna = QnAMaker(QnaApplicationTest.tests_endpoint, options)
        context = QnaApplicationTest._get_context(question, TestAdapter())
        response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json")

        with patch(
            "aiohttp.ClientSession.post",
            return_value=aiounittest.futurized(response_json),
        ):
            result = await qna.get_answers(context, options)

            self.assertIsNotNone(result)
            self.assertEqual(
                options.timeout, qna._generate_answer_helper.options.timeout
            ) 
開發者ID:microsoft,項目名稱:botbuilder-python,代碼行數:19,代碼來源:test_qna.py

示例5: test_should_filter_low_score_variation

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientSession [as 別名]
def test_should_filter_low_score_variation(self):
        options = QnAMakerOptions(top=5)
        qna = QnAMaker(QnaApplicationTest.tests_endpoint, options)
        question: str = "Q11"
        context = QnaApplicationTest._get_context(question, TestAdapter())
        response_json = QnaApplicationTest._get_json_for_file("TopNAnswer.json")

        with patch(
            "aiohttp.ClientSession.post",
            return_value=aiounittest.futurized(response_json),
        ):
            results = await qna.get_answers(context)
            self.assertEqual(4, len(results), "Should have received 4 answers.")

            filtered_results = qna.get_low_score_variation(results)
            self.assertEqual(
                3,
                len(filtered_results),
                "Should have 3 filtered answers after low score variation.",
            ) 
開發者ID:microsoft,項目名稱:botbuilder-python,代碼行數:22,代碼來源:test_qna.py

示例6: test_should_answer_with_prompts

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientSession [as 別名]
def test_should_answer_with_prompts(self):
        options = QnAMakerOptions(top=2)
        qna = QnAMaker(QnaApplicationTest.tests_endpoint, options)
        question: str = "how do I clean the stove?"
        turn_context = QnaApplicationTest._get_context(question, TestAdapter())
        response_json = QnaApplicationTest._get_json_for_file("AnswerWithPrompts.json")

        with patch(
            "aiohttp.ClientSession.post",
            return_value=aiounittest.futurized(response_json),
        ):
            results = await qna.get_answers(turn_context, options)
            self.assertEqual(1, len(results), "Should have received 1 answers.")
            self.assertEqual(
                1, len(results[0].context.prompts), "Should have received 1 prompt."
            ) 
開發者ID:microsoft,項目名稱:botbuilder-python,代碼行數:18,代碼來源:test_qna.py

示例7: test_should_answer_with_high_score_provided_context

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientSession [as 別名]
def test_should_answer_with_high_score_provided_context(self):
        qna = QnAMaker(QnaApplicationTest.tests_endpoint)
        question: str = "where can I buy?"
        context = QnARequestContext(
            previous_qna_id=5, previous_user_query="how do I clean the stove?"
        )
        options = QnAMakerOptions(top=2, qna_id=55, context=context)
        turn_context = QnaApplicationTest._get_context(question, TestAdapter())
        response_json = QnaApplicationTest._get_json_for_file(
            "AnswerWithHighScoreProvidedContext.json"
        )

        with patch(
            "aiohttp.ClientSession.post",
            return_value=aiounittest.futurized(response_json),
        ):
            results = await qna.get_answers(turn_context, options)
            self.assertEqual(1, len(results), "Should have received 1 answers.")
            self.assertEqual(1, results[0].score, "Score should be high.") 
開發者ID:microsoft,項目名稱:botbuilder-python,代碼行數:21,代碼來源:test_qna.py

示例8: test_should_answer_with_low_score_without_provided_context

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientSession [as 別名]
def test_should_answer_with_low_score_without_provided_context(self):
        qna = QnAMaker(QnaApplicationTest.tests_endpoint)
        question: str = "where can I buy?"
        options = QnAMakerOptions(top=2, context=None)

        turn_context = QnaApplicationTest._get_context(question, TestAdapter())
        response_json = QnaApplicationTest._get_json_for_file(
            "AnswerWithLowScoreProvidedWithoutContext.json"
        )

        with patch(
            "aiohttp.ClientSession.post",
            return_value=aiounittest.futurized(response_json),
        ):
            results = await qna.get_answers(turn_context, options)
            self.assertEqual(
                2, len(results), "Should have received more than one answers."
            )
            self.assertEqual(True, results[0].score < 1, "Score should be low.") 
開發者ID:microsoft,項目名稱:botbuilder-python,代碼行數:21,代碼來源:test_qna.py

示例9: _get_service_result

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientSession [as 別名]
def _get_service_result(
        cls,
        utterance: str,
        response_file: str,
        bot_adapter: BotAdapter = TestAdapter(),
        options: QnAMakerOptions = None,
    ) -> [dict]:
        response_json = QnaApplicationTest._get_json_for_file(response_file)

        qna = QnAMaker(QnaApplicationTest.tests_endpoint)
        context = QnaApplicationTest._get_context(utterance, bot_adapter)

        with patch(
            "aiohttp.ClientSession.post",
            return_value=aiounittest.futurized(response_json),
        ):
            result = await qna.get_answers(context, options)

            return result 
開發者ID:microsoft,項目名稱:botbuilder-python,代碼行數:21,代碼來源:test_qna.py

示例10: _get_service_result_raw

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientSession [as 別名]
def _get_service_result_raw(
        cls,
        utterance: str,
        response_file: str,
        bot_adapter: BotAdapter = TestAdapter(),
        options: QnAMakerOptions = None,
    ) -> [dict]:
        response_json = QnaApplicationTest._get_json_for_file(response_file)

        qna = QnAMaker(QnaApplicationTest.tests_endpoint)
        context = QnaApplicationTest._get_context(utterance, bot_adapter)

        with patch(
            "aiohttp.ClientSession.post",
            return_value=aiounittest.futurized(response_json),
        ):
            result = await qna.get_answers_raw(context, options)

            return result 
開發者ID:microsoft,項目名稱:botbuilder-python,代碼行數:21,代碼來源:test_qna.py

示例11: __init__

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientSession [as 別名]
def __init__(self, token, session=None, is_async=False, **options):
        self.token = token
        self.is_async = is_async
        self.error_debug = options.get('error_debug', False)
        self.timeout = options.get('timeout', 10)
        self.api = API(options.get('url', 'https://api.clashroyale.com/v1'))
        self.session = session or (aiohttp.ClientSession() if is_async else requests.Session())
        self.camel_case = options.get('camel_case', False)
        self.headers = {
            'Authorization': 'Bearer {}'.format(token),
            'User-Agent': 'python-clashroyale-client (fourjr/kyb3r) ' + options.get('user_agent', '')
        }
        self.cache_fp = options.get('cache_fp')
        self.using_cache = bool(self.cache_fp)
        self.cache_reset = options.get('cache_expires', 300)
        if self.using_cache:
            table = options.get('table_name', 'cache')
            self.cache = SqliteDict(self.cache_fp, table)

        constants = options.get('constants')
        if not constants:
            with Path(__file__).parent.parent.joinpath('constants.json').open(encoding='utf8') as f:
                constants = json.load(f)
        self.constants = BaseAttrDict(self, constants, None) 
開發者ID:cgrok,項目名稱:clashroyale,代碼行數:26,代碼來源:client.py

示例12: __init__

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientSession [as 別名]
def __init__(self, token, session=None, is_async=False, **options):
        self.token = token
        self.is_async = is_async
        self.error_debug = options.get('error_debug', False)
        self.timeout = options.get('timeout', 10)
        self.api = API(options.get('url', 'https://api.royaleapi.com'))
        self.session = session or (aiohttp.ClientSession() if is_async else requests.Session())
        self.camel_case = options.get('camel_case', False)
        self.headers = {
            'Authorization': 'Bearer {}'.format(token),
            'User-Agent': 'python-clashroyale-client (fourjr/kyb3r) ' + options.get('user_agent', '')
        }
        self.cache_fp = options.get('cache_fp')
        self.using_cache = bool(self.cache_fp)
        self.cache_reset = options.get('cache_expires', 300)
        self.ratelimit = [10, 10, 0]
        if self.using_cache:
            table = options.get('table_name', 'cache')
            self.cache = SqliteDict(self.cache_fp, table) 
開發者ID:cgrok,項目名稱:clashroyale,代碼行數:21,代碼來源:client.py

示例13: run

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientSession [as 別名]
def run(self, host):
        tasks = []
        # 默認limit=100,enable_cleanup_closed設置為True防止ssl泄露,ttl_dns_cache調高dns緩存
        conn = aiohttp.TCPConnector(
            limit=LIMIT,
            enable_cleanup_closed=True,
            ttl_dns_cache=100,
            ssl=False,
        )
        timeout = aiohttp.ClientTimeout(total=60, connect=2)
        async with aiohttp.ClientSession(connector=conn, timeout=timeout) as session:
            for url in self.urls:
                task = asyncio.ensure_future(self.scan(host, url, session))
                tasks.append(task)
            # gather方法是所有請求完成後才有輸出
            _ = await asyncio.gather(*tasks)
            # for i in asyncio.as_completed(tasks):  # 類似於線程池中的task一樣
            #     answer = await i
    
    # 創建啟動任務 
開發者ID:al0ne,項目名稱:Vxscan,代碼行數:22,代碼來源:async_scan.py

示例14: test_http_session

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientSession [as 別名]
def test_http_session(self, loop, local_timeout_server, consul_port):
        async def test_session_close():
            http_server = await local_timeout_server
            c = consul.aio.Consul(port=http_server.port, loop=loop)
            c.agent.services()

            c.http._session = aiohttp.ClientSession()

            assert not c.http._session.closed
            c.http.__del__()
            await c.http.close()
            assert c.http._session.closed
            http_server.server.stop()
            ...

        loop.run_until_complete(test_session_close()) 
開發者ID:poppyred,項目名稱:python-consul2,代碼行數:18,代碼來源:test_aio.py

示例15: _request

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import ClientSession [as 別名]
def _request(self, callback, method, uri, data=None, headers=None):
        connector = aiohttp.TCPConnector(loop=self._loop,
                                         verify_ssl=self.verify)
        async with aiohttp.ClientSession(connector=connector) as session:
            self._session = session
            resp = await session.request(method=method,
                                         url=uri,
                                         data=data,
                                         headers=headers)
            body = await resp.text(encoding='utf-8')
            content = await resp.read()
            if resp.status == 599:
                raise base.Timeout
            r = base.Response(resp.status, resp.headers, body, content)
            await session.close()
            return callback(r)

    # python prior 3.4.1 does not play nice with __del__ method 
開發者ID:poppyred,項目名稱:python-consul2,代碼行數:20,代碼來源:aio.py


注:本文中的aiohttp.ClientSession方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。