Azure Signal R 和 Azure Function Python

问题描述

我一直在从事一个项目,我们需要在该项目中集成 Azure Signal R(或任何后端/前端通知系统)。我一直在努力寻找有关其工作原理的文档,但发现推荐的 Python 集成是使用 Azure 函数

我的使用工作流程如下:

  • 在我的 Azure 函数调用 /negociate 以获取新的 connectionId(或设置 userId):
    • 此端点应调用我的后端以检索用户 ID(我未使用内置用户 ID)或发送 connectionId,以便我的后端可以识别用户并与用户建立链接
    • 如果可能,我想将后端令牌与 /negociate 一起传递,但我不知道这是否可行。
  • 连接到 Signal R 并接收通知

您有任何实现此目的的代码示例吗?或解释该过程的特定文档。我发现 Azure 文档非常复杂......我也不确定这是否是 SignalR 的做事方式......

目前,我只有:

import logging
import azure.functions as func

def main(req: func.HttpRequest,connectionInfo: str,context: func.Context) -> func.HttpResponse:
    logging.info(connectionInfo)
    return func.HttpResponse(
        connectionInfo,status_code=200,headers={
            'Content-type': 'application/json'
        }
    )

我希望这个 /negociate 端点这样做:

  • 只有连接到我的后端的用户才能检索到 SignalR 的连接
  • 我的后端可以将用户映射到 SignalR userId 或 connectionId 但是这里的连接信息只有一个令牌和一个端点......

感谢您的帮助!

解决方法

好的, 在这里回答我自己的问题,我们最终做的是这样的:

  • 后端的 GET 方法将调用 /negociate 执行此操作:
def main(req: func.HttpRequest,connectionInfo: str,context: func.Context) -> func.HttpResponse:
    return func.HttpResponse(
        connectionInfo,status_code=200,headers={
            'Content-type': 'application/json'
        }
    )

另一个将管理其他事物的入口点(发送消息/等)。因此 Azure 函数仅由我们的后端与管理员密钥一起使用。 以下是我们使用的函数:

  • 向所有用户发送消息:
def main(req: func.HttpRequest) -> str:
    message = req.get_json()
    return json.dumps({
        'target': 'newMessage','arguments': [ message ]
    })
  • 向特定用户发送消息
def main(req: func.HttpRequest,context: func.Context) -> str:
    message = req.get_json()
    return json.dumps({
        'userId': message['userId'],'target': 'newMessage','arguments': [ message ]
    })
  • 向群组发送消息:
def main(req: func.HttpRequest) -> str:
    message = req.get_json()
    return json.dumps({
        'groupName': message['groupName'],'arguments': [ message ]
    })
  • 将用户添加到群组
def main(req: func.HttpRequest,action: func.Out[str]) -> func.HttpResponse:
    message = req.get_json()
    action.set(json.dumps({
        'userId': message['userId'],'groupName': message['groupName'],'action': 'add'
    }))

绑定可能会发生一些变化,但您可以在此处找到文档: https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-signalr-service