Tornado-异步编程

2018-07-22  本文已影响0人  Python野路子

同步和异步

同步

异步

阻塞与非阻塞

阻塞调用

非阻塞调用

异步编程

tornado是单线程的,一次只能处理一个请求;但是由于他是异步的,所以是高并发的,那么在tornado中,同时有多个请求发送过来时,而且其中还有请求发生阻塞,会产生什么样的后果呢?

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

from pycket.session import SessionMixin

import tornado.httpclient

from tornado.options import define,options

define('port', default= 8080, help='run port', type=int)



#设置BaseHandler类,重写函数get_current_user
class BaseHandler(tornado.web.RequestHandler, SessionMixin):
    def get_current_user(self): #前面有绿色小圆圈带个o,再加一个箭头表示重写
        print('********')
        current_user = self.session.get('user') #获取加密的cookie
        print(current_user)
        if current_user:
            return current_user
        return None


class SyncHandler(BaseHandler):  #同步
    def get(self):
        client = tornado.httpclient.HTTPClient() ## 同步HTTPClient
        response = client.fetch("http://127.0.0.1:8000/sleep") ##这是模拟阻塞的接口,该接口代码里面有sleep用来模拟阻塞
        print(response)
        self.write(response.body)


#1、通过回调函数实现异步
class CallbackHandler(BaseHandler): #这便是异步的方法,在阻塞的时候就直接处理其他的请求
    @tornado.web.asynchronous   #将请求变成长连接
    def get(self):
        client = tornado.httpclient.AsyncHTTPClient() # 异步AsyncHTTPClient
        client.fetch("http://127.0.0.1:8000/sleep",callback=self.on_response) #当这个地方发生阻塞时,并没有在这个地方等待,而是后面的全部处理完了才来处理这个
        self.write('OK!'+'<br>')  #这便是通过回调函数实现异步,先出现ok,在回到上面

    def on_response(self,response):
        self.write(response.body)
        self.finish()  #在这个回调函数中必须加上finish,不加上的话就会不知道上面的接口函数什么时候结束


#2.通过协程实现异步
import tornado.gen

class GenHandler(BaseHandler):
    @tornado.web.asynchronous
    @tornado.gen.coroutine   #协程
    def get(self):
        client = tornado.httpclient.AsyncHTTPClient()
        response = yield tornado.gen.Task(client.fetch,"http://127.0.0.1:8000/sleep") #yield生成器,有等待、暂停的功能
        self.write(response.body)

#3.通过协程实现异步(自定义函数)
class FuncHandler(BaseHandler):
    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def get(self):
        response = yield self.func()
        print(response)
        self.write(response.body)

    @tornado.gen.coroutine
    def func(self):
        client = tornado.httpclient.AsyncHTTPClient()
        response = yield tornado.gen.Task(client.fetch,"http://127.0.0.1:8000/sleep")
        raise tornado.gen.Return(response)

#4. 通过协程来实现异步(使用requests模块),需要安装requests和futures模块
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor  #(它是由thread模块封装的(创建线程的模块))
import requests
import requests

class MyFuncHandler(BaseHandler):

    executor = ThreadPoolExecutor() #当发生阻塞时,能够创建一个新的线程来执行阻塞的任务(多线程)

    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def get(self):
        response = yield self.func()
        print(response)
        self.write(response.text)

    @run_on_executor
    def func(self):
        response = requests.get("http://127.0.0.1:8000/sleep")
        return response



application = tornado.web.Application(
    handlers = [
        (r'/sync',SyncHandler),
        (r'/call', CallbackHandler),
        (r'/gen',GenHandler),
        (r'/func',FuncHandler),
        (r'/myfunc',MyFuncHandler)
    ],

    static_path='static',
    template_path = 'templates', #想要Tornado能够正确的找到html文件,需要在 Application 中指定文件的位置
    debug = True   #调试模式,修改后自动重启服务,不需要自动重启,生产情况下切勿开启,安全性
)

if __name__ == '__main__':
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()
上一篇 下一篇

猜你喜欢

热点阅读