【发布时间】:2019-11-21 14:47:23
【问题描述】:
我试图在一个脚本中运行 2 个不同的代码。我可以让它们分开工作,但我很难让它们一起工作。
第一个是:
import asyncio
import websockets
import json
msg = \
{
"jsonrpc" : "2.0",
"id" : 9929,
"method" : "public/auth",
"params" : {
"grant_type" : "client_credentials",
"client_id" : "xxxxxxxxxxxxxxxxxx",
"client_secret" : "xxxxxxxxxxxxxxxxx"
}
}
async def call_api(msg):
async with websockets.connect('wss://testapp.deribit.com/ws/api/v2') as websocket:
await websocket.send(msg)
while websocket.open:
response = await websocket.recv()
# do something with the response...
print(response)
asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))
第二个是:
import asyncio
import websockets
import json
# To subscribe to this channel:
msg = \
{"jsonrpc": "2.0",
"method": "public/subscribe",
"id": 42,
"params": {
"channels": ["ticker.BTC-PERPETUAL.raw"]}
}
async def call_api(msg):
async with websockets.connect('wss://testapp.deribit.com/ws/api/v2') as websocket:
await websocket.send(msg)
while websocket.open:
response = await websocket.recv()
# do something with the notifications...
print(response)
asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))
我曾尝试将它们组合在 1 个脚本中,如下所示:
import asyncio
import websockets
import json
# To subscribe to this channel:
msg = \
{"jsonrpc": "2.0",
"method": "public/subscribe",
"id": 42,
"params": {
"channels": ["ticker.BTC-PERPETUAL.raw"]}
}
msg1 = \
{
"jsonrpc" : "2.0",
"id" : 9929,
"method" : "public/auth",
"params" : {
"grant_type" : "client_credentials",
"client_id" : "xxxxxxxxxxxxxxxxx",
"client_secret" : "xxxxxxxxxxxxxxxxxxxxxxxxx"
}
}
async def call_api1():
async with websockets.connect('wss://testapp.deribit.com/ws/api/v2') as websocket:
await websocket.send(msg)
await websocket.send(msg1)
while websocket.open:
response = await websocket.recv()
# do something with the response...
print(response)
#access_token=response['access_token']
#print(access_token)
asyncio.get_event_loop().run_until_complete(call_api1())
我如何得到一个错误说 websockets.exceptions.InvalidStatusCode: server denied WebSocket connection: HTTP 502.
我想我在最后一行 asyncio.get_event_loop().run_until_complete(call_api1()) 上搞砸了。请注意,我已经读到我需要从同一个 websocket 进行两个订阅,因为 API 一次只允许 1 个。
感谢任何帮助,因为我还是新手。
【问题讨论】:
标签: python json websocket python-asyncio