def POST(self): userid = self.user.userid if not SpecialApi.check_allow_create(userid): raise ParamError('禁止创建特卖通知!') args = self.req.input() # 参数 params = {i : args.get(i) for i in ['title', 'descr', 'redeem_start_date', 'redeem_end_date', 'img'] } params['redeem_start_time'] = args.get('redeem_start_time', "05:00") params['redeem_end_time'] = args.get('redeem_end_time', "23:00") params['quantity'] = int(args['quantity']) # 价格 price, origin_price = int(args['price']), int(args['origin_price']) price_limit = int(redis_pool.get('_mchnt_api_sale_price_limit_') or 70000) if price > price_limit: raise ParamError('创建特卖失败') if price > origin_price * 0.8: raise ParamError('至少8折才有吸引力') params['price'] = price params['origin_price'] = origin_price result = self.create(**params) return self.write(success({'activity_id' : result}))
def get_avg_stat(self): ret = {} try: ret = json.loads(redis_pool.get('_mchnt_api_bk_avg_stat_')) except: log.debug(traceback.format_exc()) return ret
def _trans_input(self): d = {k:v.strip() for k, v in self.req.input().iteritems()} userid = int(self.user.userid) # 若在黑名单 if redis_pool.sismember('_mchnt_api_sale_limit_userids_', userid): raise ParamError('修改特卖活动失败') actv, actv_id = None, d.get('id') or '' with get_connection('qmm_wx') as db: where = {'qf_uid' : userid, 'id' : actv_id, 'atype' : SpecialDefine.ATYPE_SALE} actv = db.select_one('market_activity', where=where) # 若活动不存在 if not actv: raise ParamError('活动不存在') # 审核状态 state = SpecialApi.get_actv_state(actv) # 进行中 if state == SpecialDefine.STATE_ON: data = {i:d.get(i, '')for i in ['descr', 'img', 'quantity', 'redeem_start_time', 'redeem_end_time']} data['buyable_end_time'] = d['redeem_end_time'] data['online_time'] = str(actv['redeem_start_date']) + ' ' + data['redeem_start_time'] data['offline_time'] = str(actv['redeem_end_date']) + ' ' + data['redeem_end_time'] # 审核失败 elif state == SpecialDefine.STATE_REJECT: data = {i:d.get(i, '') for i in ['descr', 'img', 'quantity', 'title', 'price', 'origin_price']} if not is_valid_int(data['price']) and not is_valid_int(data['origin_price']): raise ParamError('价格必须为整数') # 价格限制 price_limit = int(redis_pool.get('_mchnt_api_sale_price_limit_') or 70000) if int(data['price']) > price_limit: raise ParamError('修改特卖活动失败') data['redeem_start_date'] = d.get('redeem_start_date') data['redeem_end_date'] = d.get('redeem_end_date') data['redeem_start_time'] = d.get('redeem_start_time', "05:00") data['redeem_end_time'] = d.get('redeem_end_time', "23:00") data['buyable_start_date'] = time.strftime('%Y-%m-%d') data['buyable_end_date'] = d.get('redeem_end_date') data['buyable_start_time'] = time.strftime('%H:%M:%S') data['buyable_end_time'] = d['redeem_end_time'] data['online_time'] = data['redeem_start_date'] + ' ' + data['redeem_start_time'] data['offline_time'] = data['redeem_end_date'] + ' ' + data['redeem_end_time'] else: raise ParamError('该活动不允许修改') if not is_valid_int(data['quantity']): raise ParamError('库存必须为整数') data['quantity'] = max(data['quantity'], 0) data['daily_quantity'] = actv['daily_quantity'] or actv['quantity'] data['daily_quantity'] += int(data['quantity']) - actv['quantity'] data['audit_status'] = SpecialDefine.AUDIT_STATUS_PLACED return {'actv_id' : actv['id'], 'data' : data}
def get_actv_pv(ids): '''获取活动的pv''' if not isinstance(ids, (types.ListType, types.TupleType)): ids = [ids] r = {} try: for i in ids: r[i] = redis_pool.get( '__member_actv_customer_%s_pv__' % i) or 0 except: log.warn('get pv error:%s' % traceback.format_exc()) return r
def password_error(self, userid, password, opuid=None): '''密码错误''' log.debug('[userid:%s opuid:%s password:%s]错误密码' % (userid, opuid, password)) if self.pwderr_conf.get('can_many_pwderr'): return redis_key = self.pwderr_fmt.format(userid=userid, opuid=opuid or 0, udid=self.req.input().get('udid')) if not redis_pool.get(redis_key): redis_pool.set(redis_key, 1, self.pwderr_conf['time']) else: redis_pool.incr(redis_key)
def __getitem__(self, key): '''获取缓存''' rkey = self._prefix + str(key) try: return json.loads(redis_pool.get(rkey)) except: pass ret = None try: ret = self._update_func(key) redis_pool.setex(rkey, json.dumps(ret, default=json_default_trans), self._timeout) except: log.warn(traceback.format_exc()) return ret
def GET(self): # userid = self.get_input_userid() params = self.req.input() if params.has_key('enuserid'): userid = params.get('enuserid') try: userid = int(userid) except: raise ParamError('enuserid参数错误') else: userid = int(self.user.userid) amt_per_wxpay = -1 # 获取每笔限额 try: is_display = int(redis_pool.get('mchnt_api_audit_display') or 0) if is_display: ret = thrift_call(DataEngine, 'get_risk_param', config.DATAENGINE_SERVERS, int(userid), '', 0x02) amt_per_wxpay = ret.user_param.param_list.param.get( 'amt_per_wxpay', 0) except: log.debug(traceback.format_exc()) # 获取审核信息 state = self.get_audit_state(userid) audit_info = {'info': '', 'title': '', 'memo': '', 'state': state} audit_info.update(UserDefine.AUDIT_STATE_DICT.get(state, {})) if state == UserDefine.AUDIT_FAIL: r = {} with get_connection('qf_mis') as db: other = 'order by create_date desc' where = {'user_id': int(userid)} r = db.select_one('mis_auditlog', where=where, other=other) or {} audit_info['memo'] = r.get('memo', '') # 更新审核状态 self.set_cache_audit(userid, state) return success({ 'amt_per_wxpay': amt_per_wxpay, 'audit_info': audit_info })
def check_user(self, userid, opuid): if self.pwderr_conf.get('can_many_pwderr'): return redis_key = self.pwderr_fmt.format(userid=userid, opuid=opuid or 0, udid=self.req.input().get('udid')) # 密码错误频繁, 用户需要稍后重试 pwderr_cnt = int(redis_pool.get(redis_key) or 0) if pwderr_cnt >= self.pwderr_conf['cnt']: if pwderr_cnt == self.pwderr_conf['cnt']: retry_time = self.pwderr_conf['retry_time'] redis_pool.incr(redis_key) redis_pool.expire(redis_key, retry_time) else: retry_time = redis_pool.ttl(redis_key) errinfo = '密码错误频繁, 请{}分钟后重试'.format(retry_time / 60) raise UserError(errinfo)
def POST(self): info = {'code': '', 'codeDesc': ''} params = self.req.inputjson() banktype = params.get('banktype', '1') if banktype == '1': userid = int(self.user.userid) key = 'verify_account_{}'.format(str(userid)) if redis_pool.exists(key): count = int(redis_pool.get(key)) if count >= config.CHANGE_BANK_LIMIT: info['codeDesc'] = config.CHANGE_LIMIT_TIP return self.write(success(info)) else: redis_pool.incr(key) else: redis_pool.incr(key) start_time_stmp = int(time.time()) end_time = datetime.now().strftime('%Y-%m-%d') + " 23:59:59" end_time_stmp = str_to_tstamp(end_time) expire_time = end_time_stmp - start_time_stmp redis_pool.expire(key, expire_time) bankuser = params.get('bankuser', '') bankaccount = params.get('bankaccount', '') r = apcli.userprofile_by_id(userid) if not r: raise ParamError('获取用户信息失败') else: idCard = r.get('user', {}).get('idnumber', '') result = verify_account(config.PATH, config.APPKEY, userCode="CITI20170912174935", sysCode="CITIAPP20170912175227", bankuser=bankuser, bankaccount=bankaccount, idCard=idCard) return self.write(success(result)) else: return self.write(success(info))
def is_new_card(userid, customer_id, src): '''将用户设置为新用户''' is_new = 0 TIME_LIMIT = 24 * 3600 with get_connection('qf_mchnt') as db: member = db.select_one('member', where={ 'customer_id': customer_id, 'userid': userid, }, fields='id, ctime') or [] key = '_mchnt_api_is_new_{}_{}_{}__'.format( userid, customer_id, src) now = int(time.time()) if (not member or (now - member['ctime'] < TIME_LIMIT and not redis_pool.get(key))): is_new = 1 redis_pool.set(key, 1, TIME_LIMIT) return is_new
def check(self, mobile, mode): if not is_valid_mobile(mobile): raise ParamError('手机号码不合法') if mode not in PRESMS_FMT: raise ParamError('发送验证码模式错误') # 验证ip是否受限 ip = self.req.clientip() log.debug('ip:%s' % ip) if redis_pool.sismember('_mchnt_api_sms_code_ip_', ip): raise ParamError('ip受限') # 手机号码是不是频繁获取验证码 key = '_mchnt_api_sms_code_get_{}_'.format(mobile) if int(redis_pool.get(key) or 0) >= config.SMS_CODE_RULE['count_limit']: raise ParamError('该手机号频繁获取验证码') self._rkey = key self._groupid = None if mode.startswith('signup'): self.check_signup(mobile) elif callable(getattr(self, 'check_' + mode, None)): getattr(self, 'check_' + mode)(mobile)
def GET(self): try: params = self.req.input() for i in ('client_id', 'code', 'client_secret'): if not params.get(i): raise ParamError('%s is must' % i) if (params['client_id'] != config.LST_CONF['client_id'] or params['client_secret'] != config.LST_CONF['client_secret'] ): raise MacError('client 验证失败') # 验证code rkey = config.LST_CONF['code_fmt'].format(params['code']) userid = redis_pool.get(rkey) if not userid: raise MacError('code 验证失败') redis_pool.delete(rkey) # 生成access_token access_token = str(uuid.uuid1()) ak_rkey = config.LST_CONF['access_token_fmt'].format(access_token) redis_pool.hmset(ak_rkey, {'cnt': 0, 'userid': userid}) expire = config.LST_CONF['access_token_expire'] redis_pool.expire(ak_rkey, expire) ret = { 'access_token': access_token, 'expire' : expire } except: log.warn(traceback.format_exc()) ret = {} return json.dumps(ret)
class Send(BaseHandler): ''' 获取验证码, 发验证码 ''' _base_err = '获取验证码失败' def check_signup(self, mobile): ''' 登录验证码验证 ''' # 验证手机号是否注册 user = apcli.user_by_mobile(mobile) if user: raise ParamError('该手机已经注册') # 验证登录信息 if self.check_login(): self._groupid = self.get_groupid() # saleman_mobile d = self.req.input() if (not getattr(self, '_groupid', None) and 'saleman_mobile' in d and d['saleman_mobile']): user = apcli.user_by_mobile(d['saleman_mobile']) if user: self._groupid = user['groupid'] def check_reset_pwd(self, mobile): user = apcli.user_by_mobile(mobile) if not user: raise ParamError('该手机号还未注册') self._groupid = user['groupid'] def check_customer(self, mobile): ''' 消费者补充会员休息 ''' enuserid = self.req.input().get('enuserid') if enuserid: try: userid = hids.decode(enuserid)[0] except: if not is_valid_int(enuserid): return userid = int(enuserid) user = apcli('findUserBriefById', userid) if user: self._groupid = user.groupid @login def check_modify_username_grant(self, mobile): userid = int(self.user.userid) user = apcli_ex('findUserBriefById', userid) if not user: raise ParamError('商户不存在') if mobile != user.mobile: raise ParamError('账号信息错误, 联系客服更改') self._groupid = user.groupid @login def check_modify_username_verify(self, mobile): with get_connection_exception('qf_core') as db: new_user = db.select_one('auth_user', where={'mobile': mobile}) if new_user: raise ParamError('该手机已经注册') userid = int(self.user.userid) user = apcli_ex('findUserBriefById', userid) if not user: raise ParamError('商户不存在') self._groupid = user.groupid def check(self, mobile, mode): if not is_valid_mobile(mobile): raise ParamError('手机号码不合法') if mode not in PRESMS_FMT: raise ParamError('发送验证码模式错误') # 验证ip是否受限 ip = self.req.clientip() log.debug('ip:%s' % ip) if redis_pool.sismember('_mchnt_api_sms_code_ip_', ip): raise ParamError('ip受限') # 手机号码是不是频繁获取验证码 key = '_mchnt_api_sms_code_get_{}_'.format(mobile) if int(redis_pool.get(key) or 0) >= config.SMS_CODE_RULE['count_limit']: raise ParamError('该手机号频繁获取验证码') self._rkey = key self._groupid = None if mode.startswith('signup'): self.check_signup(mobile) elif callable(getattr(self, 'check_' + mode, None)): getattr(self, 'check_' + mode)(mobile) @dec_check() def GET(self): d = {k: v.strip() for k, v in self.req.input().iteritems()} mobile = d.get('mobile') mode = d.get('mode', 'signup') # 验证信息 self.check(mobile, mode) # 获取验证码 try: smsexpires = config.SMS_CODE_RULE.get('expires', 6 * 50) smslength = config.SMS_CODE_RULE.get('length', 6) smsmode = config.SMS_CODE_RULE.get('mode', 1) limit_time = config.SMS_CODE_RULE.get('limit_time', 60) code = thrift_callex(config.CAPTCHA_SERVERS, CaptchaServer, 'captcha_get_ex', ucode=mobile, src=config.CAPTCHA_SRC, expires=smsexpires, length=smslength, mode=smsmode, limit_time=limit_time) log.debug('获取验证码:%s' % code) except CaptchaException, e: raise ParamError(str(e.respmsg)) # 短信内容 groupid = getattr(self, '_groupid', None) if 'group' in d and d['group']: group = d['group'] else: group = redis_pool.get( '_mchnt_api_group_{}_'.format(groupid)) or 'hjsh' log.debug('groupid:{} group:{}'.format(groupid, group)) fmt = PRESMS_FMT.get(mode + '_' + group, PRESMS_FMT[mode]) csinfo = get_qd_conf_value( userid=None, mode=None, key='csinfo', groupid=groupid) or {} csinfo = {k: unicode_to_utf8_ex(v) for k, v in csinfo.iteritems()} content = fmt.format(code=code, **csinfo) log.debug('content:%s' % content) # 短信tag tags = config.PRESMS_TAG tag = tags.get(groupid or group, tags['hjsh']) r, respmsg = smscli.sendSms(mobile=mobile, content=str(content), tag=tag, source='merchant', target=mode) if not r: log.debug('调起发送短信服务失败:%s' % respmsg) raise ThirdError('发送验证码失败') # 设置获取验证码限制 if not redis_pool.exists(self._rkey): redis_pool.set(self._rkey, 0, config.SMS_CODE_RULE['expire_limit']) redis_pool.incr(self._rkey) return self.write(success({}))
def __getitem__(self, k, default=None): return json.loads(redis_pool.get(k))
def GET(self): userid = int(self.user.userid) allgoods = copy.deepcopy(config.GOODS) payinfos = [] vip_goods = {} gratis_goods = config.GOODS[0] for goods in allgoods: if goods.get('is_gratis'): gratis_goods = goods else: vip_goods[goods['code']] = goods with get_connection('qf_mchnt') as db: payinfos = db.select( table= 'recharge', where= { 'userid': userid, 'goods_code': ('in', vip_goods.keys()) }, fields= 'expire_time, status, goods_code') or [] payinfos = {payinfo['goods_code']:payinfo for payinfo in payinfos} # 当前服务 now = datetime.datetime.now() expire_code = vip_code = None for code, payinfo in payinfos.iteritems(): if not vip_code or vip_goods[code]['vip'] > vip_goods[vip_code]['vip']: vip_code = code if ((payinfo['expire_time'] > now) and (not expire_code or vip_goods[code]['vip'] > vip_goods[expire_code]['vip'])): expire_code = code curgoods = vip_goods.get(expire_code or vip_code, gratis_goods) # 当前服务信息 cur_payinfo = { 'name': curgoods['name'], 'logo_url': curgoods['logo_url'], 'code': curgoods['code'] } if curgoods.get('is_gratis'): cur_payinfo['expire_time'] = '' else: cur_payinfo['expire_time'] = payinfos[curgoods['code']]['expire_time'] # 更高级服务信息 up_goods, up_opt = [], [] fields = ['services', 'color', 'pg_name', 'desc'] for goods in allgoods: if goods['vip'] < curgoods['vip']: continue elif goods['code'] == curgoods['code']: goods['pg_name'] = '我的权益' else: goods['pg_name'] = '{}权益'.format(goods['name']) up_opt.append({ 'name': '升级到{}'.format(goods['name']), 'code': goods['code'] }) goods['services'] = [{i:service.get(i, '') for i in ['title', 'icon_url', 'info_url']} for service in goods['services']] t = {field:goods[field] for field in fields} try: redis_key = '__mchnt_api_goods_info_{}_{}__'.format(userid, goods['code']) update_data = json.loads(redis_pool.get(redis_key)) t.update(update_data) except: pass up_goods.append(t) return self.write(success({'payinfo': cur_payinfo, 'up_goods': up_goods, 'up_opt': up_opt}))