Python 3.12 中的 SignalR 客户端存在问题 -“AuthHubConnection”对象缺少“connection_id”

问题描述 投票:0回答:1

Stack Overflow 社区您好,

我目前正在为一个需要使用 API 建立订阅的项目将 SignalR 集成到 Python 3.12 中。我使用 signalrcore 库来实现 SignalR 客户端。但是,我遇到了一个问题,“AuthHubConnection”对象似乎缺少“connection_id”属性,这对我的应用程序至关重要。

这是我的代码的相关部分:

import logging
import traceback
from signalrcore.hub_connection_builder import HubConnectionBuilder

logger = logging.getLogger(__name__)

def establish_signalr_connection(api_url, token):
    global connection
    if not token:
        logger.error("No valid token available for SignalR connection.")
        return None

    try:
        logger.info("Attempting to establish SignalR connection...")
        connection = HubConnectionBuilder()\
            .with_url(api_url + "/signalr", options={"access_token_factory": lambda: token})\
            .configure_logging(logging.DEBUG)\
            .with_automatic_reconnect()\
            .build()

        connection.start()
        logger.info("SignalR connection started, checking for connection_id...")
        if hasattr(connection, "connection_id"):
            logger.info(f"Connection ID: {connection.connection_id}")
        else:
            logger.warning("Connection established but no 'connection_id' attribute found.")
        return connection
    except Exception as e:
        logger.error(f"Error establishing SignalR connection: {e}")
        logger.error(traceback.format_exc())
        return None

当我运行此代码时,我收到以下日志:

2023-12-21 11:06:11,349 - INFO - Authenticated successfully
2023-12-21 11:06:11,349 - INFO - Attempting to establish SignalR connection...
2023-12-21 11:06:11,783 - INFO - Heartbeat refreshed successfully
2023-12-21 11:06:11,789 - INFO - SignalR connection started, checking for connection_id...
2023-12-21 11:06:11,789 - WARNING - Connection established but no 'connection_id' attribute found.
2023-12-21 11:06:11,789 - INFO - SignalR connection established.
2023-12-21 11:06:11,789 - ERROR - Error subscribing to values: 'AuthHubConnection' object has no attribute 'connection_id'
2023-12-21 11:06:11,789 - INFO - Subscribed to values with request ID: None

我非常感谢有关如何解决此问题的任何见解或建议。具体来说,我正在寻找以下方面的指导:

  1. 为什么“AuthHubConnection”对象中可能缺少“connection_id”属性。
  2. 成功建立 SignalR 连接并订阅值的任何潜在修复或解决方法。

谢谢大家!

根据 SignalR 文档,我预计一旦建立连接,我将能够检索 connection_id 以继续订阅。

python authentication signalr subscription signalrcore
1个回答
0
投票

您可以参考我的代码来获取

connection_Id

import logging
from signalrcore.hub_connection_builder import HubConnectionBuilder
import asyncio
import urllib.parse as parse

class SignalRClient:
    def __init__(self):
        self.hub_connection = None
        self.connection_id = None
        self.connected = False
        self.logger = logging.getLogger("SignalRClient")

    def configure_logging(self):
        logging.basicConfig(level=logging.DEBUG)

    def on_open(self):
        self.connected = True
        try:
            connection_id = parse.parse_qs(parse.urlparse(self.hub_connection.transport.url).query)['id'][0]
            self.connection_id = connection_id
            self.logger.info(f"Connected with connection ID: {self.connection_id}")
        except Exception as e:
            self.logger.error(f"Error retrieving connection ID: {e}")
        
        self.hub_connection.send("SendGemstoneDetailMessage", [["aa"]])

    def on_close(self):
        self.connected = False
        self.logger.info("Connection closed")

    def on_error(self, data):
        self.logger.error(f"An exception was thrown: {data.error}")

    def connect(self):
        self.configure_logging()
        try:
            self.hub_connection = HubConnectionBuilder() \
                .with_automatic_reconnect({
                    "type": "raw",
                    "keep_alive_interval": 10,
                    "reconnect_interval": 5,
                    "max_attempts": 5
                }) \
                .with_url("https://localhost:7262/mainHub?uid=jason&sid=test&api-key=112233", options={"verify_ssl": False}) \
                .build()

            self.hub_connection.on("ReceiveMessage", self.receive_message)
            self.hub_connection.on_open(self.on_open)
            self.hub_connection.on_close(self.on_close)
            self.hub_connection.on_error(self.on_error)

            self.hub_connection.start()
        except Exception as e:
            self.logger.error(f"Failed to connect to the server: {e}")

    def receive_message(self, *args, **kwargs):
        self.logger.info(f"Message received: {args}")

    async def listen_forever(self):
        while True:
            if not self.connected:
                self.logger.warning("Disconnected, attempting to reconnect...")
                self.connect()
            await asyncio.sleep(1)

async def main():
    signalr_client = SignalRClient()
    signalr_client.connect()
    await signalr_client.listen_forever()

if __name__ == "__main__":
    asyncio.run(main())
© www.soinside.com 2019 - 2024. All rights reserved.