Beispiel #1
0
 def get_sale_msg(self):
     package_size = config.get('package_size') or 50
     if self.stock_order_ids.ssize() > 0:
         _logging.info("get order masg, package_size = " + str(package_size))
         order_ids = self.stock_order_ids.get_list(package_size)
         _logging.info("order_ids = " + str(order_ids))
         msg_lists = []
         for i in order_ids:
             # 订单详情查询
             req = top.api.AliexpressTradeRedefiningFindorderbyidRequest("gw.api.taobao.com", 80)
             req.set_app_info(top.appinfo(config.get("appkey", i[1]), config.get("secret", i[1])))
             req.param1 = {"order_id": i[0]}
             try:
                 resp = req.getResponse(config.get("session", i[1]))
                 msg = self.load_findorderbyid_response(resp, i[1])
                 msg_lists.append(msg)
                 _logging.info("append a msg " + str(i[0]))
             except Exception, e:
                 _logging.error(e)
                 if hasattr(e, 'errorcode') and e.errorcode == 15:
                     self._send_to_ding("请跳转到:{}进行人工授权".format(self.get_access_token(i[1])))
                 else:
                     self._send_to_ding("拉取订单详情失败:{}".format(i[0]))
         _logging.info('put msg list' + str(len(msg_lists)))
         self.stock_order_msg.put(msg_lists)
Beispiel #2
0
 def call_odoos(params,
                db_name=None,
                user_name=None,
                user_password=None,
                method_name=None):
     try:
         db_name = db_name or config.get('db_name')
         user_name = user_name or config.get('user_name')
         user_password = user_password or config.get('user_password')
         method_name = method_name or config.get('method_name')
     except Exception, e:
         _logging.error(e)
Beispiel #3
0
 def __init__(self, split_type=','):
     self.shops = config.get('shops').split(split_type)
     self.stock_order_ids = MyStock(int(config.get('maxsize')) if config.get('maxsize') else 10000)
     self.stock_order_msg = MyStock(int(config.get('maxsize')) if config.get('maxsize') else 10000)
     self._lock = threading.Lock()
     self._rolling = True
     self.oc = OdooCall(config.get("user_id"), config.get("password"), config.get("dbname"))
Beispiel #4
0
 def _send_to_ding(self, msg):
     url = config.get('aliexpress_error_ding')
     text_phone = config.get('text_phone') if config.get('text_phone') else ''
     param = json.dumps(
         {
             "msgtype": "text",
             "text": {
                 "content": text_phone + ' ' + __name__ + str(msg) + "\n"
             },
             "at": {
                 "atMobiles": [text_phone],
                 "isAtAll": False
             }
         }
     )
     dp._do_post(url, param)
Beispiel #5
0
 def load_findorderbyid_response(self, resp, shop):
     """
     解析订单详情信息
     :param resp: 接口返回信息
     :param shop: 配置文件店铺名称
     :return:
     """
     if 'aliexpress_trade_redefining_findorderbyid_response' in resp:
         res = resp['aliexpress_trade_redefining_findorderbyid_response']['result']
         res.update({'shop_code': config.get('shop_code', shop)})
         return res
     return []
Beispiel #6
0
 def update_aliexpress_token(self, shop=None, repeat_times=3):
     """
     更新token 现在token固定时长为1年,此方法不可用
     :param shop:
     :param repeat_times: 重试次数
     :return:
     """
     shops = self.shops
     if shops and shop in shops:
         shops = [shop]
     for shop_id in shops:
         url = 'https://gw.api.alibaba.com/openapi/param2/1/system.oauth2/getToken/{}'.format(
             config.get("appkey", shop_id))
         # url = "https://oauth.taobao.com/token"
         refresh_token_config = config.get("refresh_token", shop_id)
         data = {
             'grant_type': 'refresh_token',
             'client_id': config.get("appkey", shop_id),
             'client_secret': config.get("secret", shop_id),
             'refresh_token': refresh_token_config
         }
         try:
             refresh_response = requests.post(url=url, data=data, headers=HEADERS, timeout=5)
             if hasattr(refresh_response, 'status_code') and refresh_response.status_code > 200:
                 if refresh_response.status_code == 401:
                     while repeat_times > 0:
                         self.update_aliexpress_token(shop_id)
                         repeat_times -= 1
                     _logging.info(
                         u'请跳转到:{}进行人工授权;'.format(self.get_access_token(shop_id)))
                 raise ValueError(refresh_response.text)
             response_json = refresh_response.json()
         except requests.exceptions.Timeout, e:
             _logging.info(u'更新AliExpress Token,调用速卖通接口超时:{e}'.format(e=e))
             pass
         except Exception, e:
             _logging.info(u'更新AliExpress Token,调用速卖通接口产生了一个异常:{e}'.format(e=e))
             pass
