예제 #1
0
파일: manager.py 프로젝트: GSIL-Monitor/xxw
 def put(self):
     # 抢单动作
     logger.info("[D] [功能 客户经理抢单动作]")
     req = self.validate_data
     logger_req(req)
     manager = request.current_user
     facesign_code = req["facesign_code"]
     facesign = TbFaceSignUser.query.filter_by(code=facesign_code,
                                               status=0).first()
     if not facesign:
         logger.info("[T] [The facesign does not exist]")
         return Msg.MANAGER_FACESIGN_NOT_EXIST, -200
     if redis.zadd("support_facesign_order", facesign.update_time,
                   facesign.code) == 0:
         logger.info("[T] [The redis.zadd is fail]")
         return Msg.MANAGER_FACESIGN_NOT_EXIST, -200
     if facesign.status != 0:
         logger.info("[T] [Check status is not 0 ]")
         return Msg.MANAGER_FACESIGN_NOT_EXIST, -200
     try:
         facesign.manager_code = manager.code
         facesign.manager_name = manager.name
         facesign.status = 1
         facesign.update_time = utc_timestamp()
         db.session.commit()
         logger.info(
             "[T] [Update tb_manager where manager_code= {}]".format(
                 manager.code))
     except Exception as e:
         logger.info("[T] {}".format(str(e)))
         return str(e)
     redis.zremrangebyscore("support_facesign_order", 0, utc_timestamp())
     return get_data(facesign, TbFaceSignUser, exclude=["id", "extend"])
예제 #2
0
def generate_token(user) -> str:

    token = jwt.encode({
        "code": user.code,
        "time": utc_timestamp()
    }, app.config["SECRET_KEY"]).decode()
    key = "support_jwt_{}".format(user.code)
    data = {"exp_time": utc_timestamp() + 24 * 60 * 60, "token": token}
    redis.set(key, value=json.dumps(data), ex=24 * 60 * 60)
    return token
예제 #3
0
파일: config.py 프로젝트: GSIL-Monitor/xxw
 def put(self):
     """
     """
     schema = Schema({
         "user_code": And(str),
         "category": And(Use(int), lambda x: x in list(ConfigNameMap.name.keys())),
     }, ignore_extra_keys=True)
     req, error = validate_schema(schema, request.json)
     if error:
         return error, 400
     user = TbUser.query.filter_by(code=request.json.pop("user_code")).first()
     # 解锁
     release_lock(req, user)
     request.json.pop("category")
     category = ConfigNameMap.name[req["category"]]
     if not user:
         return Msg.USER_NOT_EXISTS, 400
     # 处理 VERSION
     version = get_version(category)
     # 处理 python 精度问题
     request.json["VERSION"] = round(version + 0.1, 2)
     # support 的配置里面需要隔离掉 SQLALCHEMY_DATABASE_URI
     if category == ConfigNameMap.SUPPORT and request.json.get("SQLALCHEMY_DATABASE_URI"):
         request.json.pop("SQLALCHEMY_DATABASE_URI")
     data = {
         "config": request.json,
         "creator_name": user.name,
         "creator_code": user.code,
         "create_time": utc_timestamp(),
         "category": category,
         "is_sync": False
     }
     msg = "SUPPORT | MONITOR | EDIT_CONFIG | SUCCESS | USER: {} {} | CATEGORY: {}".format(
         user.code, user.name, category)
     try:
         support_config_storage.insert_one(data)
         operation = TbOperation(
             operator_code=user.code,
             content=msg,
             operate_time=utc_timestamp(),
             category=category,
             type="EDIT"
         )
         db.session.add(operation)
         db.session.commit()
         logger.info(msg)
         return {}, 200
     except Exception as e:
         logger.warn("SUPPORT | MONITOR | EDIT_CONFIG | FAILED | CATEGORY: {}| ERROR: {}".format(category, str(e)))
         return Msg.UPDATE_CONFIG_FAILED, 400
