HTTPClient 使用例子:
    from tornado.httpclient import HTTPClient 

    def synchronous_fetch(url): 
     http_client = HTTPClient()
     response = http_client.fetch(url)
     return response.body
AsyncHTTPClient使用例子:

方法1:
from tornado.httpclient import AsyncHTTPClient def asynchronous_fetch(url, callback):
  http_client = AsyncHTTPClient()
def handle_response(response): # 创建一个函数内的函数,来处理返回的结果
callback(response.body)
http_client.fetch(url, callback=handle_response) # 异步处理结束后会调用指定的callback的函数 方法2:
from tornado.httpclient import AsyncHTTPClient
from tornado.concurrent import Future def async_fetch_future(url):
http_client = AsyncHTTPClient()
my_future = Future()
fetch_future = http_client.fetch(url)
fetch_future.add_done_callback(lambda f: my_future.set_result(f.result()))
return my_future
方法3:
from tornado.httpclient import AsyncHTTPClient
from tornado import gen @gen.coroutine #添加异步访问的装饰器
def fetch_coroutine(url):
http_client = AsyncHTTPClient()
response = yield http_client.fetch(url) # 获取异步结果时要使用yield
raise gen.Return(response.body) # 使用抛出异常的方式来返回结果,不能使用return来返回 以下知识是额外的可以了解下,但不保证知识是完整的:
  async and await 在python3.5,tornado4.3中可以了解下   例子:
async deffetch_coroutine(url):
   http_client = AsyncHTTPClient()
response = await http_client.fetch(url)
return response.body
使用yield来遍历异步的结果是,以下方法是在项目中没有试验过的
--------------------------------- start --------------------------------------
@gen.coroutine
def parallel_fetch(url1, url2):
resp1, resp2 = yield [http_client.fetch(url1),
http_client.fetch(url2)] @gen.coroutine
def parallel_fetch_many(urls):
responses = yield [http_client.fetch(url) for url in urls]
# responses is a list of HTTPResponses in the same order @gen.coroutine
def parallel_fetch_dict(urls):
responses = yield {url: http_client.fetch(url)
for url in urls}
# responses is a dict {url: HTTPResponse} --------------------------------- end ----------------------------------------
												

最新文章

  1. [LeetCode] Binary Tree Inorder Traversal 二叉树的中序遍历
  2. gulp外挂 uglify 的使用
  3. asp.net中打印指定控件内容
  4. Python开发【第六篇】:模块
  5. PinPhoto On OS X
  6. Android开发艺术探索学习笔记(三)
  7. angular(常识)
  8. 第二周 WBS、NABCD查阅
  9. node操作mysql数据库
  10. CI框架中自定义view文件夹位置
  11. Mac os 10.9下面配置JAVA_HOME
  12. Javascript 类数组(Array-like)对象
  13. js高级程序设计学习之高级函数
  14. vue-resource pos提交t数据时碰到Django csrf
  15. 局域网内一台电脑的ip地址自己会变,怎样让它不变
  16. W3CSchool闯关笔记(JQuery)
  17. SpringBoot-目录及说明
  18. JavaScript中数组的应用
  19. spring4学习笔记
  20. http.lua里的装饰器

热门文章

  1. Android多线程下载
  2. Oracle SQL:select各类查询语句总结
  3. Javascript-关于for in和forEach
  4. urllib模块学习
  5. MicroMsg.SDK.WXApiImplV10: register app failed for wechat app signature check failed
  6. linux守护进程与&的区别
  7. (一)apache atlas源代码编译与打包
  8. 阿里Canal配置(编写中)
  9. 9.纯 CSS 创作一种按钮被瞄准的交互特效
  10. 《算法》第四章部分程序 part 3