Tornadao—异步

目录

  1. tornado异步化
  2. 异步访问

 

  • tornado异步化


    import time
    
    import tornado.web
    import tornado.ioloop
    import asyncio
    class IndexHandler(tornado.web.RequestHandler):
         async def get(self):
            await asyncio.sleep(5)
            self.write(time.ctime())
    
    def main():
        app = tornado.web.Application([(r'/',IndexHandler)],debug=True)
        app.listen(8888)
        print("server start")
        tornado.ioloop.IOLoop.current().start()
    
    if __name__ == '__main__':
        main()

     

  • 异步访问


    from tornado.web import StaticFileHandler, RedirectHandler
    from aiomysql import create_pool
    import time
    
    from tornado import web
    import tornado
    from tornado.web import template
    
    class MainHandler(web.RequestHandler):
        def initialize(self, db):
            self.db = db
        # 异步访问
        async def get(self, *args, **kwargs):
            uid = ""
            username = ""
            password = ""
    
            async with create_pool(host=self.db["host"], port=self.db["port"],
                                   user=self.db["user"], password=self.db["password"],
                                   db=self.db["name"], charset="utf8") as pool:
                async with pool.acquire() as conn:
                    async with conn.cursor() as cur:
                        await cur.execute("SELECT uid, username, password from user")
                        try:
                            uid, username, password = await cur.fetchone()
                        except Exception as e:
                            print(e)
                            pass
            self.render("message.html", uid=uid,  username=username, password=password)
    # 配置
    settings = {
        "static_path": "static",#静态资源路径
        "template_path": "templates",   #模板路径
        'debug':True,
        "db": {    #数据库配置
            "host": "127.0.0.1",
            "user": "root",
            "password": "xxx",
            "name": "xxxx",
            "port": 3306
        }
    }
    
    if __name__ == "__main__":
        app = web.Application([
            ("/", MainHandler, {"db": settings["db"]}),], **settings)
        app.listen(8888)
        tornado.ioloop.IOLoop.current().start()

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>用户信息</title>
    </head>
    <body>
    <p>{{ uid }}</p>
    <p>{{ username }}</p>
    <p>{{ password }}</p>
    </body>
    </html>

     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值