接口开发通用套路

予早 2025-08-31 14:59:19
Categories: Tags:

新增一条数据

注意幂等性

删除一条数据

注意幂等性

修改一条数据

注意幂等性

查询列表数据

通用查询参数q要做空格去除前后缀

批量修改状态操作

优化性能

class MsgService:

    @classmethod
    def _process_batch(cls, user_id, limit, offset):
        with SessionLocal() as db:
            deleted_msgs = MessageDao.batch_msg_read(user_id, db, limit, offset)  # 获取未读消息
            if not deleted_msgs:
                return  # 如果没有消息,直接返回

            message_ids = [msg.id for msg in deleted_msgs]  # 提取消息 ID
            MessageDao.batch_msg_is_read(message_ids, db)  # 更新消息为已读状态

    @classmethod
    def batch_all_msgs(cls, user_id):
        offset = 0
        limit = CommonConstant.slice_msg_count
        with SessionLocal() as db:
            total_count = MessageDao.count_msg_of_unread(user_id, db)  # 获取用户未读消息总数

        with ThreadPoolExecutor(max_workers=os.cpu_count() * 2 + 1) as executor:
            tasks = []
            while offset < total_count:  # 循环处理所有消息
                future = executor.submit(cls._process_batch, user_id, limit, offset)
                tasks.append(future)
                offset += limit  # 更新偏移量

            # 上下文自动完成如下操作
            # wait(tasks)  # 等待所有任务完成
            # executor.shutdown()  # 关闭线程池