urban-investment-research/Utils/MongoUtils.py

26 lines
621 B
Python
Raw Normal View History

2023-03-20 17:05:17 +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)
2023-03-20 17:05:17 +08:00
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):
self.host = host
self.port = port
self.db = db
self.client = MongoClient(host=self.host, port=self.port)
self.db = self.client[self.db]
def get_db(self):
yield self.db