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

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

四种异步:

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()

tornado--同步异步的更多相关文章

  1. 【测试】Gunicorn , uWSGI同步异步测试以及应用场景总结

    最近使用uwsgi出了一些问题,于是测试下Gunicorn测试对比下 环境 一颗cpu 1g内存 Centos系统 Django作为后端应用,Gunicorn默认模式和异步模式,响应基本是无阻塞类型 ...

  2. 深入理解yield(三):yield与基于Tornado的异步回调

    转自:http://beginman.cn/python/2015/04/06/yield-via-Tornado/ 作者:BeginMan 版权声明:本文版权归作者所有,欢迎转载,但未经作者同意必须 ...

  3. tornado 之 异步非阻塞

    异步非阻塞 1.基本使用 装饰器 + Future 从而实现Tornado的异步非阻塞 import tornado.web import tornado.ioloop from tornado im ...

  4. tornado 11 异步编程

    tornado 11 异步编程 一.同步与异步 同步 #含义:指两个或两个以上随时间变化的量在变化过程中保持一定的相对关系 #现象:有一个共同的时钟,按来的顺序一个一个处理 #直观感受:需要等待,效率 ...

  5. Python核心框架tornado的异步协程的2种方式

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

  6. Tornado中异步框架的使用

    tornado的同步框架与其他web框架相同都是处理先来的请求,如果先来的请求阻塞,那么后面的请求也会处理不了.一直处于等待过程中.但是请求一旦得到响应,那么: 请求发送过来后,将需要的本站资源直接返 ...

  7. Tornado之异步非阻塞

    同步模式:同步模式下,只有处理完前一个任务下一个才会执行 class MainHandler(tornado.web.RequestHandler): def get(self): time.slee ...

  8. .Net Core WebAPI 基于Task的同步&异步编程快速入门

    .Net Core WebAPI 基于Task的同步&异步编程快速入门 Task.Result async & await 总结 并行任务(Task)以及基于Task的异步编程(asy ...

  9. AJAX请求详解 同步异步 GET和POST

    AJAX请求详解 同步异步 GET和POST 上一篇博文(http://www.cnblogs.com/mengdd/p/4191941.html)介绍了AJAX的概念和基本使用,附有一个小例子,下面 ...

  10. 同步异步,阻塞非阻塞 和nginx的IO模型

    同步与异步 同步和异步关注的是消息通信机制 (synchronous communication/ asynchronous communication).所谓同步,就是在发出一个*调用*时,在没有得 ...

随机推荐

  1. su:鉴定故障

    deepin中从普通用户切换到管理员时出现su:鉴定故障 使用命令:su root [mylinux@localhost ~]$ su root 密码: su: 鉴定故障 解决方法: 使用命令:sud ...

  2. 《DSP using MATLAB》Problem 3.6

    逆DTFT定义如下: 需要求积分,

  3. 最短路--dijkstra+优先队列优化模板

    不写普通模板了,还是需要优先队列优化的昂 #include<stdio.h> //基本需要的头文件 #include<string.h> #include<queue&g ...

  4. C#编程之IList<T>、List<T>、ArrayList、IList, ICollection、IEnumerable、IEnumerator、IQueryable 和 IEnumerable的区别

    额...今天看了半天Ilist<T>和List<T>的区别,然后惊奇的发现使用IList<T>还是List<T>对我的项目来说没有区别...  在C#中 ...

  5. jsfl读取xml,图片,并生成swf

    var newdoc = fl.createDocument(); var doc = fl.getDocumentDOM(); var URI = fl.browseForFolderURL(&qu ...

  6. php 的交互命令行

    php 的交互命令行 使用过 python 都知道 python 可以使用交互命令. 如下图: 但是 执行 php 显示这个是什么鬼? 按回车和加分号都没用,这是什么原因? 其实是因为使用 php 交 ...

  7. Oracle数据泵的使用

    几乎所有DBA都熟悉oracle的导出和导入实用程序,它们将数据装载进或卸载出数据库,在oracle  database 10g和11g中,你必须使用更通用更强大的数据泵导出和导入(Data Pump ...

  8. http报头 Accept 与 Content-Type 的区别

    Accept属于请求头, Content-Type属于实体头. Http报头分为通用报头,请求报头,响应报头和实体报头. 请求方的http报头结构:通用报头|请求报头|实体报头 响应方的http报头结 ...

  9. 【python】单下划线与双下划线的区别

    Python 用下划线作为变量前缀和后缀指定特殊变量. _xxx 不能用'from moduleimport *'导入 __xxx__ 系统定义名字 __xxx 类中的私有变量名 以单下划线开头(_f ...

  10. zabbix cpu 负载不对的原因

    最近给客户安装了一个zabbix服务器,运行了几天发现cpu load值不准确, 请教了运维和系统工程师,说是zabbix2.0以后的问题.   解决方案如下1(推荐): 修改模板(Template ...