Sqlalchemy 选择 AttributeError: 'dict' 对象没有属性

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

我正在构建 fastapi + sqlalchemy 应用程序

我的代码

sql.py

form sqlalchemy import Table, String, BigInteger, MetaData

metadata = MetaData()

custom_datasets = Table(
    "custom_datasets",
    metadata,
    Column("project_id", String(500), primary_key=True),
    Column("id", BigInteger, primary_key=True),
    Column("name", String(500), unique=True),
    Column("path", String(500), unique=True),
    Column("feature_service", String(500), nullable=False),
    Column("last_updated_timestamp", BigInteger, nullable=False),
)


main.py

import os
from sqlalchemy.orm import Session
from sqlalchemy import select

def get_db():
    if os.getenv("REGISTRY_CONNECTION_STRING"):
        db = SessionLocal()
        yield db
    yield None


@app.get("/datasets/")
def get_project_registry(body: Dict[str, Any], db: Session = Depends(get_db)):
    print("XXX_ ", custom_datasets.c) # XXX_  ImmutableColumnCollection(custom_datasets.project_id, custom_datasets.id, 
    stmt = select(custom_datasets).where(
        custom_datasets.c.project_id in body.project_ids
    )
    res = db.execute().all()
    return res

我有一个错误

python3.8/site-packages/feast/feature_server.py", line 469, in get_project_registry
    custom_datasets.c.project_id in body.project_ids
AttributeError: 'dict' object has no attribute 'project_ids'

如何修复错误?

python sqlalchemy
1个回答
0
投票

在Python中,如果你想访问字典中的属性,你需要使用方括号表示法:

@app.get("/datasets/")
def get_project_registry(body: Dict[str, Any], db: Session = Depends(get_db)):
    print("XXX_ ", custom_datasets.c) # XXX_  ImmutableColumnCollection(custom_datasets.project_id, custom_datasets.id, 
    stmt = select(custom_datasets).where(
        custom_datasets.c.project_id in body['project_ids']
    )
    res = db.execute().all()
    return res

当您使用点表示法时,Python 实际上并不查看字典中的键,而是查看字典对象的属性。

© www.soinside.com 2019 - 2024. All rights reserved.