等待数据库将来完成?

时间:2018-09-26 21:53:20

标签: python-3.x async-await python-asyncio sanic

我已经为sanic应用程序编写了代码,rethinkdb被用作后端数据库。我想等待rethinkdb连接功能初始化,然后再执行其他功能,因为它们依赖于rethinkdb连接。

我的rethinkdb连接初始化函数是:

async def open_connections(app):
   logger.warning('opening database connection')
   r.set_loop_type('asyncio')
   connection= await r.connect(
       port=app.config.DATABASE["port"],
       host=app.config.DATABASE["ip"],
       db=app.config.DATABASE["dbname"],
       user=app.config.DATABASE["user"],
       password=app.config.DATABASE["password"])
   print (f"connection established {connection}")
   return connection

将来解决后将执行的回调函数是

def db_callback(future):
        exc = future.exception()
        if exc:
            # Handle wonderful empty TimeoutError exception
            logger.error(f"From mnemonic api isnt working with error {exc}")
            sys.exit(1)

        result = future.result()
        return result

sanic应用程序:

def main():
        app = Sanic(__name__)
        load_config(app)
        zmq = ZMQEventLoop()
        asyncio.set_event_loop(zmq)
        server = app.create_server(
            host=app.config.HOST, port=app.config.PORT, debug=app.config.DEBUG, access_log=True)
        loop = asyncio.get_event_loop()

        ##not wait for the server to strat, this will return a future object
        asyncio.ensure_future(server)

        ##not wait for the rethinkdb connection to initialize, this will return
        ##a future object
        future = asyncio.ensure_future(open_connections(app))
        result = future.add_done_callback(db_callback)
        logger.debug(result)

        future = asyncio.ensure_future(insert_mstr_account(app))
        future.add_done_callback(insert_mstr_acc_callback)


        future = asyncio.ensure_future(check_master_accounts(app))
        future.add_done_callback(callbk_check_master_accounts)

        signal(SIGINT, lambda s, f: loop.close())


        try:
            loop.run_forever()
        except KeyboardInterrupt:
            close_connections(app)
            loop.stop()

当我启动此应用程序时,open_connections函数中的print语句将在最后执行。

1 个答案:

答案 0 :(得分:1)

future = asyncio.ensure_future(open_connections(app))
result = future.add_done_callback(db_callback)

ensure_future同时安排协同程序

add_done_callback不等待将来的完成,而只是在将来完成之后安排函数调用。您可以看到它here

因此,您应该在执行其他功能之前明确await open_connections的未来:

future = asyncio.ensure_future(open_connections(app))
future.add_done_callback(db_callback)
result = await future

已编辑:以上答案仅适用于协程

在这种情况下,我们要等待功能主体中future的完成。为此,我们应该使用loop.run_until_complete

def main():
    ...
    future = asyncio.ensure_future(open_connections(app))
    future.add_done_callback(db_callback)
    result = loop.run_until_complete(future)