有一次,我需要大量的时间来提交一个非阻塞请求和2秒,用龙卷风写一个例子,帮帮我!
我在 python 中有一个使用 Tornado 的服务器客户端程序。
服务器.py:
import tornado.httpserver
import tornado.ioloop
import random
import time
def handle_request(request):
t = random.randint(1, 10) / 10.
_str = "%s rep_time: %s delay %s" % (request.body, time.time(), t)
time.sleep(t)
request.write('HTTP/1.1 200 OK\r\nContent-Length: %s\r\n\r\n%s' % (len(_str), _str))
request.finish()
http_server = tornado.httpserver.HTTPServer(handle_request)
http_server.listen(8888)
print "server start..."
tornado.ioloop.IOLoop.instance().start()
客户端.py:
# -*- coding: utf-8 -*-
from tornado.httpclient import AsyncHTTPClient, HTTPRequest
import tornado.ioloop
import time
from tornado.log import gen_log
from tornado import gen
from tornado.options import parse_command_line
import datetime
@gen.coroutine
def handle_requst(response):
if response.body:
gen_log.info("response body: %s" % response.body)
@gen.coroutine
def send_request(num):
yield AsyncHTTPClient().fetch("http://localhost:8888", handle_requst, method="POST", body="req_time: %s no.: %s" % (time.time(), num))
@gen.coroutine
def run():
begin_time = int(time.time() + 1)
while True:
yield gen.Task(tornado.ioloop.IOLoop.current().add_timeout, datetime.timedelta(seconds=1))
now_time = int(time.time())
if now_time == begin_time:
gen_log.info('begin_time:%s' % time.time())
num = 0
while True:
num = num + 1
if num < 10:
#Begin submitting data
send_request(num)
# Submit two seconds
if time.time() > (begin_time + 2):
break
break
gen_log.info('end_time:%s' % time.time())
if __name__ == '__main__':
parse_command_line()
tornado.ioloop.IOLoop.instance().add_callback(run)
tornado.ioloop.IOLoop.instance().start()
结果
[I 141230 19:05:32 2:24] begin_time:1419937532.08
[I 141230 19:05:34 2:36] end_time:1419937534.0
[I 141230 19:05:34 2:11] response body: req_time: 1419937532.1 no.: 1 rep_time: 1419937534.0 delay 0.1
开始时间:32s
结束时间:34s
请求时间:32s
服务器接受时间:34s
如您所见,服务器接受时间是 34 秒,我希望服务器接受时间在 32 秒左右