首页 > 解决方案 > python aiohttp 客户端响应对象到 io.Text IO Wrapper

问题描述

我一直在偶然发现我的代码有问题,我想使用一个库来打开网页的内容并以特定的方式查看它们,在查看了该库的源代码后,我发现要使用这个库,我需要使用 _io.TextIOWrapper 对象而不是 aiohttp 对象,所以我想知道是否有任何方法可以转换它。这里有一些例子

>>> open('./NEWS.txt')
<_io.TextIOWrapper name='./NEWS.txt' mode='r' encoding='cp1252'>
>>> import aiohttp
>>> import asyncio
>>> async def fetch(session, url):
...     async with session.get(url) as response:
...         return response
...
>>> async def main():
...     async with aiohttp.ClientSession() as session:
...         html = await fetch(session, 'http://python.org')
...         print(html)
...
>>> if __name__ == '__main__':
...     loop = asyncio.get_event_loop()
...     loop.run_until_complete(main())
...
<ClientResponse(https://www.python.org/) [200 OK]>
<CIMultiDictProxy('Server': 'nginx', 'Content-Type': 'text/html; charset=utf-8', 'X-Frame-Options': 'DENY', 'Via': '1.1 vegur', 'Via': '1.1 varnish', 'Content-Length': '49058', 'Accept-Ranges': 'bytes', 'Date': 'Fri, 08 May 2020 14:20:23 GMT', 'Via': '1.1 varnish', 'Age': '1960', 'Connection': 'keep-alive', 'X-Served-By': 'cache-bwi5137-BWI, cache-pao17432-PAO', 'X-Cache': 'HIT, HIT', 'X-Cache-Hits': '2, 2', 'X-Timer': 'S1588947623.222259,VS0,VE0', 'Vary': 'Cookie', 'Strict-Transport-Security': 'max-age=63072000; includeSubDomains')>

>>>


有什么想法吗?请告诉我

标签: pythonaiohttp

解决方案


TextIOWrapper 将缓冲区作为第一个参数。由于您的响应只是一个字符串,您可以将字符串转换为缓冲阅读器并将其传递给 TextIOWrapper。

import io
html = await response.text()
buffer = io.BufferedReader(io.BytesIO(html.encode("utf-8")))
textWrapper = io.TextIOWrapper(buffer)
print(textWrapper.read())

现在可能有更好的方法。aiohttp 让您可以将响应直接解码为字节。如果你能以某种方式使用它会更有效,因为你不必在两者之间转换为文本。

async with session.get('https://api.github.com/events') as resp:
    await resp.content.read()

在这里检查有关此的文档


推荐阅读