예제 #4
0
 def put(self):
     _id = request.json.get('id')
     if not _id:
         raise RequestsError(code=1014010001, message=",id参数缺失")
     try:
         instance = self.model.objects.filter(id=_id).first()
     except:
         instance = None
     if not instance:
         raise RequestsError(code=1014010005, message=",id对应数值不存在")
     if set(self.add_alter_have_fields) - set(request.json.keys()):
         raise RequestsError(code=1014010001, message=",必需字段缺失")
     operator = request.json.get('operator')
     operator_id = request.json.get('operator_id')
     datas = request.json.get('data')
     if not datas:
         return instance.to_pretty()
     datas = move_space(json.loads(datas))
     if not datas:
         raise RequestsError(code=1014000000, message=",data参数无数据")
     if not datas.get('code'):
         raise RequestsError(code=1014000000, message=",code数值不能为空")
     datas['operator'] = operator
     datas['operator_id'] = operator_id
     instance["update_time"] = utc_timestamp()
     if set(datas.keys()) & set(self.undate_exclude_fields):
         raise RequestsError(code=1014010004, message=",存在不允许更新的参数")
     try:
         instance.update(**datas)
         instance.save()
     except:
         raise RequestsError(code=1014020001, message=",更新数据失败")
     instance = self.model.objects.filter(id=_id).first()
     return instance.to_pretty()
예제 #5
0
파일: user.py 프로젝트: GSIL-Monitor/xxw
 def __init__(self, **kwargs):
     self.merchant_code = kwargs.get("merchant_code", "")
     self.production_code = kwargs.get("production_code", "")
     self.interface = kwargs.get("interface", "")
     self.status = kwargs.get("status", "")
     self.interface_status = kwargs.get("interface_status", "")
     self.update_time = utc_timestamp()
예제 #6
0
def token_verify(token):
    try:
        data = jwt.decode(token, app.config["SECRET_KEY"])
        code = data["code"]
        key = "support_jwt_{}".format(code)
        data = json.loads(redis.get(key))
        if not data:
            return "EXPIRED"
        elif data.get("token") != token:
            return "OFFLINE"
        else:
            user = TbUser.query.filter_by(code=code).first()
            if not user:
                return "NOT_EXIST"
            request.token = data
            # 更新 token
            redis.set(key,
                      value=json.dumps({
                          "exp_time": utc_timestamp() + 24 * 60 * 60,
                          "token": token
                      }),
                      ex=24 * 60 * 60)
            return user
    except TypeError:
        # 代表没有从 redis 中取得数据
        return "EXPIRED"
    except Exception as e:
        app.logger.info("obtain data error: {}".format(str(e)))
        return "INVALID"
예제 #7
0
파일: manager.py 프로젝트: GSIL-Monitor/xxw
 def get(self):
     logger.info("[D] [功能 商户经理面签单审核占比获取]")
     req = self.validate_data
     logger_req(req)
     days = req.get("days") or 30
     time_start = utc_timestamp() - (days * 24 * 60 * 60)
     time_end = utc_timestamp()
     manager = request.current_user
     # 面签审核条件
     a = TbFaceSignUser.manager_code == manager.code  # 商户编码
     b = (TbFaceSignUser.update_time >= time_start)  # 预约起始起始时间
     c = (TbFaceSignUser.update_time <= time_end)  # 预约结束时间
     d = TbFaceSignUser.status.in_([2, 3, 4])  # 审核总数
     e = TbFaceSignUser.status == 3  # 面签成功
     e_f = TbFaceSignUser.status == 4
     # 扫码量条件
     f = LogLoading.manager_id == manager.code
     g = LogLoading.load_time >= time_start  # 起始时间
     h = LogLoading.load_time >= time_start  # 结束时间
     # 注册量条件
     i = LogRegister.manager_id == manager.code
     j = LogRegister.reg_time >= time_start
     k = LogRegister.reg_time >= time_start
     # 面签总数
     ke = [a, b, c, d]
     all_facesign = TbFaceSignUser.query.filter(*ke).count()
     # 面签审核成功
     ke_p = [a, b, c, e]
     pass_facesign = TbFaceSignUser.query.filter(*ke_p).count()
     # 面签审核失败
     ke_p = [a, b, c, e_f]
     refuse_facesign = TbFaceSignUser.query.filter(*ke_p).count()
     # 扫码量
     ke_sc = [f, g, h]
     scan_code = LogLoading.query.filter(*ke_sc).count()
     # 注册量
     ke_r = [i, j, k]
     register = LogRegister.query.filter(*ke_r).count()
     return {
         "all_number": all_facesign,
         "pass_number": pass_facesign,
         "refuse_number": refuse_facesign,
         "scan_code_number": scan_code,
         "register_number": register
     }
