如何在 FastAPI 上个性化响应模型(包括状态代码和 StreamingResponse)?
我希望我的发布请求响应采用这种格式,我正在使用 FastAPI:
{
"message": "",
"status": 200,
"data": {}
}
因此我声明一个类来指定我的响应格式并在 response_model 参数中发送此模型。问题是,在我的例子中,数据键是一个 CSV 文件,这就是为什么在发布请求时我有这个:
@app.post('/some-path', response_model = ResponseBase)
async def some_path():
....
new_df = pd.DataFrame(final_data, columns=header)
stream = io.StringIO()
new_df.to_csv(stream, index=False)
my_data: Response = StreamingResponse(
iter([stream.getvalue()]), media_type="text/csv"
)
return ResponseBase(
message="Some message",
status = status.HTTP_200_OK,
data = my_data
)
响应模型类,应该是这样的:
class ResponseBase(BaseModel):
message: str
status:
data:
但我想知道如何指定状态来自 HTTP 状态代码模块,数据来自StreamingResponse 类。
I want my post request response on this format, I'm using FastAPI:
{
"message": "",
"status": 200,
"data": {}
}
So I declare a class to specify my response format and send this model in the response_model parameter. The thing is that in my case data key is a CSV file that's why on post request I have this:
@app.post('/some-path', response_model = ResponseBase)
async def some_path():
....
new_df = pd.DataFrame(final_data, columns=header)
stream = io.StringIO()
new_df.to_csv(stream, index=False)
my_data: Response = StreamingResponse(
iter([stream.getvalue()]), media_type="text/csv"
)
return ResponseBase(
message="Some message",
status = status.HTTP_200_OK,
data = my_data
)
Response model class, should be something like this:
class ResponseBase(BaseModel):
message: str
status:
data:
But I wonder how to specify that status comes from HTTP status code module and data comes from StreamingResponse class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论