Merge pull request #527 from r0fls/asyncpg-example

update asyncpg example
This commit is contained in:
Raphael Deem 2017-03-07 19:34:10 -08:00 committed by GitHub
commit b3b27cab34

View File

@ -5,14 +5,14 @@ import os
import asyncio import asyncio
import uvloop import uvloop
from asyncpg import create_pool from asyncpg import connect
from sanic import Sanic from sanic import Sanic
from sanic.response import json from sanic.response import json
DB_CONFIG = { DB_CONFIG = {
'host': '<host>', 'host': '<host>',
'user': '<username>', 'user': '<user>',
'password': '<password>', 'password': '<password>',
'port': '<port>', 'port': '<port>',
'database': '<database>' 'database': '<database>'
@ -22,8 +22,7 @@ def jsonify(records):
""" """
Parse asyncpg record response into JSON format Parse asyncpg record response into JSON format
""" """
return [{key: value for key, value in return [dict(r.items()) for r in records]
zip(r.keys(), r.values())} for r in records]
app = Sanic(__name__) app = Sanic(__name__)
@ -32,27 +31,23 @@ async def create_db(app, loop):
""" """
Create some table and add some data Create some table and add some data
""" """
async with create_pool(**DB_CONFIG) as pool: conn = await connect(**DB_CONFIG)
async with pool.acquire() as connection: await conn.execute('DROP TABLE IF EXISTS sanic_post')
async with connection.transaction(): await conn.execute("""CREATE TABLE sanic_post (
await connection.execute('DROP TABLE IF EXISTS sanic_post') id serial primary key,
await connection.execute("""CREATE TABLE sanic_post ( content varchar(50),
id serial primary key, post_date timestamp);"""
content varchar(50), )
post_date timestamp for i in range(0, 100):
);""") await conn.execute(f"""INSERT INTO sanic_post
for i in range(0, 100): (id, content, post_date) VALUES ({i}, {i}, now())""")
await connection.execute(f"""INSERT INTO sanic_post
(id, content, post_date) VALUES ({i}, {i}, now())""")
@app.route("/") @app.route("/")
async def handler(request): async def handler(request):
async with create_pool(**DB_CONFIG) as pool: conn = await connect(**DB_CONFIG)
async with pool.acquire() as connection: results = await conn.fetch('SELECT * FROM sanic_post')
async with connection.transaction(): return json({'posts': jsonify(results)})
results = await connection.fetch('SELECT * FROM sanic_post')
return json({'posts': jsonify(results)})
if __name__ == '__main__': if __name__ == '__main__':