Merge pull request #542 from nszceta/master
Faster asyncpg queries via a global connection pool
This commit is contained in:
commit
23a1174aa2
|
@ -1,11 +1,8 @@
|
||||||
""" To run this example you need additional asyncpg package
|
|
||||||
|
|
||||||
"""
|
|
||||||
import os
|
import os
|
||||||
import asyncio
|
import asyncio
|
||||||
|
|
||||||
import uvloop
|
import uvloop
|
||||||
from asyncpg import connect
|
from asyncpg import connect, create_pool
|
||||||
|
|
||||||
from sanic import Sanic
|
from sanic import Sanic
|
||||||
from sanic.response import json
|
from sanic.response import json
|
||||||
|
@ -18,39 +15,37 @@ DB_CONFIG = {
|
||||||
'database': '<database>'
|
'database': '<database>'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def jsonify(records):
|
def jsonify(records):
|
||||||
"""
|
"""
|
||||||
Parse asyncpg record response into JSON format
|
Parse asyncpg record response into JSON format
|
||||||
"""
|
"""
|
||||||
return [dict(r.items()) for r in records]
|
return [dict(r.items()) for r in records]
|
||||||
|
|
||||||
|
|
||||||
app = Sanic(__name__)
|
app = Sanic(__name__)
|
||||||
|
|
||||||
|
|
||||||
@app.listener('before_server_start')
|
@app.listener('before_server_start')
|
||||||
async def create_db(app, loop):
|
async def register_db(app, loop):
|
||||||
"""
|
app.pool = await create_pool(**DB_CONFIG, loop=loop, max_size=100)
|
||||||
Create some table and add some data
|
async with app.pool.acquire() as connection:
|
||||||
"""
|
await connection.execute('DROP TABLE IF EXISTS sanic_post')
|
||||||
conn = await connect(**DB_CONFIG)
|
await connection.execute("""CREATE TABLE sanic_post (
|
||||||
await conn.execute('DROP TABLE IF EXISTS sanic_post')
|
|
||||||
await conn.execute("""CREATE TABLE sanic_post (
|
|
||||||
id serial primary key,
|
id serial primary key,
|
||||||
content varchar(50),
|
content varchar(50),
|
||||||
post_date timestamp);"""
|
post_date timestamp
|
||||||
)
|
);""")
|
||||||
for i in range(0, 100):
|
for i in range(0, 1000):
|
||||||
await conn.execute(f"""INSERT INTO sanic_post
|
await connection.execute(f"""INSERT INTO sanic_post
|
||||||
(id, content, post_date) VALUES ({i}, {i}, now())""")
|
(id, content, post_date) VALUES ({i}, {i}, now())""")
|
||||||
await conn.close()
|
|
||||||
|
|
||||||
|
|
||||||
@app.route("/")
|
@app.get('/')
|
||||||
async def handler(request):
|
async def root_get(request):
|
||||||
conn = await connect(**DB_CONFIG)
|
async with app.pool.acquire() as connection:
|
||||||
results = await conn.fetch('SELECT * FROM sanic_post')
|
results = await connection.fetch('SELECT * FROM sanic_post')
|
||||||
await conn.close()
|
|
||||||
return json({'posts': jsonify(results)})
|
return json({'posts': jsonify(results)})
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
app.run(host='0.0.0.0', port=8000)
|
app.run(host='127.0.0.1', port=8080)
|
||||||
|
|
Loading…
Reference in New Issue
Block a user