首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >FastAPI部署在Heroku上,连接到MongoDB时内部服务器出错

FastAPI部署在Heroku上,连接到MongoDB时内部服务器出错
EN

Stack Overflow用户
提问于 2021-12-11 19:18:47
回答 1查看 263关注 0票数 0

我想将database与我的mongodb数据库连接起来,当我在本地主机上运行我的后端时,它可以正常工作。但是当我在heroku上部署这段代码并尝试方法时,它返回“内部服务器错误”。我再次检查发现put、post和delete方法在某种程度上是有效的,我的意思是它在数据库上创建和更新数据,但同时给出内部服务器错误。所以我无法从数据库中读取数据,只能创建、更新和删除。

db.py

代码语言:javascript
复制
    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

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

发布于 2022-03-01 20:01:23

问题在于MongoDB驱动程序,更新修复了问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70318276

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档