2
\$\begingroup\$

This is the first time I am posting here, so please go easy on me : ).

I am also writing for the first time python code which uses async / await for streaming web-socket information.

My main goal is to:

  1. Connect to a web-socket
  2. Stream info from web-socket
  3. Continuously save the streaming info somewhere (to DB for example).

My main concerns are:

  1. Whether the code below is streaming information from a web-socket correctly - to be clear: the code is working, but I am not 100% certain it's doing what I want it to do, albeit showing results as expected. There's a lot happening under the hood, hence my concern.
  2. Whether it's also closing the connection to the web-socket.
  3. How to wrap a function over it (i.e. the function that save the data somewhere).

If you see other problems with it, please let me know.

msg = {'message': 'subscribe'}

async def stream_websocket_info():
    async with websockets.connect(WEBSOCKET_URL) as websocket:
        await websocket.send(json.dumps(MESSAGE))
        while True:
            print(await websocket.recv())

# This is how I run it:
asyncio.get_event_loop().run_until_complete(stream_websocket_info())
\$\endgroup\$
3
  • \$\begingroup\$ So is this code working? Whether the code below is streaming information from a web-socket correctly seems to allude that it isn't working. \$\endgroup\$ Commented Mar 30, 2020 at 5:36
  • \$\begingroup\$ The code is working and as an event occurs in the server, the client prints it. But since I am doing this for the first time and sine it's a convoluted subject, I wonder whether I am doing this right and what are potential places which may be future technical debt if I can say so. \$\endgroup\$ Commented Mar 30, 2020 at 13:36
  • \$\begingroup\$ I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. The example code that you have posted is not reviewable in this form because it leaves us guessing at your intentions. Unlike Stack Overflow, Code Review needs to look at concrete code in a real context. Please see Why is hypothetical example code off-topic for CR? \$\endgroup\$ Commented Aug 28 at 12:28

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.