python - fastapi.Response() 不返回自定义响应

标签 python api http fastapi

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”而不是内容。

output

最佳答案

如果您希望对象以 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/

相关文章:

python - Django 模板每次返回 True 时都会刺痛比较

python - 如何在字段中的最后一个逗号之后获取字符串

api - drupal Bootstrap 脚本 : how to get list of all nodes of type x?

api - Instagram API 如何获取用户发表的评论?

r - 如何正确发起 POST 请求

python - 无 M2Crypto 的非分离 PKCS#7 SHA1+RSA 签名

python - 将 .SVG 图像放入 tkinter Frame

Python程序跨计算机操作netflix同时同步视频

javascript - 防止下载错误文件时出现空白页

http - 在 GET 请求中发送用户电子邮件是否安全?