api = fastapi.FastAPI()
@api.get('/api/sum')
def caculate(z):
if z == 0 :
return fastapi.Response(content = {'Error' : 'Z must be an integer'},
status_code=400,
media_type="application/json")
return
uvicorn.run(api, host="127.0.0.50", port=8000) #server
我正在尝试返回内容中提到的响应和 400 http 响应。但它给了我一个 200 响应,并且还给了我“null”而不是内容。
最佳答案
如果您希望对象以 json 形式返回或自己序列化数据,则需要为查询参数提供类型并使用 JSONResponse
作为返回json.dumps()
如果您想使用Response
。
def caculate(z: int=0):
if z == 0 :
return fastapi.responses.JSONResponse(content = {'Error' : 'Z must be an integer'},status_code=400)
关于python - fastapi.Response() 不返回自定义响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66076487/