相关疑难解决方法(0)

如何在 Python FastAPI 中记录原始 HTTP 请求/响应?

我们正在使用 Python FastAPI 编写一个 Web 服务,该服务将托管在 Kubernetes 中。出于审计目的,我们需要保存特定路由的request/的原始 JSON 正文。JSON的主体大小约为1MB,最好这不应该影响响应时间。我们怎样才能做到这一点?responserequestresponse

python logging audit-logging python-logging fastapi

25
推荐指数
2
解决办法
3万
查看次数

如何在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
查看次数