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'
相关推荐
yannan201903138 分钟前
【算法】(Python)动态规划
python·算法·动态规划
蒙娜丽宁18 分钟前
《Python OpenCV从菜鸟到高手》——零基础进阶,开启图像处理与计算机视觉的大门!
python·opencv·计算机视觉
光芒再现dev20 分钟前
已解决,部署GPTSoVITS报错‘AsyncRequest‘ object has no attribute ‘_json_response_data‘
运维·python·gpt·语言模型·自然语言处理
好喜欢吃红柚子34 分钟前
万字长文解读空间、通道注意力机制机制和超详细代码逐行分析(SE,CBAM,SGE,CA,ECA,TA)
人工智能·pytorch·python·计算机视觉·cnn
小馒头学python38 分钟前
机器学习是什么?AIGC又是什么?机器学习与AIGC未来科技的双引擎
人工智能·python·机器学习
神奇夜光杯1 小时前
Python酷库之旅-第三方库Pandas(202)
开发语言·人工智能·python·excel·pandas·标准库及第三方库·学习与成长
千天夜1 小时前
使用UDP协议传输视频流!(分片、缓存)
python·网络协议·udp·视频流
测试界的酸菜鱼1 小时前
Python 大数据展示屏实例
大数据·开发语言·python
时差9531 小时前
【面试题】Hive 查询:如何查找用户连续三天登录的记录
大数据·数据库·hive·sql·面试·database
让学习成为一种生活方式1 小时前
R包下载太慢安装中止的解决策略-R语言003
java·数据库·r语言