在这种情况下,为什么 ws.run_forever() return True 而不是 api 值?

Why does ws.run_forever() return True instead of the api values in this case?

我正在尝试从 binance 获取 BTC-USDT 的 klines 值,但我似乎无法获取正确的值

def on_message(ws, message):
    print("received a message")
    print(json.loads(message))     

def on_close(ws):
    print("closed connection")        

def on_open(ws):
    print("opened")


ws = websocket.WebSocketApp('https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1s', on_open=on_open,on_message=on_message, on_close=on_close)
ws.run_forever()

为什么 ws.run_forever() return True 而不是值?

websocket api 基础 url 是 wss://stream.binance.com:9443,而不是 http/rest api url。这就是为什么你没有从 websocket 收到任何东西。

另外 run_forever() 会在没有 return 任何东西的情况下阻止。您需要的“值”将作为 on_message.

的参数给出
def on_message(ws, message):
     print("received a message:")
     print(json.loads(message))

def on_close(ws):
     print("closed connection")

def on_open(ws):
     print("opened")
    
    
ws = websocket.WebSocketApp('wss://stream.binance.com:9443/ws/btcusdt@kline_1m', on_open=on_open,on_message=on_message, on_close=on_close)
# please check binance document to write the correct stream name
ws.run_forever()

或者,如果您需要一些不是流的信息:

# REST API example

import httpx
resp = httpx.get('https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1m&limit=1')
print(resp.json())