Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

python - Alternative to using global variables in WebSockets

I'm new to python and coding in general, but it seems to me like the use of global variables is generally speaking a result of bad code design, especially when it comes to speed/performance. However I can't seem to figure out a way to avoid using global variables with WebSockets. I've looked into using classes and definitions as alternatives but I haven't been able to get them to work with WebSockets.


Using the example below, without setting action_1_performed as global, print('Action 1 performed') will repeat as the WebSocket data will continuously trigger this action so long as it conforms to action_1.

Any help would be much appreciated by this novice coder!

import websockets

action_1_performed = False

def on_message(websocket, message): 
  global action_1_performed

  data = json.loads(message)[0]
  action_1 = (calculation using data)
  action_2 = (calculation using data)

  if not action_1_performed and action_1:
    action_1_performed = True
    print('Action 1')

  if action_1_performed and action_2:
    action_1_performed = False
    print('Action 2')

websocket = websocket.WebSocketApp('URL', on_message = on_message)
websocket.run_forever()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...