首页 > 解决方案 > 如何使用python Websocket-client lib传递令牌以连接Websocket API

问题描述

介绍

我正在尝试使用Websocket API从Indodax交换访问订单簿数据。文档可以在这里找到。. 我正在使用带有websocket-client库的 python 3.9。

问题

根据文档配置所有内容后,它给了我不好的请求。我已经按照this answer中给出的示例在握手期间启用了令牌

--- request header ---
GET /ws/ HTTP/1.1
Upgrade: websocket
Host: ws.indodax.com
Origin: http://ws.indodax.com
Sec-WebSocket-Key: X+jRgd8pM0XefcT1/xwHNQ==
Sec-WebSocket-Version: 13
Connection: Upgrade
extension-token:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiaW5mbyI6eyJuYW1lIjoiUHVibGljIn19.VJAHTrrfwxceSITpuPBl75LVM5bgojKGiUTOwCZxw-k


-----------------------
--- response header ---
HTTP/1.1 101 Switching Protocols
Server: nginx
Date: Wed, 20 Oct 2021 10:41:13 GMT
Connection: upgrade
Upgrade: websocket
Sec-WebSocket-Accept: rI37u4yeNItEuZP5MeqZ254XGuo=
Via: 1.1 google
Alt-Svc: clear
-----------------------
++Sent raw: b'\x81\x8eb\xb2\x18\xc9@\xd0l\xaa\x0b\xd6j\xe7\x16\xc0y\xad\x07\x90'
++Sent decoded: fin=1 opcode=1 data=b'"btcidr.trade"'
thread terminating...
++Rcv raw: b'\x88,\x0b\xbb{"reason":"bad request","reconnect":false}'
++Rcv decoded: fin=1 opcode=8 data=b'\x0b\xbb{"reason":"bad request","reconnect":false}'
++Sent raw: b'\x88\x82\xc3Q K\xc0\xb9'
++Sent decoded: fin=1 opcode=8 data=b'\x03\xe8'
### closed ###

代码

import websocket
import json
import _thread


def on_message(ws, message):
    print(message)

def on_error(ws, error):
    print(error)

def on_close(ws, close_status_code, close_msg):
    print("### closed ###")

def on_open(ws):
    subscribeEvent(ws, "btcidr"+".trade")
    print("thread terminating...")
    _thread.start_new_thread(send_heartbeat, ())x`

def send_heartbeat(*args):
    pass

def subscribeEvent(ws, event, auth_key=''):
    try:
        ws.send(json.dumps(event))
    except Exception as e:
        print(e)

if __name__ == "__main__":
    websocket.enableTrace(True)
    token='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiaW5mbyI6eyJuYW1lIjoiUHVibGljIn19.VJAHTrrfwxceSITpuPBl75LVM5bgojKGiUTOwCZxw-k'
    protocol_str = "extension-token:" + token
    while True:
        ws = websocket.WebSocketApp("wss://ws.indodax.com/ws/",
                                  on_open=on_open,
                                  on_message=on_message,
                                  on_error=on_error,
                                  on_close=on_close,
                                  header = [protocol_str])
        ws.run_forever()

附加信息

我认为问题在于令牌。我的意思是关于我应该如何将令牌传递给服务器的一些格式问题。如果您需要任何其他信息,请告诉我。

标签: pythonwebsocketserverclientcryptocurrency

解决方案


推荐阅读