0

我正在使用 Tornado 编写应用程序。我需要发出很多 HTTP 请求,但是 Tornado 的 HTTP 客户端有点糟糕(没有 Keep-Alive 支持而且速度很慢),所以我尝试使用 Pulsar HttpClient:

import tornado.web
import tornado.gen
import tornado.httpserver
from tornado.platform.asyncio import AsyncIOMainLoop
from tornado.platform import asyncio as tornasync
import asyncio
from pulsar.apps import http as pulsar_http


class MyHandler(tornado.web.RequestHandler):

    @tornado.gen.coroutine
    def get(self):
        http_client = self.application.http_client

        future = tornasync.to_tornado_future(asyncio.async(http_client.request('GET', 'http://httpbin.org', timeout=.25)))
        try:
            result = yield future
        except TimeoutError as e:
            print('Timeout!')

        print(result.get_content())

        self.write('OK')
        self.finish()


if __name__ == '__main__':
    AsyncIOMainLoop().install()

    app = tornado.web.Application([(r'/', MyHandler)], debug=False)
    server = tornado.httpserver.HTTPServer(app)
    server.bind(8888)
    server.start(1)

    app.http_client = pulsar_http.HttpClient(loop=asyncio.get_event_loop())

    asyncio.get_event_loop().run_forever()

当发生超时时,我得到一个异常:

Traceback (most recent call last):
  File "/home/vitaliy/.virtualenvs/tornado/local/lib/python3.4/site-packages/tornado/web.py", line 1415, in _execute
    result = yield result
  File "/home/vitaliy/.virtualenvs/tornado/local/lib/python3.4/site-packages/tornado/gen.py", line 870, in run
    value = future.result()
  File "/home/vitaliy/.virtualenvs/tornado/local/lib/python3.4/site-packages/tornado/concurrent.py", line 215, in result
    raise_exc_info(self._exc_info)
  File "<string>", line 3, in raise_exc_info
  File "/home/vitaliy/.virtualenvs/tornado/local/lib/python3.4/site-packages/tornado/gen.py", line 876, in run
    yielded = self.gen.throw(*exc_info)
  File "bpp.py", line 19, in get
    result = yield future
  File "/home/vitaliy/.virtualenvs/tornado/local/lib/python3.4/site-packages/tornado/gen.py", line 870, in run
    value = future.result()
  File "/home/vitaliy/.virtualenvs/tornado/local/lib/python3.4/site-packages/tornado/concurrent.py", line 215, in result
    raise_exc_info(self._exc_info)
  File "<string>", line 3, in raise_exc_info
  File "/usr/lib/python3.4/asyncio/tasks.py", line 300, in _step
    result = coro.send(value)
  File "/usr/lib/python3.4/asyncio/tasks.py", line 436, in wait_for
    raise futures.TimeoutError()
concurrent.futures._base.TimeoutError

我能以某种方式捕捉到这个异常吗?

4

1 回答 1

2

只需将该错误导入您的代码:

from concurrent.futures import TimeoutError

否则抓不到

于 2015-08-27T12:23:31.287 回答