FastAPI 服务器返回“422 无法处理的实体”- value_error.missing

问题描述 投票:0回答:1
from http.client import responses
from random import randrange
from tkinter.tix import STATUS
from typing import Optional
from urllib import response
from fastapi import Body, FastAPI, Response ,status, HTTPException
from pydantic import BaseModel

app= FastAPI()

class Post(BaseModel):
    title: str
    content: str
    Published: bool = True
    rating: Optional[int] = None

my_post = [{"title": "title of post 1", "content": "content of post 1", "id": 2},{"title": "title of post 2","content":"content of post 2", "id":3}]

def find_post(id):
    for p in my_post:
        if p["id"] == id:
         return p

def find_index_post(id):
    for i,p in enumerate(my_post):
        if p["id"]== id:

            return i 



@app.get("/posts/{id}")
def get_posts(id: int , response: Response):
    post= find_post(id)
    if not post :

        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail= f"post with id {id} not found bludd")


        # response.status_code=status.HTTP_404_NOT_FOUND
        # return {"message": f" post with id : {id} not found"}

    return{"here is the post": post}  

@app.delete("/posts/{id}", status_code= status.HTTP_204_NO_CONTENT)
def delete_post(id: int):
    index= find_index_post(id)
    if index == None:
        raise HTTPException(status_code= status.HTTP_404_NOT_FOUND, detail= f"post with id {id} does not exist")
    my_post.pop(index)
    
    return Response(status_code= status.HTTP_204_NO_CONTENT)

@app.put("/posts/{id}")
def update_post(id: int , post: Post):
    index = find_index_post(id)
    if index == None :
        raise HTTPException(status_code= status.HTTP_404_NOT_FOUND, detail= f"post with id {id} does not exist")
    post_dict = my_post.dict()
    post_dict["id"]= id
    my_post[index]= post_dict
    return {"message" : "updated post"}

   

其他一切都有效,但最后的

put/update
功能。 从字面上看,随着教程编码,并且有不停的烦人问题。

Python 控制台说:

 422 Unprocessable Entity
.

邮递员说:

"detail": 
"loc":
"body","msg": "field required",
"type": "value_error.missing"
python api backend crud fastapi
1个回答
1
投票

422 unprocessable entity
错误准确地告诉您请求的哪一部分与预期格式不匹配或丢失。在你的情况下,它说
body
不见了。使用 Pydantic 模型时,您实际上声明了一个
JSON
对象(或 Python 字典),因此,您的端点需要一个 JSON 格式的 request body。因此,您发送的请求必须包含与 Pydantic 模型匹配的
JSON
负载。下面是一个使用 Python 请求的示例(更多详细信息可以在this answer中找到),但您也可以使用位于http://127.0.0.1:8000/docs的OpenAPI/Swagger UI autodocs来测试API。另外,请查看 this answer 有关发布 JSON 数据时
422 unprocessable entity
错误的更多详细信息和示例。

例子

app.py

from pydantic import BaseModel

class Post(BaseModel):
    title: str
    content: str
    Published: bool = True
    rating: Optional[int] = None

# ...

@app.put('/posts/{id}')
def update_post(id: int , post: Post):
    pass

test.py

import requests

post_id = 2
url = f'http://127.0.0.1:8000/posts/{post_id}'
payload = {"title": "string", "content": "string", "Published": True, "rating": 0}
resp = requests.put(url, json=payload)
print(resp.json())

© www.soinside.com 2019 - 2024. All rights reserved.