예제 #8
0
 def put(self):
     _id = request.json.get('id')
     if not _id:
         raise RequestsError(code=1014010001, message=",修改数据时需要必需参数id")
     instance = self.model.query.filter(self.model.id == _id).one_or_none()
     if not instance:
         raise RequestsError(code=1014010005, message=",修改数据时id对应数值不存在")
     operator = request.json.get('operator')
     operator_id = request.json.get('operator_id')
     if not all([operator, operator_id]):
         raise RequestsError(code=1014000000, message=",修改数据时无操作人信息")
     try:
         data = json.loads(request.json.get('data'))
     except:
         data = {}
     if not data:
         # 如果没有data数据
         return instance.to_pretty()
     #如果有data数据 进行数据修改
     data['operator_id'] = operator_id
     data['operator'] = operator
     data = move_null(data)
     type = data.get('type')
     push_method = data.get('push_method')
     status = data.get('status')
     if not type:
         type = instance.type
     if not push_method:
         push_method = instance.push_method
     if status is None:
         status = instance.status
     # 检测修改后的数据 是否与数据库中有重复
     if instance.push_method != push_method or instance.type != type:
         ins = self.model.query.filter(
             self.model.merchant_code == instance.merchant_code,
             self.model.type == type,
             self.model.push_method == push_method).one_or_none()
         if ins:
             raise RequestsError(code=1014000000, message=",修改后唯一性数据重复")
     #修改数据
     try:
         instance.update_time = utc_timestamp()
         instance.type = type
         instance.push_method = push_method
         instance.status = status
         instance.operator = operator
         instance.operator_id = operator_id
         db.session.commit()
     except:
         # 事务回滚
         db.session.rollback()
         raise RequestsError(code=1014020001, message=",修改数据失败")
     return instance.to_pretty()
예제 #9
0
파일: config.py 프로젝트: GSIL-Monitor/xxw
 def post(self):
     req, error = validate_schema(universal_schema, request.json)
     if error:
         return error, 400
     category = ConfigNameMap.name[req["category"]]
     config_info = support_config_storage.find_one({
         "_id": ObjectId(req["id"]),
         "category": category
         })
     user = TbUser.query.filter_by(code=req["user_code"]).first()
     if not user:
         return Msg.USER_NOT_EXISTS, 400
     # 把获取到的配置信息插入库中
     version = get_version(category) + 0.1
     config_info["config"]["VERSION"] = version + 0.1
     support_config_storage.insert_one({
         "config": config_info["config"],
         "creator_name": user.name,
         "creator_code": user.code,
         "create_time": utc_timestamp(),
         "category": category,
         "is_sync": False
     })
     msg = "SUPPORT | MONITOR | CONFIG_ROLL_BACK | SUCCESS | USER: {} {} | CATEGORY: {} | CONFIG: {}".format(
         user.code, user.name, category, config_info["config"])
     operation = TbOperation(
             operator_code=user.code,
             content=msg,
             operate_time=utc_timestamp(),
             category=category,
             type="CONFIG_ROLL_BACK"
         )
     db.session.add(operation)
     db.session.commit()
     logger.info(msg)
     return {}, 200
예제 #10
0
파일: user.py 프로젝트: GSIL-Monitor/xxw
 def put(self):
     schema = Schema({
         Optional("sex"): str,
         Optional("address"): str,
         Optional("wechat"): str,
         Optional("qq"): str,
         Optional("mail"): str,
         "name": str,
         "id": str,
         "mobile": str
     })
     req, error = validate_schema(schema, request.json)
     if error:
         return error, 400
     current_user = request.current_user
     user = TbUser.query.filter_by(code=req["id"]).first()
     if not user:
         return Msg.USER_NOT_EXISTS, 400
     phone = req["mobile"]
     if len(phone) != 11:
         return Msg.PARAMS_ERROR, 400
     elif TbUser.query.filter(TbUser.code != req["id"],
                              TbUser.phone == phone).first():
         return Msg.PHONE_USED, 400
     user.phone = phone
     user.name = req["name"]
     user.sex = req.get("sex", user.sex)
     user.mail = req.get("mail", user.mail)
     user.wechat = req.get("wechat", user.wechat)
     user.qq = req.get("qq", user.qq)
     user.address = req.get("address", user.address)
     user.update_time = utc_timestamp()
     msg = "SUPPORT | B_USER | EDIT_USER | SUCCESS | EDITOR: {} {} | USER: {} {} | MERCHANT: {} {}".format(
         current_user.code, current_user.name, user.code, user.name,
         user.merchant.code, user.merchant.name)
     operation = TbOperation(operator_code=user.code,
                             content=msg,
                             category="USER_MANAGE",
                             type="EDIT")
     db.session.add(operation)
     db.session.commit()
     logger.info(msg)
     return {}, 200
