如何消除SQLAlchemy 1.4中cache_ok相关的SAWarning警告
解决方案
该警告是SQLAlchemy 1.4版本新增查询缓存机制导致的:GUID作为TypeDecorator子类,默认没有设置cache_ok参数,因此触发警告。由于GUID类型逻辑固定无动态状态,设置cache_ok=True是完全安全的,可通过以下任意一种方式消除警告:
- 方案1:给GUID类型显式开启缓存许可
如果你是自行实现的GUID类型,直接在类定义中添加cache_ok = True属性即可:
class GUID(TypeDecorator): impl = UUID cache_ok = True # 新增这一行 # 原有其他逻辑保持不变
如果GUID是从第三方库导入的,可通过猴子补丁全局设置:
from your_module import GUID GUID.cache_ok = True
- 方案2:直接使用PostgreSQL原生UUID类型
PostgreSQL方言自带的UUID类型已经默认配置了cache_ok=True,直接替换原有GUID即可:
from sqlalchemy.dialects.postgresql import UUID class User(Base): __tablename__ = "user" id = Column(UUID, primary_key=True, server_default=DefaultClause(text("gen_random_uuid()")))
- 方案3:全局过滤对应警告(适合测试场景快速处理)
在项目入口或者pytest的conftest.py中添加过滤规则,屏蔽该类警告:
import warnings from sqlalchemy.exc import SAWarning warnings.filterwarnings( "ignore", category=SAWarning, message=r"TypeDecorator GUID\(\) will not produce a cache key because the ``cache_ok`` flag is not set to True" )
内容的提问来源于stack exchange,提问作者foobar8675
相关产品推荐
相关产品推荐

