python+couchdb封装了数据库的增删改查方法

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'
相关推荐
troy1281 小时前
Python 基础语法(九):Django/Flask/FastAPI 三大 Web 框架详细对比解析
python·jupyter·django·flask·github·fastapi
jzshmyt1 小时前
我用 Python 从零“生成“了一个宇宙,然后让它观察自己(v14)
人工智能·pytorch·python·numpy·matplotlib·空间计算·scipy
螺蛳粉 螺蛳粉2 小时前
MySQL 分布式集群系列 · 第五篇——全方位对比:NDB、MGR、主从复制、分库分表怎么选?
数据库·分布式·mysql
用户8356290780513 小时前
使用 Python 将 DOCX 转换为 Markdown
后端·python
小玮看世界3 小时前
[Python]ADAS工程实战(三):多传感器扇区统计疑难点全解——归一化、跨边界、去重与置信度
python
TomEval4 小时前
【测AI】第02篇:Python 环境搭建与基础语法速通
人工智能·python·功能测试·aigc
归去来 兮4 小时前
LangChain从入门到精通
python·langchain·langgraph
淘气的小猴子5 小时前
Python 魔术方法入门
python
我要见SA姐15 小时前
DeepSeek Harness 开源贡献手记:从 Issue 到 Merge 的完整旅程
ide·vscode·python·自动化·编辑器
沉下心来学鲁班5 小时前
初识DeepAgents搭建第一个智能体
人工智能·python·langchain