我怎样才能只定义一次异步客户端 - 一个与服务器的连接然后使用它,但我不知道如何将此客户端定义为类的全局。我只是猜测在每次使用之前创建一个新连接,但这当然是浪费时间。布德欢迎任何建议。图书馆:https ://pypi.org/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())