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'
相关推荐
了一li1 小时前
Qt中的QProcess与Boost.Interprocess:实现多进程编程
服务器·数据库·qt
算法小白(真小白)1 小时前
低代码软件搭建自学第二天——构建拖拽功能
python·低代码·pyqt
唐小旭1 小时前
服务器建立-错误:pyenv环境建立后python版本不对
运维·服务器·python
码农君莫笑1 小时前
信管通低代码信息管理系统应用平台
linux·数据库·windows·低代码·c#·.net·visual studio
007php0072 小时前
Go语言zero项目部署后启动失败问题分析与解决
java·服务器·网络·python·golang·php·ai编程
别致的影分身2 小时前
使用C语言连接MySQL
数据库·mysql
Chinese Red Guest2 小时前
python
开发语言·python·pygame
骑个小蜗牛2 小时前
Python 标准库:string——字符串操作
python
京东零售技术3 小时前
“慢”增长时代的企业数据体系建设:超越数据中台
数据库