如何为整个班级定义异步客户端?

发布于 2025-02-12 03:23:49 字数 1858 浏览 0 评论 0原文

嗨,我只能仅一次定义ASYNC客户端对象 - 与服务器的一个连接,然后使用它,但是我不知道如何定义该类别的clobal for类。我只是猜想在每次使用之前都建立一个新连接,但是当然会浪费额外的时间。任何报价都会很高兴。库: https://pypi.org/project/project/project/python-binance/

工作代码:

import asyncio
from binance import AsyncClient

class Binance:
    async def get_trades(self):
        client = await AsyncClient.create() # define two times(two connections) need only one
        aggregate_trades = await client.get_all_tickers()
        print(aggregate_trades)
        await client.close_connection()

    async def exchange_info(self):
        client = await AsyncClient.create() # define two times(two connections) need only one
        exchange_info = await client.get_exchange_info()
        print(exchange_info)
        await client.close_connection()

async def main():
    b = Binance()
    await asyncio.gather(b.get_trades(), b.exchange_info())
 
if __name__ == "__main__":
    asyncio.run(main())

应该是(但不工作):

import asyncio
from binance import AsyncClient

class Binance:
    def __init__(self):
        asyncio.run(self.async_init())

    async def async_init(self):
        self.client = await AsyncClient.create() # define only one time because use much time

    async def get_trades(self):
        aggregate_trades = await self.client.get_all_tickers()
        print(aggregate_trades)

    async def exchange_info(self):
        exchange_info = await self.client.get_exchange_info()
        print(exchange_info)

async def main():
    b = Binance()
    await asyncio.gather(b.get_trades(), b.exchange_info())
 
if __name__ == "__main__":
    asyncio.run(main())

upd:错误: runtimeerror:asyncio.run()无法从运行事件循环中调用 系统:1:Runtime Warning:Coroutine'Binance.async_init'从未等待过

Hi I can define async client object only one time - one connection to server and then working with it, but I coudn't undestand how to define this client global for class. I just guessed to create a new connection before each use, but of course that wastes extra time. Will be glad for any offers. Library: https://pypi.org/project/python-binance/

Working code:

import asyncio
from binance import AsyncClient

class Binance:
    async def get_trades(self):
        client = await AsyncClient.create() # define two times(two connections) need only one
        aggregate_trades = await client.get_all_tickers()
        print(aggregate_trades)
        await client.close_connection()

    async def exchange_info(self):
        client = await AsyncClient.create() # define two times(two connections) need only one
        exchange_info = await client.get_exchange_info()
        print(exchange_info)
        await client.close_connection()

async def main():
    b = Binance()
    await asyncio.gather(b.get_trades(), b.exchange_info())
 
if __name__ == "__main__":
    asyncio.run(main())

Should be(but not working):

import asyncio
from binance import AsyncClient

class Binance:
    def __init__(self):
        asyncio.run(self.async_init())

    async def async_init(self):
        self.client = await AsyncClient.create() # define only one time because use much time

    async def get_trades(self):
        aggregate_trades = await self.client.get_all_tickers()
        print(aggregate_trades)

    async def exchange_info(self):
        exchange_info = await self.client.get_exchange_info()
        print(exchange_info)

async def main():
    b = Binance()
    await asyncio.gather(b.get_trades(), b.exchange_info())
 
if __name__ == "__main__":
    asyncio.run(main())

UPD: Error:
RuntimeError: asyncio.run() cannot be called from a running event loop
sys:1: RuntimeWarning: coroutine 'Binance.async_init' was never awaited

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

神也荒唐 2025-02-19 03:23:49

Asyncio不支持从异步代码转变为同步代码回异步代码。这就是为什么您

无法从运行事件循环获得runtimeerror:asyncio.run(),

您可以通过几种方法来解决此问题。您可以

async def main():
    b = Binance()
    await b.async_init()

根据async_init的实际工作来调用async_init外部,这可能是最简单的方法。 我会自己为客户提供

class Binance:
    def __init__(self, client):
        self.client = client

async def main():
    client = await AsyncClient.create()
    b = Binance(client=client)

另一个选择是如果您没有太多的事情要传递, ,我更喜欢这种方法。它使clientbinance实例之外可重复使用,并且通常可以使binance类通过提供伪造的客户端实例来更容易测试。

asyncio doesn't support moving from asynchronous code to synchronous code back to asynchronous code. That is why you're getting

RuntimeError: asyncio.run() cannot be called from a running event loop

There are a couple of ways you can address this. You can call async_init externally

async def main():
    b = Binance()
    await b.async_init()

Depending on how much work actually needs to be done by async_init, this could be the simplest approach. The other option is to provide the client yourself

class Binance:
    def __init__(self, client):
        self.client = client

async def main():
    client = await AsyncClient.create()
    b = Binance(client=client)

If you don't have too many things to pass in, I like this approach better. It makes client reusable outside of the Binance instance and it can often make it easier to test the Binance class by providing a fake client instance.

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