#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import pymysql
from tormysql import ConnectionPool
from tornado import gen
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
define("port", default=8888, help="run on the given port", type=int)
pool = ConnectionPool(
max_connections=int(os.getenv("MYSQL_POOL", 5)),
idle_seconds=7200,
user="test",
passwd="test",
db="test",
charset="utf8",
no_delay=True,
sql_mode="REAL_AS_FLOAT",
init_command="SET max_join_size=DEFAULT"
)
@gen.coroutine
def get_data(pool):
sql = """select id, value from mytable;"""
with (yield pool.Connection()) as conn:
try:
with conn.cursor(pymysql.cursors.DictCursor) as cursor:
yield cursor.execute(sql)
datas = cursor.fetchall()
print(datas)
return datas
except Exception as e:
yield conn.rollback()
raise e
else:
yield conn.commit()
class MainHandler(tornado.web.RequestHandler):
@gen.coroutine
def get(self):
datas = yield get_data(pool)
print("datas is ", datas)
self.write("YES")
def main():
tornado.options.parse_command_line()
application = tornado.web.Application([
(r"/", MainHandler),
])
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(options.port)
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
main()