mmyjh86

[러닝-인강] websockets - 데이터의 양이 많지 않을 때

Oct 9th, 2020
765
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import websocket
  2. import json
  3. try:
  4.     import thread
  5. except ImportError:
  6.     import _thread as thread
  7. import time
  8. from pandas import DataFrame
  9.  
  10. dataFromServer = [ ]
  11.  
  12. def on_message(ws, message):
  13.     get_message = json.loads(message.decode('utf-8'))
  14.     dataFromServer.append(get_message)
  15.     print(get_message)
  16.  
  17. def on_error(ws, error):
  18.     print(error)
  19.  
  20. def on_close(ws):
  21.     df = DataFrame(dataFromServer)
  22.     print(df.head())
  23.     print("close")
  24.  
  25. def on_open(ws):
  26.     def run(*args):
  27.         sendData = '[{"ticket":"test"},{"type":"ticker","codes":["KRW-CPT","KRW-ADA"]}]'
  28.         for i in range(3):
  29.             ws.send(sendData)
  30.             time.sleep(1)
  31.         ws.close()
  32.     thread.start_new_thread(run, ())
  33.  
  34. ws = websocket.WebSocketApp("wss://api.upbit.com/websocket/v1",
  35.                               on_message = on_message,
  36.                               on_error = on_error,
  37.                               on_close = on_close)
  38. ws.on_open = on_open
  39. ws.run_forever()
RAW Paste Data