0

我正在尝试从 database.py 访问 main.py 中的 mongodb 连接。但我得到 None 类型。请建议任何方法。下面是我的代码。我对从 database.py 获取 db 对象感到困惑。

浏览了互联网上的所有文档。但仍然没有解决办法。下面是我的 database.py 代码

**database.py**

import urllib
from motor.motor_asyncio import AsyncIOMotorClient

db = None

async def connect_db():
    """Create database connection."""
    try:
        # MongoDB attributes
        user = 'admin'
        pwd  = urllib.parse.quote_plus('*****')
        mongodb_uri = 'mongodb+srv://'+user+':'+pwd+'@test.***.mongodb.net/test_db?retryWrites=true&w=majority'
        # connect to mongodb
        db = AsyncIOMotorClient(mongodb_uri)
        print('connected')

    except Exception as e:
        print(str(e))

async def close_db():
    """Close database connection."""
    print('closing')
    db.close()
    print('db closed')

下面是主要的py代码。

**main.py**

import uvicorn, logging, asyncio
from fastapi import Depends, FastAPI, HTTPException
from typing import List
from fastapi.middleware.cors import CORSMiddleware
from motor.motor_asyncio import AsyncIOMotorClient

from database import  connect_db,close_db



app = FastAPI(title="test", version="1")

app.add_event_handler("startup", connect_db)

# print(db.list_database_names())

app.add_event_handler("shutdown", close_db)



#CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
    allow_credentials=True,
)



@app.get("/db_list")
async def show_db():
    resp =  db.list_collection_names()
    print(resp)
    return {"result":resp}








if __name__ == "__main__":
  uvicorn.run(app, host="127.0.0.1", port=8081,log_level=logging.DEBUG,
  log_config=logging.basicConfig(filename='backend/logs/backend_server.log',
    filemode='a+',
    level=logging.DEBUG,
    format='%(asctime)s %(levelname)s %(message)s'))
4

0 回答 0