首页 > 解决方案 > aiohttp 客户端会话未保持登录状态

问题描述

我将 aiohttp 与 ClientSession 一起使用来创建登录请求,然后继续执行其他需要登录的请求。

经过一段时间的挖掘和环顾,似乎我的会话发出请求,就好像它没有登录一样。我真的确定我已经登录了,因为登录和未登录时会话的 cookie 是不同的。

这也是我第一次同时使用 asyncio、aiohttp 和 Python 类,因为在我只是调用任务中的函数并以这种方式登录之前,然后 ClientSession 确实登录了所需的请求。

这是我的班级的样子以及我如何创建 ClientSession。start 函数启动类的整个过程,即登录,然后执行需要用户登录的请求。

class Task:
    def __init__(self, index, email, password):
        self.index = index
        self.email = email
        self.password = password
        self.session = aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False))

    async def start(self):
        await self.get_login_page()
        await self.get_profile_page()
        await self.session.close()

以下是我使用 asyncio 启动任务的方式:

 loop = asyncio.get_event_loop()
 task_object = Task(index, task_email, task_password)
 loop.create_task(task_object.start())
 loop.run_forever()
 

所以现在我将范围缩小到我如何编写影响 ClientSession 行为的代码,但我只是不确定。

标签: pythonpython-requestspython-asyncioaiohttp

解决方案


修复它,我的代码很好。aiohttp 只是不能正确处理重定向,所以我切换到另一个 http 客户端。


推荐阅读