예제 #11
0
파일: util.py 프로젝트: GSIL-Monitor/xxw
def sync_config(category: str, user: TbUser, wait_to_sync_config: dict,
                _type: str) -> tuple:
    """
    同步配置
    """
    cache_data = CacheData(category)
    if category == "SUPPORT":
        # 现在的配置
        now_config = support_config_db.find_one() or {}
        if not judge_version(now_config, wait_to_sync_config):
            return Msg.WRONG_VERSION, 400
        # 先remove 再 insert
        support_config_db.delete_many({})
        support_config_db.insert_one(wait_to_sync_config.get("config"))
        wait_to_sync_config.get("config").pop("_id")
        app.config.update(wait_to_sync_config.get("config"))
        cache_data.set(wait_to_sync_config.get("config"))
        logger.info("SUPPORT | SYNC {} CONFIG".format(category))
    else:
        now_config = zk.get_config(category)
        if not judge_version(now_config, wait_to_sync_config):
            return Msg.WRONG_VERSION, 400
        status = zk.write_config(category, wait_to_sync_config["config"])
        if status is False:
            return Msg.SYNC_FAILED, 400
        cache_data.set(wait_to_sync_config["config"])
        logger.info("SUPPORT | SYNC {} CONFIG".format(category))
    # 将待更新数据里面的 is_sync 修改为 True
    wait_to_sync_config["is_sync"] = True
    _id = str(wait_to_sync_config.pop("_id"))
    support_config_storage.update({"_id": ObjectId(_id)}, wait_to_sync_config)
    msg = "SUPPORT | MONITOR | {} | SUCCESS | USER: {} {} | CATEGORY: {}".format(
        _type, user.code, user.name, category)
    operation = TbOperation(operator_code=user.code,
                            content=msg,
                            operate_time=utc_timestamp(),
                            category=category,
                            type=_type)
    db.session.add(operation)
    db.session.commit()
    logger.info(msg)
    return {}, 200
예제 #12
0
파일: user.py 프로젝트: GSIL-Monitor/xxw
 def put(self):
     """
     修改用户信息
     """
     req = user_info.parse_args(strict=True)
     user = request.current_user
     user.name = req.get("name")
     user.sex = req.get("sex") if req.get("sex") else "unknown"
     user.address = req.get("address")
     user.wechat = req.get("wechat")
     user.qq = req.get("qq")
     user.avatar = req.get("avatar")
     user.mail = req.get("mail")
     user.update_time = utc_timestamp()
     msg = "SUPPORT | B_USER | EDIT_SELF_INFO | SUCCESS | USER_CODE: {} | USER_NAME: {}".format(
         user.code, user.name)
     operation = TbOperation(operator_code=user.code,
                             content=msg,
                             category="USER",
                             type="EDIT")
     db.session.add(operation)
     db.session.commit()
     logger.info(msg)
     return {}, 200
