【发布时间】:2022-03-02 04:01:23
【问题描述】:
我想将 fastapi 与我的 mongodb 数据库连接,当我在 localhost 上运行我的后端时它工作正常。但是当我在heroku上部署这段代码并尝试它返回“内部服务器错误”的方法时。 我再次检查发现 put、post 和 delete 方法以某种方式工作,我的意思是它正在创建和更新数据库上的数据,但同时给出内部服务器错误。所以我无法从数据库中读取数据,只能创建、更新和删除。
db.py
from model import *
import motor.motor_asyncio
DATABASE_URI = "mongodb+srv://mongodb_url"
client = motor.motor_asyncio.AsyncIOMotorClient(DATABASE_URI)
database = client.todoList
collection = database.todo
async def fetch_one_todo(nanoid):
document = await collection.find_one({"nanoid": nanoid})
return document
async def fetch_all_todos():
todos = []
cursor = collection.find({})
async for document in cursor:
todos.append(ToDo(**document))
return todos
async def create_todo(todo):
document = todo
await collection.insert_one(document)
return document
async def update_todo(nanoid, data):
await collection.update_one({"nanoid": nanoid}, {"$set": data})
document = await collection.find_one({"nanoid": nanoid})
return document
async def remove_todo(nanoid):
await collection.delete_one({"nanoid": nanoid})
return True
main.py
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from db import *
from model import ToDo
from UpdateModel import UpdateToDo
app = FastAPI()
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
async def read_root():
return {"Hi!"}
@app.get("/api/get-todo")
async def get_todo():
response = await fetch_all_todos()
return response
@app.get("/api/get-todo/{nanoid}", response_model=ToDo)
async def get_todo_id(nanoid):
todo = await fetch_one_todo(nanoid)
if todo:
return todo
raise HTTPException(404)
@app.post("/api/add-todo", response_model=ToDo)
async def post_todo(todo: ToDo):
response = await create_todo(todo.dict())
if response:
return response
raise HTTPException(400, "Something went wrong")
@app.put("/api/update-todo/{nanoid}", response_model=ToDo)
async def put_todo(nanoid: str, updatetodo: UpdateToDo):
response = await update_todo(nanoid, updatetodo.dict())
if response:
return response
raise HTTPException(404, 'wrong')
@app.delete("/api/delete-todo/{nanoid}")
async def delete_todo(nanoid):
response = await remove_todo(nanoid)
if response:
return response
raise HTTPException(404)
【问题讨论】:
-
Please don't post screenshots of text。它们无法被屏幕阅读器等自适应技术的用户搜索或复制,甚至无法使用。相反,将代码作为文本直接粘贴到您的问题中。如果选择它并单击
{}按钮或Ctrl+K,则代码块将缩进四个空格,这将导致其呈现为代码。