Ich spiele mit Aiohttp + Aiomysql. Ich möchte dieselbe Verbindungspoolinstanz zwischen Anforderungsaufrufen freigeben.Singleton Verbindungen Pool für Aiohttp + Aiomysql (Python 3.5)
Also ich erstelle eine globale Var und preinit es einmal in Corouting-Aufruf.
Mein Code:
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)
Ist es convinient Weg, dies zu tun, oder vielleicht etwas besser sein?
Finden Sie einfach Ihre andere Antwort für ähnliche Frage. https://github.com/aio-libs/aiohttp/issues/2495. Sie sagten, dass "propagieren request.app - technisch ist es das gleiche Maß an Hässlichkeit als App beim Import bekommen". Also keine Globals, und keine Ausbreitung .... Dann wie ??? ... –