構建一個 API 并得到一個沒有意義的錯誤。這是代碼:
from typing import Optional
from fastapi import Body, FastAPI, Response,status
import psycopg2
import time
from pydantic import BaseModel
from psycopg2.extras import RealDictCursor
app = FastAPI()
while True:
try :
conn=psycopg2.connect(host='localhost', database='FASTAPIdb' , user= 'postgres' , password= '----', cursor_factory= RealDictCursor)
cursor=conn.cursor()
print('Connection to database succesfull')
break
except Exception as error:
print('Connection to database failed')
print('Error', error)
time.sleep(2)
class post(BaseModel):
title: str
content: str
published: bool=True
@app.get("/")
def root():
return {"message": "sup biatch"}
@app.get("/posts",status_code=status.HTTP_200_OK)
def get_posts():
cursor.execute("select * from posts")
posts=cursor.fetchall()
return {'data':posts}
@app.get("/post/id", status_code=status.HTTP_200_OK)
def find_posts(id):
return {'post': 'retrieved post'}
@app.post("/createpost", status_code= status.HTTP_201_CREATED)
def create_posts(postcreated: post):
cursor.execute("""insert into posts (title,content,published) VALUES(%s,%s,%s) RETURNING * """,(post.title,post.content,post.published))
new_post=cursor.fetchone()
conn.commit()
return {'new post': "new post returned"}
我正在構建一個 API 以將一些資料發布到 Postgres 資料庫,但出現服務器錯誤:型別物件帖子沒有屬性標題。如您所見,它確實如此。這是怎么回事?我正在使用郵遞員來測驗它。
uj5u.com熱心網友回復:
錯誤說明了一切post has no attribute title,在線上觸發
cursor.execute("""insert into posts (title,content,published) VALUES(%s,%s,%s) RETURNING * """,(post.title,post.content,post.published))
該變數post沒有欄位title(我猜其他兩個也是如此)。
我可以在您的代碼中發現的問題是您使用的是post類而不是保存post資料的變數。因此,您應該使用行postcreated中的型別變數post
def create_posts(postcreated: post):
注意問題
下次發布您得到的確切錯誤,其中將包含對閱讀該問題的人有用的資訊。這種情況是一個例外,因為可以通過閱讀代碼來發現錯誤
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/534469.html
