使用WebSocket扩展Flask REST API

彼得·摩恩斯

我目前正在扩展使用Flask-RESTPlus和WebSocket支持创建的现有REST API。这个想法是创建一个兼容Web Thing模型的Web Thing(网关)。用例中的“事物”是动态添加或删除的。

当前设置允许消费者使用对/ thingId / properties / temperature的HTTP GET请求从Thing(例如温度传感器)获取最新值这些值实际上是从Kafka消耗的,并临时存储在Redis中。

现在,我想知道如何扩展此设置,并允许使用者不仅可以轮询最新值,还可以使用WebSocket订阅Thing的属性。我有一个可行的解决方案,其中为每个属性创建“房间”,但这需要两台单独的服务器和端点的重复。

对于REST我有

@app.route('/<thingId>/properties/<propertyId>')
    # get latest datapoint
    return latestDatapoint

对于Flask-SocketIO我有

@socketio.on('join')
def on_join(data):
    username = data['username']
    room = data['room'] # e.g. /thingId/properties/temperature
    join_room(room)
    send(username + ' has entered the room.', room=room)

然后将数据转发到来自Kafka的正确房间。然后在客户端,我需要连接到WebSocket服务器并加入会议室

socket.on('connection', function(socket){
  socket.emit('join', 'some room');
});

此实现有效,但我强烈希望有一个替代工作流,如下图所示,其中客户端连接到REST API中使用的同一终结点,但使用WebSocket协议而不是加入会议室等。 网络事物订阅

您是否知道这是否已经存在或是否可以实施?

米格尔

I have a working solution where I create "Rooms" for each property, but this requires two separate servers and duplication of endpoints.

The Socket.IO server and your HTTP server do not necessarily need to be separate, In all supported configurations you can host HTTP and Socket.IO applications with a single server.

I also don't see the endpoint duplication, but maybe this is because you think of Socket.IO event handlers as endpoints, while in fact they are not. With Socket.IO there is a single endpoint in the HTTP sense, since all Socket.IO traffic travels on a single URL. Your event handlers are just that, functions that are invoked when certain events pop up on the Socket.IO endpoint.

where the client connects to the same endpoint used in the REST API, but with the WebSocket protocol instead of joining rooms etc.

So you want your client to establish a separate WebSocket connection for each thing it wants to watch? That seems a bit resource intensive and not very scalable to me. If the client needs to watch 100 things, then it will have to maintain 100 WebSocket connections. Keep in mind that most browsers cap the number of WebSocket connections they can have open at a time, both per page and globally.

Socket.IO is a higher-level protocol that is built on top of WebSocket and HTTP. If you still prefer to use WebSocket directly, then you can take any of the available open source WebSocket servers and implement your application with that instead of Socket.IO. Here are a few options for Python off the top of my mind:

您将失去Socket.IO提供的一些非常方便的功能:

  • 自动重新连接
  • 通过长轮询自动支持非WebSocket客户端
  • 基于事件的调度
  • 房间数

因此,您需要确保这些不是重要功能,或者可以直接在WebSocket服务器上自己实现它们。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章