couchDBManager:
python
import couchdb
from common.exceptions.exception import CsException, ErrorCodes
from .couchdbConfig import config
class CouchDBManager:
server = couchdb.Server(config.URL)
server.resource.credentials = (config.USERNAME, config.PASSWORD)
db = None
def __init__(self, db_name):
self.connect_database(db_name)
# 连接数据库
def connect_database(cls, db_name):
if db_name in cls.server:
cls.db = cls.server[db_name]
else:
raise CsException(ErrorCodes.INTERNAL_SERVER_ERROR,
f"数据库'{db_name}'不存在")
# 判断当前id文档是否存在
def is_exists_doc(self, document_id):
if self.db[document_id]['is_deleted'] is True:
raise CsException(ErrorCodes.NOT_FOUND,
f"ID为'{document_id}'的文档不在数据库{self.db.name}中")
# 判断数据库是否存在
@classmethod
def is_exists_database(cls, db_name):
if db_name in cls.server:
return True
else:
return False
# 创建数据库
@classmethod
def create_database(cls, db_name):
if db_name in cls.server:
raise CsException(ErrorCodes.PRECONDITION_FAILED,
f"数据库'{db_name}'已存在")
cls.server.create(db_name)
print(f"Database '{db_name}' created successfully.")
return cls.server[db_name]
# 删除数据库
@classmethod
def delete_database(cls, db_name):
if db_name not in cls.server:
raise CsException(ErrorCodes.INTERNAL_SERVER_ERROR,
f"数据库'{db_name}'不存在")
cls.server.delete(db_name)
print(f"Database '{db_name}' deleted successfully.")
# 断开数据库连接
@classmethod
def disconnect_database(cls):
cls.db = None
def get_next_id(self):
# 检查是否已经存在一个名为 'counter' 的文档,用于保存计数器的值
if 'counter' not in self.db:
self.db.save({'_id': 'counter', 'value': 1})
# 获取当前计数器的值
counter_doc = self.db['counter']
current_value = counter_doc['value']
return current_value
def increase_id(self, count=1):
# 获取当前计数器的值
counter_doc = self.db['counter']
current_value = counter_doc['value']
print(current_value)
# 递增计数器的值
counter_doc['value'] = current_value + count
self.db.save(counter_doc)
def decrease_id(self, count=1):
# 获取当前计数器的值
counter_doc = self.db['counter']
current_value = counter_doc['value']
# 递增计数器的值
counter_doc['value'] = current_value - count
self.db.save(counter_doc)
# 创建文档
def create_doc(self, document):
document['_id'] = str(self.get_next_id())
document['is_deleted'] = False
print(self.get_next_id())
doc_id = self.db.save(document)
self.increase_id()
print(f"Document created with ID '{doc_id}'.")
# 批量创建文档
def bulk_create_doc(self, documents):
# 获取documents的长度
length = len(documents)
next_id = self.get_next_id()
ids = [str(i) for i in range(next_id, next_id+length)]
for index, doc in enumerate(documents):
doc['_id'] = ids[index]
doc['is_deleted'] = False
self.db.update(documents)
print("批量创建成功.")
self.increase_id(length)
# 更新文档
def update_doc(self, updated_document):
self.is_exists_doc(updated_document['_id'])
doc = self.db[updated_document['_id']]
for key, value in updated_document.items():
doc[key] = value
self.db.save(doc)
print(
f"Document with ID '{updated_document['_id']}' updated successfully.")
# 批量更新文档
def bulk_update_doc(self, updated_documents):
for updated_document in updated_documents:
self.is_exists_doc(updated_document['_id'])
doc = self.db[updated_document['_id']]
for key, value in updated_document.items():
doc[key] = value
result = self.db.save(doc)
print(result)
# 删除文档
def delete_doc(self, document_id):
self.is_exists_doc(document_id)
deleted_document = self.db[document_id]
deleted_document['is_deleted'] = True
self.db.save(deleted_document)
self.decrease_id()
print(f"Document with ID '{document_id}' deleted successfully.")
# 批量删除文档
def bulk_delete_doc(self, document_ids):
for document_id in document_ids:
self.is_exists_doc(document_id)
for document_id in document_ids:
deleted_document = self.db[document_id]
deleted_document['is_deleted'] = True
self.db.save(deleted_document)
print(f"Document with ID '{document_id}' deleted successfully.")
self.decrease_id(len(document_ids))
# 查询文档
def query_docs(self, query):
query['selector']['is_deleted'] = False
return self.db.find(query)
exception:
python
class ErrorCodes:
""" 错误码
"""
INTERNAL_SERVER_ERROR = 500, 'Internal Server Error'
PRECONDITION_FAILED = 412, 'Precondition Failed'
NOT_FOUND = 404, 'Not Found'
CONFLICT = 409, 'Conflict'
def __init__(self, code: int, message: str):
self.code = code
self.message = message
class CsException(Exception):
def __init__(self, error_code: int, message: str = ''):
self.code = error_code
self.message = message if message else self.get_error_message(
error_code)
# 获取错误码对应的错误消息
@staticmethod
def get_error_message(error_code: int) -> str:
if error_code == ErrorCodes.INTERNAL_SERVER_ERROR:
return ErrorCodes.MESSAGE_INTERNAL_SERVER_ERROR
if error_code == ErrorCodes.PRECONDITION_FAILED:
return ErrorCodes.PRECONDITION_FAILED
if error_code == ErrorCodes.NOT_FOUND:
return ErrorCodes.NOT_FOUND
if error_code == ErrorCodes.CONFLICT:
return ErrorCodes.CONFLICT
# 在这里可以添加其他错误码的对应消息
# elif error_code == OtherErrorCode:
# return OtherErrorMessage
else:
return 'Unknown Error'
couchdbConfig:
python
class config:
URL = 'http://localhost:5984'
USERNAME = 'admin'
PASSWORD = 'admin'