def validate_params(params, validators): for key, validator in validators.items(): if key not in params: raise AppError(40000, '缺少参数', data=dict(key=key, params=params)) if callable(validator): if not validator(params[key]): raise AppError(40001, '参数校验失败', data=dict(key=key, params=params))
def reject(self, reason, *args, **kwargs): from django_base.base_utils.app_error.exceptions import AppError if self.status not in (self.STATUS_PENDING, ): raise AppError('ERR092', '审批对象的状态必须为等待审批') if not reason: raise AppError('ERR093', '请填写驳回理由') self.status = self.STATUS_REJECTED self.date_response = datetime.now() self.remark = reason self.save()
def from_url_download(cls, url): """ TODO: 工厂方法 根据指定的 url 下载图片保存,生成一个对象 :return: """ from django_base.base_utils.app_error.exceptions import AppError raise AppError(99999, '尚未实现', debug=True)
def approve(self, *args, **kwargs): if self.status not in (self.STATUS_PENDING, self.STATUS_REJECTED): from django_base.base_utils.app_error.exceptions import AppError raise AppError('ERR091', '审批对象的状态必须为等待审批或者驳回') self.status = self.STATUS_SUCCESS self.date_response = datetime.now() self.save()
def _wrapped_view(self, request, *args, **kwargs): vcode = request.data.get(vcode_field) or '' mobile = request.data.get(mobile_field) or '' result = validate_mobile_vcode(request, action, mobile, vcode) if not result: from django_base.base_utils.app_error.exceptions import AppError raise error or AppError(99999, '验证码错误', debug=False) return view_func(self, request, *args, **kwargs)
def validate_mobile_vcode(request, action, mobile, vcode): """ 要求 post 中提供 Session 中产生的验证码 :param request: 请求对象 :param action: 验证的 action 动作(不同的 action 独享一套 vcode) :param mobile: POST 提交过来的手机号码 :param vcode: POST 提交过来的验证码 :return: 如果成功返回 True,失败返回 False """ from django_base.base_utils.app_error.exceptions import AppError _mobile, _vcode = get_vcode_info(request, action) if not vcode or vcode != _vcode: raise AppError(50001, '验证码不正确', debug=False) if not mobile or mobile != _mobile: raise AppError(50002, '手机号码不一致', debug=False) # 验证成功马上擦除 clear_vcode_info(request) return True
def request_mobile_vcode(request, mobile, action=''): """ 为传入的 request 上下文(Session)产生一个手机验证码, 发送给指定的手机号码,并且记录在 session.vcode 中。 :param request: :param mobile: :return: """ mobile = sanitize_mobile(mobile) prefix = 'mobile_vcode_' + action # 上次请求验证码的时间 last_sms_request_time = int(request.session.get(prefix + '_time', 0)) # 一分钟内不允许重发 if time() < last_sms_request_time + settings.SMS_SEND_INTERVAL: from django_base.base_utils.app_error.exceptions import AppError raise AppError( 99999, '您的操作过于频繁,请在 %d 秒后再试。' % ( last_sms_request_time + settings.SMS_SEND_INTERVAL - time()), debug=False ) vcode = '%06d' % (random.randint(0, 1000000)) # 如果开启了调试选项,不真正发送短信 if not settings.SMS_DEBUG: sms_send( mobile, settings.SMS_TEMPLATES.get(action), dict(code=vcode), ) set_vcode_info(request, mobile, vcode, action) return vcode