如何像Python请求一样返回aiohttp?

时间:2019-08-20 01:16:56

标签: python aiohttp

我想返回回复列表request.get or post 但是,我不能... 首先,我尝试return response 但是它返回了协程对象。...

这是我的代码

import aiohttp
from aiohttp import ClientSession as AioClientSession

class MultiSession(object):
    def __init__(self, method, urls, **kwargs):
        self.method = method
        self.urls = urls
        self.kwargs = kwargs
        self.loop = asyncio.get_event_loop()

    async def get(self, session, url, **kwargs):
        async with session.get(url, **kwargs) as response:
            return await response.json()

    async def post(self, session, url, **kwargs):
        async with session.post(url, **kwargs) as response:
            return await response.text()

    async def fetch_all(self):
        async with AioClientSession(loop=self.loop) as session:
            if self.method == "GET":
                results = await asyncio.gather(*[self.get(session, url, **self.kwargs) for url in self.urls])
            elif self.method == "POST":
                results = await asyncio.gather(*[self.post(session, url, **self.kwargs) for url in self.urls])
            else:
                assert False
            return results

    def run_until_complete(self):
        return self.loop.run_until_complete(self.fetch_all())

这是我的测试代码

from utils import multi_requests_get

urls = ["https://httpbin.org/get?{}={}".format(x, x) for x in range(10)]

result = multi_requests_get(urls=urls)

assert result
assert result[0]["args"] == {"0": "0"}

但是,我想要这样

from utils import multi_requests_get

urls = ["https://httpbin.org/get?{}={}".format(x, x) for x in range(10)]

result = multi_requests_get(urls=urls)

assert result
assert result[0].status_code == 200
assert result[0].json()["args"] == {"0": "0"}

看起来像python requests模块...

request怎么样? 这是可能的...? 请帮我...

1 个答案:

答案 0 :(得分:0)

我解决了这个问题

这是我的代码

from requests import Response
from aiohttp import ClientSession as AioClientSession

class MultiSession(object):
    def __init__(self, method, urls, **kwargs):
        self.method = method
        self.urls = urls
        self.kwargs = kwargs
        self.loop = asyncio.get_event_loop()

    def wrapping_response_instance(self, aio_response, content):
        response = Response()
        response._content = content
        response.url = str(aio_response.url)
        response.status_code = aio_response.status
        headers = {row[0]: row[1] for row in aio_response.headers.items()}
        response.headers = headers
        return response

    async def get(self, session, url, **kwargs):
        async with session.get(url, **kwargs) as aio_response:
            content, _ = await aio_response.content.readchunk()
            response = self.wrapping_response_instance(aio_response, content)
            return response

    async def post(self, session, url, **kwargs):
        async with session.post(url, **kwargs) as aio_response:
            content, _ = await aio_response.content.readchunk()
            response = self.wrapping_response_instance(aio_response, content)
            return response

    async def fetch_all(self):
        async with AioClientSession(loop=self.loop) as session:
            # task 생성
            if self.method == "GET":
                results = await asyncio.gather(*[self.get(session, url, **self.kwargs) for url in self.urls])
            elif self.method == "POST":
                results = await asyncio.gather(*[self.post(session, url, **self.kwargs) for url in self.urls])
            else:
                assert False
            return results

    def run_until_complete(self):
        return self.loop.run_until_complete(self.fetch_all())


def multi_requests_get_json(urls, params=None, **kwargs):
    session = MultiSession(method="GET", urls=urls, params=params, **kwargs)
    return session.run_until_complete()


def multi_requests_post_json(urls, data=None, **kwargs):
    session = MultiSession(method="POST", urls=urls, data=data, **kwargs)
    return session.run_until_complete()

wrapping_response_instance被转换为Response()