既然你已经定义了
from_orm
在模型的配置中,不必使用
from_orm(x)
在你的
get_blobs
视图-仅返回查询结果就足够了。
@router.get("/blobs", response_model=List[BlobBase])
async def get_blobs():
return db.session.query(Blob).all()
还建议使用依赖项来解决问题
db
对于每个异步端点(FastAPI文档中有一个示例),而不是全局
分贝
进入
由于反向URL实际上不是模式本身的属性,我想我应该添加一个复合模式,然后在您的视图中填充它:
class BlobWithUrl(BaseModel):
blob: BaseBlob # Consider using Blob as the name instead - base indicates that it should only be inherited
url: str
@router.get("/blobs", response_model=List[BlobWithUrl])
async def get_blobs(request: Request):
return [
{'url': url_for(...), 'blob': blob}
for blob in db.session.query(Blob).all()
]
另一个选择是使用手动调用的策略
来自
,然后有一个扩展的模式
BlobBase
:
class BlobWithUrl(BaseBlob):
url: Optional[str]
@router.get("/blobs", response_model=List[BlobWithUrl])
async def get_blobs(request: Request):
blobs = []
for retrieved_blob in db.session.query(Blob).all():
blob = BlobWithUrl.from_orm(retrieved_blob)
blob.url = url_for(...)
blobs.append(blob)
return blobs