rate-sys-template/Utils/MongoUtils.py

32 lines
911 B
Python
Raw Normal View History

2023-06-12 10:47:25 +08:00
import json
from copy import deepcopy
from pydantic import BaseModel
from pymongo import MongoClient
from typing import Generic, TypeVar
ModelType = TypeVar("ModelType", bound=BaseModel)
def pydantic_to_mg_dict(data: BaseModel):
data = json.loads(data.json(exclude_none=True))
return data
class MongoConnect:
def __init__(self, host="localhost", port: int = 27017, db: str = None, user: str = None, password: str = None):
self.host = host
self.port = port
self.db = db
self.user = user
self.password = password
if self.user:
self.client = MongoClient(host=self.host, port=self.port,
username=self.user, password=self.password)
else:
self.client = MongoClient(host=self.host, port=self.port)
self.db = self.client[self.db]
def get_db(self):
yield self.db