fastapi用户系统模块——“获取字典kv“

@router.get("/dict/type/{_type}", summary="获取字典kv")
async def getDict(*,
                  _type: str,
                  r: asyncRedis = Depends(deps.get_redis),
                  db: Session = Depends(deps.get_db)
                  ):
    if r: 
        result = await curd_dict_data.getByTypeWithCache(r, db, _type=_type)
    else: 
        result = curd_dict_data.getByType(db, _type=_type)
    return respSuccessJson(result)

这段代码是一个基于FastAPI框架的路由处理函数。当收到一个GET请求,路径为"/dict/type/{_type}"时,会执行这个函数。这个函数接受一个名为_type的参数,并且依赖于asyncRedis和Session两个对象。

在函数内部,首先检查是否存在asyncRedis对象r。如果存在,就调用curd_dict_data.getByTypeWithCache函数,使用传入的r和db对象以及_type参数来获取数据。如果不存在asyncRedis对象r,就调用curd_dict_data.getByType函数,使用传入的db对象和_type参数来获取数据。

无论是通过缓存获取数据还是直接从数据库获取数据,最终都会将结果通过respSuccessJson函数返回。

    def getByType(self, db: Session, _type: str, status_in: Tuple[int] = None) -> dict:
        status_in = status_in or (0,)
        obj = db.query(self.model).filter(self.model.dict_type == _type, self.model.is_deleted == 0,
                                          self.model.status.in_(status_in)).first()  # type: DictData
        if not obj:
            return {}
        dict_details = [{
            'id': detail.id,
            'label': detail.dict_label,
            'value': int(detail.dict_value) if detail.dict_value.isdigit() else detail.dict_value,
            'is_default': detail.is_default,
            'remark': detail.remark
        } for detail in obj.dict_detail.filter(DictDetails.is_deleted == 0)]
        return {'id': obj.id, 'type': obj.dict_type, 'name': obj.dict_name, 'details': dict_details}

这是一个方法,名为getByType,它接受一个db会话对象和一个_type字符串作为参数,并且有一个可选的status_in参数,默认值为None。这个方法返回一个字典。

在方法内部,首先对status_in进行了处理,如果它是None,就将其设为(0,)。然后使用传入的db会话对象执行了一个查询操作,从数据库中获取了符合条件的第一个DictData对象。如果没有找到符合条件的对象,就返回一个空字典。

如果找到了符合条件的对象,就构建一个dict_details列表,其中包含了该对象相关联的DictDetails对象的一些属性。然后将这些信息和一些来自obj对象的属性组合成一个字典,并返回这个字典。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值