使用Asyncio从Websocket输出变量的更好方法?
我一直在玩Websocket和Asyncio,以获取从BitStamp流出的价格数据。连接到Websocket Feed后,我正在努力返回要在其他功能中使用的数据。我目前使用函数store_data()
作为占位符,以检查返回的价格数据。
我想出了一种相当粗略的方式来存储价格,其中涉及声明全局变量bitstamp_asks
,然后在Websockets 中覆盖循环。
我觉得必须有更好的方法,因此任何帮助都将不胜感激。我的代码如下:
import asyncio
import websockets
import json
bitstamp_asks = []
async def bitstamp_connect():
global bitstamp_asks
uri = "wss://ws.bitstamp.net/"
subscription = {
"event": "bts:subscribe",
"data": {
"channel": "order_book_btcusd"
}
}
async with websockets.connect(uri) as ws:
await ws.send(json.dumps(subscription))
subscription_response = await ws.recv()
print(json.loads(subscription_response)['event'])
while True:
response = await ws.recv()
bitstamp_data = json.loads(response)['data']
bitstamp_asks = float(bitstamp_data['asks'][0][0])
print(bitstamp_asks)
await asyncio.sleep(0.0001)
async def store_data():
while True:
print(f'The stored value is: {bitstamp_asks}')
await asyncio.sleep(0.1)
asyncio.get_event_loop().run_until_complete(asyncio.wait([bitstamp_connect(),store_data()]))
I have been playing around with websockets and asyncio to get price data streamed from Bitstamp. After connecting to the websockets feed I am struggling to return the data I'm receiving for use in another function. I'm currently using the function store_data()
as a placeholder to check the price data being returned.
I have come up with a fairly crude way of storing the price, which involves declaring the global variable bitstamp_asks
and then overwriting it within the websockets while
loop.
I feel there must be a better way, so any help would be really appreciated. My code is below:
import asyncio
import websockets
import json
bitstamp_asks = []
async def bitstamp_connect():
global bitstamp_asks
uri = "wss://ws.bitstamp.net/"
subscription = {
"event": "bts:subscribe",
"data": {
"channel": "order_book_btcusd"
}
}
async with websockets.connect(uri) as ws:
await ws.send(json.dumps(subscription))
subscription_response = await ws.recv()
print(json.loads(subscription_response)['event'])
while True:
response = await ws.recv()
bitstamp_data = json.loads(response)['data']
bitstamp_asks = float(bitstamp_data['asks'][0][0])
print(bitstamp_asks)
await asyncio.sleep(0.0001)
async def store_data():
while True:
print(f'The stored value is: {bitstamp_asks}')
await asyncio.sleep(0.1)
asyncio.get_event_loop().run_until_complete(asyncio.wait([bitstamp_connect(),store_data()]))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
asyncio.queue.queue.queue
在任务之间共享值。例如:You can use
asyncio.Queue
to share values between the tasks. For example: