Evg
Evg

Reputation: 3080

singleton connections pool for aiohttp+aiomysql (python 3.5)

I am playing with aiohttp+aiomysql. I want to share same connection pool instance between request calls.

So i create a global var and preinit it once in corouting call.

My 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)

Is it convinient way of doing this, or may be something better?

Upvotes: 3

Views: 2847

Answers (2)

Andrew Svetlov
Andrew Svetlov

Reputation: 17376

I highly discourage global variable usage.

Please take a look on aiohttp demo for canonical approach.

SiteHandler is a class that implements website views.

Upvotes: 2

Alex-droid AD
Alex-droid AD

Reputation: 645

But you've given demos for a case where request object in access.

I have the same problem using aiohttp. In my application I've done to parts of modules:
one is for server functionality, and one for client (crawler).

So in server part it's ok, I can user request.app['dbpool']

But in crawler part I want use db connections to, and I can't see reasons for another one pool connection creation.

Upvotes: 0

Related Questions