我想构建一个小型REST API服务器,返回在Binance Exchange WebSocket上监听的最后100笔交易。我使用uvicorn启动应用程序,但返回的json是'{}'。如果我用普通的python命令执行程序,WebSocket的侦听就可以工作,我希望有一个独立的服务器,既响应REST请求,又侦听Binance的websocket。
下面是我的代码:
import websocket
import json
import time
import uvicorn
app = FastAPI()
last_trade = []
def on_message(ws, message):
global last_trade
data = json.loads(message)
if 'e' in data and data['e'] == 'trade':
last_trades += data
if len(last_trade) > LASTS:
last_trade.pop(0)
# print(data)
def on_error(ws, error):
print(error)
def on_close(ws):
print("Connexion fermée")
reconnect()
def on_open(ws):
ws.send(json.dumps({
"method": "SUBSCRIBE",
"params": ["btctusd@trade"],
"id": 1
}))
def reconnect():
delay = 5 # Délai de reconnexion en secondes
print(f"Reconnexion dans {delay} secondes...")
time.sleep(delay)
connect_to_binance_websocket()
def connect_to_binance_websocket():
websocket_url = "wss://stream.binance.com:9443/ws"
ws = websocket.WebSocketApp(websocket_url,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.on_open = on_open
ws.run_forever()
@app.get("/")
async def root():
return json.dumps(last_trade)
LASTS=100
if __name__ == '__main__':
connect_to_binance_websocket()
uvicorn.run(app, host="0.0.0.0", port=8000)
Thanks
字符串
1条答案
按热度按时间n3schb8v1#
您可以在uvicorn启动后需要调用的函数上使用
on_event
装饰器和startup
字符串