#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from motor.motor_asyncio import AsyncIOMotorClient
from 主体.配置 import MONGODB
class MotorObj:
'''
use motor to connect mongodb as client
'''
__instance = None
def __new__(cls, *args, **kwd):
if MotorObj.__instance is None:
MotorObj.__instance = object.__new__(cls, *args, **kwd)
print('\n创建数据库链接类 ' + str(id(MotorObj.__instance)) + '\n')
else:
print('\n数据库链接类已经存在 ' + str(id(MotorObj.__instance)) + '\n')
return MotorObj.__instance
host = MONGODB['HOST'] if MONGODB['HOST'] else 'localhost'
port = MONGODB['PORT'] if MONGODB['PORT'] else 27017
username = MONGODB['USERNAME'] if MONGODB['USERNAME'] else ''
password = MONGODB['PASSWORD'] if MONGODB['PASSWORD'] else ''
database = MONGODB['DATABASE'] if MONGODB['DATABASE'] else ''
__client = None
def client(self):
self.mongo_uri = 'mongodb://{account}{host}:{port}/{db}'.format(
account='{username}:{password}@'.format(
username=self.username,
password=self.password) if MONGODB['USERNAME'] else '',
host=self.host,
port=self.port,
db=self.database)
motor_client = AsyncIOMotorClient(self.mongo_uri)
print('\n链接建立,在 ' + self.mongo_uri + ' ' + str(id(motor_client)))
self.__client = motor_client
return motor_client
__db = None
@property
def db(self):
if self.__db is None:
self.__db = self.client()[self.database]
print('连接数据: ' + self.database + ', 建立链接实例 ' + str(id(self.__db)) + '\n')
else:
print('已经连接数据库: ' + self.database + ', 链接实例为 ' + str(
id(self.__db)) + '\n')
return self.__db
@property
def close(self):
self.__client.close()
print('关闭链接 : ' + str(id(self.__client)) + '\n')
motor_obj = MotorObj()
motor数据库链接类
最新推荐文章于 2024-04-02 14:00:00 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)