为了使用单个
aiohttp.ClientSession实例,我们只需要实例化一次会话,并在应用程序的其余部分中使用该特定实例。
为此,我们可以使用
before_server_start侦听器,该侦听器将允许我们在应用程序提供第一个字节之前创建实例。
from sanic import Sanic from sanic.response import jsonimport aiohttpapp = Sanic(__name__)@app.listener('before_server_start')def init(app, loop): app.aiohttp_session = aiohttp.ClientSession(loop=loop)@app.listener('after_server_stop')def finish(app, loop): loop.run_until_complete(app.aiohttp_session.close()) loop.close()@app.route("/")async def test(request): """ Download and serve example JSON """ url = "https://api.github.com/repos/channelcat/sanic" async with app.aiohttp_session.get(url) as response: return await response.json()app.run(host="0.0.0.0", port=8000, workers=2)代码明细:
- 我们正在创建一个
aiohttp.ClientSession
作为参数,将Sanic
应用程序在开始时创建的循环作为参数传递,从而避免了此过程中的陷阱。 - 我们将该会话存储在Sanic中
app
。 - 最后,我们正在使用此会话来发出请求。



