.Tang

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

同步:指两个或两个以上随时间变化的量在变化过程中保持一定的相对关系 现象:有一个共同的时钟,按来的顺序一个一个处理

异步:双方不需要共同的时钟,也就是接收方不知道发送方什么时候发送,所以在发送的信息中就要有提示接收方开始接收的信息,如开始位,同时在结束时有停止位 现象:没有共同的时钟,不考虑顺序来了就处理 

 

四种异步:

import tornado.ioloop
import tornado.web

from data.table_1 import User
from tornado.web import authenticated

from pycket.session import SessionMixin

import tornado.websocket
from datetime import datetime
import time

import tornado.options
import tornado.httpserver
from tornado.options import define, options


define('port',default=8000, help='run port', type=int)
define('version', default=0.1, help='version', type=str)


class BaseHandler(tornado.web.RequestHandler, SessionMixin):
    def get_current_user(self):
        # current_user = self.get_secure_cookie('ID')
        current_user = self.session.get('ID')
        if current_user:
            return current_user
        return None


class AbcHandler(BaseHandler):
    def get(self):
        self.write('abc')


import tornado.httpclient
class SyncHandler(BaseHandler):
    def get(self):
        client = tornado.httpclient.HTTPClient()     # 同步HTTPClient
        response = client.fetch('http://127.0.0.1:8000/sync')  # 8000已经启动,去访问sync(相当于调用接口)
        print(response)
        self.write('----SyncHandler---')


# 可能发生阻塞用异步
class CallbackHandler(BaseHandler):
    """  1.通过回调函数实现异步 """
    @tornado.web.asynchronous  # 将请求变成长连接
    def get(self):
        client = tornado.httpclient.AsyncHTTPClient()     # 异步AsyncHTTPClient
                                                # 阻塞完毕后调用 callback
        response = client.fetch('http://127.0.0.1:8000/sync', callback=self.on_response)
        print(response)
        self.write('OK'+'<br>')

    def on_response(self, response):
        print(response)
        self.write('----CallbackSyncHandler---')
        self.finish()   # 回调结束,请求结束,响应到浏览器(否则浏览器一直等待状态)


import tornado.gen
class GenHandler(BaseHandler):
    """ 2.通过协程实现异步 yield """
    @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/sync')
        print(response)
        self.write('---gen----')


class FuncHandler(BaseHandler):
    """ 3.通过协程实现异步  yield 调用函数 @tornado.gen.coroutine装饰函数(函数需要用到yield"""
    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def get(self):
        response = yield self.fun()
        print(response)
        self.write('---gen----')

    @tornado.gen.coroutine
    def fun(self):
        client = tornado.httpclient.AsyncHTTPClient()     # 异步
        response = yield tornado.gen.Task(client.fetch, 'http://127.0.0.1:8000/sync')
        raise tornado.gen.Return(response)


from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor # (它是由thread模块封装的(创建线程的模块))
import requests


class ExeHandler(BaseHandler):
    """ 4.通过协程实现异步  yield 调用函数 @run_on_executor装饰函数(函数不用yield)
    需要下载requests 和futures"""
    executor = ThreadPoolExecutor() # 当发生阻塞时,能够创建一个新的线程来执行阻塞的任务(多线程)
    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def get(self):
        response = yield self.fun()
        print(response)
        self.write('---exe----')

    @run_on_executor
    def fun(self):
        response = requests.get( 'http://127.0.0.1:8000/sync')
        return response

application = tornado.web.Application(
    handlers=[
        (r"/sync", SyncHandler),
        (r"/abc", AbcHandler),
        (r"/callback", CallbackHandler),
        (r"/gen", GenHandler),
        (r"/func", FuncHandler),
        (r"/exe", ExeHandler),
    ],
    cookie_secret='haha',
    debug=True
)

if __name__ == '__main__':
    tornado.options.parse_command_line()  # 获取命令行的参数 --port=1040 就能使用这个参数
    print(options.port)
    print(options.version)

    http_server = tornado.httpserver.HTTPServer(application)
    application.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

 

posted on 2018-03-17 14:00  .Tang  阅读(1039)  评论(0编辑  收藏  举报