예제 #13
0
 def put(self):
     """
     更新征信配置
     """
     self.reqparse.add_argument("interface",
                                type=str,
                                required=True,
                                location=['json', 'args'],
                                code=1014010001,
                                desc="接口编号")
     self.reqparse.add_argument("operator_id",
                                type=str,
                                location=['json', 'args'],
                                required=True,
                                code=1014010001,
                                desc="操作人ID")
     self.reqparse.add_argument("supplier",
                                type=str,
                                location=['json', 'args'],
                                code=1014010002,
                                desc="接口供应商")
     self.reqparse.add_argument("product",
                                type=str,
                                location=['json', 'args'],
                                code=1014010002,
                                desc="产品名称")
     self.reqparse.add_argument("type",
                                type=str,
                                location=['json', 'args'],
                                code=1014010002,
                                desc="接口类型")
     self.reqparse.add_argument("desc",
                                type=str,
                                location=['json', 'args'],
                                code=1014010002,
                                desc="接口描述")
     self.reqparse.add_argument("secret_key",
                                type=str,
                                location=['json', 'args'],
                                code=1014010002,
                                desc="安全码")
     self.reqparse.add_argument("url",
                                type=str,
                                location=['json', 'args'],
                                code=1014010002,
                                desc="接口api")
     self.reqparse.add_argument("retry",
                                type=int,
                                location=['json', 'args'],
                                code=1014010002,
                                desc="重试次数")
     self.reqparse.add_argument("method",
                                type=str,
                                location=['json', 'args'],
                                code=1014010002,
                                desc="请求方式")
     self.reqparse.add_argument("headers",
                                type=dict,
                                location=['json', 'args'],
                                code=1014010002,
                                desc="请求头参数字典")
     self.reqparse.add_argument("auth_info",
                                type=dict,
                                location=['json', 'args'],
                                code=1014010002,
                                desc="接口认证信息")
     self.reqparse.add_argument("account_config",
                                type=dict,
                                location=['json', 'args'],
                                code=1014010002,
                                desc="人行账号配置")
     self.reqparse.add_argument("rate_limit",
                                type=dict,
                                location=['json', 'args'],
                                code=1014010002,
                                desc="限速配置字典")
     self.reqparse.add_argument("timeout",
                                type=int,
                                location=['json', 'args'],
                                code=1014010002,
                                desc="超时时间")
     self.reqparse.add_argument("expire",
                                type=int,
                                location=['json', 'args'],
                                code=1014010002,
                                desc="缓存过期时间")
     self.reqparse.add_argument("status",
                                type=int,
                                location=['json', 'args'],
                                code=1014010002,
                                desc="接口状态")
     self.reqparse.add_argument("sys_params",
                                type=dict,
                                location=['json', 'args'],
                                code=1014010002,
                                desc="系统参数字典")
     self.reqparse.add_argument("user_params",
                                type=dict,
                                location=['json', 'args'],
                                code=1014010002,
                                desc="用户参数字典")
     self.reqparse.add_argument("input_params",
                                type=dict,
                                location=['json', 'args'],
                                code=1014010002,
                                desc="请求参数字典")
     self.reqparse.add_argument("success_code_dict",
                                type=dict,
                                location=['json', 'args'],
                                code=1014010002,
                                desc="成功状态码字典")
     self.reqparse.add_argument("retry_code_dict",
                                type=dict,
                                location=['json', 'args'],
                                code=1014010002,
                                desc="失败重试状态码字典")
     self.reqparse.add_argument("failed_code_dict",
                                type=dict,
                                location=['json', 'args'],
                                code=1014010002,
                                desc="失败状态码字典")
     raw_args_dict = self.reqparse.parse_args(strict=True)
     if not CreditConf.objects(interface=raw_args_dict["interface"],
                               is_delete=0).count() == 1:
         return 1014010004  # 接口编码错误
     up_data = CreditConf.objects.filter(
         interface=raw_args_dict["interface"])[0]
     raw_args_dict["update_time"] = utc_timestamp()
     try:
         for k, v in raw_args_dict.items():
             if k not in ["operator_id"]:
                 setattr(up_data, k, v or None)
         up_data.save()
         msg = self.create_log_msg(operator_id=raw_args_dict["operator_id"],
                                   interface=raw_args_dict["interface"],
                                   data=json.dumps(raw_args_dict,
                                                   ensure_ascii=False),
                                   status="SUCCESS")
         self.operator_log(operator_id=raw_args_dict["operator_id"],
                           log_data=msg,
                           method="PUT")
         logger.info(msg)
         return 0
     except Exception as e:
         msg = self.create_log_msg(operator_id=raw_args_dict["operator_id"],
                                   interface=raw_args_dict["interface"],
                                   data=json.dumps(raw_args_dict,
                                                   ensure_ascii=False),
                                   status="FAILED")
         self.operator_log(operator_id=raw_args_dict["operator_id"],
                           log_data=msg,
                           method="PUT")
         logger.error(msg)
         return 1014020001  # 数据格式错误
