1

我正在尝试将 cookie 与 aiohttp.ClientSession 一起使用,但它似乎没有跨多个请求处理 cookie。那或者我没有正确使用它。

我有一个简单的服务器,它在客户端上保存一个 cookie。从浏览器访问时,这工作正常。

服务器代码:(从这里修改)

import asyncio
import time
from aiohttp import web
from aiohttp_session import get_session, setup
from aiohttp_session.cookie_storage import EncryptedCookieStorage

import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)

async def handler(request):
    session = await get_session(request)
    last_visit = session.get('last_visit', 'Never')
    if last_visit == 'Never':
        message = "Welcome, I don't think you've visited here before."
    else:
        message = 'Welcome back, last visited: {} secs ago'.format(time.time() -
                last_visit)
    session['last_visit'] = time.time()

    return web.Response(body=message.encode('utf-8'))

async def init(loop):
    app = web.Application()
    setup(app,
        EncryptedCookieStorage(b'Thirty  two  length  bytes  key.'))
    app.router.add_route('GET', '/', handler)
    srv = await loop.create_server(
        app.make_handler(), '0.0.0.0', 8080)
    return srv

loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
try:
    loop.run_forever()
except KeyboardInterrupt:
    pass

从浏览器访问时,我得到:

Welcome back, last visited: 1176.336282491684 secs ago

现在,我正在尝试在当前无法正常工作的 python 客户端中模仿这种行为。我知道我没有将 cookie 保存到文件中,但我在同一个会话中尝试了多个请求,所以这应该可以正常工作吗?

客户端会话中的 cookie 似乎没有跨多个请求持续存在。

客户端代码:

import aiohttp
import asyncio

jar = aiohttp.CookieJar(unsafe=True)

async def blah():
    async with aiohttp.ClientSession(cookie_jar=jar) as session:
        for i in range(2):
            async with session.get('http://localhost:8080') as resp:
                print(resp.status)
                print(await resp.text())
                print(session.cookies)

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(blah())

当我运行客户端代码时,我得到:

> python client.py
200
Welcome, I don't think you've visited here before.
Set-Cookie: AIOHTTP_SESSION="gAAAAABXpF_SYEhcMpT-1Q_g6V-SwDuWh-XZipIMre5GgYvJ513ao4BaVgN4kcQM4b91umGCgWuoCEe5RCpZ5ryA30rchUAaojH3B35OL9LjH-kLJ3Md0PhfaylWl3_ct5K2aSwdBdMU_mACaHeTV0FA7yiT0DrMI_n9ct3D-jRTYCsKc5xLI2I="; Domain=localhost; HttpOnly; Path=/
200
Welcome, I don't think you've visited here before.
Set-Cookie: AIOHTTP_SESSION="gAAAAABXpF_SiCl07HDerId98tjI6hTrWOcEmCRVELV3F_sif3XkzgjS_hfwlkMK4HpoWbRrNoxJZpERPKkxRJi9AOpUeleWTkfkjXUcNk13OX5GCOZDSLbSbTkqdoiiAYfAsQ3CNHZWGWd2xzlha_E54ig3Jq1sQsAXV6rgcrqxh0xMGYWfseM="; Domain=localhost; HttpOnly; Path=/
4

0 回答 0