python - 如何在 Python 中使用 aiohttp 或 asyncio 创建并行循环?

标签 python rethinkdb python-asyncio rethinkdb-python aiohttp

我想使用 rethinkdb .changes() 功能向用户推送一些消息。消息应在用户没有任何请求的情况下发送。

我正在将 rethinkdb 与 aiohttp 和 websockets 一起使用。工作原理:

  1. 用户发送消息
  2. 服务器放入rethinkdb
  3. 我需要的是:一个额外的循环使用 rethinkdb .changes 函数向连接的用户发送更新

这是我启动应用程序的方式:

@asyncio.coroutine
def init(loop):
    app = Application(loop=loop)
    app['sockets'] = []
    app['susers'] = []
    app.router.add_route('GET', '/', wshandler)
    handler = app.make_handler()
    srv = yield from loop.create_server(handler, '127.0.0.1', 9080)
    print("Server started at http://127.0.0.1:9080")
    return app, srv, handler

wshandler 中,我有一个循环,它处理传入的消息:

@asyncio.coroutine
def wshandler(request):
    resp = WebSocketResponse()
    if not resp.can_prepare(request):
        return Response(
            body=bytes(json.dumps({"error_code": 401}), 'utf-8'),
            content_type='application/json'
        )
    yield from resp.prepare(request)
    request.app['sockets'].append(resp)
    print('Someone connected')
    while True:
        msg = yield from resp.receive()
        if msg.tp == MsgType.text:
            runCommand(msg, resp, request)
        else:
            break
    request.app['sockets'].remove(resp)
    print('Someone disconnected.')
    return resp

如何创建第二个循环将消息发送到同一个打开的连接池?如何使其成为线程安全的?

最佳答案

一般来说,您应该尝试在运行事件循环时尽可能避免使用线程。

不幸的是,rethinkdb 不支持开箱即用的 asyncio,但它确实支持 Tornado & Twisted构架。 所以,你可以 bridge Tornado 和 asyncio 并使其在不使用线程的情况下工作。

编辑:

正如 Andrew 所指出的,rethinkdb 确实 支持asyncio。在2.1.0之后你大概可以这样做:

rethinkdb.set_loop_type("asyncio")

然后在您的网络处理程序中:

res = await rethinkdb.table(tbl).changes().run(connection)
while await res.fetch_next():
   ...

关于python - 如何在 Python 中使用 aiohttp 或 asyncio 创建并行循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33870603/

相关文章:

python - 比特币安倍代码, "dotdot": "../" * (env ['PATH_INFO' ]. count ('/' ) - 1) 是什么意思?

python - google-cloud-bigquery pgk_resources

RethinkDB:​​Create Index on field in field in nested array(跑大数据场景)

python - 获取 FastAPI 并行处理请求

python - 使用带修饰协程的单个事件循环返回 future 结果

python - 在 PyQt 中,如何使用信号和槽将下拉列表连接到函数?

python - 原始错误是 : DLL load failed while importing _multiarray_umath

rethinkdb - 允许用户仅访问 RethinkDB 表中的特定数据

rethinkdb - 如何在RethinkDB中将getall与orderby一起使用

python - 将元素从一个出队移动到另一个时,C++ 使用两倍的内存