在 asyncpg 中禁用缓存

问题描述 投票:0回答:1

我想禁用 asyncpg+postgresql 中的缓存,以便从数据库中获取及时的结果,而不是过时的结果。但是,我遇到了一个不允许我这样做的问题:

RuntimeWarning: coroutine 'AsyncConnection.execution_options' was never awaited
  async with engine.connect().execution_options(compiled_cache=None) \
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

我的代码如下:

...
query = select(CardBase).where(CardBase.user_id==str(message.from_user.id))
current_cards = await retrieve_data_from_db(query, engine)
current_cards = current_cards.fetchone()
...

retrieve_data_from_db:

async def retrieve_data_from_db(query, engine):

""" Connects to the database and returns the results by a given query """

    async with engine.connect().execution_options(compiled_cache=None) \
        as conn:
        try:
            executed_query = await conn.execute(query)
            await conn.commit()
        except SQLAlchemyError as exc:
            print(exc)
            raise
        finally:
            await conn.close()
        return executed_query

一切都在等待,我不明白问题是什么。那么,如何正确使用asyncpg+postgresql编写禁用缓存呢?指定引擎中的缓存大小不会产生任何结果。

engine = create_async_engine(f'postgresql+asyncpg://{username}:{password}'
                   f'@{host}/{database}?prepared_statement_cache_size=0',
                   pool_pre_ping=True,
                   echo=True,
                   )
python postgresql asynchronous caching asyncpg
1个回答
0
投票

要在使用asyncpg时正确禁用sqlachemy中的缓存,您需要在

compiled_cache
中指定
execution_options
选项,尝试修改您的代码;

async with engine.connect() as conn:
    try:
        executed_query = await conn.execution_options(compiled_cache=None).execute(query)
        await conn.commit()
    except SQLAlchemyError as exc:
        print(exc)
        raise
    finally:
        await conn.close()
    return executed_query
© www.soinside.com 2019 - 2024. All rights reserved.