不知道如何删除sqlalchemy 1.4关于cache_ok的警告



我将sqlalchemy1.4.17与postgres一起使用,并且有一个pytest-asyncio测试,它调用一个函数来创建包含uuid的记录。


async def create_user(session: AsyncSession, input_user_data):
new_user = model.User(**dict(input_user_data))
session.add(new_user)
await session.commit()
class User(Base):
__tablename__ = "user"
id = Column(GUID, primary_key=True,
server_default=DefaultClause(text("gen_random_uuid()")))

它运行正常,但会产生一个警告

sys:1: SAWarning: TypeDecorator GUID() will not produce a cache key because the ``cache_ok`` flag is not set to True.  Set this flag to True if this type object's state is safe to use in a cache key, or False to disable this warning.

我不知道如何让它沉默。任何帮助都是感激的!

感谢@sakecharmerb。这让我意识到我做错了什么。如果这对其他人有帮助,我从fastapi_utils导入GUID,而不是直接从sqlalchemy 导入

# from fastapi_utils.guid_type import GUID, GUID_SERVER_DEFAULT_POSTGRESQL
from sqlalchemy.dialects.postgresql import UUID
class User(Base):
__tablename__ = "user"
id = Column(UUID, primary_key=True,
server_default=DefaultClause(text("gen_random_uuid()")))

与更改fastapi-utils-lib相比,使用SQL炼金术类型装饰器要容易得多。

如果出于任何原因使用自定义TypeDecorator,例如:

class MyUUIDType(TypeDecorator):
impl = sqlalchemy.dialects.postgresql.UUID

...

然后您需要添加cache_ok = True作为类成员

class MyUUIDType(TypeDecorator):
impl = sqlalchemy.dialects.postgresql.UUID
cache_ok = True    
...

当然,只有当列的TypeDecorator是可缓存的时,才能执行此操作。