tornado使用AsyncHTTPClient和gen来请求一个url,使用raise gen.Return获取Exceptions

时间:2014-09-25 09:40:45

标签: python tornado

我是龙卷风的新手,所以我按照龙卷风的指导练习,当我来使用Coroutines时,例子说:     来自tornado import gen

@gen.coroutine
def fetch_coroutine(url):
    http_client = AsyncHTTPClient()
    response = yield http_client.fetch(url)
    # In Python versions prior to 3.3, returning a value from
    # a generator is not allowed and you must use
    #   raise gen.Return(response.body)
    # instead.
    return response.body

当我运行此测试时,它会引发SyntaxError ' return'使用生成器内的参数,所以我取消注释建议,如下所示:     import tornado.httpserver     import tornado.ioloop     导入tornado.options     import tornado.web

from tornado.options import define, options

define("port", default=8888, help="run on the given port", type=int)
from tornado import gen
from tornado.httpclient import AsyncHTTPClient

@gen.coroutine
def fetch_coroutine(url):
    http_client = AsyncHTTPClient()
    response = yield http_client.fetch(url)
    #return response.body
    raise gen.Return(response.body)

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")
        data = fetch_coroutine(url = "http://www.baidu.com")
        self.write(data)
        print data


def main():
    tornado.options.parse_command_line()
    application = tornado.web.Application([
        (r"/", MainHandler),
    ])
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()


if __name__ == "__main__":
    main()

但它引发了这样的异常:

[E 140925 17:35:53 web:1407] Uncaught exception GET / (::1)
    HTTPServerRequest(protocol='http', host='localhost:8888', method='GET', uri='/', version='HTTP/1.1', remote_ip='::1', headers={'Accept-Language': 'zh-TW,zh;q=0.8,zh-CN;q=0.6,en;q=0.4', 'Accept-Encoding': 'gzip,deflate,sdch', 'Host': 'localhost:8888', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36', 'Connection': 'keep-alive', 'Cache-Control': 'max-age=0', 'If-None-Match': '"e02aa1b106d5c7c6a98def2b13005d5b84fd8dc8"'})
    Traceback (most recent call last):
      File "/Library/Python/2.7/site-packages/tornado-4.0.2-py2.7-macosx-10.9-intel.egg/tornado/web.py", line 1332, in _execute
        result = method(*self.path_args, **self.path_kwargs)
      File "helloworld.py", line 39, in get
        self.write(data)
      File "/Library/Python/2.7/site-packages/tornado-4.0.2-py2.7-macosx-10.9-intel.egg/tornado/web.py", line 656, in write
        raise TypeError("write() only accepts bytes, unicode, and dict objects")
    TypeError: write() only accepts bytes, unicode, and dict objects
[E 140925 17:35:53 web:1811] 500 GET / (::1) 3.94ms

1 个答案:

答案 0 :(得分:7)

文档非常similar example

class GenAsyncHandler(RequestHandler):
    @gen.coroutine
    def get(self):
        http_client = AsyncHTTPClient()
        response = yield http_client.fetch("http://example.com")
        do_something_with_response(response)
        self.render("template.html")

总结:

  • 在python 2.x中,你不能在块内返回一些内容,用@gen.coroutine修饰,只允许单return
  • 在python 2.x中,如果你需要在@ gen.coroutine块中返回一些内容,那么使用raise gen.Return,正确理解
  • 您无需以get方法返回任何内容即可向客户端回复某些数据。您需要write某些内容(例如上面的示例,通过调用self.render来完成)。

所以,替换此代码

        do_something_with_response(response)
        self.render("template.html")

用这个:

        self.write(response.body)
        self.finish()

self.finish()将完成响应,结束HTTP请求。它在self.render方法中自动调用。

最终请求处理程序

from tornado import gen
from tornado.web import RequestHandler
from tornado.httpclient import AsyncHTTPClient


class GenAsyncHandler(RequestHandler):
    @gen.coroutine
    def get(self):
        http_client = AsyncHTTPClient()
        response = yield http_client.fetch("http://google.com")
        self.write(response.body)
        self.finish()