当WebSocket客户端在RethinkDB的.Changes feed

时间:2019-05-30 14:48:31

标签: python asynchronous websocket rethinkdb

我正在RethinkDB上运行实时.changes()提要,并使用Sanic WebSocket流式传输更改。

由于无法保证.changes()提要何时关闭,因此我希望能够在WS Client断开连接后关闭连接。 在下面的代码中,我尝试使用装饰器建立和关闭连接,但似乎执行从未达到conn.close()

有其他方法吗?

from sanic import Sanic
from sanic.websocket import WebSocketProtocol
import json
import asyncio
from rethinkdb import RethinkDB
r = RethinkDB()
r.set_loop_type('asyncio')

app = Sanic()

def closeDBDecorator(func):
    async def wrapper(request, ws, *args, **kwargs):
        conn = await r.connect(host="localhost", user="admin", db="test")
        await func(request, ws, conn)
        conn.close()
    return wrapper


@app.websocket('/status')
@closeDBDecorator
async def status(request, ws, conn):
    data = await ws.recv()
    data = json.loads(data)
    status_table = r.db("x").table("y")
    cursor = await status_table.get(data["id"]).changes().run(conn) # Changes cursor
    async for update in cursor:
        await ws.send(json.dumps(dict(update)))


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8080, workers=1, protocol=WebSocketProtocol)

0 个答案:

没有答案