From 154f8570f073c94bec55f1c2681162d6b1beec16 Mon Sep 17 00:00:00 2001 From: Anton Zhyrney Date: Sun, 11 Dec 2016 13:43:31 +0200 Subject: [PATCH 1/4] add sanic aiopg example with raw sql --- examples/sanic_aiopg_example.py | 58 +++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 examples/sanic_aiopg_example.py diff --git a/examples/sanic_aiopg_example.py b/examples/sanic_aiopg_example.py new file mode 100644 index 00000000..7f4901e6 --- /dev/null +++ b/examples/sanic_aiopg_example.py @@ -0,0 +1,58 @@ +import os +import asyncio +import datetime + +import uvloop +import aiopg + +from sanic import Sanic +from sanic.response import json + +asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) + +database_name = os.environ['DATABASE_NAME'] +database_host = os.environ['DATABASE_HOST'] +database_user = os.environ['DATABASE_USER'] +database_password = os.environ['DATABASE_PASSWORD'] + +connection = 'postgres://{0}:{1}@{2}/{3}'.format(database_user, database_password, database_host, database_name) +loop = asyncio.get_event_loop() + + +async def get_pool(): + return await aiopg.create_pool(connection) + +app = Sanic(name=__name__) +pool = loop.run_until_complete(get_pool()) + + +async def prepare_db(): + """ Let's create some table and add some data + + """ + async with pool.acquire() as conn: + async with conn.cursor() as cur: + await cur.execute("""CREATE TABLE sanic_poll ( + id integer primary key, + question varchar(50), + pub_date timestamp + );""") + for i in range(0, 100): + await cur.execute("""INSERT INTO sanic_poll (id, question, pub_date) VALUES ({}, {}, now()) + """.format(i, i)) + + +@app.route("/") +async def handle(request): + async with pool.acquire() as conn: + async with conn.cursor() as cur: + result = [] + await cur.execute("SELECT question, pub_date FROM sanic_poll") + async for row in cur: + result.append({"question": row[0], "pub_date": row[1]}) + return json({"polls": result}) + + +if __name__ == '__main__': + loop.run_until_complete(prepare_db()) + app.run(host="0.0.0.0", port=8100, workers=3, loop=loop) From 721044b3786f4ac190256a3d0d870cf51077e2a8 Mon Sep 17 00:00:00 2001 From: Anton Zhyrney Date: Sun, 11 Dec 2016 14:04:24 +0200 Subject: [PATCH 2/4] improvements for aiopg example --- examples/sanic_aiopg_example.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/sanic_aiopg_example.py b/examples/sanic_aiopg_example.py index 7f4901e6..539917df 100644 --- a/examples/sanic_aiopg_example.py +++ b/examples/sanic_aiopg_example.py @@ -1,6 +1,5 @@ import os import asyncio -import datetime import uvloop import aiopg @@ -32,13 +31,14 @@ async def prepare_db(): """ async with pool.acquire() as conn: async with conn.cursor() as cur: - await cur.execute("""CREATE TABLE sanic_poll ( + await cur.execute('DROP TABLE IF EXISTS sanic_polls') + await cur.execute("""CREATE TABLE sanic_polls ( id integer primary key, question varchar(50), pub_date timestamp );""") for i in range(0, 100): - await cur.execute("""INSERT INTO sanic_poll (id, question, pub_date) VALUES ({}, {}, now()) + await cur.execute("""INSERT INTO sanic_polls (id, question, pub_date) VALUES ({}, {}, now()) """.format(i, i)) @@ -47,7 +47,7 @@ async def handle(request): async with pool.acquire() as conn: async with conn.cursor() as cur: result = [] - await cur.execute("SELECT question, pub_date FROM sanic_poll") + await cur.execute("SELECT question, pub_date FROM sanic_polls") async for row in cur: result.append({"question": row[0], "pub_date": row[1]}) return json({"polls": result}) From f9176bfdea547bcc3202316c3eb1fd563ace01e7 Mon Sep 17 00:00:00 2001 From: Anton Zhyrney Date: Sun, 11 Dec 2016 14:14:03 +0200 Subject: [PATCH 3/4] pep8&improvements --- examples/sanic_aiopg_example.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/examples/sanic_aiopg_example.py b/examples/sanic_aiopg_example.py index 539917df..ff9ec65e 100644 --- a/examples/sanic_aiopg_example.py +++ b/examples/sanic_aiopg_example.py @@ -14,7 +14,10 @@ database_host = os.environ['DATABASE_HOST'] database_user = os.environ['DATABASE_USER'] database_password = os.environ['DATABASE_PASSWORD'] -connection = 'postgres://{0}:{1}@{2}/{3}'.format(database_user, database_password, database_host, database_name) +connection = 'postgres://{0}:{1}@{2}/{3}'.format(database_user, + database_password, + database_host, + database_name) loop = asyncio.get_event_loop() @@ -33,12 +36,13 @@ async def prepare_db(): async with conn.cursor() as cur: await cur.execute('DROP TABLE IF EXISTS sanic_polls') await cur.execute("""CREATE TABLE sanic_polls ( - id integer primary key, + id serial primary key, question varchar(50), pub_date timestamp );""") for i in range(0, 100): - await cur.execute("""INSERT INTO sanic_polls (id, question, pub_date) VALUES ({}, {}, now()) + await cur.execute("""INSERT INTO sanic_polls + (id, question, pub_date) VALUES ({}, {}, now()) """.format(i, i)) From b44e9baaecee1ec757409e9d1ce263f58e22fc86 Mon Sep 17 00:00:00 2001 From: Anton Zhyrney Date: Sun, 11 Dec 2016 14:21:02 +0200 Subject: [PATCH 4/4] aiopg with sqlalchemy example --- examples/sanic_aiopg_example.py | 5 +- examples/sanic_aiopg_sqlalchemy_example.py | 73 ++++++++++++++++++++++ 2 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 examples/sanic_aiopg_sqlalchemy_example.py diff --git a/examples/sanic_aiopg_example.py b/examples/sanic_aiopg_example.py index ff9ec65e..73ef6c64 100644 --- a/examples/sanic_aiopg_example.py +++ b/examples/sanic_aiopg_example.py @@ -1,3 +1,6 @@ +""" To run this example you need additional aiopg package + +""" import os import asyncio @@ -59,4 +62,4 @@ async def handle(request): if __name__ == '__main__': loop.run_until_complete(prepare_db()) - app.run(host="0.0.0.0", port=8100, workers=3, loop=loop) + app.run(host='0.0.0.0', port=8000, loop=loop) diff --git a/examples/sanic_aiopg_sqlalchemy_example.py b/examples/sanic_aiopg_sqlalchemy_example.py new file mode 100644 index 00000000..cb9f6c57 --- /dev/null +++ b/examples/sanic_aiopg_sqlalchemy_example.py @@ -0,0 +1,73 @@ +""" To run this example you need additional aiopg package + +""" +import os +import asyncio +import datetime + +import uvloop +from aiopg.sa import create_engine +import sqlalchemy as sa + +from sanic import Sanic +from sanic.response import json + +asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) + +database_name = os.environ['DATABASE_NAME'] +database_host = os.environ['DATABASE_HOST'] +database_user = os.environ['DATABASE_USER'] +database_password = os.environ['DATABASE_PASSWORD'] + +connection = 'postgres://{0}:{1}@{2}/{3}'.format(database_user, + database_password, + database_host, + database_name) +loop = asyncio.get_event_loop() + + +metadata = sa.MetaData() + +polls = sa.Table('sanic_polls', metadata, + sa.Column('id', sa.Integer, primary_key=True), + sa.Column('question', sa.String(50)), + sa.Column("pub_date", sa.DateTime)) + + +async def get_engine(): + return await create_engine(connection) + +app = Sanic(name=__name__) +engine = loop.run_until_complete(get_engine()) + + +async def prepare_db(): + """ Let's add some data + + """ + async with engine.acquire() as conn: + await conn.execute('DROP TABLE IF EXISTS sanic_polls') + await conn.execute("""CREATE TABLE sanic_polls ( + id serial primary key, + question varchar(50), + pub_date timestamp + );""") + for i in range(0, 100): + await conn.execute( + polls.insert().values(question=i, + pub_date=datetime.datetime.now()) + ) + + +@app.route("/") +async def handle(request): + async with engine.acquire() as conn: + result = [] + async for row in conn.execute(polls.select()): + result.append({"question": row.question, "pub_date": row.pub_date}) + return json({"polls": result}) + + +if __name__ == '__main__': + loop.run_until_complete(prepare_db()) + app.run(host='0.0.0.0', port=8000, loop=loop)