def replace_with_taobao_img(content, app_info): """替换淘宝推送时详情中的图片为淘宝的图片""" img_tag_ptn = re.compile("""<img[^>]*src=["']([^"^']*)""") cdn_o_ptn = re.compile("""(.+)%s/o/(\d+)/(\d+)/(\d+)/(.+)""" % options.img_host) cdn_p_ptn = re.compile("""(.+)%s/p/(\d+)/(\d+)/(\d+)/(.+)""" % options.img_host) # 找出所有的<img> tag img_tags = re.findall(img_tag_ptn, content) for tag in img_tags: m = cdn_p_ptn.match(tag) file_path = "p" # 匹配的图片 if not m: m = cdn_o_ptn.match(tag) file_path = "o" if m: file_path += "/%s/%s/%s/%s" % (m.group(2), m.group(3), m.group(4), m.group(5)) file_path = os.path.join(options.cdn_root, file_path) fo = open(file_path, "rb") request = Taobao("taobao.picture.upload") request.set_app_info(app_info.app_key, app_info.app_secret_key) request.set_session(app_info.session) request.add_file("img", fo.name, fo.read()) response = yield request(picture_category_id="0", image_input_title=fo.name.encode("utf-8")) request.parse_response(response.body) if request.is_ok(): new_src = request.message.picture.picture_path else: continue content = content.decode("utf-8") if isinstance(content, str) else content # 替换 content = re.sub(tag, new_src, content) raise tornado.gen.Return(content)
def post(self): self.set_header("Content-Type", "application/json; charset=UTF-8") if (not self.request.files) or (not "imgFile" in self.request.files): return img_file = self.request.files["imgFile"][0] o_filename = img_file["filename"] shop_id = self.get_argument("shop_id", "13") distributor_shop = self.db.get( "select taobao_api_info, taobao_nick from distributor_shop where id = %s", shop_id ) app_info = json.loads(distributor_shop.taobao_api_info, object_hook=json_hook) try: request = Taobao("taobao.picture.upload") request.set_app_info(app_info.app_key, app_info.app_secret_key) request.set_session(app_info.session) request.add_file("img", o_filename, img_file["body"]) response = yield request(picture_category_id="0", image_input_title=o_filename.encode("utf-8")) request.parse_response(response.body) if request.is_ok(): self.write({"error": 0, "url": request.message.picture.picture_path}) else: err_msg = request.error.sub_msg if "sub_msg" in request.error else request.error.msg self.write(json_dumps({"error": err_msg})) except IOError: self.write(json_dumps({"error": "没有找到图片文件"})) return
def post(self): num_iid = self.get_argument("num_iid").encode("utf-8") arg_img_url = self.get_argument("img_url") shop_id = self.get_argument("shop_id") distributor_shop = self.db.get( "select taobao_api_info, taobao_nick from distributor_shop where id = %s", shop_id ) app_info = json.loads(distributor_shop.taobao_api_info, object_hook=json_hook) img_path = os.path.join(options.upload_img_path, arg_img_url[1:]) try: fo = open(img_path, "rb") except IOError: self.write(json_dumps({"error": "没有找到图片文件"})) return request = Taobao("taobao.item.img.upload") request.set_app_info(app_info.app_key, app_info.app_secret_key) request.set_session(app_info.session) request.add_file("image", fo.name, fo.read()) fo.close() response = yield request(num_iid=num_iid, is_major="true") request.parse_response(response.body) if request.is_ok(): self.write(json_dumps({"success": "图片上传成功"})) else: err_msg = request.error.sub_msg if "sub_msg" in request.error else request.error.msg self.write(json_dumps({"error": err_msg}))
def post(self): distributor_goods_id = self.get_argument('distributor_goods_id') #删除淘宝上的商品 is_exist = self.db.get( 'select * from goods_distributor_shop g where g.distributor_goods_id = %s ' 'and g.deleted = 0 and distributor_shop_id = %s limit 1', distributor_goods_id, 1) if not is_exist: self.render('ktv/manage/result.html', message='没有对应的商品可以删除') logging.info('delete distributer_goods_id: %s' % distributor_goods_id) app_info = json.loads(self.db.get( 'select taobao_api_info from distributor_shop where id = %s', options.shop_id_taobao).taobao_api_info, object_hook=json_hook) goods_delete = Taobao('taobao.item.delete') goods_delete.set_app_info(app_info.app_key, app_info.app_secret_key) goods_delete.set_session(app_info.session) response = yield goods_delete(num_iid=distributor_goods_id) goods_delete.parse_response(response.body) if goods_delete.is_ok(): self.db.execute( 'update goods_distributor_shop set deleted = 1 where distributor_goods_id = %s and ' 'distributor_shop_id = 1 and deleted = 0', distributor_goods_id) else: self.render('ktv/manage/result.html', message='在淘宝上删除商品失败') self.redirect(self.reverse_url('ktv.show'))
def post(self): distributor_goods_id = self.get_argument('distributor_goods_id') #删除淘宝上的商品 is_exist = self.db.get('select * from goods_distributor_shop g where g.distributor_goods_id = %s ' 'and g.deleted = 0 and distributor_shop_id = %s limit 1', distributor_goods_id, 1) if not is_exist: self.render('ktv/manage/result.html', message='没有对应的商品可以删除') logging.info('delete distributer_goods_id: %s' % distributor_goods_id) app_info = json.loads(self.db.get('select taobao_api_info from distributor_shop where id = %s', options.shop_id_taobao).taobao_api_info, object_hook=json_hook) goods_delete = Taobao('taobao.item.delete') goods_delete.set_app_info(app_info.app_key, app_info.app_secret_key) goods_delete.set_session(app_info.session) response = yield goods_delete(num_iid=distributor_goods_id) goods_delete.parse_response(response.body) if goods_delete.is_ok(): self.db.execute('update goods_distributor_shop set deleted = 1 where distributor_goods_id = %s and ' 'distributor_shop_id = 1 and deleted = 0', distributor_goods_id) else: self.render('ktv/manage/result.html', message='在淘宝上删除商品失败') self.redirect(self.reverse_url('ktv.show'))
def get(self): shop_id = self.get_argument('shop_id') product_id = self.get_argument('product_id') product_name = self.get_argument('product_name') shop = self.db.get('select name from supplier_shop where id = %s', shop_id) taobao_sku_list = build_taobao_sku(self.db, shop_id, product_id) title = shop.name + '-' + product_name.encode('utf-8') app_info = json.loads(self.db.get('select taobao_api_info from distributor_shop where id = %s', options.shop_id_taobao).taobao_api_info, object_hook=json_hook) attribute_request = Taobao('taobao.itemprops.get') attribute_request.set_app_info(app_info.app_key, app_info.app_secret_key) attribute_request.set_session(app_info.session) response = yield attribute_request(cid=50644003, fields='pid,name,must,multi,prop_values,is_input_prop,features') attribute_request.parse_response(response.body) if attribute_request.is_ok() and 'item_props' in attribute_request.message: if 'item_prop' in attribute_request.message.item_props: attributes = attribute_request.message.item_props.item_prop else: attributes = [] else: attributes = [] self.render('ktv/manage/publish.html', taobao_sku_list=taobao_sku_list, title=title, shop_id=shop_id, product_id=product_id, attributes=json_dumps(attributes))
def get_shop_category(app_info, taobao_nick): """获取店内目录""" category_request = Taobao('taobao.sellercats.list.get') category_request.set_app_info(app_info.app_key, app_info.app_secret_key) category_request.set_session(app_info.session) category_response = yield category_request(nick=taobao_nick) category_request.parse_response(category_response.body) item_cats = [] if category_request.is_ok( ) and 'seller_cat' in category_request.message.seller_cats: item_cats = category_request.message.seller_cats.seller_cat raise tornado.gen.Return(item_cats)
def get_category_props(cid, app_info): """获取标准类目的属性""" attribute_request = Taobao('taobao.itemprops.get') attribute_request.set_app_info(app_info.app_key, app_info.app_secret_key) attribute_request.set_session(app_info.session) response = yield attribute_request( cid=cid, fields='pid,name,must,multi,prop_values,is_input_prop,features') attribute_request.parse_response(response.body) attributes = [] if attribute_request.is_ok() and 'item_props' in attribute_request.message: if 'item_prop' in attribute_request.message.item_props: attributes = attribute_request.message.item_props.item_prop raise tornado.gen.Return(attributes)
def get_shop_category(app_info, taobao_nick): """获取店内目录""" category_request = Taobao("taobao.sellercats.list.get") category_request.set_app_info(app_info.app_key, app_info.app_secret_key) category_request.set_session(app_info.session) category_response = yield category_request(nick=taobao_nick) category_request.parse_response(category_response.body) item_cats = [] if category_request.is_ok() and "seller_cat" in category_request.message.seller_cats: item_cats = category_request.message.seller_cats.seller_cat raise tornado.gen.Return(item_cats)
def get_category_props(cid, app_info): """获取标准类目的属性""" attribute_request = Taobao("taobao.itemprops.get") attribute_request.set_app_info(app_info.app_key, app_info.app_secret_key) attribute_request.set_session(app_info.session) response = yield attribute_request(cid=cid, fields="pid,name,must,multi,prop_values,is_input_prop,features") attribute_request.parse_response(response.body) attributes = [] if attribute_request.is_ok() and "item_props" in attribute_request.message: if "item_prop" in attribute_request.message.item_props: attributes = attribute_request.message.item_props.item_prop raise tornado.gen.Return(attributes)
def order_status(tid, app_info): order_status = Taobao('taobao.trade.get') order_status.set_app_info(app_info.app_key, app_info.app_secret_key) order_status.set_session(app_info.session) response = yield order_status(tid=tid, fields='status') logging.info("response.body:%s", response.body) order_status.parse_response(response.body) if order_status.is_ok(): logging.info('order_status.message.trade.status :%s,%s', order_status.message.trade.status) if order_status.message.trade.status == 'WAIT_SELLER_SEND_GOODS': raise tornado.gen.Return(PropDict(ok=True, status='SEND')) elif order_status.message.trade.status == 'TRADE_CLOSED': raise tornado.gen.Return(PropDict(ok=False, status='REFUND')) else: raise tornado.gen.Return(PropDict(ok=False, status='OTHER')) else: raise tornado.gen.Return(PropDict(ok=False, status='OTHER'))
def express_auto_push(db, redis, message_raw, distr_shop_id): express_info = json.loads(message_raw, object_hook=json_hook) logging.info('taobao_express_update consumer pop taobao tid =%s ' % express_info.tid) app_info = json.loads(db.get( 'select taobao_api_info from distributor_shop where id = %s', distr_shop_id).taobao_api_info, object_hook=json_hook) express_company = Taobao('taobao.logistics.offline.send') express_company.set_app_info(app_info.app_key, app_info.app_secret_key) express_company.set_session(app_info.session) response = express_company.sync_fetch(**express_info) express_company.parse_response(response) if express_company.is_ok(): logging.info('outer order express info update success. order %s', express_info.tid) redis.lrem(options.queue_taobao_express_processing, 0, express_info) else: logging.error('outer order express info update failure. order %s', express_info.tid)
def order_status(tid, app_info): order_status = Taobao('taobao.trade.get') order_status.set_app_info(app_info.app_key, app_info.app_secret_key) order_status.set_session(app_info.session) response = yield order_status(tid=tid, fields='status') logging.info("response.body:%s",response.body) order_status.parse_response(response.body) if order_status.is_ok(): logging.info('order_status.message.trade.status :%s,%s', order_status.message.trade.status) if order_status.message.trade.status == 'WAIT_SELLER_SEND_GOODS': raise tornado.gen.Return(PropDict(ok=True, status='SEND')) elif order_status.message.trade.status == 'TRADE_CLOSED': raise tornado.gen.Return(PropDict(ok=False, status='REFUND')) else: raise tornado.gen.Return(PropDict(ok=False, status='OTHER')) else: raise tornado.gen.Return(PropDict(ok=False, status='OTHER'))
def order_status(tid, app_info): order_status_request = Taobao("taobao.trade.get") order_status_request.set_app_info(app_info.app_key, app_info.app_secret_key) order_status_request.set_session(app_info.session) response = yield order_status_request(tid=tid, fields="status") order_status_request.parse_response(response.body) if order_status_request.is_ok(): if order_status_request.message.trade.status == "WAIT_SELLER_SEND_GOODS": raise tornado.gen.Return(PropDict(ok=True, status="SEND")) elif order_status_request.message.trade.status == "TRADE_CLOSED": raise tornado.gen.Return(PropDict(ok=False, status="REFUND")) else: raise tornado.gen.Return(PropDict(ok=False, status="OTHER")) else: raise tornado.gen.Return(PropDict(ok=False, status="OTHER"))
def get(self): shop_id = self.get_argument('shop_id') product_id = self.get_argument('product_id') product_name = self.get_argument('product_name') shop = self.db.get('select name from supplier_shop where id = %s', shop_id) taobao_sku_list = build_taobao_sku(self.db, shop_id, product_id) title = shop.name + '-' + product_name.encode('utf-8') app_info = json.loads(self.db.get( 'select taobao_api_info from distributor_shop where id = %s', options.shop_id_taobao).taobao_api_info, object_hook=json_hook) attribute_request = Taobao('taobao.itemprops.get') attribute_request.set_app_info(app_info.app_key, app_info.app_secret_key) attribute_request.set_session(app_info.session) response = yield attribute_request( cid=50644003, fields='pid,name,must,multi,prop_values,is_input_prop,features') attribute_request.parse_response(response.body) if attribute_request.is_ok( ) and 'item_props' in attribute_request.message: if 'item_prop' in attribute_request.message.item_props: attributes = attribute_request.message.item_props.item_prop else: attributes = [] else: attributes = [] self.render('ktv/manage/publish.html', taobao_sku_list=taobao_sku_list, title=title, shop_id=shop_id, product_id=product_id, attributes=json_dumps(attributes))
def get(self, goods_id): shop_id = self.get_argument('shop_id') distributor_shop = self.db.get( 'select taobao_api_info, taobao_nick from distributor_shop where id = %s', shop_id) app_info = json.loads(distributor_shop.taobao_api_info, object_hook=json_hook) taobao_nick = distributor_shop.taobao_nick # 获取店铺类型 request = Taobao('taobao.user.seller.get') request.set_app_info(app_info.app_key, app_info.app_secret_key) request.set_session(app_info.session) response = yield request(fields=','.join([taobao_nick, 'type'])) request.parse_response(response.body) # C店,B店不同流程 # todo B店部分推送的商品必须有一个对应的产品 self.render('goods/distributor/taobao/category.html', goods_id=goods_id, shop_id=self.get_argument('shop_id'), user_type=request.message.user.type)
def get(self, goods_id): shop_id = self.get_argument("shop_id") distributor_shop = self.db.get( "select taobao_api_info, taobao_nick from distributor_shop where id = %s", shop_id ) app_info = json.loads(distributor_shop.taobao_api_info, object_hook=json_hook) taobao_nick = distributor_shop.taobao_nick # 获取店铺类型 request = Taobao("taobao.user.seller.get") request.set_app_info(app_info.app_key, app_info.app_secret_key) request.set_session(app_info.session) response = yield request(fields=",".join([taobao_nick, "type"])) request.parse_response(response.body) # C店,B店不同流程 # todo B店部分推送的商品必须有一个对应的产品 self.render( "goods/distributor/taobao/category.html", goods_id=goods_id, shop_id=self.get_argument("shop_id"), user_type=request.message.user.type, )
def replace_with_taobao_img(content, app_info): """替换淘宝推送时详情中的图片为淘宝的图片""" img_tag_ptn = re.compile("""<img[^>]*src=["']([^"^']*)""") cdn_o_ptn = re.compile("""(.+)%s/o/(\d+)/(\d+)/(\d+)/(.+)""" % options.img_host) cdn_p_ptn = re.compile("""(.+)%s/p/(\d+)/(\d+)/(\d+)/(.+)""" % options.img_host) # 找出所有的<img> tag img_tags = re.findall(img_tag_ptn, content) for tag in img_tags: m = cdn_p_ptn.match(tag) file_path = 'p' # 匹配的图片 if not m: m = cdn_o_ptn.match(tag) file_path = 'o' if m: file_path += '/%s/%s/%s/%s' % (m.group(2), m.group(3), m.group(4), m.group(5)) file_path = os.path.join(options.cdn_root, file_path) fo = open(file_path, 'rb') request = Taobao('taobao.picture.upload') request.set_app_info(app_info.app_key, app_info.app_secret_key) request.set_session(app_info.session) request.add_file('img', fo.name, fo.read()) response = yield request(picture_category_id='0', image_input_title=fo.name.encode('utf-8')) request.parse_response(response.body) if request.is_ok(): new_src = request.message.picture.picture_path else: continue content = content.decode('utf-8') if isinstance(content, str) else content # 替换 content = re.sub(tag, new_src, content) raise tornado.gen.Return(content)
def post(self): params = dict([(name, self.get_argument(name).encode('utf-8')) for name in self.request.arguments]) #判断是否存在对应的商品,如果没有则添加 goods = self.db.get( 'select goods_id from ktv_product_goods where product_id = %s and shop_id = %s', params['product_id'], params['shop_id']) shop = self.db.get('select * from supplier_shop where id = %s', params['shop_id']) product = self.db.get('select * from ktv_product where id = %s', params['product_id']) taobao_sku_list = build_taobao_sku(self.db, shop.id, product.id) props = '' if 'attr-name' in self.request.arguments: for pid in self.request.arguments['attr-name']: if pid in self.request.arguments: for i in self.request.arguments[pid]: props += pid + ':' + i + ';' if not goods: shop_name = self.db.get( 'select name from supplier_shop where id = %s', params['shop_id'])['name'] sql = """insert into goods(supplier_id, sales_price, face_value, purchase_price, category_id, name, short_name, sms_name, created_at, expire_at, type, detail, created_by, generate_type, all_shop) values(%s, 1, 1, 1, 1021, %s, %s, %s, NOW(), NOW(), 'E', 'ktv产品', %s, 'GENERATE', 0)""" combo = shop_name + product['name'] param = [ self.current_user.supplier_id, combo, combo, combo, self.current_user.name ] goods_id = self.db.execute(sql, *param) self.db.execute( 'insert into goods_property(goods_id, name, value) values(%s, "ktv", 1)', goods_id) self.db.execute( 'insert into goods_property(goods_id, name, value) values(%s, "hidden", 1)', goods_id) self.db.execute( 'insert into ktv_product_goods(shop_id, product_id, goods_id, created_at) ' 'values(%s, %s, %s, NOW())', params['shop_id'], params['product_id'], goods_id) self.db.execute( 'insert into goods_supplier_shop(goods_id,supplier_shop_id) values(%s, %s)', goods, shop.id) else: goods_id = goods.goods_id # shop_id 如果是银乐迪,指定为31, 否则默认是券生活8的id(13) shop_id = { 629: 31 }.get(self.current_user.supplier_id, options.shop_id_taobao) dg = alloc_distributor_goods(self.db, goods_id, shop_id) outer_id = str(dg.goods_link_id) sku_properties = [] sku_quantities = [] sku_prices = [] sku_outer_ids = [] props_set = [] goods_number = 0 min_price = 100000 max_price = 0 room_type_taobao_info = { 'MINI': '27426219:6312905', 'SMALL': '27426219:3442354', 'MIDDLE': '27426219:6769368', 'LARGE': '27426219:3374388', 'DELUXE': '27426219:40867986' } for taobao_sku in taobao_sku_list: sku_properties.append(get_taobao_propertities(taobao_sku)) sku_quantities.append(taobao_sku.quantity) sku_prices.append(taobao_sku.price) sku_outer_ids.append(get_taobao_outer_id(taobao_sku)) for i in sku_quantities: goods_number += i props_set = remove_repeat( props_set, room_type_taobao_info[taobao_sku.room_type]) if taobao_sku.price < min_price: min_price = taobao_sku.price if taobao_sku.price > max_price: max_price = taobao_sku.price props += ';'.join(props_set) sku_properties_str = ','.join(sku_properties) # sku_properties_str = sku_properties_str.encode('utf-8') sku_quantities_str = ','.join([str(i) for i in sku_quantities ]).encode('utf-8') sku_prices_str = ','.join([str(i) for i in sku_prices]).encode('utf-8') sku_outer_ids_str = ','.join(sku_outer_ids).encode('utf-8') input_pid = [] input_s = [] # props += self.get_argument('face_value') + ':' + str(int(max_price) * 1.5) + ';' # 增加品牌、省份、城市属性 props += ';' + params['ktv_brand'] + ':' + params['brand'] + ';' ktv_province = self.request.arguments['ktv_provinces'] for province_item in ktv_province: props += params['ktv_province'] + ':' + province_item + ';' ktv_cities = self.request.arguments['ktv_cities'] for city_item in ktv_cities: props += params['ktv_city'] + ':' + city_item + ';' merchant = params['merchant'] input_pid.append(self.get_argument('face_value')) input_s.append(str(int(int(max_price) * 1.5))) input_pids = ','.join(input_pid).encode('utf-8') input_str = ','.join(input_s).encode('utf-8') app_info = json.loads(self.db.get( 'select taobao_api_info from distributor_shop where id = %s', options.shop_id_taobao).taobao_api_info, object_hook=json_hook) goods_push = Taobao('taobao.item.add') goods_push.set_app_info(app_info.app_key, app_info.app_secret_key) goods_push.set_session(app_info.session) publish = self.get_argument('publish', 0) image = img_url(params['img_url']) # image = 'http://img0.bdstatic.com/img/image/9196a600c338744ebf8e350016bdbf9d72a6059a745.jpg' if publish: approve_status = 'onsale' else: approve_status = 'instock' args = { 'num': goods_number, 'price': min_price, 'type': 'fixed', 'image': image, 'stuff_status': 'news', 'title': params['title'], 'location__state': params['location_state'], 'location__city': params['location_city'], 'cid': 50644003, 'approve_status': approve_status, 'desc': params['desc'], 'props': props, 'sku_properties': sku_properties_str, 'sku_quantities': sku_quantities_str, 'sku_prices': sku_prices_str, 'sku_outer_ids': sku_outer_ids_str, 'input_pids': input_pids, 'input_str': input_str, 'outer_id': outer_id, 'locality_life__merchant': merchant, 'locality_life__choose_logis': '0', 'locality_life__expirydate': '30', 'locality_life__onsale_auto_refund_ratio': 100 } response = yield goods_push(**args) goods_push.parse_response(response.body) if goods_push.is_ok(): message = '发布成功' self.db.execute( 'update goods_distributor_shop set status="PENDING", created_by=%s, created_at=NOW(), ' 'distributor_goods_id = %s where goods_id=%s and distributor_shop_id=%s and ' 'goods_link_id=%s', self.current_user.name, goods_push.message.item.num_iid, goods_id, shop_id, dg.goods_link_id) else: err_msg = goods_push.error.sub_msg if 'sub_msg' in goods_push.error else goods_push.error.msg message = '发布失败:' + err_msg.encode('utf-8') self.render('ktv/manage/result.html', message=message)
def post(self): app_info = json.loads(self.db.get( 'select taobao_api_info from distributor_shop where id = %s', self.get_argument('shop_id')).taobao_api_info, object_hook=json_hook) parent_id = self.get_argument('id', '0') # 第一次请求的类目不同,天猫请求授权类目,淘宝请求所有标准类目 user_type = self.get_argument('user_type') if parent_id == '0' and user_type == u'B': taobao = Taobao('taobao.itemcats.authorize.get') taobao.add_fields( fields= 'item_cat.cid,item_cat.name,item_cat.parent_cid,item_cat.is_parent' ) else: taobao = Taobao('taobao.itemcats.get') taobao.add_fields(parent_cid=parent_id, fields='cid,name,is_parent') taobao.set_app_info(app_info.app_key, app_info.app_secret_key) taobao.set_session(app_info.session) response = yield taobao() self.set_header('Content-Type', 'application/json; charset=UTF-8') taobao.parse_response(response.body) if parent_id == '0' and user_type == u'B': item_cats = taobao.message.seller_authorize.item_cats.item_cat else: item_cats = taobao.message.item_cats.item_cat if taobao.is_ok(): result = [] for node in item_cats: result.append({ 'id': node.cid, 'name': node.name, 'isParent': node.is_parent, }) self.write(json_dumps(result)) else: self.write('[]')
def post(self): self.set_header('Content-Type', 'application/json; charset=UTF-8') if (not self.request.files) or (not 'imgFile' in self.request.files): return img_file = self.request.files['imgFile'][0] o_filename = img_file['filename'] shop_id = self.get_argument('shop_id', '13') distributor_shop = self.db.get( 'select taobao_api_info, taobao_nick from distributor_shop where id = %s', shop_id) app_info = json.loads(distributor_shop.taobao_api_info, object_hook=json_hook) try: request = Taobao('taobao.picture.upload') request.set_app_info(app_info.app_key, app_info.app_secret_key) request.set_session(app_info.session) request.add_file('img', o_filename, img_file['body']) response = yield request( picture_category_id='0', image_input_title=o_filename.encode('utf-8')) request.parse_response(response.body) if request.is_ok(): self.write({ 'error': 0, 'url': request.message.picture.picture_path }) else: err_msg = request.error.sub_msg if 'sub_msg' in request.error else request.error.msg self.write(json_dumps({'error': err_msg})) except IOError: self.write(json_dumps({'error': "没有找到图片文件"})) return
def post(self): num_iid = self.get_argument('num_iid').encode('utf-8') arg_img_url = self.get_argument('img_url') shop_id = self.get_argument('shop_id') distributor_shop = self.db.get( 'select taobao_api_info, taobao_nick from distributor_shop where id = %s', shop_id) app_info = json.loads(distributor_shop.taobao_api_info, object_hook=json_hook) img_path = os.path.join(options.upload_img_path, arg_img_url[1:]) try: fo = open(img_path, 'rb') except IOError: self.write(json_dumps({'error': "没有找到图片文件"})) return request = Taobao('taobao.item.img.upload') request.set_app_info(app_info.app_key, app_info.app_secret_key) request.set_session(app_info.session) request.add_file('image', fo.name, fo.read()) fo.close() response = yield request(num_iid=num_iid, is_major='true') request.parse_response(response.body) if request.is_ok(): self.write(json_dumps({'success': '图片上传成功'})) else: err_msg = request.error.sub_msg if 'sub_msg' in request.error else request.error.msg self.write(json_dumps({'error': err_msg}))
def get_taobao(self, app_info, existed_orders, unbind_goods, success_orders, partner): page_index = 0 taobao = Taobao('taobao.trades.sold.get') taobao.set_app_info(app_info.app_key, app_info.app_secret_key) taobao.set_session(app_info.session) while True: page_index += 1 response = yield taobao(status='WAIT_SELLER_SEND_GOODS', use_has_next='true', page_size='100', page_no=page_index, fields='orders.outer_iid,tid,orders.payment,orders.num,pay_time,orders.price,' 'shipping_type,orders.logistics_company,receiver_mobile,receiver_phone,' 'receiver_name,receiver_state,receiver_city,receiver_district,' 'receiver_address,receiver_zip,has_buyer_message') taobao.parse_response(response.body) if not taobao.is_ok(): logging.error(taobao.error) break converted_data = [] if 'trades' not in taobao.message.keys(): logging.info(taobao.message) else: for trade in taobao.message.trades.values(): for i in range(len(trade)): buy_message = "" #如果买家有留言,就去单独获取留言 if trade[i].has_buyer_message: trade_get = Taobao('taobao.trade.get') trade_get.set_app_info(app_info.app_key, app_info.app_secret_key) trade_get.set_session(app_info.session) trade_get_response = yield trade_get(tid=trade[i]['tid'], fields='buyer_message') trade_get.parse_response(trade_get_response.body) #取得订单留言信息 buy_message = trade_get.message.trade.buyer_message if not 'order' in trade[i].orders: continue for order_detail in trade[i].orders.order: if trade[i].shipping_type == 'virtual': logging.info('虚拟发货 跳过: ' + trade[i]['tid']) continue if not order_detail.outer_iid: logging.info('该商品在淘宝上没有设置商品编码,请确认一下:' + trade[i].tid) continue mapping = {'goods_no': 'outer_iid', 'sales_price': 'price', 'buy_num': 'num'} order_dict = {} for key, value in mapping.iteritems(): order_dict[key] = order_detail[value] order_dict['distr_order_no'] = trade[i].tid order_dict['paid_at'] = trade[i].pay_time order_dict['receiver'] = trade[i].receiver_name order_dict['zip_code'] = trade[i].receiver_zip order_dict['remarks'] = buy_message order_dict['express_info'] = buy_message if not trade[i].receiver_mobile: order_dict['phone'] = trade[i].receiver_phone else: order_dict['phone'] = trade[i].receiver_mobile order_dict['address'] = trade[i].receiver_state + trade[i].receiver_city + \ trade[i].receiver_district + trade[i].receiver_address converted_data.append(order_dict) #处理渠道产生一百券对应的订单信息 process_partner_order(self, partner, converted_data, True, existed_orders, unbind_goods, success_orders) if taobao.message.has_next is False: break
def post(self): props = "" args = self.request.arguments.copy() shop_id = args.pop("shop_id")[0] input_pids = "" input_str = "" if "attr-name" in args: for pid in args.pop("attr-name"): if pid in args: for v in args.pop(pid): if v == "_custom_": input_pids += "%s," % pid input_str += "%s," % args.pop("%s_custom" % pid)[0] break props += "%s:%s;" % (pid, v) if "seller_cids" in args: seller_cids = ",".join(args.pop("seller_cids")) args["seller_cids"] = seller_cids args = dict([(key, args[key][0]) for key in args]) args["props"] = props args["input_str"] = input_str args["input_pids"] = input_pids goods_id = args.pop("goods_id") dg = alloc_distributor_goods(self.db, goods_id, shop_id) args["outer_id"] = dg.goods_link_id app_info = json.loads( self.db.get("select taobao_api_info from distributor_shop where id = %s", shop_id).taobao_api_info, object_hook=json_hook, ) goods_push = Taobao("taobao.item.add") goods_push.set_app_info(app_info.app_key, app_info.app_secret_key) goods_push.set_session(app_info.session) response = yield goods_push(**args) goods_push.parse_response(response.body) ok = 0 num_iid = "" if goods_push.is_ok(): ok = 1 num_iid = goods_push.message.item.num_iid message = "发布成功" self.db.execute( 'update goods_distributor_shop set status="PENDING", created_by=%s, created_at=NOW(), ' "distributor_goods_id=%s where goods_id=%s and distributor_shop_id=%s and goods_link_id=%s", self.current_user.name, num_iid, goods_id, shop_id, dg.goods_link_id, ) else: err_msg = goods_push.error.sub_msg if "sub_msg" in goods_push.error else goods_push.error.msg message = "发布失败:" + err_msg.encode("utf-8") img_paths = self.db.get("select img_paths from goods where id=%s", goods_id).img_paths img_paths = json.loads(img_paths) if img_paths else dict() self.render( "goods/distributor/taobao/result.html", message=message, ok=ok, num_iid=num_iid, shop_id=shop_id, img_paths=img_paths, img_url=img_url, )
def post(self): params = dict([(name, self.get_argument(name).encode('utf-8')) for name in self.request.arguments]) #判断是否存在对应的商品,如果没有则添加 goods = self.db.get('select goods_id from ktv_product_goods where product_id = %s and shop_id = %s', params['product_id'], params['shop_id']) shop = self.db.get('select * from supplier_shop where id = %s', params['shop_id']) product = self.db.get('select * from ktv_product where id = %s', params['product_id']) taobao_sku_list = build_taobao_sku(self.db, shop.id, product.id) props = '' if 'attr-name' in self.request.arguments: for pid in self.request.arguments['attr-name']: if pid in self.request.arguments: for i in self.request.arguments[pid]: props += pid + ':' + i + ';' if not goods: shop_name = self.db.get('select name from supplier_shop where id = %s', params['shop_id'])['name'] sql = """insert into goods(supplier_id, sales_price, face_value, purchase_price, category_id, name, short_name, sms_name, created_at, expire_at, type, detail, created_by, generate_type, all_shop) values(%s, 1, 1, 1, 1021, %s, %s, %s, NOW(), NOW(), 'E', 'ktv产品', %s, 'GENERATE', 0)""" combo = shop_name + product['name'] param = [self.current_user.supplier_id, combo, combo, combo, self.current_user.name] goods_id = self.db.execute(sql, *param) self.db.execute('insert into goods_property(goods_id, name, value) values(%s, "ktv", 1)', goods_id) self.db.execute('insert into goods_property(goods_id, name, value) values(%s, "hidden", 1)', goods_id) self.db.execute('insert into ktv_product_goods(shop_id, product_id, goods_id, created_at) ' 'values(%s, %s, %s, NOW())', params['shop_id'], params['product_id'], goods_id) self.db.execute('insert into goods_supplier_shop(goods_id,supplier_shop_id) values(%s, %s)', goods, shop.id) else: goods_id = goods.goods_id # shop_id 如果是银乐迪,指定为31, 否则默认是券生活8的id(13) shop_id = {629: 31}.get(self.current_user.supplier_id, options.shop_id_taobao) dg = alloc_distributor_goods(self.db, goods_id, shop_id) outer_id = str(dg.goods_link_id) sku_properties = [] sku_quantities = [] sku_prices = [] sku_outer_ids = [] props_set = [] goods_number = 0 min_price = 100000 max_price = 0 room_type_taobao_info = {'MINI': '27426219:6312905', 'SMALL': '27426219:3442354', 'MIDDLE': '27426219:6769368', 'LARGE': '27426219:3374388', 'DELUXE': '27426219:40867986'} for taobao_sku in taobao_sku_list: sku_properties.append(get_taobao_propertities(taobao_sku)) sku_quantities.append(taobao_sku.quantity) sku_prices.append(taobao_sku.price) sku_outer_ids.append(get_taobao_outer_id(taobao_sku)) for i in sku_quantities: goods_number += i props_set = remove_repeat(props_set, room_type_taobao_info[taobao_sku.room_type]) if taobao_sku.price < min_price: min_price = taobao_sku.price if taobao_sku.price > max_price: max_price = taobao_sku.price props += ';'.join(props_set) sku_properties_str = ','.join(sku_properties) # sku_properties_str = sku_properties_str.encode('utf-8') sku_quantities_str = ','.join([str(i) for i in sku_quantities]).encode('utf-8') sku_prices_str = ','.join([str(i) for i in sku_prices]).encode('utf-8') sku_outer_ids_str = ','.join(sku_outer_ids).encode('utf-8') input_pid = [] input_s = [] # props += self.get_argument('face_value') + ':' + str(int(max_price) * 1.5) + ';' # 增加品牌、省份、城市属性 props += ';' + params['ktv_brand'] + ':' + params['brand'] + ';' ktv_province = self.request.arguments['ktv_provinces'] for province_item in ktv_province: props += params['ktv_province'] + ':' + province_item + ';' ktv_cities = self.request.arguments['ktv_cities'] for city_item in ktv_cities: props += params['ktv_city'] + ':' + city_item + ';' merchant = params['merchant'] input_pid.append(self.get_argument('face_value')) input_s.append(str(int(int(max_price) * 1.5))) input_pids = ','.join(input_pid).encode('utf-8') input_str = ','.join(input_s).encode('utf-8') app_info = json.loads(self.db.get('select taobao_api_info from distributor_shop where id = %s', options.shop_id_taobao).taobao_api_info, object_hook=json_hook) goods_push = Taobao('taobao.item.add') goods_push.set_app_info(app_info.app_key, app_info.app_secret_key) goods_push.set_session(app_info.session) publish = self.get_argument('publish', 0) image = img_url(params['img_url']) # image = 'http://img0.bdstatic.com/img/image/9196a600c338744ebf8e350016bdbf9d72a6059a745.jpg' if publish: approve_status = 'onsale' else: approve_status = 'instock' args = { 'num': goods_number, 'price': min_price, 'type': 'fixed', 'image': image, 'stuff_status': 'news', 'title': params['title'], 'location__state': params['location_state'], 'location__city': params['location_city'], 'cid': 50644003, 'approve_status': approve_status, 'desc': params['desc'], 'props': props, 'sku_properties': sku_properties_str, 'sku_quantities': sku_quantities_str, 'sku_prices': sku_prices_str, 'sku_outer_ids': sku_outer_ids_str, 'input_pids': input_pids, 'input_str': input_str, 'outer_id': outer_id, 'locality_life__merchant': merchant, 'locality_life__choose_logis': '0', 'locality_life__expirydate': '30', 'locality_life__onsale_auto_refund_ratio': 100 } response = yield goods_push(**args) goods_push.parse_response(response.body) if goods_push.is_ok(): message = '发布成功' self.db.execute('update goods_distributor_shop set status="PENDING", created_by=%s, created_at=NOW(), ' 'distributor_goods_id = %s where goods_id=%s and distributor_shop_id=%s and ' 'goods_link_id=%s', self.current_user.name, goods_push.message.item.num_iid, goods_id, shop_id, dg.goods_link_id) else: err_msg = goods_push.error.sub_msg if 'sub_msg' in goods_push.error else goods_push.error.msg message = '发布失败:' + err_msg.encode('utf-8') self.render('ktv/manage/result.html', message=message)
def post(self): app_info = json.loads( self.db.get( "select taobao_api_info from distributor_shop where id = %s", self.get_argument("shop_id") ).taobao_api_info, object_hook=json_hook, ) parent_id = self.get_argument("id", "0") # 第一次请求的类目不同,天猫请求授权类目,淘宝请求所有标准类目 user_type = self.get_argument("user_type") if parent_id == "0" and user_type == u"B": taobao = Taobao("taobao.itemcats.authorize.get") taobao.add_fields(fields="item_cat.cid,item_cat.name,item_cat.parent_cid,item_cat.is_parent") else: taobao = Taobao("taobao.itemcats.get") taobao.add_fields(parent_cid=parent_id, fields="cid,name,is_parent") taobao.set_app_info(app_info.app_key, app_info.app_secret_key) taobao.set_session(app_info.session) response = yield taobao() self.set_header("Content-Type", "application/json; charset=UTF-8") taobao.parse_response(response.body) if parent_id == "0" and user_type == u"B": item_cats = taobao.message.seller_authorize.item_cats.item_cat else: item_cats = taobao.message.item_cats.item_cat if taobao.is_ok(): result = [] for node in item_cats: result.append({"id": node.cid, "name": node.name, "isParent": node.is_parent}) self.write(json_dumps(result)) else: self.write("[]")
def taobao_order(db, redis, distributor_order_id, message_raw): """ 处理淘宝的分销订单队列 :param db :param redis :param distributor_order_id: 分销订单id :param message_raw: redis 队列元素值 :type db:torndb.Connection :type redis:redis.client.StrictRedis :type distributor_order_id: int """ distributor_order = db.get('select * from distributor_order where id=%s', distributor_order_id) params = json.loads(distributor_order.message, object_hook=json_hook) shop = db.get('select * from distributor_shop where taobao_seller_id=%s', params.taobao_sid) api_info = json.loads(shop.taobao_api_info, object_hook=json_hook) if not distributor_order.order_id: # 如果还没生成一百券订单 goods_link_id = int(params.outer_iid) # 找到关联的商品 goods_info = db.get('select g.* from goods g, goods_distributor_shop gds ' 'where g.id = gds.goods_id and distributor_shop_id=%s and goods_link_id=%s', shop.id, goods_link_id) if not goods_info and goods_link_id < 20000: goods_info = db.get('select g.* from goods g where g.type="E" and g.id=%s', goods_link_id) if not goods_info: logging.error('taobao order consume failed: goods not found. link_id: %s', goods_link_id) return taobao = Taobao('taobao.trade.get') taobao.set_app_info(api_info.app_key, api_info.app_secret_key) taobao.set_session(api_info.session) response = taobao.sync_fetch(tid=distributor_order.order_no, fields='total_fee,payment,orders.payment,orders.num,' 'orders.sku_properties_name,orders.price') taobao.parse_response(response) order_payment = Decimal(taobao.message.trade.payment) # 创建订单 order_id, order_no = new_distributor_order(db, shop.id, Decimal(taobao.message.trade.total_fee), order_payment, params.mobile) result = new_distributor_item(db, order_id, order_no, order_payment / int(params.num), int(params.num), goods_info, params.mobile, shop.id, params.num_iid, None, False) if not result.ok: logging.error('taobao order consume failed. %s', result.msg) return else: db.execute('update orders set distributor_order_id=%s where id = %s', distributor_order_id, result.order_id) db.execute('update distributor_order set order_id=%s where id=%s', result.order_id, distributor_order_id) ktv_order_result = create_ktv_order(db, order_id, params) else: order_id = distributor_order.order_id ktv_order_result = [] coupons = db.query('select c.sn as coupon_sn from item i, item_coupon c where i.id=c.item_id and i.order_id=%s', order_id) # 告诉淘宝我们已发货 taobao = Taobao('taobao.vmarket.eticket.send') taobao.set_app_info(api_info.app_key, api_info.app_secret_key) if api_info.app_key == options.taobao_kunran_app_key: # 如果是码商,要加上码商的信息 taobao.add_field('codemerchant_id', options.taobao_kunran_id) taobao.set_session(api_info.merchant_session) else: taobao.set_session(api_info.session) response = taobao.sync_fetch(order_id=params.order_id, token=params.token, verify_codes=','.join(['%s:1' % item.coupon_sn for item in coupons])) logging.info('tell taobao coupon send response: %s', response) taobao.parse_response(response) if taobao.is_ok(): logging.info('taobao order complete. distributor_order_id: %s', distributor_order_id) all_order_items = db.query('select * from order_item where order_id=%s', order_id) for item in all_order_items: CouponSMSMessage(db, redis, order_item=item).remark('淘宝订单短信发送').send() redis.lrem(options.queue_distributor_order_processing, 0, message_raw) #只要ktv预订时间有,就给门店经理发送ktv预订的包厢信息 for ktv_info in ktv_order_result: sku = ktv_info['sku'] phone_numbers = ktv_info['manager_mobile'] for phone in (phone_numbers.split(',') if phone_numbers else []): content = str(sku.date) + ktv_info['shop_name'] + '预订【' + str(params.mobile) + \ sku.room_name + " (" + str(params.num) + "间)" + sku.human_time_range + "】" #给经理发送短信告知预订信息 logging.info('send message to manager,phone:%s,content:%s', phone, content) SMSMessage(content, phone).send(redis) else: logging.error('tell taobao coupon send failed: %s', taobao.error)
def sync_stock(): sql = """ select g.id, gds.distributor_shop_id, gds.distributor_goods_id, gds.goods_link_id, g.stock, ds.taobao_api_info, ds.distributor_id from goods g, distributor_shop ds, goods_distributor_shop gds where g.id = gds.goods_id and gds.distributor_shop_id = ds.id and g.generate_type = 'IMPORT' and gds.deleted = '0' and gds.distributor_shop_id in (%s, %s, %s, %s) """ params = [options.shop_id_taobao, options.shop_id_tmall, options.shop_id_jingdong, options.shop_id_wuba] sync_list = db.query(sql, *params) for item in sync_list: if not item.distributor_goods_id or item.distributor_goods_id == '0': logging.error('商品找不到对应的外部id.商品id: %s', item.id) continue if item.distributor_shop_id in (options.shop_id_taobao, options.shop_id_tmall): if not item.taobao_api_info: logging.error('商品没有对应的taobao_api_info.商品id: %s', item.id) continue app_info = json.loads(item.taobao_api_info, object_hook=json_hook) # 获取店铺类型 request = Taobao('taobao.item.quantity.update') request.set_app_info(app_info.app_key, app_info.app_secret_key) request.set_session(app_info.session) args = { 'num_iid': item.distributor_goods_id, 'quantity': item.stock, 'type': 1 } response = yield request(**args) request.parse_response(response.body) if request.is_ok(): logging.info('商品id: %s在 %s上更新库存成功,更新为%s', item.id, {options.shop_id_tmall: '天猫', options.shop_id_taobao: '淘宝'}.get(item.distributor_shop_id), item.stock) else: logging.info('商品id: %s在 %s上更新库存失败', item.id, {options.shop_id_tmall: '天猫', options.shop_id_taobao: '淘宝'}.get(item.distributor_shop_id)) elif item.distributor_id == options.distributor_id_jingdong: args = { 'vender_team_id': item.goods_link_id, 'jd_team_id': item.distributor_goods_id, 'max_number': item.stock } shop = db.get('select taobao_seller_id, taobao_api_info from distributor_shop where id=%s', item.distributor_shop_id) api_info = json.loads(shop.taobao_api_info, object_hook=json_hook) jd_push = Jingdong('updateMaxNumber', str(shop.taobao_seller_id), api_info.vender_key, api_info.secret_key) response = yield jd_push.fetch(**args) jd_push.parse_response(response.body) if jd_push.is_ok(): logging.info('商品id: %s在京东上更新库存成功,更新为%s', item.id, item.stock) else: logging.info('商品id: %s在京东上更新库存失败', item.id) elif item.distributor_shop_id == options.shop_id_wuba: args = { 'groupbuyId': item.goods_link_id, 'num': item.stock } wuba = Wuba('changeinventory') response = yield wuba.fetch(**args) wuba.parse_response(response.body) if wuba.is_ok(): logging.info('商品id: %s在58上更新库存成功,更新为%s', item.id, item.stock) else: logging.info('商品id: %s在58上更新库存失败', item.id) else: pass
def post(self): props = '' args = self.request.arguments.copy() shop_id = args.pop('shop_id')[0] input_pids = '' input_str = '' if 'attr-name' in args: for pid in args.pop('attr-name'): if pid in args: for v in args.pop(pid): if v == '_custom_': input_pids += '%s,' % pid input_str += '%s,' % args.pop('%s_custom' % pid)[0] break props += '%s:%s;' % (pid, v) if 'seller_cids' in args: seller_cids = ','.join(args.pop('seller_cids')) args['seller_cids'] = seller_cids args = dict([(key, args[key][0]) for key in args]) args['props'] = props args['input_str'] = input_str args['input_pids'] = input_pids goods_id = args.pop('goods_id') dg = alloc_distributor_goods(self.db, goods_id, shop_id) args['outer_id'] = dg.goods_link_id app_info = json.loads(self.db.get( 'select taobao_api_info from distributor_shop where id = %s', shop_id).taobao_api_info, object_hook=json_hook) goods_push = Taobao('taobao.item.add') goods_push.set_app_info(app_info.app_key, app_info.app_secret_key) goods_push.set_session(app_info.session) response = yield goods_push(**args) goods_push.parse_response(response.body) ok = 0 num_iid = '' if goods_push.is_ok(): ok = 1 num_iid = goods_push.message.item.num_iid message = '发布成功' self.db.execute( 'update goods_distributor_shop set status="PENDING", created_by=%s, created_at=NOW(), ' 'distributor_goods_id=%s where goods_id=%s and distributor_shop_id=%s and goods_link_id=%s', self.current_user.name, num_iid, goods_id, shop_id, dg.goods_link_id) else: err_msg = goods_push.error.sub_msg if 'sub_msg' in goods_push.error else goods_push.error.msg message = '发布失败:' + err_msg.encode('utf-8') img_paths = self.db.get('select img_paths from goods where id=%s', goods_id).img_paths img_paths = json.loads(img_paths) if img_paths else dict() self.render('goods/distributor/taobao/result.html', message=message, ok=ok, num_iid=num_iid, shop_id=shop_id, img_paths=img_paths, img_url=img_url)
def sync(db, products): for product in products: if not product.taobao_api_info: logging.error('sync_ktv_sku: invalid taobao_api_info. product_id: %s', product.product_id) continue taobao_api_info = json.loads(product.taobao_api_info, object_hook=json_hook) iid = product.distributor_goods_id taobao = Taobao('taobao.item.get') taobao.set_app_info(taobao_api_info.app_key, taobao_api_info.app_secret_key) response = taobao.sync_fetch(fields='sku', num_iid=iid) taobao.parse_response(response) if not taobao.is_ok(): logging.error('sync_ktv_sku: get taobao item info failed. goods_distributor_shop_id: %s', product.gds_id) if taobao.error.sub_code == 'isv.item-get-service-error:ITEM_NOT_FOUND': # 商品在淘宝不存在,于是在我们系统中设置为逻辑删除 logging.error('sync_ktv_sku: product not exist. goods_distributor_shop_id: %s', product.gds_id) db.execute('update goods_distributor_shop set deleted=1 where id=%s', product.gds_id) continue local_sku_list = build_taobao_sku(db, product.shop_id, product.product_id) remote_sku_list = [] invalid_skus = [] if 'skus' in taobao.message.item and 'sku' in taobao.message.item.skus: for sku in taobao.message.item.skus.sku: tmp = sku_split_re.split(sku.properties_name) # 例: 27426219:3442354:包厢房型:小包;-1:-1:欢唱时间:17点至20点;-2:-45:日期:12月11日(周三) tb_sku = TaobaoSku( room_type='', dt=None, price=Decimal(sku.price), quantity=sku.quantity, start_time=0, duration=0, sku_id=sku.sku_id ) if len(tmp) != 12: invalid_skus.append(tb_sku) continue tb_sku.parse_taobao_property(tmp[3].encode('utf-8'), tmp[7].encode('utf-8'), tmp[11].encode('utf-8')) remote_sku_list.append(tb_sku) add_sku_list, delete_sku_list, update_price_sku_list, update_quantity_sku_list = diff_local_and_remote( local_sku_list, remote_sku_list ) delete_sku_list.extend(invalid_skus) remote_price_set = set([sku.price for sku in remote_sku_list]) for sku in delete_sku_list: if sku.price in remote_price_set: remote_price_set.remove(sku.price) taobao = Taobao('taobao.item.sku.delete') taobao.set_app_info(taobao_api_info.app_key, taobao_api_info.app_secret_key) taobao.set_session(taobao_api_info.session) response = taobao.sync_fetch( num_iid=iid, properties='%s;$欢唱时间:%s;$日期:%s' % (sku.room_key, sku.human_time_range, sku.human_date), item_price=str(min(remote_price_set) if remote_price_set else sku.price) ) taobao.parse_response(response) logging.info('sync_ktv_sku: %s DELETE[%s] %s %s', product.gds_id, 'OK' if taobao.is_ok() else 'FAIL', sku, '' if taobao.is_ok() else taobao.error.sub_code.encode('utf-8')) for sku in add_sku_list: remote_price_set.add(sku.price) taobao = Taobao('taobao.item.sku.add') taobao.set_app_info(taobao_api_info.app_key, taobao_api_info.app_secret_key) taobao.set_session(taobao_api_info.session) end = sku.start_time + sku.duration end = end - 24 if end >= 24 else end response = taobao.sync_fetch( num_iid=iid, properties='%s;$欢唱时间:%s;$日期:%s' % (sku.room_key, sku.human_time_range, sku.human_date), quantity=sku.quantity, price=sku.price, outer_id=sku.room_type+sku.date.strftime('%Y%m%d')+str(sku.start_time*100+end), item_price=str(min(remote_price_set)) ) taobao.parse_response(response) logging.info('sync_ktv_sku: %s ADD[%s] %s %s', product.gds_id, 'OK' if taobao.is_ok() else 'FAIL', sku, '' if taobao.is_ok() else taobao.error.sub_code.encode('utf-8')) if update_quantity_sku_list: taobao = Taobao('taobao.skus.quantity.update') taobao.set_app_info(taobao_api_info.app_key, taobao_api_info.app_secret_key) taobao.set_session(taobao_api_info.session) response = taobao.sync_fetch( num_iid=iid, skuid_quantities=';'.join(['%s:%s' % (sku.sku_id, sku.quantity) for sku in update_quantity_sku_list]) ) taobao.parse_response(response) logging.info('sync_ktv_sku: UPDATE_QUANTITY[%s] %s', 'OK' if taobao.is_ok() else 'FAIL', taobao.get_field('skuid_quantities')) for sku in update_price_sku_list: taobao = Taobao('taobao.item.sku.price.update') taobao.set_app_info(taobao_api_info.app_key, taobao_api_info.app_secret_key) taobao.set_session(taobao_api_info.session) response = taobao.sync_fetch( num_iid=iid, properties='%s;$欢唱时间:%s;$日期:%s' % (sku.room_key, sku.human_time_range, sku.human_date), quantity=sku.quantity, price=sku.price, item_price=sku.price, # 此处不好确定此时的该商品所有SKU的最低价格,所以就填了当前价格 ) taobao.parse_response(response) logging.info('sync_ktv_sku: %s UPDATE_PRICE[%s] %s', product.gds_id, 'OK' if taobao.is_ok() else 'FAIL', sku, '' if taobao.is_ok() else taobao.error.sub_code.encode('utf-8'))
def get_taobao(self, app_info, existed_orders, unbind_goods, success_orders, partner): page_index = 0 taobao = Taobao('taobao.trades.sold.get') taobao.set_app_info(app_info.app_key, app_info.app_secret_key) taobao.set_session(app_info.session) while True: page_index += 1 response = yield taobao( status='WAIT_SELLER_SEND_GOODS', use_has_next='true', page_size='100', page_no=page_index, fields= 'orders.outer_iid,tid,orders.payment,orders.num,pay_time,orders.price,' 'shipping_type,orders.logistics_company,receiver_mobile,receiver_phone,' 'receiver_name,receiver_state,receiver_city,receiver_district,' 'receiver_address,receiver_zip,has_buyer_message') taobao.parse_response(response.body) if not taobao.is_ok(): logging.error(taobao.error) break converted_data = [] if 'trades' not in taobao.message.keys(): logging.info(taobao.message) else: for trade in taobao.message.trades.values(): for i in range(len(trade)): buy_message = "" #如果买家有留言,就去单独获取留言 if trade[i].has_buyer_message: trade_get = Taobao('taobao.trade.get') trade_get.set_app_info(app_info.app_key, app_info.app_secret_key) trade_get.set_session(app_info.session) trade_get_response = yield trade_get( tid=trade[i]['tid'], fields='buyer_message') trade_get.parse_response(trade_get_response.body) #取得订单留言信息 buy_message = trade_get.message.trade.buyer_message if not 'order' in trade[i].orders: continue for order_detail in trade[i].orders.order: if trade[i].shipping_type == 'virtual': logging.info('虚拟发货 跳过: ' + trade[i]['tid']) continue if not order_detail.outer_iid: logging.info('该商品在淘宝上没有设置商品编码,请确认一下:' + trade[i].tid) continue mapping = { 'goods_no': 'outer_iid', 'sales_price': 'price', 'buy_num': 'num' } order_dict = {} for key, value in mapping.iteritems(): order_dict[key] = order_detail[value] order_dict['distr_order_no'] = trade[i].tid order_dict['paid_at'] = trade[i].pay_time order_dict['receiver'] = trade[i].receiver_name order_dict['zip_code'] = trade[i].receiver_zip order_dict['remarks'] = buy_message order_dict['express_info'] = buy_message if not trade[i].receiver_mobile: order_dict['phone'] = trade[i].receiver_phone else: order_dict['phone'] = trade[i].receiver_mobile order_dict['address'] = trade[i].receiver_state + trade[i].receiver_city + \ trade[i].receiver_district + trade[i].receiver_address converted_data.append(order_dict) #处理渠道产生一百券对应的订单信息 process_partner_order(self, partner, converted_data, True, existed_orders, unbind_goods, success_orders) if taobao.message.has_next is False: break