Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions frameworks/Python/aiohttp/app/main.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import os
import multiprocessing

import asyncpg
import asyncpg.connection
from aiohttp import web
from sqlalchemy.engine.url import URL
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
Expand Down Expand Up @@ -37,6 +37,11 @@ def pg_dsn(dialect=None) -> str:
)
return url.render_as_string(hide_password=False)

class NoResetConnection(asyncpg.Connection):
__slots__ = ()

def get_reset_query(self):
return ''

async def db_ctx(app: web.Application):
# number of gunicorn workers = multiprocessing.cpu_count() as per gunicorn_conf.py
Expand All @@ -52,7 +57,7 @@ async def db_ctx(app: web.Application):
app['db_session'] = async_sessionmaker(engine)
else:
dsn = pg_dsn()
app['pg'] = await asyncpg.create_pool(dsn=dsn, min_size=min_size, max_size=max_size, loop=app.loop)
app['pg'] = await asyncpg.create_pool(dsn=dsn, min_size=min_size, max_size=max_size, loop=app.loop, connection_class=NoResetConnection)

yield

Expand Down
8 changes: 3 additions & 5 deletions frameworks/Python/aiohttp/app/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ async def single_database_query_raw(request):
id_ = randint(1, 10000)

async with request.app['pg'].acquire() as conn:
r = await conn.fetchval('SELECT id,randomnumber FROM world WHERE id = $1', id_)
r = await conn.fetchval(READ_ROW_SQL, id_)
return json_response({'id': id_, 'randomNumber': r})


Expand Down Expand Up @@ -96,11 +96,10 @@ async def multiple_database_queries_raw(request):

result = []
async with request.app['pg'].acquire() as conn:
stmt = await conn.prepare(READ_ROW_SQL)
for id_ in ids:
result.append({
'id': id_,
'randomNumber': await stmt.fetchval(id_),
'randomNumber': await conn.fetchval(READ_ROW_SQL, id_),
})
return json_response(result)

Expand Down Expand Up @@ -160,10 +159,9 @@ async def updates_raw(request):
worlds = [{'id': row_id, 'randomNumber': number} for row_id, number in updates]

async with request.app['pg'].acquire() as conn:
stmt = await conn.prepare(READ_ROW_SQL)
for id_, _ in updates:
# the result of this is the int previous random number which we don't actually use
await stmt.fetchval(id_)
await conn.fetchval(READ_ROW_SQL, id_)
await conn.executemany(WRITE_ROW_SQL, updates)

return json_response(worlds)
Expand Down
Loading