相关疑难解决方法(0)

全局捕获快速 api 中的“异常”

我是非常新的 python 和 fastapi。我正在尝试在全局级别捕获未处理的异常。所以在main.py文件中的某个地方我写在下面:

@app.exception_handler(Exception)
async def exception_callback(request: Request, exc: Exception):
  logger.error(exc.detail)
Run Code Online (Sandbox Code Playgroud)

但上述方法从未执行过。但是如果我编写一个自定义异常并尝试捕获它(如下所示),它运行良好。

class MyException(Exception):
  #some code

@app.exception_handler(MyException)
async def exception_callback(request: Request, exc: MyException):
  logger.error(exc.detail)
Run Code Online (Sandbox Code Playgroud)

我已经完成了Catch 异常类型的 Exception 和 process body request #575。但是这个错误谈论访问请求正文。看到这个bug,感觉应该可以抓到Exception。FastApi 版本fastapi>=0.52.0

提前致谢 :)

exception python-3.x fastapi

13
推荐指数
4
解决办法
9007
查看次数

向最终用户显示 FastAPI 验证错误

我正在寻找一些库或代码示例来将 FastAPI 验证消息格式化为人类可读的格式。例如这个端点:

@app.get("/")
async def hello(name: str):
    return {"hello": name}

Run Code Online (Sandbox Code Playgroud)

如果我们错过name查询参数,将产生下一个 json 输出:

{ 
    "detail":[ 
        { 
            "loc":[ 
                "query",
                "name"
            ],
            "msg":"field required",
            "type":"value_error.missing"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是,如何:

  1. 将其转换为“需要名称字段”(针对各种可能的错误)以显示在吐司中。
  2. 使用它来显示表单验证消息
  3. 如果可能的话,从 api 描述中自己生成表单

python swagger openapi fastapi

7
推荐指数
2
解决办法
2838
查看次数

重写 FastAPI 的 HTTPException 响应正文

我目前正在为 fastAPI 中的 API 编写一些端点。我正在定义扩展 fastapi 的 HTTPException 的类。

问题是 HTTPException 返回一个响应主体,其中包含一个名为“detail”的属性,该属性可以是字符串或 json 结构,具体取决于您传递给它的对象,如下所示。

{
  "detail": {
    "msg": "error message here"
  }
}


{   "detail": "error message here" }
Run Code Online (Sandbox Code Playgroud)

我想覆盖这种行为并让它以我自己的结构做出响应。

我知道我可以使用异常处理程序装饰器安装自定义异常并返回 JSONResponse 对象,但这不是我想要的。

python starlette pydantic fastapi

6
推荐指数
1
解决办法
6702
查看次数

当请求失败并在 FastAPI 中引发 HTTPException 时,如何添加后台任务?

当 FastAPI 端点发生异常时,我尝试使用后台任务生成日志:

from fastapi import BackgroundTasks, FastAPI

app = FastAPI()

def write_notification(message=""):
    with open("log.txt", mode="w") as email_file:
        content = f"{message}"
        email_file.write(content)

@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
    if "hello" in email:
        background_tasks.add_task(write_notification, message="helloworld")
        raise HTTPException(status_code=500, detail="example error")

    background_tasks.add_task(write_notification, message="hello world.")
    return {"message": "Notification sent in the background"}
Run Code Online (Sandbox Code Playgroud)

但是,不会生成日志,因为根据此处此处的文档,后台任务“仅”在return执行语句后运行。

有什么解决方法吗?

python logging starlette fastapi

6
推荐指数
1
解决办法
3953
查看次数

如何在FastAPI中自定义错误响应?

我有以下 FastAPI 后端:

from fastapi import FastAPI

app = FastAPI

class Demo(BaseModel):
    content: str = None
    
@app.post("/demo")
async def demoFunc(d:Demo):
    return d.content
Run Code Online (Sandbox Code Playgroud)

问题是,当我向此 API 发送带有额外数据的请求时,例如:

data = {"content":"some text here"}aaaa
Run Code Online (Sandbox Code Playgroud)

或者

data = {"content":"some text here"aaaaaa}

resp = requests.post(url, json=data)
Run Code Online (Sandbox Code Playgroud)

422 unprocessable entity在以下情况下,它会抛出状态代码错误,返回字段中包含 Actual("some text here") 和 Extra("aaaaa") 数据data = {"content":"some text here"}aaaa

{
  "detail": [
    {
      "loc": [
        "body",
        47
      ],
      "msg": "Extra data: line 4 column 2 (char 47)",
      "type": "value_error.jsondecode",
      "ctx": {
        "msg": "Extra …
Run Code Online (Sandbox Code Playgroud)

python json pydantic fastapi

4
推荐指数
1
解决办法
8721
查看次数

如何使用 FastAPI 返回自定义 404 Not Found 页面?

我正在为 Discord 制作一个 rick roll 网站,我想重定向到404响应状态代码的 rick roll 页面。

我尝试了以下方法,但没有成功:

 @app.exception_handler(fastapi.HTTPException)
 async def http_exception_handler(request, exc):
     ...
Run Code Online (Sandbox Code Playgroud)

python exception http-status-code-404 starlette fastapi

4
推荐指数
1
解决办法
7753
查看次数