rank_backend/database.py

19 lines
747 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from pymongo import MongoClient
import config
# from mongo_listeners import all_event_listeners # 导入监听器(暂时注释掉,因为文件不存在)
MONGO_URI = config.MONGO_URI
DB_NAME = config.MONGO_DB_NAME
# 创建MongoDB客户端连接
try:
# 实例化MongoClient时传入事件监听器
client = MongoClient(MONGO_URI, serverSelectionTimeoutMS=5000) # 设置5秒超时
db = client[DB_NAME]
# 主动检查连接状态
client.admin.command('ping')
success_message = f"\033[92m成功连接到MongoDB: {DB_NAME}\033[0m"
print(success_message)
except Exception as e:
error_message = f"\033[91m数据库连接失败: {MONGO_URI}请检查MongoDB服务是否已启动。\033[0m"
print(error_message)