def pay_goods_id(gid, count, session, pay_type): ''' pay by the count and the id the goods; input: gid --- the id of the goods; count --- the count of the goods; session --- the login session of the user; pay_type --- payment type; ''' user_session = check_session(session) if not user_session: return 10000, u'login expire' LOG.info(user_session) user_openid = user_session['openid'] order_obj, data = place_order_by_gid(gid, count, user_openid, pay_type) if not order_obj: return -1, data total_fee = order_obj.total_fee out_trade_no = order_obj.out_trade_no desc = order_obj.body place_order_ret, ret_msg = unified_order(total_fee, pay_type, out_trade_no, user_openid, desc) if not place_order_ret: return -1, u'place order to wx error: %s' % ret_msg return 0, ret_msg
def send_template_poetry(user_data, poetry_data): author_id = poetry_data['author_id'] author = poetry_data['author'] title = poetry_data['title'] openid = user_data['openid'] recited = user_data['recited'] if not isinstance(author, unicode): author = unicode(author, 'utf-8') if not isinstance(title, unicode): title = unicode(title, 'utf-8') form_obj = FormId(openid=openid) form_record = form_obj.get_one_formid() if not form_record: LOGGER.info("openid: %s not found formid", openid) return {} template_id = 'tm5oAyq-YcBJhP2EOIAskBbGZp2Iyq0JVzfv0083e-Y' data = {} data['touser'] = openid data['template_id'] = template_id data['form_id'] = form_record['formid'] data['page'] = '/pages/authorPoetry/authorPoetry?id=%s' % author_id keywords = {} keywords['keyword1'] = {'value': u'每日一学'.encode("utf-8")} keywords['keyword2'] = {'value': title.encode("utf-8")} keywords['keyword3'] = {'value': (u"%s诗词" % author).encode("utf-8")} keywords['keyword4'] = {'value': recited} keywords['keyword5'] = {'value': u"点击进去查看详情".encode("utf-8")} data['data'] = keywords LOGGER.info(data) client = WechatClient(XCX_APPID, XCX_APPSEC, session=data_cache) res = client.weapp.send_template_msg(data) return res
def save_formid(session_data, formid): openid = session_data['openid'] LOGGER.info("openid: %s, formid: %s", openid, formid) if formid.find('mock') != -1: return formid_obj = FormId(openid=openid, formid=formid) formid_obj.save()
def local_search(params): keyword = params.get("keyword") page = int(params.get("page", 1)) count = int(params.get("count", 20)) sort = int(params.get('tid', 1)) if isinstance(keyword, unicode): keyword = keyword.encode("utf-8") share_text_info = find_goods_info(keyword) if share_text_info: num_id = share_text_info['num_id'] save_goods_info(num_id, share_text_info) tmp = _ship_miniapp(share_text_info) return {'errcode': 0, 'data': [tmp]} data = [] sort_dict = {} if sort == 8: sort_dict.update({'coupon_amount': -1}) elif sort == 6: sort_dict.update({'sales': -1}) elif sort == 7: sort_dict.update({'coupon_fee': 1}) elif sort == 9: super_params = { 'keyword': keyword, 'page': page, 'count': count, 'yq': 0, 'tid': 0 } return super_search_miniapp(super_params) data = searcher.search(keyword, sort_dict, page=page, count=count) # ids = map(lambda x: int(x['id']), data) # LOG.info("data: %s", data) LOG.info('keyword: %s, ret: %s', keyword, len(data)) table_dict = {} ordered_id = [] for item in data: table = item.get("table", 'goods') table_dict.setdefault(table, []) table_dict[table].append(int(item['id'])) ordered_id.append(int(item['id'])) goods_obj = TbkGoods() data_dict = {} for table, ids in table_dict.items(): goods_obj.__table__ = table cond = {'num_id': {'$in': ids}} goods_list = goods_obj.find_goods_by_cond(cond, 1, count=100) for goods in goods_list: if goods.get('num_id') is None: LOG.info(goods['_id']) continue tmp = _ship_miniapp(goods) data_dict[goods['num_id']] = tmp result = [] for _id in ordered_id: tmp = data_dict.get(_id) if not tmp: continue result.append(tmp) return {'errcode': 0, 'data': result}
def super_search(params): keyword = params.get("keyword") if keyword is None: return False, u"搜索关键字不能为空" page = params.get("page", 1) count = params.get("count", 50) is_tmall = params.get("is_tmall") if isinstance(page, (unicode, str)) and not page.isdigit() or\ (isinstance(count, (unicode, str)) and not count.isdigit()): return False, u"page非法" sp = SearchParams() sp.keyword = keyword sp.page = int(page) sp.count = int(count) sp.is_tmall = 'true' if is_tmall else 'false' result = [] try: # result = tbk_client.super_search(sp) result = _super_search(sp, tbk_client) result = result['tbk_dg_material_optional_response'][ 'result_list']['map_data'] except Exception as ex: LOG.error("super search ex: %s, word: %s", ex, keyword) return False, u"数据异常: %s" % ex goods_data = [] for goods in result: tmp = _ship_goods_supers(goods) if not tmp: continue num_id = tmp['num_id'] save_goods_info(num_id, tmp) tmp = _ship_db_goods(tmp) goods_data.append(tmp) return True, goods_data
def super_search(self, search_params): top.setDefaultAppInfo(self.appid, self.appsec) keyword = search_params.keyword client_req = top.api.TbkDgMaterialOptionalRequest() if keyword: if isinstance(keyword, unicode): keyword = keyword.encode("utf-8") client_req.q = keyword if not keyword: client_req.cat = search_params.cat client_req.page_no = search_params.page client_req.page_size = search_params.count client_req.platform = search_params.platform client_req.is_overseas = search_params.is_overseas client_req.is_tmall = search_params.is_tmall if search_params.sort: client_req.sort = search_params.sort client_req.has_coupon = search_params.has_coupon client_req.need_free_shipment = search_params.need_free_shipment client_req.adzone_id = self.adzone_id client_req.site_id = self.site_id res = {'errcode': -1} try: res = client_req.getResponse() res['errcode'] = 0 except Exception as ex: LOG.error("super search keyword: %s, ex: %s", keyword, ex, exc_info=True) return res
def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception as ex: exc_type, value, detail = sys.exc_info() formatted_tb = traceback.format_tb(detail) _LOGGER.exception(formatted_tb) return {'errcode': -1, 'errmsg': ex}
def upload_image(user, files): result_dict = {} for filename, file_storage in files.items(): url = upload_image_qiniu(file_storage.read()) LOGGER.info("filename: %s, url: %s, type: %s", filename, url, file_storage.mimetype) result_dict[file_storage.filename] = url return result_dict
def process(self): LOG.info(self.message_instance.msg_id) event_type = self.message_instance.event_type handler = MESSAGE_HANDLER.get(event_type) LOG.info("type: %s, handler: %s", event_type, handler) if handler: return handler(self.message_instance, self.visitor, self.channel).process() return
def code2userinfo(code): user_token_data = CLIENT.oauth.fetch_user_access_token(code) LOGGER.info(user_token_data) openid = user_token_data['openid'] refresh_token = user_token_data['refresh_token'] userdata = CLIENT.oauth.get_user_info(openid) userdata.update({"refresh_token": refresh_token}) LOGGER.info(userdata) return userdata
def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception as ex: exc_type, value, detail = sys.exc_info() formatted_tb = traceback.format_tb(detail) message = "url: %s traceback=%s" % (request.url, formatted_tb) _LOGGER.exception(message) return jsonify({'sta': -1, 'msg': '%s' % ex})
def _check_order(out_trade_no): order_data = {} try: order_data = pay_client.order.query(out_trade_no) except Exception as ex: LOG.error("query order: %s, ex: %s", out_trade_no, ex) if order_data.get("trade_state") == 'SUCCESS': return True return False
def get_subscribe_userdata(openid): res = {"errcode": -1} try: userdata = CLIENT.user.get(openid) res.update({'errcode': 0, 'data': userdata}) except Exception as ex: LOGGER.error("openid: %s, ex: %s", openid, ex, exc_info=True) res.update({"errmsg": ex}) return res
def wrapper(self, url, **kwargs): LOG.info(kwargs) res = func(self, url, **kwargs) if not res: return {'errcode': -1, 'errmsg': "no data return"} he_res = res['HeWeather6'][0] if he_res['status'] != 'ok': LOG.error("he weather return error: %s", he_res) return {"errcode": -1, 'errmsg': he_res['status']} return {'errcode': 0, 'data': he_res}
def check_image(sio): content = sio.read() filename = '/tmp/{}'.format(uuid.uuid4().hex) with open(filename, 'w') as _file: _file.write(content) res = check_img_risk(filename) LOGGER.info(res) if res.get('errcode') != 0: return False return True
def reply(self): '''reply content''' event_key = self.event_obj.key LOGGER.info(event_key) if event_key == 'we': return TextReply(message=self.event_obj, content=MY_MSG) elif event_key == 'randomPoetry': ret = send_random_poetry(self.event_obj.source) LOGGER.info("send openid: %s, ret: %s", self.event_obj.source, ret) return EmptyReply(message=self.event_obj)
def search_coupon_by_id(num_iid, TBK_REQ_CLIENT=None, fields_goods=False): if TBK_REQ_CLIENT: client = TBK_REQ_CLIENT else: client = tbk_client res = {'errcode': -1} goods_info = get_goods_info(num_iid) if not goods_info: res.update({'errmsg': u"商品不存在"}) return res title = goods_info['title'] page = 1 count = 200 sp = SearchParams() sp.keyword = title sp.page = int(page) sp.count = int(count) sp.is_tmall = 'false' sp.has_coupon = 'false' result = [] try: # result = client.super_search(sp) result = _super_search(sp, client) result = result['tbk_dg_material_optional_response'][ 'result_list']['map_data'] except Exception as ex: LOG.error("super search ex: %s, word: %s", ex, title, exc_info=True) res.update({'errmsg': u"exception: %s" % ex}) return res coupon_share_url = '' for goods in result: goods = _ship_goods_supers(goods) search_id = goods.get("num_id") if not search_id: continue LOG.info( "title: %s, good: %s, coupon: %s", title, goods['title'], goods['coupon_amount']) if num_iid == goods['num_id']: coupon_share_url = goods['coupon_share_url'] break if not coupon_share_url: res.update({'errmsg': u"获取失败,请稍后重试"}) return res if fields_goods: data = goods else: tpw = generate_tpw(coupon_share_url, title, goods['pic_url']) data = { 'coupon_tpw': tpw, 'num_iid': num_iid, "coupon_url": coupon_share_url } res.update({'errcode': 0, 'data': data}) return res
def upload_qiniu_storage(url): _http = HttpClient() res = None try: res = _http.get(url) except Exception as ex: LOGGER.error("url: %s, ex: %s", url, ex, exc_info=True) return '' if not res: return '' return upload_image_qiniu(res)
def decrypt_tpw(self, tpw): top.setDefaultAppInfo(self.appid, self.appsec) client = top.api.TbkTpwQueryGetRequest() client.password_content = tpw client.adzone_id = self.adzone_id res = None try: res = client.getResponse() except Exception as ex: LOG.error("tpw: %s ex: %s", tpw, ex, exc_info=True) return res
def get_ip_info(ip): weather = '----\n----\n气温--℃/--℃' lunar_date = '' today = datetime.now() try: weather = get_ip_weather(ip) lunar_date = get_lunar_date() except Exception as ex: LOGGER.error("get ip info ex: %s", ex, exc_info=True) today = datetime.now() lunar_date = u'----\n----\n星期{}'.format(WEEK_MAP[today.weekday()]) return {'weather': weather, 'lunar_date': lunar_date}
def find(self, table, cond, fields=[], page=1, count=20, sort=None): LOG.info("cond: %s, sort: %s", cond, sort) skip = (page - 1) * count if not fields: cursor = self.db[table].find(cond) else: cursor = self.db[table].find(cond, fields) if sort: cursor = cursor.sort(sort).skip(skip).limit(count) else: cursor = cursor.skip(skip).limit(count) return cursor
def get_data(self, params): res = self.validate(params) if res['errcode'] != 0: return res cond = self.build_condition() sort = self.get_sort_field() LOG.info("cond: %s, sort: %s", cond, sort) goods_obj = TbkGoods() ret = goods_obj.find_goods_by_cond(cond, self.page, self.count) if sort: ret.sort(sort) return {'errcode': 0, 'data': ret}
def tbk_goods_info(self, num_id, platform=2): top.setDefaultAppInfo(self.appid, self.appsec) if isinstance(num_id, list): num_id = ','.join(num_id) client_req = top.api.TbkItemInfoGetRequest() client_req.num_iids = str(num_id) client_req.platform = platform res = None try: res = client_req.getResponse() except Exception as ex: LOG.error("num_id: %s, ex: %s", num_id, ex) return res
def tbk_goods_recommend(self, num_iid): top.setDefaultAppInfo(self.appid, self.appsec) client_req = top.api.TbkItemRecommendGetRequest() client_req.num_iid = str(num_iid) client_req.fields = 'num_iid,title,pict_url,small_images,'\ 'reserve_price,zk_final_price,user_type,item_url' client_req.count = 20 res = None try: res = client_req.getResponse() except Exception as ex: LOG.error("num_id: %s, ex: %s", num_iid, ex) return res
def wxpay_ok(data): res = xml_to_dict(data) LOG.info("wxpay pushed data:%s", res) out_trade_no = res['out_trade_no'] sign = res.pop('sign', '') real_sign = pay_sign(res, PAY_KEY) update_data = {} if real_sign != sign: LOG.error("id: %s, got unexcepted sign: %s, real: %s", out_trade_no, sign, real_sign) update_data.update({'status': OrderStatus.SIGNERROR.value}) return ret_code = res['return_code'] ret_msg = res.get('return_msg') if ret_code != 'SUCCESS': update_data.update({'status': OrderStatus.WXERROR.value}) LOG.error("id: %s, msg: %s", out_trade_no, ret_msg) return if not _check_order(out_trade_no): update_data.update({'status': OrderStatus.ORDERERROR.value}) LOG.error("id: %s, query error", out_trade_no) return transaction_id = res['transaction_id'] update_data.update({ "transaction_id": transaction_id, 'update_time': int(time.time() * 1000), "status": OrderStatus.OK.value }) order_instance = Order(out_trade_no=out_trade_no) order_instance.update(update_data) openid = res['openid'] do_add_credit(openid, out_trade_no)
def login_ok(event_data): user_openid = event_data.get('FromUserName') qr_scene = event_data.get('EventKey') if not user_openid or not qr_scene: LOG.error("got error data: %s", event_data) return uid = qr_scene.split('_')[-1] if not uid: LOG.error("qrscene error: %s", qr_scene) return res = get_subscribe_userdata(user_openid) if res['errcode'] != 0: LOG.error("get userinfo error: %s", res.get("errmsg")) nickname = '' avatar = '' else: userinfo = res['data'] LOG.info(userinfo) nickname = userinfo.get("nickname", '') avatar = userinfo.get("headimgurl", '') user_obj = MpUser(uid=uid, nickname=nickname, avatar=avatar, openid=user_openid, status=0) user_obj.save_mpuser() return
def user_share_morning(session_data, banner, content): res = check_msg_risk(content) LOG.info('content: %s, risk: %s', content, res) if res.get('errcode') != 0: res['errmsg'] = u'文本包含敏感词汇,请修改后重新提交' return res banner = get_local_path_from_url(banner) res = check_img_risk(banner) LOG.info('banner: %s, risk: %s', banner, res) if res.get('errcode') != 0: res['errmsg'] = u'图片包含敏感信息,请更换后重新提交' return res local_path = draw_morning_image(banner, '', '', '', content, 21) return {'errcode': 0, 'data': {'url': get_url_from_path(local_path)}}
def upload_pic(session_data, files): res = {'errcode': 0} result_dict = {} for filename, file_storage in files.items(): if not check_image(file_storage): res['errcode'] = -1 res['errmsg'] = u'图片包含敏感信息,请更换图片' return res file_storage.seek(0) url = upload_file_to_server(file_storage.read()) LOGGER.info("filename: %s, url: %s, type: %s", filename, url, file_storage.mimetype) result_dict[filename] = url res.update({'data': result_dict}) return res
def get_weather_by_ip(ip): # ip = '61.183.69.254' ip_instance = IPData() address = ip_instance.get_ip_location(ip) if not address: LOGGER.info("ip: %s, not found address: %s", ip, address) return '' weather_info = ip_instance.get_ip_weather(ip) # weather_info = get_weather_msg_hefeng(ip, address) # weather_info = get_weather_msg_turing(address) if isinstance(weather_info, unicode): weather_info = weather_info.encode("utf-8") if isinstance(address, unicode): address = address.encode("utf-8") return address + ' ' + weather_info
def super_search_miniapp(params): res = {'errcode': -1} keyword = params.get("keyword") if keyword is None: res.update({'errmsg': u"搜索关键字不能为空"}) return res page = params.get("page", 1) count = params.get("count", 50) is_tmall = params.get("is_tmall") tid = params.get("tid") yq = params.get("yq") if isinstance(page, (unicode, str)) and not page.isdigit() or\ (isinstance(count, (unicode, str)) and not count.isdigit()): res.update({'errmsg': u"page非法"}) return res yq = int(yq) tid = int(tid) sp = SearchParams() sp.keyword = keyword sp.page = int(page) sp.count = int(count) sp.is_tmall = 'true' if is_tmall else 'false' sp.has_coupon = 'true' if yq else 'false' if tid == 5: sp.sort = 'tk_total_sales_des' elif tid == 6: sp.sort = 'total_sales_des' result = [] try: # result = tbk_client.super_search(sp) result = _super_search(sp, tbk_client) result = result['tbk_dg_material_optional_response']['result_list'][ 'map_data'] except Exception as ex: LOG.error("super search ex: %s, word: %s", ex, keyword) res.update({'errmsg': u"数据异常: %s" % ex}) return res goods_data = [] for goods in result: tmp = _ship_goods_supers(goods) if not tmp: continue num_id = tmp['num_id'] save_goods_info(num_id, tmp) tmp = _ship_miniapp(tmp) goods_data.append(tmp) res.update({'errcode': 0, 'data': goods_data}) return res