使用龙卷风发送多个异步发布请求

时间:2014-11-12 16:26:30

标签: python http tornado

关于龙卷风的stackoverflow有几个问题 我还没有找到我的问题的答案 我有一个大文本文件,我希望迭代并发送每一行作为POST http请求。 我希望将其作为异步(我需要快速),然后检查请求的响应。

我有类似的东西

http_client = httpclient.AsyncHTTPClient()
with open(filename) as log_file:
    for line in log_file:
        request = httpclient.HTTPRequest(self.destination,method="POST",headers=self.headers,body=json.dumps(line))
        response = http_client.fetch(request, callback=self.handle_request)

看着tcpdump这没有做任何事情 我得到的只是一个严肃的“期货”对象 我还尝试将fetch命令放在“yield”中,然后在方法上使用@ gen.coroutine装饰器时迭代它。 这没有帮助。 任何人都可以告诉我,我做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:7)

以下是您如何使用" fetch"在协程中:

from tornado import gen, httpclient, ioloop

filename = 'filename.txt'
destination = 'http://localhost:5000'
http_client = httpclient.AsyncHTTPClient()


@gen.coroutine
def post():
    with open(filename) as log_file:
        for line in log_file:
            request = httpclient.HTTPRequest(destination,
                                             body=line,
                                             method="POST")

            response = yield http_client.fetch(request)
            print response

ioloop.IOLoop.current().run_sync(post)

您可以使用接收线路的小型服务器对其进行测试并打印出来:

from tornado import ioloop, web


class MyHandler(web.RequestHandler):
    def post(self):
        print self.request.body.rstrip()


app = web.Application([
    web.URLSpec('/', MyHandler)
])

app.listen(port=5000)
ioloop.IOLoop.current().start()

首先运行服务器代码,然后运行客户端。

如果您希望一次最多发布10个日志行,请安装Toro并执行:

from tornado import gen, ioloop
from tornado.httpclient import AsyncHTTPClient, HTTPRequest
from toro import JoinableQueue

filename = 'tox.ini'
destination = 'http://localhost:5000'
AsyncHTTPClient.configure("tornado.simple_httpclient.SimpleAsyncHTTPClient",
                          max_clients=10)

http_client = AsyncHTTPClient()
q = JoinableQueue(maxsize=10)


@gen.coroutine
def read():
    with open(filename) as log_file:
        for line in log_file:
            yield q.put(line)


@gen.coroutine
def post():
    while True:
        line = yield q.get()
        request = HTTPRequest(destination,
                              body=line,
                              method="POST")

        # Don't yield, just keep going as long as there's work in the queue.
        future = http_client.fetch(request)

        def done_callback(future):
            q.task_done()
            try:
                print future.result()
            except Exception as exc:
                print exc

        future.add_done_callback(done_callback)



# Start coroutines.
read()
post()

# Arrange to stop loop when queue is finished.
loop = ioloop.IOLoop.current()
join_future = q.join()


def done(future):
    loop.stop()

join_future.add_done_callback(done)

loop.start()