I am trying to develop a short script that connects to a real-time stock data provider through a websocket API, gets some data, makes some calculations, stores the results in a database and stops.
EDIT: I need to keep the connection alive for a few seconds until I get all required data. Thus, breaking the connection after the first message is not an option.
The problem I am facing is how to stop the run_forever()
connection.
This is what I have so far:
import websocket
import json
def on_open(ws):
channel_data = {
"action": "subscribe",
"symbols": "ETH-USD,BTC-USD"
}
ws.send(json.dumps(channel_data))
def on_message(ws, message):
# Do some stuff (store messages for a few seconds)
print(message)
def on_close(ws):
print("Close connection")
socket = "wss://ws.url"
ws = websocket.WebSocketApp(socket, on_open=on_open, on_message=on_message)
ws.run_forever()
ws.close()
# Once the connection is closed, continue with the program
I do not want to stay connected after the "Do some stuff" is executed, how can I force the connection close?
Your help is much appreciated.
CodePudding user response:
I managed how to solve this. I leave my solution in case it is useful to someone.
I just added some attributes to the ws
object that allows me to track the number of messages received and store them into a list to work with once the connection is closed.
import websocket
import json
def on_open(ws):
channel_data = {
"action": "subscribe",
"symbols": "ETH-USD,BTC-USD"
}
ws.send(json.dumps(channel_data))
def on_message(ws, message):
ws.messages_count =1
ws.messages_storage.append(message)
if ws.messages_count>50:
ws.close()
def on_close(ws):
print("Close connection")
socket = "wss://ws.url"
ws = websocket.WebSocketApp(socket, on_open=on_open, on_message=on_message)
# Create a counter and an empty list to store messages
ws.messages_count = 0
ws.messages_storage = []
# Run connection
ws.run_forever()
# Close connection
ws.close()
# Continue with the program
CodePudding user response:
My quick tip or suggestion would be to use break function once the task has been performed and you want to get out of it , and as you have mentioned you want to do the same when the task is executed , this should do it , what I think .
Else if it doesn't work , you can reply