예제 #14
0
파일: manager.py 프로젝트: GSIL-Monitor/xxw
 def post(self):
     # 商户经理登录
     logger.info("[D] [功能 商户经理登录]")
     req = self.validate_data
     logger_req(req)
     phone = req.get("phone")
     wx_openid = req.get("wx_openid")
     password = req.get("pwd")
     manager = TbManager.query.filter_by(phone=phone,
                                         is_delete=False).first()
     if not manager:
         logger.info("[T] [phone is not regist]")
         return Msg.MANAGER_PHONE_NOT_EXIST, -200
     if manager.wx_openid and manager.wx_openid != wx_openid:
         logger.info("[T] [phone is not bind wx_openid]")
         return Msg.MANAGER_BINDING_ERROR, -200
     if manager.pwd_err_count >= PWD_ERR_COUNT or \
             (manager.pwd_frozen_time and (manager.pwd_frozen_time + PWD_ERR_REFRESH_TIME) <= utc_timestamp()):
         manager.pwd_err_count = 0
         db.session.commit()
     if manager.pwd_frozen_time and manager.pwd_frozen_time >= utc_timestamp(
     ):
         logger.info("[T] [manager:{} is frozen, time:{}]".format(
             manager.code, manager.pwd_frozen_time))
         return {
             "error_name": "MANAGER_PASSWORD_ERROR_FROZEN",
             "data": {
                 "pwd_err_count_all": PWD_ERR_COUNT,
                 "pwd_err_count": PWD_ERR_COUNT,
                 "pwd_frozen_time": manager.pwd_frozen_time
             }
         }, -200
     if not check_password(manager.password, password):
         manager.pwd_err_count += 1
         manager.pwd_frozen_time = utc_timestamp()
         db.session.commit()
         logger.info("[T] [manager:{} pwd is error]".format(manager.code))
         if manager.pwd_err_count >= PWD_ERR_COUNT:
             manager.pwd_frozen_time = utc_timestamp() + PWD_FROZEN_TIME
             db.session.commit()
             logger.info("[T] [manager:{} is frozen time:{}]".format(
                 manager.code, manager.pwd_frozen_time))
         return {
             "error_name": "MANAGER_PASSWORD_ERROR",
             "data": {
                 "pwd_err_count_all": PWD_ERR_COUNT,
                 "pwd_err_count": manager.pwd_err_count,
                 "pwd_frozen_time": manager.pwd_frozen_time
             }
         }, -200
     if not manager.wx_openid:
         manager.wx_openid = wx_openid
         db.session.commit()
         logger.info("[T] [phone:{} bind wx_openid:{}]".format(
             manager.phone, manager.wx_openid))
     manager.pwd_err_count = 0
     manager.pwd_frozen_time = 0
     db.session.commit()
     safe = False
     if not check_password(manager.password, phone[-6:]):
         safe = True
     production = TbProduction.query.filter_by(
         merchant_code=manager.merchant_code).first()
     if production:
         production_code = production.code
     merchant = TbMerchant.query.filter_by(
         code=manager.merchant_code).first()
     return {
         "token": manager_generate_token(manager.code).decode(),
         "name": manager.name,
         "manager_code": manager.code,
         "safe": safe,
         "phone": phone,
         "merchant_code": manager.merchant_code,
         "production_code": production_code or "",
         "merchant_logo": merchant.logo
     }
예제 #15
0
파일: task.py 프로젝트: GSIL-Monitor/xxw
 def update(self, **kwargs):
     if hasattr(self, "update_time"):
         kwargs["update_time"] = utc_timestamp()
     return super().update(**kwargs)
예제 #16
0
파일: task.py 프로젝트: GSIL-Monitor/xxw
 def clean(self):
     if hasattr(self, "update_time"):
         self.update_time = utc_timestamp()
