Issue
In the code below I'm making two calls to two different APIs. However, instead of running the calls one after the other I would like to run them concurrently. I understand there may be different ways of doing this and I was wondering if there is a prefered way?
import asyncio
import websockets
import json
omsg = {"op": "subscribe", "args": [{"channel": "instruments", "instType": "FUTURES"}]}
dmsg = {"jsonrpc": "2.0", "method": "public/get_index_price", "id": 1, "params": {"index_name": "btc_usd"}}
async def call_oapi(omsg):
async with websockets.connect('wss://wspap.okx.com:8443/ws/v5/public?brokerId=9999') as websocket:
await websocket.send(omsg)
response1 = await websocket.recv()
response2 = await websocket.recv()
print(response1)
print(response2)
async def call_dapi(dmsg):
async with websockets.connect('wss://test.deribit.com/ws/api/v2') as websocket:
await websocket.send(dmsg)
response = await websocket.recv()
print(response)
def run(call_api, msg):
asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))
run(call_dapi, dmsg)
run(call_oapi, omsg)
Solution
Instead of
def run(call_api, msg):
asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))
run(call_dapi, dmsg)
run(call_oapi, omsg)
Use
async def main():
await asyncio.create_task(call_dapi(json.dumps(dmsg)))
await asyncio.create_task(call_oapi(json.dumps(omsg)))
asyncio.run(main())
You can do something similar with asyncio.gather
but it is not the same. I think you want the above code.
- ref: https://docs.python.org/3/library/asyncio-task.html#running-an-asyncio-program
- ref: https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task
- ref: https://docs.python.org/3/library/asyncio-task.html#asyncio.gather
Answered By - amirouche
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.