def set_value(path, value={}, ttl=None): global ETCD_SERVER data = {} if isinstance(value, basestring): data['value'] = value else: data['value'] = json.dumps(value) if ttl: data['ttl'] = ttl log.info('server=etcd|func=set|path=%s|value=%s|ttl=%s' % (path, value, ttl)) try: client = HttpClient(ETCD_SERVER) ret = client.put(path, data) if ret: ret = json.loads(ret) value = ret.get('node', {}).get('value') if value: value = json.loads(value) return value except: log.warn(traceback.format_exc()) return {}
def setUp(self): self.url = '' self.send = {} self.host = '127.0.0.1' self.port = 7010 self.timeout = 20000 self.server = [ { 'addr': (self.host, self.port), 'timeout': self.timeout }, ] self.client = HttpClient(self.server, client_class=RequestsClient) self.headers = {} self.cookies = {'csid': 'b19c0021-9b99-4fd7-b5ee-7bdb83c3f98d'}
def push_entry_bind(self, data): params = { 'userid': data['userid'], 'apptype': data['apptype'], 'deviceid': self.push_entry_get_deviceid(data), 'platform': self.platform, 'sdk': self.sdk, } if 'appver' in data: params['appversion'] = data['appver'] if not params['deviceid']: log.warn('未找到deviceid') return if params['apptype'] not in config.SIGN_KEYS: log.warn('[apptype:%s]不合法' % params['apptype']) return params['sign'] = self.sign(params, config.SIGN_KEYS[params['apptype']]) if data.get('is_logout'): url = '/pushapi/v1/dev/unbind' else: url = '/pushapi/v1/dev/bind' HttpClient(config.PUSH_BIND_SERVERS).post_json(url, params)
def qt2_requests( url, data, method='get', appcode=config.WXY_QT2_CONF['appcode'], appkey=config.WXY_QT2_CONF['appkey'] ): '''qiantai2访问''' headers = { 'X-QF-APPCODE': appcode, 'X-QF-SIGN': make_sign(data, appkey) } try: client = HttpClient(config.QT2_SERVER) func = getattr(client, method) ret = func(url, data, headers=headers) data = json.loads(ret) except: log.warn(traceback.format_exc()) raise ThirdError('服务内部错误') respcd = data.pop('respcd', None) if respcd == '0000': return data else: raise MchntException(data['respmsg'], data['resperr'], respcd)
def prepaid_actv(self): ''' 获取储值活动 ''' params = {} params['status'] = '1' params['pos'] = 0 params['count'] = 10 params['activity_status'] = '1' merchant_path = '/prepaid/v1/api/b/activity_detail' try: client = HttpClient(config.PREPAID_SERVERS) ret = json.loads( getattr(client, 'get')(merchant_path, headers={ 'COOKIE': 'sessionid={}'.format( self.get_cookie('sessionid')) })) if ret['respcd'] == "0000": rules = ret.get('data', {}).get('rules', []) if rules: mchnts_sorted = sorted(rules, key=lambda x: (x['present_amt']), reverse=True) result = mchnts_sorted[0].get('present_amt', 0) return result except: log.warn(traceback.format_exc()) return 0
def up_vouchers(self, userid, enuserid, vouchers): '''上传凭证照片''' if not vouchers: return # 特定上传enuserid, 需要移动到指定目录 if enuserid == 'EPeRaNEt': imgnames = [i['imgname'] for i in vouchers] HttpClient(config.OPENAPI2_SERVERS).post( '/util/v1/mvfile', { 'imgname': ','.join(imgnames), 'userid': userid }) insert_data = [] for i in vouchers: insert_data.append({ 'user_id': userid, 'upgrade_id': 0, 'apply_level': 0, 'cert_type': i['cert_type'], 'name': i['name'], 'submit_time': 'now()', 'state': ApplyDef.VOUCHER_STATE_PASS, 'input_state': 1, 'typist_user': 0, 'typist_time': 'now()', 'imgname': i['imgname'] }) with get_connection('qf_mis') as db: db.insert_list( 'mis_upgrade_voucher', insert_data, other=('on duplicate key update state=values(state),' 'imgname=values(imgname)'))
def _query_qt2(): '''从qt2查询订单信息''' p = {'syssn': d['out_sn']} headers = { 'X-QF-APPCODE': config.QT2_APP_CODE, 'X-QF-SIGN': RechargeUtil.make_sign(p) } try: client = HttpClient(config.QT2_SERVER) r = json.loads( client.get('/trade/v1/query', params=p, headers=headers)) if r['respcd'] == '0000' and r['data']: return r['data'][0] except: log.warn('qt2 query error:%s' % traceback.format_exc()) raise ThirdError('获取订单信息失败')
def trade_push(self, actv, member, code_info): '''推送''' customer_id = member['customer_id'] appid, hj_appid = self.get_appid() try: p = {} p['appid'] = appid # 获取openid p['openid'] = thrift_callex(config.OPENUSER_SERVER, OpenUser, 'get_openids_by_user_ids', hj_appid, [ customer_id, ])[0] # 店铺名 user = apcli_ex('findUserBriefById', int(self.user.userid)) p['shopname'] = user.shopname if user else '' p['exchange_num'] = member['exchange_num'] + 1 p['exchange_pt'] = actv['exchange_pt'] p['obtain_amt'] = actv['obtain_amt'] p['busicd'] = 'card_actv_exchange' p['goods_amt'] = actv['goods_amt'] p['goods_name'] = actv['goods_name'] p['code'] = code_info['code'] p['customer_id'] = hids.encode(customer_id) p['activity_id'] = actv['id'] p['card_id'] = member['id'] p = { unicode_to_utf8(k): unicode_to_utf8(v) for k, v in p.iteritems() } HttpClient(config.TRADE_PUSH_SERVER).post('/push/v2/push', params=p) except: log.warn('error:%s' % traceback.format_exc())
def push_msgs(result, datas): if not datas or not result: return # 写入actv_effect insert_status = None with get_connection('qf_mchnt') as db: insert_status = db.insert_list('actv_effect', result) # 推送 if not insert_status: return try: client = HttpClient(config.TRADE_PUSH_SERVER) for data in datas: data['busicd'] = 'actv_effect' client.get('/push/v2/msg', data) except: log.warn('push msg error:%s' % traceback.format_exc())
def prepaid_data(userid, **kw): '''储值面板''' actvs = None try: # 获取储值信息 actvs = json.loads( HttpClient(config.PREPAID_SERVERS).get( path='/prepaid/v1/api/b/activity_history?pos=0&count=1', headers={'COOKIE': 'sessionid={}'.format(kw.get('sesid', ''))}))['data'] actvs = [actv for actv in actvs or [] if actv['status'] == 1] except: log.warn(traceback.format_exc()) if not actvs: return None pannels = [] now = datetime.datetime.now() for actv in actvs: try: info = json.loads( HttpClient(config.PREPAID_SERVERS).get( path='/prepaid/v1/api/b/stat/activity/{}'.format( actv['activity_id']), headers={ 'COOKIE': 'sessionid={}'.format(kw.get('sesid', '')) }))['data'] start_time = datetime.datetime.strptime(actv['start_time'], DTM_FMT) actv['ondays'] = max(0, (now - start_time).days + 1) actv['create_time'] = time.mktime(start_time.timetuple()) actv['total_pay_amt'] = int(actv['total_pay_amt']) / 100.0 actv['total_txamt'] = int(actv['total_txamt']) / 100.0 actv['today_total_pay_amt'] = int( info['today_total_pay_amt']) / 100.0 pannel = adjust_data('prepaid_data', actv, **kw) if pannel: pannels.append(pannel) except: log.warn(traceback.format_exc()) return pannels
def push(cid): try: customer_info = get_customer_info(cid) p = { 'customer_id': hids.encode(int(cid)), 'busicd': 'promote_note', } p.update(customer_info) HttpClient(config.TRADE_PUSH_SERVER).post('/push/v2/msg', params=p) except: log.warn('push error :%s' % traceback.format_exc()) redis_pool.sadd('_mchnt_api_pusherror_', cid)
def today_data(userid, **kw): '''今日数据''' data = {} # 今日交易总笔数, 总金额 data['total_amt'] = data['total_count'] = 0 try: # 获取今日数据 stat = json.loads( HttpClient(config.OPENAPI_TRADE_SERVERS).get( path='/trade/v1/tradestat', headers={'COOKIE': 'sessionid={}'.format(kw.get('sesid', ''))}))['data'] td = time.strftime(DATE_FMT) stat = next((i for i in stat if i['date'] == td), None) if stat: fields = getattr(config, 'TRADE_STATE_FIELDS', ['alipay', 'weixin', 'jdpay', 'qqpay', 'card']) for key, v in stat.iteritems(): if key in fields: data['total_amt'] += v['sum'] data['total_count'] += v['count'] data['total_amt'] /= 100.0 except: log.debug(traceback.format_exc()) # 新增会员, 回头客 data['add_num'] = data['old_num'] = 0 with get_connection('qf_mchnt') as db: now = int(time.mktime(datetime.date.today().timetuple())) r = db.select( 'member', fields='(ctime > {}) as state, count(1) as num'.format(now), where={ 'userid': userid, 'utime': ('>=', now) }, other='group by ctime > {}'.format(now)) records = {i['state']: i['num'] for i in r} data['add_num'] = records.get(1, 0) data['old_num'] = records.get(0, 0) return adjust_data('today_data', data, **kw)
def send_over(userids): with get_connection('qf_mchnt') as db: users = db.select('member', where = {'userid': ('in', userids)}, fields='userid, count(1) as num', other='group by userid') or [] users = [(i['userid'],i['num']) for i in users] for userid,num in users: try: redis_pool.hincrby(SEND_KEY, userid) p = { 'userid': userid, 'num': num, 'busicd': 'app_promote_send_over', } HttpClient(config.TRADE_PUSH_SERVER).post('/push/v2/msg', params=p) except: log.warn('push app error :%s' % traceback.format_exc()) redis_pool.sadd('_mchnt_api_pushapperror_', userid)
def del_pay_sequence(self, value): conf = copy.deepcopy(value) try: actvs = json.loads( HttpClient(config.PREPAID_SERVERS).get( path='/prepaid/v1/api/b/activity_history?pos=0&count=1', headers={ 'COOKIE': 'sessionid={}'.format(self.get_cookie('sessionid')) }))['data'] if not actvs and 'prepaid' in conf: conf.remove('prepaid') except: log.warn(traceback.format_exc()) # 支持刷卡的ua user_agent = self._ua.upper() for i in UA_CARDS: if i in user_agent: conf.append('card') break return conf
def get_value(path, wait=False, index=1): global ETCD_SERVER, ETCD_INDEX value = {} try: if wait: client = HttpClient(ETCD_SERVER, log_except=False) else: client = HttpClient(ETCD_SERVER) # 如果是watch if wait: ret = client.get(path, {'wait': 'true', 'waitIndex': index}) else: ret = client.get(path) if ret: ret = json.loads(ret) #缓存index headers = client.client.headers ETCD_INDEX[path] = int(headers.get('X-Etcd-Index', 0)) #如果是目录 if ret.get('node', {}).get('dir', False): nodes = ret.get('node', {}).get('nodes', {}) for node in nodes: #TODO 忽略目录 忽略多级 理论应该递归处理 #如果是节点 if not node.get('dir', False) and not node.get( 'key', '').endswith('/base'): value[node.get('key', '')] = json.loads( node.get('value', '{}')) #如果是节点 else: j = ret.get('node', {}).get('value') if j: value = json.loads(j) except: log.warn(traceback.format_exc()) if not wait: log.info('server=etcd|func=get|path=%s|value=%s' % (path, value)) return value
class TestPayquick(unittest.TestCase): def setUp(self): self.url = '' self.send = {} self.host = '127.0.0.1' self.port = 7010 self.timeout = 20000 self.server = [ { 'addr': (self.host, self.port), 'timeout': self.timeout }, ] self.client = HttpClient(self.server, client_class=RequestsClient) self.headers = {} self.cookies = {'csid': 'b19c0021-9b99-4fd7-b5ee-7bdb83c3f98d'} @unittest.skip("skipping") def test_register(self): self.url = '/fenqi/v1/api/user/bind' self.send = { 'mobile': '13802438721', 'verify_code': '111111', 'redirect_url': 'http://www.baidu.com' } ret = self.client.post_json(self.url, self.send, cookies=self.cookies) log.info(ret) respcd = json.loads(ret).get('respcd') self.assertEqual(respcd, '0000') @unittest.skip("skipping") def test_send_sms(self): self.url = '/fenqi/v1/api/tools/send' self.send = { 'mobile': '15708478799', } ret = self.client.post_json(self.url, self.send, cookies=self.cookies) log.info(ret) respcd = json.loads(ret).get('respcd') self.assertEqual(respcd, '0000') @unittest.skip("skipping") def test_user_check(self): self.url = '/fenqi/v1/api/user/check/info' self.send = { 'mobile': '13802438721', 'verify_code': '111111', } ret = self.client.post_json(self.url, self.send, cookies=self.cookies) log.info(ret) respcd = json.loads(ret).get('respcd') self.assertEqual(respcd, '0000') #@unittest.skip("skipping") def test_user_check(self): self.url = '/fenqi/v1/api/user/info' self.send = { 'mobile': '13802438721', 'verify_code': '111111', } ret = self.client.get(self.url, self.send, cookies=self.cookies) log.info(ret) respcd = json.loads(ret).get('respcd') self.assertEqual(respcd, '0000')
def create(self, img, title, origin_price, price, quantity, redeem_start_date, redeem_end_date, redeem_start_time="01:00", redeem_end_time="23:59", descr=''): sessionid = self.get_cookie('sessionid') redeem_start_time = max(redeem_start_time, '01:00') redeem_end_time = min(redeem_end_time, '23:59') item_price = '{:.2f}'.format(origin_price / 100.0) images='["%s"]' % (img, ) client = HttpClient(config.SALE_SERVERS) headers = {'COOKIE': 'sessionid={}'.format(sessionid)} # 创建商品 try: item_ret = json.loads(client.post( path = '/qmm/near/item/new', params = { 'title' : title, 'price' : item_price, 'descr' : descr, 'images' : images }, headers = headers)) if item_ret['respcd'] != '0000': raise except: raise ParamError('创建商品失败') # 创建活动 item = item_ret['data']['item'] price = '{:.2f}'.format(price/100.0) try: actv_ret = json.loads(client.post( path = '/qmm/near/activity/new', params = { 'item_id' : item['id'], 'atype' : SpecialDefine.ATYPE_SALE, 'atag' : 7, 'price' : price, 'quantity' : quantity, 'available_date' : '["%s","%s"]' % (redeem_start_date, redeem_end_date), 'available_time' : '["%s","%s"]' % (redeem_start_time, redeem_end_time) }, headers = headers)) if actv_ret['respcd'] != '0000': raise except: raise ParamError('创建特卖失败') activity_id = actv_ret['data']['activity']['id'] # 修改活动状态为 审核成功和 上线 with get_connection('qmm_wx') as db: db.update( table = 'market_activity', values = { 'audit_status' : SpecialDefine.AUDIT_STATUS_SUCCESS, 'status' : SpecialDefine.STATUS_NORMAL, }, where = {'id' : activity_id}) return activity_id