Beispiel #7
0
 def get_sale_lists(self, shops=None):
     if not shops:
         shops = self.shops
     for shop in shops:
         # 订单列表简化查询
         create_date_end, create_date_start = self._get_start_end_time(shop)
         page, page_size, total_item = 1, 50, 51
         order_lists = []
         while page * page_size < total_item:
             req = top.api.AliexpressTradeRedefiningFindorderlistsimplequeryRequest("gw.api.taobao.com", 80)
             req.set_app_info(top.appinfo(config.get("appkey", shop), config.get("secret", shop)))
             req.param1 = {"create_date_end": create_date_end,
                           "create_date_start": create_date_start,
                           "page": page,
                           "page_size": page_size,
                           "order_status": order_status[0]
                           }
             try:
                 resp = req.getResponse(config.get("session", shop))
                 total_item = int(resp.get('aliexpress_trade_redefining_findorderlistsimplequery_response', {}).get('result', {}).get('total_item', total_item))
                 _logging.info("total_item=" + str(total_item) + "  page=" + str(page))
                 li = self.load_findorderlistsimplequery_response(resp, shop)
                 order_lists += li
             except Exception, e:
                 _logging.error(e)
                 if hasattr(e, 'errorcode') and e.errorcode == 15:
                     self._send_to_ding("请跳转到:{}进行人工授权".format(self.get_access_token(shop)))
                 break
             page += 1
         if order_lists:
             order_lists = self.oc.check_repeat(order_lists)
             lis = order_lists.get('result', [])
             self.stock_order_ids.put_list(lis)
             _logging.info("put_list into stock_order_ids" + str(lis))
         # TODO 将create_date_end,create_date_start,page,page_size 回写回配置文件
         self._write_next_start_end_time(create_date_start, create_date_end, shop)
Beispiel #8
0
 def _call_odoo(self, model, method, params={}):
     """
     调用odoo rpc方法
     :param model: 方法model
     :param method: 方法名称
     :param params: 参数
     :return: json respone
     """
     url = config.get('host')
     args = [self.dbname, self.user_id, self.password, model, method]
     if params:
         args.append(params)
     else:
         _logging.info('odoo call params is null')
     data = {
         "jsonrpc": "2.0",
         "method": "call",
         "params": {
             "service": "object",
             "method": "execute",
             "args": args
         },
         "id": 200
     }
     header = {'Content-Type': 'application/json'}
     data = json.dumps(data)
     req = urllib2.Request(url=url, data=data, headers=header)
     f = urllib2.urlopen(req)
     response = f.read()
     f.close()
     data = json.loads(response)
     # _logging.info(json.dumps(data))
     if data.get('result', {}).get('success', False):
         _logging.info('odoo call success')
         return data['result']
     else:
         _logging.info('odoo call error')
         raise ValueError(data['error'] if 'error' in
                          data else "unknow error code")
Beispiel #9
0
    def _get_start_end_time(self, shop=None):
        """
        获取该店铺拉取时间
        delay_time 是拉取多长分钟前的订单,只在第一次运行中有用
        last_run_time 是上次运行时间,将在上次结束和开始时间上加上该值生成本次运行开始结束时间
        :param shop:
        :return: (create_date_end, create_date_start)
        """
        last_run_time = config.get("last_run_time", shop) or time.time()
        last_run_time = abs(int((int(float(last_run_time)) - time.time())/60))
        delay_time = config.get("delay_time", shop)
        create_date_end_default = config.get("create_date_end", shop) if config.get("create_date_end", shop) else \
            datetime.now().strftime('%m/%d/%Y %H:%M:%S')
        create_date_start_default = config.get("create_date_start", shop) if config.get("create_date_start", shop) else \
            (datetime.strptime(create_date_end_default, '%m/%d/%Y %H:%M:%S') -
             relativedelta(minutes=delay_time or 2*24*60)).strftime('%m/%d/%Y %H:%M:%S')

        create_date_start = (datetime.strptime(create_date_start_default, '%m/%d/%Y %H:%M:%S') +
                             relativedelta(minutes=last_run_time)).strftime('%m/%d/%Y %H:%M:%S')
        create_date_end = (datetime.strptime(create_date_end_default, '%m/%d/%Y %H:%M:%S') +
                           relativedelta(minutes=last_run_time)).strftime('%m/%d/%Y %H:%M:%S')
        return create_date_end, create_date_start
Beispiel #10
0
 def __init__(self, msgstock):
     self.msgstock = msgstock  # 栈
     self.MAXT = config.get('max_thread') or 10  #最大访问odoo线程数
Beispiel #11
0
 def __init__(self, stock):
     self.stock = stock
     self._lock = threading.Lock()
     self._rolling = True
     self.oc = OdooCall(config.get("user_id"), config.get("password"),
                        config.get("dbname"))
Beispiel #12
0
 def get_access_token(self, state=None):
     return "https://oauth.aliexpress.com/authorize?response_type=token&client_id={}&state=1212&view=web&sp=ae".format(
         config.get('appkey', state))