예제 #17
0
 def post(self):
     type_filed = request.json.get('type')
     operator = request.json.get('operator')
     operator_id = request.json.get('operator_id')
     if not type_filed:
         raise RequestsError(code=1014010001, message=",批量导入数据时type数值缺失")
     if not all([operator, operator_id]):
         raise RequestsError(code=1014010001, message=",批量导入数据时操作人信息缺失")
     # 获取批量数据
     try:
         datas = json.loads(request.json.get('data'))
     except:
         datas = {}
     if not datas:
         raise RequestsError(code=1014010001, message=",批量导入数据时缺少必需参数data")
     # 校验全部数据
     for data in datas:
         data = move_null_val(move_space(data))
         if set(get_require_fileds()) - set(
                 list(data.keys()) + self.not_in_data):
             raise RequestsError(code=1014010001, message=",批量导入数据时必需参数缺失")
         sub_type = data.get('sub_type')
         if sub_type not in self.push_strategy[type_filed]:
             raise RequestsError(code=1014010005, message=",批量导入数据时无此子类型")
         code = data.get('code')
         if not code and not self.push_strategy[type_filed][sub_type][
                 'code']['nullable']:
             raise RequestsError(code=1014010002,
                                 message=",批量导入数据时此类型中的子类型 code不能为空")
     flag = utc_timestamp()
     # 检验完成进行插入 更新数据
     for data in datas:
         data['push_type'] = type_filed
         data['operator'] = operator
         data['operator_id'] = operator_id
         sub_type = data.get('sub_type')
         if not data.get('code') and self.push_strategy[type_filed][
                 sub_type]['code']['nullable']:
             data['code'] = self.push_strategy[type_filed][sub_type][
                 'code']['default']
         instance = self.model.objects.filter(**data).first()
         # 如果已经存在,则此数据不再进行插入 只更改更新时间
         if instance:
             instance.update(update_time=utc_timestamp())
             instance.save()
             continue
         else:
             ins = self.model.objects.filter(push_type=type_filed,
                                             sub_type=sub_type,
                                             code=data.get('code')).first()
             if ins:
                 # 如果三者组合已经存在,则更新数据
                 data['update_time'] = utc_timestamp()
                 ins.update(**data)
                 ins.save()
             else:
                 # 没有原有记录 直接插入
                 try:
                     ins = self.model(**data)
                     ins.save()
                 except:
                     raise RequestsError(code=1014020001, message=",新增数据失败")
     # 删除原有数据
     for instance in self.model.objects:
         if instance.update_time < flag:
             instance.delete()
     return {}
예제 #18
0
    def put(self):
        _id = request.json.get('id')
        type_filed = request.json.get('type')
        operator = request.json.get('operator')
        operator_id = request.json.get('operator_id')
        try:
            data = json.loads(request.json.get('data'))
        except:
            data = {}
        if not _id:
            raise RequestsError(code=1014010001, message=",修改数据时必需参数id缺失")
        try:
            instance = self.model.objects.filter(id=_id).first()
        except:
            instance = None
        if not instance:
            raise RequestsError(code=1014010005, message=",修改数据id对应数值不存在")
        # 如果传递过来只有一个id 则直接将原有数据进行返回  无修改
        if not data:
            return instance.to_pretty()
        data['push_type'] = type_filed
        data['operator'] = operator
        data['operator_id'] = operator_id
        data = move_null_val(move_space(data))
        if data.get("type") and data.get(
                "type") not in self.push_strategy.keys():
            raise RequestsError(code=1014010002, message=",修改数据时无此推送类型")
        if data.get('type'):
            type_filed = data.get('type')
        else:
            type_filed = instance.push_type
        if data.get('sub_type') and data.get(
                'sub_type') not in self.push_strategy[type_filed].keys():
            raise RequestsError(code=1014010002, message=",修改数据时无此推送子类型")
        if data.get('sub_type'):
            sub_type = data.get('sub_type')
        else:
            sub_type = instance.sub_type
        # 检测是否有code 如果有则检测是否符合规范
        code = data.get('code')
        if not code:
            if self.push_strategy[type_filed][sub_type]['code']['nullable']:
                data['code'] = self.push_strategy[type_filed][sub_type][
                    'code']['default']
            else:
                raise RequestsError(code=1014010002,
                                    message=",修改数据时此类型中的子类型 code不能为空")
        # 检测是否有不允许更新的字段
        if set(self.update_exclude_fileds) - set(data):
            raise RequestsError(code=1014010004, message=",更新数据有不允许字段")

        # 检测是否会与数据库中的重复
        if instance.push_type != type_filed or instance.sub_type != sub_type or instance.code != code:
            ins = self.model.objects.filter(push_type=type_filed,
                                            sub_type=sub_type,
                                            code=data.get('code')).first()
            if ins:
                raise RequestsError(code=1014000000, message=",修改后的数据唯一性重复")
        # 更新数据
        data['update_time'] = utc_timestamp()
        try:
            instance.update(**data)
            instance.save()
        except:
            raise RequestsError(code=1014020001, message=",更新数据失败")
        # 返回修改后的数据
        return self.model.objects.filter(id=_id).first().to_pretty()