使用Asyncio从Websocket输出变量的更好方法?

发布于 2025-02-08 11:09:49 字数 1262 浏览 0 评论 0原文

我一直在玩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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清风疏影 2025-02-15 11:09:49

您可以使用 asyncio.queue.queue.queue 在任务之间共享值。例如:

import asyncio
import websockets
import json


q = asyncio.Queue()


async def bitstamp_connect():

    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"])

        last_value = None
        while True:
            response = await ws.recv()
            bitstamp_data = json.loads(response)["data"]
            bitstamp_asks = float(bitstamp_data["asks"][0][0])

            if last_value is None or bitstamp_asks != last_value:
                q.put_nowait(bitstamp_asks)
                last_value = bitstamp_asks


async def store_data():
    while True:
        data = await q.get()
        print(f"The stored value is: {data}")
        q.task_done()


asyncio.get_event_loop().run_until_complete(
    asyncio.wait([bitstamp_connect(), store_data()])
)

You can use asyncio.Queue to share values between the tasks. For example:

import asyncio
import websockets
import json


q = asyncio.Queue()


async def bitstamp_connect():

    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"])

        last_value = None
        while True:
            response = await ws.recv()
            bitstamp_data = json.loads(response)["data"]
            bitstamp_asks = float(bitstamp_data["asks"][0][0])

            if last_value is None or bitstamp_asks != last_value:
                q.put_nowait(bitstamp_asks)
                last_value = bitstamp_asks


async def store_data():
    while True:
        data = await q.get()
        print(f"The stored value is: {data}")
        q.task_done()


asyncio.get_event_loop().run_until_complete(
    asyncio.wait([bitstamp_connect(), store_data()])
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文