
我想将database与我的mongodb数据库连接起来,当我在本地主机上运行我的后端时,它可以正常工作。但是当我在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 Truemain.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)发布于 2022-03-01 20:01:23
问题在于MongoDB驱动程序,更新修复了问题。
https://stackoverflow.com/questions/70318276
复制相似问题