我在玩 aiohttp+aiomysql。我想在请求调用之间共享相同的连接池实例。
所以我创建了一个全局变量并在 corouting 调用中对其进行了一次预初始化。
我的代码:
import asyncio
from aiohttp import web
from aiohttp_session import get_session, session_middleware
from aiohttp_session.cookie_storage import EncryptedCookieStorage
from aiohttp_session import SimpleCookieStorage
#from mysql_pool import POOL
from aiomysql import create_pool
M_POOL = None
async def get_pool(loop):
global M_POOL
if M_POOL: return M_POOL
M_POOL = await create_pool(host='127.0.0.1', port=3306, user='user', password='user', db='test', loop=loop)
return M_POOL
async def query(request):
loop = asyncio.get_event_loop()
pool = await get_pool(loop)
print(id(pool))
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute("SELECT 42;")
value = await cur.fetchone()
print(value)
return web.Response(body=str.encode(str(value)))
app = web.Application(middlewares=[session_middleware(SimpleCookieStorage())])
app.router.add_route('GET', '/query', query)
web.run_app(app)
这样做是方便的方式,还是更好的方式?