我正在构建 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),
)
主程序
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'
如何修复错误?
更新:
过滤对请求不起作用
GET http://127.0.0.1:8009/datasets
{
"project_ids": ["proj_id1"]
}
表格如下所示:
testdb=# SELECT * FROM custom_datasets;
project_id | id | name | path | feature_service | last_updated_timestamp
------------+----+-------+-----------+-----------------+------------------------
proj_id1 | 1 | name1 | path/path | service_name | 1
更新代码
@app.get("/datasets/")
def get_project_registry(body: Dict[str, Any], db: Session = Depends(get_db)):
print("XXX_ ", body['project_ids']) # prints XXX_ ['proj_id1']
stmt = select(custom_datasets).where(
custom_datasets.c.project_id in body['project_ids']
)
#stmt = select(custom_datasets)
res = db.execute(stmt).all()
return res
在 python 中,如果要访问字典中的值,则需要使用方括号表示法:
当您使用点符号时,python 实际上并不会查看字典中的键,而是查看字典对象的属性。
过滤
where ... in
不起作用,因为您不能in
在 SQLAlchemy 语句中直接使用select
。SQLAlchemy.in_
为此提供了一种方法: