import tornado.web
import tornado.ioloop
import tornado.httpserver
import os
import pymysql
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.conn = self.application.db
self.cursor = self.conn.cursor()
#index = self.cursor.execute("select ui_user_name from ih_user_info where ui_user_id=%s",1)
index = self.cursor.execute("select ui_user_name from ih_user_info ")
print(index)
ret = self.cursor.fetchall()
print(ret)
houses = []
if ret:
for house in ret:
houses.append(house)
self.write({"houses":houses})
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", IndexHandler),
]
settings = dict(
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "statics"),
debug=True,
)
super(Application, self).__init__(handlers, **settings)
# 创建一个全局mysql连接实例供handler使用
self.db = pymysql.connect(
host="127.0.0.1",
port=3306,
db="ihome",
user="root",
passwd="root",
charset="utf8",
)
if __name__ == "__main__":
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()