我是非常新的 python 和 fastapi。我正在尝试在全局级别捕获未处理的异常。所以在main.py文件中的某个地方我写在下面:
@app.exception_handler(Exception)
async def exception_callback(request: Request, exc: Exception):
  logger.error(exc.detail)
但上述方法从未执行过。但是如果我编写一个自定义异常并尝试捕获它(如下所示),它运行良好。
class MyException(Exception):
  #some code
@app.exception_handler(MyException)
async def exception_callback(request: Request, exc: MyException):
  logger.error(exc.detail)
我已经完成了Catch 异常类型的 Exception 和 process body request #575。但是这个错误谈论访问请求正文。看到这个bug,感觉应该可以抓到Exception。FastApi 版本fastapi>=0.52.0。
提前致谢 :)
我正在寻找一些库或代码示例来将 FastAPI 验证消息格式化为人类可读的格式。例如这个端点:
@app.get("/")
async def hello(name: str):
    return {"hello": name}
如果我们错过name查询参数,将产生下一个 json 输出:
{ 
    "detail":[ 
        { 
            "loc":[ 
                "query",
                "name"
            ],
            "msg":"field required",
            "type":"value_error.missing"
        }
    ]
}
所以我的问题是,如何:
我目前正在为 fastAPI 中的 API 编写一些端点。我正在定义扩展 fastapi 的 HTTPException 的类。
问题是 HTTPException 返回一个响应主体,其中包含一个名为“detail”的属性,该属性可以是字符串或 json 结构,具体取决于您传递给它的对象,如下所示。
{
  "detail": {
    "msg": "error message here"
  }
}
{   "detail": "error message here" }
我想覆盖这种行为并让它以我自己的结构做出响应。
我知道我可以使用异常处理程序装饰器安装自定义异常并返回 JSONResponse 对象,但这不是我想要的。
当 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"}
但是,不会生成日志,因为根据此处和此处的文档,后台任务“仅”在return执行语句后运行。
有什么解决方法吗?
我有以下 FastAPI 后端:
from fastapi import FastAPI
app = FastAPI
class Demo(BaseModel):
    content: str = None
    
@app.post("/demo")
async def demoFunc(d:Demo):
    return d.content
问题是,当我向此 API 发送带有额外数据的请求时,例如:
data = {"content":"some text here"}aaaa
或者
data = {"content":"some text here"aaaaaa}
resp = requests.post(url, json=data)
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 …我正在为 Discord 制作一个 rick roll 网站,我想重定向到404响应状态代码的 rick roll 页面。
我尝试了以下方法,但没有成功:
 @app.exception_handler(fastapi.HTTPException)
 async def http_exception_handler(request, exc):
     ...