sanic/examples/sanic_aiomysql_with_global_pool.py

61 lines
1.9 KiB
Python
Raw Normal View History

2017-03-15 06:12:37 +00:00
# encoding: utf-8
"""
You need the aiomysql
"""
import os
import aiomysql
2017-03-15 06:12:37 +00:00
from sanic import Sanic
from sanic.response import json
database_name = os.environ['DATABASE_NAME']
database_host = os.environ['DATABASE_HOST']
database_user = os.environ['DATABASE_USER']
database_password = os.environ['DATABASE_PASSWORD']
app = Sanic()
@app.listener("before_server_start")
async def get_pool(app, loop):
2017-03-15 06:12:37 +00:00
"""
the first param is the global instance ,
2017-03-15 06:12:37 +00:00
so we can store our connection pool in it .
and it can be used by different request
:param args:
:param kwargs:
:return:
"""
app.pool = {
2017-03-15 06:12:37 +00:00
"aiomysql": await aiomysql.create_pool(host=database_host, user=database_user, password=database_password,
db=database_name,
maxsize=5)}
async with app.pool['aiomysql'].acquire() as conn:
2017-03-15 06:12:37 +00:00
async with conn.cursor() as cur:
await cur.execute('DROP TABLE IF EXISTS sanic_polls')
await cur.execute("""CREATE TABLE sanic_polls (
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())
""".format(i, i))
@app.route("/")
async def test():
data = {}
async with app.pool['aiomysql'].acquire() as conn:
2017-05-27 09:06:45 +01:00
async with conn.cursor(aiomysql.DictCursor) as cur:
2017-03-15 06:12:37 +00:00
await cur.execute("SELECT question, pub_date FROM sanic_polls")
2017-05-27 09:06:45 +01:00
result = await cur.fetchall()
2017-03-15 06:12:37 +00:00
if result or len(result) > 0:
2017-05-27 09:06:45 +01:00
data['data'] = result
2017-03-15 06:12:37 +00:00
return json(data)
if __name__ == '__main__':
app.run(host="127.0.0.1", workers=4, port=12000)