2017-01-04 15:29:09 +00:00
|
|
|
""" To run this example you need additional asyncpg package
|
|
|
|
|
|
|
|
"""
|
|
|
|
import os
|
|
|
|
import asyncio
|
|
|
|
|
|
|
|
import uvloop
|
2017-03-08 03:31:44 +00:00
|
|
|
from asyncpg import connect
|
2017-01-04 15:29:09 +00:00
|
|
|
|
|
|
|
from sanic import Sanic
|
|
|
|
from sanic.response import json
|
|
|
|
|
|
|
|
DB_CONFIG = {
|
2017-01-04 15:30:29 +00:00
|
|
|
'host': '<host>',
|
2017-03-08 03:31:44 +00:00
|
|
|
'user': '<user>',
|
2017-01-04 15:30:29 +00:00
|
|
|
'password': '<password>',
|
|
|
|
'port': '<port>',
|
|
|
|
'database': '<database>'
|
2017-01-04 15:29:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
def jsonify(records):
|
2017-01-22 02:26:32 +00:00
|
|
|
"""
|
|
|
|
Parse asyncpg record response into JSON format
|
2017-01-04 15:29:09 +00:00
|
|
|
"""
|
2017-03-08 03:31:44 +00:00
|
|
|
return [dict(r.items()) for r in records]
|
2017-01-04 15:29:09 +00:00
|
|
|
|
|
|
|
app = Sanic(__name__)
|
|
|
|
|
2017-02-11 14:30:17 +00:00
|
|
|
@app.listener('before_server_start')
|
2017-01-22 02:26:32 +00:00
|
|
|
async def create_db(app, loop):
|
|
|
|
"""
|
|
|
|
Create some table and add some data
|
2017-01-04 15:29:09 +00:00
|
|
|
"""
|
2017-03-08 03:31:44 +00:00
|
|
|
conn = await connect(**DB_CONFIG)
|
|
|
|
await conn.execute('DROP TABLE IF EXISTS sanic_post')
|
|
|
|
await conn.execute("""CREATE TABLE sanic_post (
|
|
|
|
id serial primary key,
|
|
|
|
content varchar(50),
|
|
|
|
post_date timestamp);"""
|
|
|
|
)
|
|
|
|
for i in range(0, 100):
|
|
|
|
await conn.execute(f"""INSERT INTO sanic_post
|
|
|
|
(id, content, post_date) VALUES ({i}, {i}, now())""")
|
2017-01-04 15:29:09 +00:00
|
|
|
|
|
|
|
|
|
|
|
@app.route("/")
|
|
|
|
async def handler(request):
|
2017-03-08 03:31:44 +00:00
|
|
|
conn = await connect(**DB_CONFIG)
|
|
|
|
results = await conn.fetch('SELECT * FROM sanic_post')
|
|
|
|
return json({'posts': jsonify(results)})
|
2017-01-04 15:29:09 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2017-02-11 14:30:17 +00:00
|
|
|
app.run(host='0.0.0.0', port=8000)
|