【发布时间】:2022-12-18 12:30:12
【问题描述】:
在这里我们可以声明调用端点时应该向客户端发送什么状态码:
@router.post("/", status_code=status.HTTP_201_CREATED)
我在响应主体中遇到的问题我必须返回一些东西,无论是 JSONResponse 还是 PlainTextResponse 我想知道是否可以不返回路由器主体中的任何内容,而是为任何状态代码定义默认行为和响应,例如这例如:
@router.post("/", status_code=status.HTTP_201_CREATED)
async def create_post(req: post_schemas.Post):
# create the post record
# I wanna get rid of this part and do this automatically in a way
return PlainTextResponse(status_code=status.HTTP_201_CREATED, content="Created")
并且客户端收到“已创建”消息而不是空消息
编辑这是我想出的
responses = {200: "OK", 201: "Created"}
@app.middleware("http")
async def no_response_middleware(request: Request, call_next):
response = await call_next(request)
if (
response.status_code in responses
and int(response.headers["content-length"]) == 4
):
return PlainTextResponse(
status_code=response.status_code, content=responses.get(response.status_code)
)
return response
【问题讨论】: