文檔說重複使用ClientSession:如何重用aiohttp ClientSession池?
不要爲每個請求創建會話。最有可能你需要一個會話,每個 應用程序完全執行所有請求。
會話中包含連接池,連接重用和keepalive(默認情況下都處於打開狀態)可能會加速整體性能。 1
但是在文檔中似乎沒有關於如何做到這一點的任何解釋?有一個例子可能是相關的,但它並沒有說明如何在其他地方重新使用該池:http://aiohttp.readthedocs.io/en/stable/client.html#keep-alive-connection-pooling-and-cookie-sharing
會是這樣的正確方法嗎?
@app.listener('before_server_start')
async def before_server_start(app, loop):
app.pg_pool = await asyncpg.create_pool(**DB_CONFIG, loop=loop, max_size=100)
app.http_session_pool = aiohttp.ClientSession()
@app.listener('after_server_stop')
async def after_server_stop(app, loop):
app.http_session_pool.close()
app.pg_pool.close()
@app.post("/api/register")
async def register(request):
# json validation
async with app.pg_pool.acquire() as pg:
await pg.execute() # create unactivated user in db
async with app.http_session_pool as session:
# TODO send activation email using SES API
async with session.post('http://httpbin.org/post', data=b'data') as resp:
print(resp.status)
print(await resp.text())
return HTTPResponse(status=204)
只要添加到3),它說如果使用SSL(即https?)則使用0.25s。另外,我討厭問,但是我還沒有在其他地方找到對'__aenter__' /'__aexit__'的任何解釋......請你解釋它有什麼不同? (看起來他們只是用'@ asyncio.coroutine'裝飾器包裝?) – dtgq
@dtgq我更新了答案,添加了一些關於'__aenter__' /'__aexit__'的信息。什麼來到0.25s - 是的,如果你認爲你可能要求https網址,這是有道理的。 –