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"