tornaodo异步编程

一、书写一个休眠5秒的视图

#coding=utf-8
import time
import tornado.httpserver
import tornado.web
import tornado.ioloop
from tornado.options import define, options
#定义一个默认的端口
define("port", default=4000, help="run port ", type=int)

class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        #设置休眠时间
        time.sleep(5)
        self.write("我是休眠的")

if __name__ == "__main__":
    options.parse_command_line()
    app = tornado.web.Application(
        handlers=[
            (r'/', IndexHandler)
        ],
        template_path='templates',
        static_path='static',
        debug=True
    )

    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    print 'start server...'
    tornado.ioloop.IOLoop.instance().start()

二、使用回调函数实现异步编程

  • 1、导包import tornado.httpclient
  • 2、书写一个正常的视图
  • 3、在get或post方法里 实例化异步客户端

    client = tornado.httpclient.AsyncHTTPClient()
  • 4、通过异步客户端的fetch方法请求一个耗时的网络接口,并传入callback回调函数

  • 5、编写回调函数,主要要带self.finish()
  • 6、给异步的方法加上装饰器@tornado.web.asynchronous

    
    #coding=utf-8
    
    import time
    import tornado.httpclient
    import tornado.httpserver
    import tornado.web
    import tornado.ioloop
    from tornado.options import define, options
    
    #定义一个默认的端口
    
    define("port", default=8000, help="run port ", type=int)
    
    
    #使用回调函数实现异步编程
    
    class IndexHandler(tornado.web.RequestHandler):
        @tornado.web.asynchronous
        def get(self):
            client = tornado.httpclient.AsyncHTTPClient()
            client.fetch("http://xx.xx.xx.xxx:4000",callback=self.on_response)
            self.write("我是主页")
    
        def on_response(self,response):
            print response
            self.write(response.body)
            self.finish()
    
    
    if __name__ == "__main__":
        options.parse_command_line()
        app = tornado.web.Application(
            handlers=[
                (r'/', IndexHandler)
            ],
            template_path='templates',
            static_path='static1',
            debug=True
        )
    
        http_server = tornado.httpserver.HTTPServer(app)
        http_server.listen(options.port)
        print 'start server...'
        tornado.ioloop.IOLoop.instance().start()

三、通过协程实现的异步

  • 1、导包

    import tornado.gen
    import tornado.httpclient
  • 2、书写路由视图函数

  • 3、在getpost方法里 实例化异步客户端

    client = tornado.httpclient.AsyncHTTPClient()
  • 4、使用yield返回一个任务,需要传入异步客户端fetch方法,和耗时的url作为参数

    response  = yield tornado.gen.Task(client.fetch, "http://xx.xx.xx.xxx:8000/sync?id=2")
  • 5、处理通过yield返回的结果response
  • 6、给getpost方法添加两个装饰器

    @tornado.web.asynchronous
    @tornado.gen.coroutine
  • 7、具体视图代码

    
    #使用协程实现异步编程
    
    class IndexHandler(tornado.web.RequestHandler):
        @tornado.web.asynchronous
        @tornado.gen.coroutine
        def get(self):
            client = tornado.httpclient.AsyncHTTPClient()
            response = yield tornado.gen.Task(client.fetch,"http://xx.xx.xx.xxx:4000")
            self.write("我是主页")
            self.write(response.body)

四、协程实现的异步,返回的是自定义的函数

  • 1、导包

    import tornado.gen
    import tornado.httpclient
  • 2、书写路由视图函数

  • 3、通过yield关键字返回我们自定义的函数
  • 4、处理yield返回的结果response

    self.write(response.body)
  • 5、书写自定义函数

    • 1、在函数中实例化异步客户端

      client = tornado.httpclient.AsyncHTTPClient()
    • 2、使用yield返回一个任务,需要传入异步客户端fetch方法,和耗时的url作为参数

      response  = yield tornado.gen.Task(client.fetch, "http://xx.xx.xx.xxx:4000")
    • 3、处理通过raise返回的结果

      raise tornado.gen.Return(response)
    • 4、在自定义函数上加装饰符

      @tornado.gen.coroutine
  • 6、具体代码

    class IndexHandler(tornado.web.RequestHandler):
        @tornado.web.asynchronous
        @tornado.gen.coroutine
        def get(self):
            response = yield self.myfunc()
            self.write(response.body)
    
        @tornado.gen.coroutine
        def myfunc(self):
            client = tornado.httpclient.AsyncHTTPClient()
            response = yield tornado.gen.Task(client.fetch,"http://xx.xx.xx.xxx:4000/")
            raise tornado.gen.Return(response)

五、异步线程实现的异步,返回的是自定义的函数

  • 1、在虚拟环境下安装模块

    pip install futures
  • 2、导入模块

    from tornado.concurrent import run_on_executor
    from concurrent.futures import ThreadPoolExecutor
    import tornado.gen
  • 3、书写视图函数

  • 4、通过yield关键字返回我们自定义的函数

    response = yield self.myfunc()
  • 5、处理yield返回的结果response

    self.write(response.body)
  • 6、书写自定义函数myfunc

    • 1、在函数中使用requests模块发送get请求

      response = requests.get("http://xx.xx.xx.xxx:4000")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水痕01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值