Я пробовал ограничить количество транзакций в секунду до 2, но я не уверен, как Azure устанавливает эти ограничения, поскольку я все еще получаю слишком много ошибок вызова API
Для ограничение скорости транзакций - 2 транзакции в секунду.
- Я пробовал использовать многопоточные вызовы API, проверяя при этом время между запуском каждого потока. за определенное время я смог получить результаты без ошибок, поскольку задержка между запуском потока установлена на 600 мс, но иногда это не удается, когда запускается большее количество потоков.
- Я пробовал асинхронные API с ограничением количества звонков в течение секунды до лимита с помощью этого кода.
Код: Выделить всё
import asyncio
import aiohttp
import time,glob
from aiolimiter import AsyncLimiter
import json ,requests,time
from datetime import datetime ,timezone
with open('Config.json','r') as f:
data=json.load(f)
headers = {
'Content-Type': 'application/octet-stream',
'Prediction-Key': data['customvisionPredict_key']
}
url=data['customvision_predict_image']
# Create a rate limiter with a maximum of 5 requests per second
rate_limiter = AsyncLimiter(max_rate=2, time_period=1)
async def upload( data):
async with rate_limiter:
current_time = datetime.now(timezone.utc).timestamp()
async with aiohttp.request('POST', url, data=data, headers=headers) as response:
return await response.json(), current_time
async def demonstrate_throughput():
n=20
files = glob.glob("Input/*.png")[:n]
start_time = time.monotonic()
tasks=[]
for file in files:
with open(file,'rb') as f:
data=f.read()
tasks.append(upload(data))
responses = await asyncio.gather(*tasks)
end_time=time.monotonic()
times=[]
failurecount=0
for result,current_time in sorted(responses,key=lambda x:x[1]):
timecount=0
for t in times:
if t>=current_time-1:
timecount+=1
times.append(current_time)
if 'error' in result:
failurecount+=1
print(times[-1],timecount,times[-1]-times[-2] if len(times)>1 else 0,'error')
else:
print(times[-1],timecount,times[-1]-times[-2] if len(times)>1 else 0)
print("failurecount:",failurecount,'out of ',len(responses))
return end_time - start_time
if __name__== "__main__":
execution_time = asyncio.run(demonstrate_throughput())
print(f"Total execution time: {execution_time:.2f} seconds")
`1735958486.4236 0 0
1735958486.424062 1 0.0004620552062988281
1735958486.925118 2 0.5010559558868408 ошибка
1735958487.424466 1 0.4993479251861572 ошибка
1735958487.92597 1 0.5015041828155518
1735958488.424549 1 0.4985790252685547
1735958488.924499 2 0.49994993209838867 ошибка
1735958489.425684 1 0.5011849403381348
1735958489.924275 2 0.49859094619750977
1735958490.425021 2 0.5007460117340088
1735958490.924875 1 0.49985408782958984 ошибка
1735958491.425195 1 0.5003199577331543
1735958491.924389 2 0.4991939067840576
1735958492.424755 2 0.5003662109375 ошибка
1735958492.924596 1 0.49984097480773926
1735958493.424598 2 0.5000019073486328
1735958493.924703 1 0.5001049041748047 ошибка
1735958494.424771 1 0.500068187713623
1735958494.925141 1 0.5003700256347656
1735958495.424439 2 0.4992978572845459 ошибка
количество неудач: 7 из 20
Подробнее здесь: https://stackoverflow.com/questions/793 ... ver-the-tr
Мобильная версия