python - Tornado - 如何获得 AsynHTTPClient.fetch() 的响应?

标签 python debugging http web tornado

#!/usr/bin/env python

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

import urllib
import json
import datetime
import time

from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)

config = {
        'proxy_host': '58.59.21.228',
        'proxy_port': 25,
        'proxy_username': 'yz',
        'proxy_password': 'fangbinxingqusi',
}

def handle_request(response):
    if response.error:
        print "Error:", response.error

tornado.httpclient.AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient")

class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        client = tornado.httpclient.AsyncHTTPClient()
        response = client.fetch("http://twitter.com/", handle_request,
                **config)
        self.write(response.body)

if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = tornado.web.Application(handlers=[(r"/", IndexHandler)],
            debug=True)
    httpserver = tornado.httpserver.HTTPServer(app)
    httpserver.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

在运行时,get() 方法中的response 对象被报告为None 类型。如何在get()方法中得到fetch()方法的响应?

最佳答案

您正在使用 AsyncHTTPClient ,因此 fetch 方法不会返回任何内容。您需要使用“异步”装饰器并记住在 fetch 调用的回调中调用 finish

代码如下:

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

from tornado.options import define, options                                  
define("port", default=8000, help="run on the given port", type=int)         

config = {                                                                   
    'proxy_host': '58.59.21.228',                                            
    'proxy_port': 25,                                                        
    'proxy_username': 'yz',                                                  
    'proxy_password': 'fangbinxingqusi',                                     
}                                                                            

tornado.httpclient.AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient")


class IndexHandler(tornado.web.RequestHandler):                              

    @tornado.web.asynchronous                                                
    def get(self):                                                           
        client = tornado.httpclient.AsyncHTTPClient()                        
        client.fetch("http://twitter.com/", self.handle_request, **config)   

    def handle_request(self, response):                                      
        if response.error:                                                   
            print("Error:", response.error)                                  
        else:                                                                
            self.write(response.body)                                        
        self.finish()                                                        


if __name__ == "__main__":                                                   
    tornado.options.parse_command_line()                                     
    app = tornado.web.Application(handlers=[(r"/", IndexHandler)], debug=True)
    httpserver = tornado.httpserver.HTTPServer(app)                          
    httpserver.listen(options.port)                                          
    tornado.ioloop.IOLoop.instance().start()             

您还可以使用 Tornado's gen让你的处理程序更漂亮:

class IndexHandler(tornado.web.RequestHandler):                              

    @tornado.web.asynchronous                                                
    @tornado.gen.engine                                                      
    def get(self):                                                           
        client = tornado.httpclient.AsyncHTTPClient()                        
        response = yield tornado.gen.Task(client.fetch, "http://twitter.com/",
                                        **config)                            
        if response.error:                                                   
            self.write("Error: %s" % response.error)                         
        else:                                                                
            self.write(response.body)                                        

        self.finish()                                                        

关于python - Tornado - 如何获得 AsynHTTPClient.fetch() 的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14829047/

相关文章:

debugging - 当 "codec => rubydebug"时,logstash 在哪里写入日志?

django - 如何删除 Flutter 中的 "XMLHttpRequest error"? (Django 后端,Flutter 前端)

python - 创建一个新的 DataFrame,将列字典中的每个键添加为标题

python - 与 'as' 关键字一起使用时覆盖 python open 函数以打印任何内容

python - 编写将分钟整数转换为格式为 "X hour(s) Y minute(s)"的字符串的函数的最佳方法是什么?

python - 如何使用 BeautifulSoup 4 替换或删除 HTML 实体,如 " "

python - 使用 Python 程序的结果进行算术运算

c - 为什么我的代码返回的数字低于应返回的数字?

python - 如何使用 HTTP 服务器从客户端获取输入并对其进行操作

http - 将 interface{} 参数转换为 Go 中的 *http.Request 或 *http.Response