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'
相关推荐
川贝枇杷膏cbppg几秒前
dm_unknown_202512.log:达梦数据库 “未分类日志“
数据库·oracle
我送炭你添花8 分钟前
Pelco KBD300A 模拟器:03.Pelco-P 协议 8 字节完整拆解 + 与 Pelco-D 一一对应终极对照表
python·测试工具·运维开发
计算机毕设VX:Fegn089513 分钟前
计算机毕业设计|基于springboot + vue图书商城系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·课程设计
R.lin25 分钟前
Java 8日期时间API完全指南
java·开发语言·python
西南胶带の池上桜1 小时前
1.Pytorch模型应用(线性与非线性预测)
人工智能·pytorch·python
求学中--1 小时前
MySQL 数据库完整操作命令与使用指南
数据库·sql·mysql·oracle
丘狸尾2 小时前
gradio uv无法add
开发语言·python
DKunYu2 小时前
误删数据库表导致出现1146报错
数据库
全栈陈序员2 小时前
【Python】基础语法入门(十七)——文件操作与数据持久化:安全读写本地数据
开发语言·人工智能·python·学习
爱笑的眼睛112 小时前
FastAPI 路由系统深度探索:超越基础 CRUD 的高级模式与架构实践
java·人工智能·python·ai