我有一个要测试鲁棒性的链接,因为缺少更好的词。我拥有的代码可按顺序多次ping URL:
# Testing for robustness
for i in range(100000):
city = 'New York'
city = '%20'.join(city.split(' '))
res = requests.get(f'http://example.com/twofishes?query={city}')
data = res.json()
geo = data['interpretations'][0]['feature']['geometry']['center']
print('pinging xtime: %s ' % str(i))
print(geo['lat'], geo['lng'])
我想获取这段代码,但是一次ping通链接,一次10或12次。我不介意顺序ping,但这不如一次多次ping效率高。我觉得这是一个快速的修改,其中for
循环出现并且PULL
函数进入其中?
答案 0 :(得分:1)
这是一个应执行此任务的示例程序。鉴于我不想被列入黑名单,因此我实际上并未测试代码以查看其是否有效。无论如何,它至少应该在您所寻找的范围内。如果您实际上希望所有线程同时执行,则可以考虑添加events。希望这会有所帮助。
代码
import threading
import requests
import requests.exceptions as exceptions
def stress_test(s):
for i in range(100000):
try:
city = 'New York'
city = '%20'.join(city.split(' '))
res = s.get(f'http://example.com/twofishes?query={city}')
data = res.json()
geo = data['interpretations'][0]['feature']['geometry']['center']
print('pinging xtime: %s ' % str(i))
print(geo['lat'], geo['lng'])
except (exceptions.ConnectionError, exceptions.HTTPError, exceptions.Timeout):
pass
if __name__ == '__main__':
for i in range(1, 12):
s = requests.session()
t = threading.Thread(target=stress_test, args=(s,))
t.start()
for th in threading.enumerate():
if th != threading.current_thread():
th.join()