为什么我的龙卷风应用程序不起作用?(带有aiomysql的龙卷风博客)

时间:2019-04-09 14:34:17

标签: python tornado

import tornado.ioloop
import tornado.web
import tornado.options
import tornado.locks
import os.path

from tornado.options import define, options
from aiomysql import create_pool

define("port", default=8080, help="run on the given port", type=int)
define("db_host", default="localhost", help="blog database host")
define("db_port", default=3306, help="blog database port")
define("db_database", default="{db_name}", help="blog database name")
define("db_user", default="{db_user}", help="blog database user")
define("db_password", default="{password}", help="blog database password")

async def maybe_create_tables(db):
    async with db.acquire() as conn:
        async with conn.cursor() as cur:
            try:
                await cur.execute("SELECT COUNT(*) FROM user LIMIT 1")
                await cur.fetchone()
            except Exception as e:
                with open("schema.sql") as f:
                    schema = f.read()
                    await cur.execute(schema)

class Application(tornado.web.Application):
    def __init__(self, db):
        self.db = db
        handlers = [
            (r"/", HomeHandler),
            (r".*", BaseHandler)
        ]
        settings = dict(
            debug=True
        )
        super(Application, self).__init__(handlers, **settings)

class BaseHandler(tornado.web.RequestHandler):
   def set_default_headers(self):
        self.set_header("Server", "tornado")

class HomeHandler(BaseHandler):
    async def get(self):
        self.write("hello")

async def main():
    tornado.options.parse_command_line()

    async with create_pool(
        host=options.db_host,
        port=options.db_port,
        user=options.db_user,
        password=options.db_password,
        db=options.db_database,
    ) as db:
        await maybe_create_tables(db)
        app = Application()
        app.listen(options.port)

    shutdown_event = tornado.locks.Event()
    await shutdown_event.wait()

if __name__ == "__main__":
    tornado.ioloop.IOLoop.current().run_sync(main)

我从这里(https://github.com/xzhdream/tornado-blog-aiomysql/blob/master/blog.py)复制了这些代码,但是它不起作用。 当我运行此应用程序时,没有输出错误,但控制台被冻结。 Mysql和Mysql用户设置必须正确完成。我检查了很多次。

1 个答案:

答案 0 :(得分:0)

  1. 您的Application.__init__接受一个db参数,但是调用Application时您没有传递参数。我不知道为什么您没有得到关于此问题的任何错误回溯。

  2. await shutdown_event.wait()调用位于async with create_pool之外,因此一旦完成初始化,数据库连接池将关闭,并且在服务器运行时将不可用。缩进这些行,使它们包含在async with块中。