首先让我解释一下我将要做的事情的确是在测试Web服务器API。我是python的初学者,想尽快发送以下请求5000次(不超过一秒)。对我来说唯一重要的是,这5000个请求同时到达我的服务器,并且我可以找出服务器的能力。我对bash的要求是
curl 'https://myserver.com/api/order'
-H 'Accept: application/json, text/plain, */*'
--data-binary '{"id":"ID201","financeId":1,"name":name,"family":family,"side":0,"validityType":99}'
答案 0 :(得分:1)
您可能可以使用Grequest基本上将gevent用于您的请求:
import grequests
urls = [
'http://www.heroku.com',
'http://tablib.org',
'http://httpbin.org',
'http://python-requests.org',
'http://kennethreitz.com'
]
rs = (grequests.get(u) for u in urls)
>>> grequests.map(rs)
[<Response [200]>, <Response [200]>, <Response [200]>, <Response [200]>, <Response [200]>]
另一种可行的方法是使用asyncio的事件循环(类似于js), 这种方法可能更现代,并且不使用与其他第三方库不兼容的gevent:
#!/usr/local/bin/python3.5
import asyncio
from aiohttp import ClientSession
async def fetch(url, session):
async with session.get(url) as response:
return await response.read()
async def run(r):
url = "http://localhost:8080/{}"
tasks = []
# Fetch all responses within one Client session,
# keep connection alive for all requests.
async with ClientSession() as session:
for i in range(r):
task = asyncio.ensure_future(fetch(url.format(i), session))
tasks.append(task)
responses = await asyncio.gather(*tasks)
# you now have all response bodies in this variable
print(responses)
def print_responses(result):
print(result)
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(run(4))
loop.run_until_complete(future)
答案 1 :(得分:1)
这类似于Maxim Dunavicher的回答,因为它使用aiohttp
发出异步请求,以便可以同时完成多个请求。与他的方法尝试保持连接开放以在并发请求中重用的方法不同,他没有这样做。但是,当我使用N = 100
在本地Apache服务器上对它的性能进行基准测试时,我发现它大约需要三分之一的时间才能完成,对此我没有很好的解释。
import asyncio
from aiohttp import ClientSession
N = 5000
async def get(url):
async with ClientSession() as session:
async with session.get(url) as response:
return await response.read()
loop = asyncio.get_event_loop()
coroutines = [get(f"http://localhost?x={i}") for i in range(N)]
results = loop.run_until_complete(asyncio.gather(*coroutines))
#print(results)
答案 2 :(得分:0)
对于测试json请求,最好使用ab(Apache基准测试工具)。