0

我使用的脚本似乎向 API 发送请求太快了。如果请求排队超过 100 次,API 会发送此错误并停止:

{'e': 'error', 'm': 'Queue overflow. Message not filled'}  

发送和接收的脚本部分如下:

while True:
    await socket.__aenter__()
    msg = await socket.recv()
    frame = createframe(msg)
    frame.to_sql(symbol, engine, if_exists="append", index=False)
    print(frame)

从打印帧的时间中可以看出,请求发送得非常快。

    Symbol                    Time     Price
0  BTCUSDT 2021-09-23 21:30:15.009  44663.17
    Symbol                    Time     Price
0  BTCUSDT 2021-09-23 21:30:15.061  44663.17
    Symbol                    Time     Price
0  BTCUSDT 2021-09-23 21:30:15.061  44663.17
    Symbol                    Time     Price
0  BTCUSDT 2021-09-23 21:30:15.133  44663.17
    Symbol                    Time     Price
0  BTCUSDT 2021-09-23 21:30:15.190  44663.17
    Symbol                    Time     Price
0  BTCUSDT 2021-09-23 21:30:15.261  44663.17
    Symbol                    Time     Price
0  BTCUSDT 2021-09-23 21:30:15.261  44663.17

在理想情况下,每秒应该有 1 个请求。但是,该脚本似乎向 API 发出请求。我尝试了 time.sleep() 函数,但似乎无法稳定请求速度。

4

1 回答 1

1

你试过睡觉吗?

import asyncio, time
...
last_request_time = 0.0
while True:
    # Calculate delay from now to the moment of previous request + 1 sec
    # btw, it's Ok to sleep negative delays as well, so we don't need an `if`
    delay = last_request_time + 1.0 - time.monotonic()
    await asyncio.sleep(delay)  # sleep
    last_request_time = time.monotonic()  # write timestamp at the moment of the new request
    await socket.__aenter__()  # That's bad, use `async with` instead 
    msg = await socket.recv()
    
    frame = createframe(msg)
    frame.to_sql(symbol, engine, if_exists="append", index=False)
    print(frame)  # <- That's bad, `print()` is blocking
于 2021-09-23T23:48:13.593 回答