I’m trying to write some concurrent Python.
In my app below, I’m trying to subscribe to a websocket feed, but then continue through the app, so this code should just print hello
. Instead, it blocks on feed.__init__
.
I’m hoping I can build a websocket client to some update some application state.
How do I do feed.__init__
and continue running my program, while the websocket runs in the background?
def main():
myFeed = feed('XBTUSD')
while True:
"hello"
import websockets
import asyncio
import json
class feed:
def __init__(self, symbol):
self.symbol = symbol
self.uri = "wss://www.bitmex.com/realtime?subscribe=instrument,quote:{}".format(symbol)
asyncio.get_event_loop().run_until_complete(self.socket())
# asyncio.get_event_loop().run_forever()
async def socket(self):
async with websockets.connect(self.uri) as websocket:
while True:
msg = await websocket.recv()
self.process_msg(json.loads(msg))
def process_msg(self, msg):
try:
data = msg['data'][0]
if data['symbol'] == self.symbol:
self.last_message = msg
except:
print("Unhandled")
Go to Source
Author: cjm2671