加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – tornado使用AsyncHTTPClient和gen来请求url,使用raise

发布时间:2020-12-20 11:37:59 所属栏目:Python 来源:网络整理
导读:我是龙卷风的新手,所以我按照龙卷风的指导练习,当我来使用Coroutines时,例子说: ????来自龙卷风进口 @gen.coroutinedef fetch_coroutine(url): http_client = AsyncHTTPClient() response = yield http_client.fetch(url) # In Python versions prior to 3.
我是龙卷风的新手,所以我按照龙卷风的指导练习,当我来使用Coroutines时,例子说:
????来自龙卷风进口

@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

当我运行这个测试时,它会在生成器内部引发语法错误’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,and dict objects
[E 140925 17:35:53 web:1811] 500 GET / (::1) 3.94ms

解决方法

文档有一个非常 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修饰,只允许单个返回
>在python 2.x中,如果你需要在@ gen.coroutine块中返回一些东西,那么使用raise gen.Return,正如你正确理解的那样
>您不需要在get方法中返回任何内容来向客户端响应一些数据.你需要为它写一些东西(在上面的例子中,通过调用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()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读