Let's assume I have a simple file storage in the database. The SQLAlchemy model looks like this:
class Blob(Base):
id = Column(Integer, primary_key=True)
blob = deferred(Column(LargeBinary().with_variant(LONGBLOB, "mysql")))
The respective Pydantic model looks like this:
class BlobBase(sqlalchemy_to_pydantic(Blob, exclude=["blob"])):
class Config:
orm_mode = True
There is also a FastAPI route intented for fetching single files by ID:
@router.get("/blob/{blob_id}")
async def get_blob(blob_id: str):
[...]
And a route for fetching a list of all files:
@router.get("/blobs", response_model=List[BlobBase])
async def get_blobs():
return [BlobBase.from_orm(x) for x in db.session.query(Blob).all()]
Now, I would like to include the resolved get_blob
URL in each entry in get_blobs
. Naively, I suppose this should look like this:
class BlobBase(sqlalchemy_to_pydantic(Blob, exclude=["blob"])):
class Config:
orm_mode = True
url: Optional[str]
@validator("url")
def make_url(cls, v, values):
return request.url_for("get_blob", blob_id=values["id"])
However, I do not have access to a request
or an app
object in the validator, so that I cannot properly resolve the URL. NB: I do have access to the router
object, which is an APIRouter
for the current sub-URL, but get_blob
in the actual application is in a different APIRouter
, so I can't use that without jamming everything in a single file.
What is the correct way to solve this, i.e. include a resolved URL in model's output?