sp_api_client.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. import clickhouse_connect
  2. import time
  3. import warnings
  4. warnings.filterwarnings('ignore')
  5. import numpy as np
  6. from pymysql import Timestamp
  7. from sp_api.util import throttle_retry, load_all_pages
  8. from sp_api.api import Orders,ListingsItems,Inventories,Reports,CatalogItems
  9. from sp_api.base import Marketplaces,ReportType,ProcessingStatus
  10. import pandas as pd
  11. import gzip
  12. from io import BytesIO,StringIO
  13. from datetime import datetime, timedelta,timezone
  14. import pytz
  15. import time
  16. from dateutil.parser import parse
  17. import pymysql
  18. from typing import List, Literal
  19. class SpApiRequest:
  20. def __init__(self, credentials,marketplace):
  21. self.credentials = credentials
  22. self.marketplace = marketplace
  23. # self.shopInfo = shop_infos('3006125408623189')
  24. # self.timezone = self.shopInfo['time_zone']
  25. # self.profileid = '3006125408623189'
  26. @classmethod
  27. def mysql_connect_auth(cls):
  28. conn = pymysql.connect(user="admin",
  29. password="NSYbBSPbkGQUbOSNOeyy",
  30. host="retail-data.cnrgrbcygoap.us-east-1.rds.amazonaws.com",
  31. database="ansjer_dvadmin",
  32. port=3306)
  33. return conn
  34. @classmethod
  35. def mysql_connect_auth_lst(cls):
  36. conn = pymysql.connect(user="huangyifan",
  37. password="123456",
  38. host="127.0.0.1",
  39. database="amz_sp_api",
  40. port=3306)
  41. return conn
  42. @classmethod
  43. def mysql_connect(cls):
  44. conn = pymysql.connect(user="huangyifan",
  45. password="123456",
  46. host="127.0.0.1",
  47. database="amz_sp_api",
  48. port=3306)
  49. return conn
  50. @classmethod
  51. def mysql_adTest_connect(cls):
  52. conn = pymysql.connect(user="root",
  53. password="sandbox",
  54. host="192.168.1.225",
  55. database="asj_ads",
  56. port=3306)
  57. return conn
  58. @classmethod
  59. def get_catelog(cls,account_name,country=Marketplaces.US,asin=None):
  60. if country in [Marketplaces.US, Marketplaces.BR, Marketplaces.CA,Marketplaces.MX]:
  61. region = 'NA'
  62. elif country in [Marketplaces.DE,Marketplaces.AE, Marketplaces.BE, Marketplaces.PL,
  63. Marketplaces.EG,Marketplaces.ES, Marketplaces.GB, Marketplaces.IN, Marketplaces.IT,
  64. Marketplaces.NL, Marketplaces.SA, Marketplaces.SE, Marketplaces.TR,Marketplaces.UK,Marketplaces.FR,
  65. ]:
  66. region = 'EU'
  67. else:
  68. region = str(country)[-2:]
  69. df = cls.auth_info()
  70. try:
  71. refresh_token = df.query("account_name==@account_name and region==@region")['refresh_token'].values[0]
  72. except:
  73. print("请输入正确的account name与Marketplace")
  74. return '获取失败'
  75. cred = {
  76. 'refresh_token': refresh_token,
  77. 'lwa_app_id': 'amzn1.application-oa2-client.1f9d3d4747e14b22b4b598e54e6b922e', # 卖家中心里面开发者资料LWA凭证
  78. 'lwa_client_secret': 'amzn1.oa2-cs.v1.3af0f5649f5b8e151cd5bd25c10f2bf3113172485cd6ffc52ccc6a5e8512b490',
  79. 'aws_access_key': 'AKIARBAGHTGOZC7544GN',
  80. 'aws_secret_key': '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',
  81. 'role_arn': 'arn:aws:iam::070880041373:role/Amazon_SP_API_ROLE'
  82. }
  83. cate_item = CatalogItems(credentials=cred, marketplace=country)
  84. images_info = cate_item.get_catalog_item(asin=asin,**{"includedData":['images']})
  85. images = images_info.images[0].get('images')[0]['link']
  86. title_info = cate_item.get_catalog_item(asin=asin)
  87. title = title_info.payload['summaries'][0]['itemName']
  88. return {'images':images,'title':title}
  89. def create_report(self,**kwargs):
  90. reportType = kwargs['reportType']
  91. reportOptions =kwargs.get("reportOptions")
  92. dataStartTime = datetime.now().strftime("%Y-%m-%dT%H:%M:%S") if kwargs.get("dataStartTime") is None else kwargs.get("dataStartTime")+"T00:00:00"
  93. dataEndTime = datetime.now().strftime("%Y-%m-%dT%H:%M:%S") if kwargs.get("dataEndTime") is None else kwargs.get("dataEndTime")+"T23:59:59"
  94. report = Reports(credentials=self.credentials, marketplace=self.marketplace)
  95. rel = report.create_report(
  96. reportType=reportType,marketplaceIds=[kwargs['marketpalceids'] if kwargs.get('marketpalceids') is not None else self.marketplace.marketplace_id],
  97. reportOptions=reportOptions,dataStartTime=dataStartTime,dataEndTime=dataEndTime
  98. )
  99. reportId = rel.payload.get("reportId")
  100. # print(reportId)
  101. return reportId
  102. def decompression(self,reportId):
  103. report = Reports(credentials=self.credentials, marketplace=self.marketplace)
  104. while True:
  105. reportId_info = report.get_report(reportId=reportId)
  106. # print(reportId_info.payload)
  107. print("please wait...")
  108. if reportId_info.payload.get("processingStatus")==ProcessingStatus.DONE:
  109. reportDocumentId = reportId_info.payload.get("reportDocumentId")
  110. rp_table = report.get_report_document(reportDocumentId=reportDocumentId,download=False)
  111. print(rp_table)
  112. if rp_table.payload.get('compressionAlgorithm') is not None and self.marketplace.marketplace_id not in ['A1VC38T7YXB528']:#
  113. df = pd.read_table(filepath_or_buffer=rp_table.payload['url'],compression={"method":'gzip'},encoding='iso-8859-1')
  114. return df
  115. elif rp_table.payload.get('compressionAlgorithm') is not None and self.marketplace.marketplace_id in ['A1VC38T7YXB528']:
  116. df = pd.read_table(filepath_or_buffer=rp_table.payload['url'], compression={"method": 'gzip'},
  117. encoding='Shift-JIS')
  118. # df.columns =
  119. return df
  120. elif rp_table.payload.get('compressionAlgorithm') is None and self.marketplace.marketplace_id not in ['A1VC38T7YXB528']:
  121. df = pd.read_table(rp_table.payload.get("url"),encoding='iso-8859-1')
  122. return df
  123. elif rp_table.payload.get('compressionAlgorithm') is None and self.marketplace.marketplace_id in ['A1VC38T7YXB528']:
  124. df = pd.read_table(rp_table.payload.get("url"),encoding='Shift-JIS')
  125. return df
  126. elif reportId_info.payload.get("processingStatus") in [ProcessingStatus.CANCELLED,ProcessingStatus.FATAL]:
  127. print(reportId_info)
  128. print("取消或失败")
  129. break
  130. time.sleep(15)
  131. print("please wait...")
  132. def data_deal(self,decom_df,seller_id):
  133. decom_df['mainImageUrl'] = decom_df['seller-sku'].map(lambda x: self.get_mainImage_url(x))
  134. url_columns = [i for i in decom_df.columns if "url" in i.lower()]
  135. if len(url_columns) > 0:
  136. decom_df[url_columns] = decom_df[url_columns].astype("string")
  137. asin_columns = [i for i in decom_df.columns if 'asin' in i.lower()]
  138. if len(asin_columns) > 0:
  139. decom_df[asin_columns] = decom_df[asin_columns].astype("string")
  140. if 'pending-quantity' in decom_df.columns:
  141. decom_df['pending-quantity'] = decom_df['pending-quantity'].map(
  142. lambda x: 0 if pd.isna(x) or np.isinf(x) else x).astype("int32")
  143. deletecolumns = [i for i in decom_df.columns if 'zshop' in i.lower()]
  144. decom_df.drop(columns=deletecolumns, inplace=True)
  145. if 'quantity' in decom_df.columns:
  146. decom_df['quantity'] = decom_df['quantity'].map(lambda x: 0 if pd.isna(x) or np.isinf(x) else x).astype(
  147. "int32")
  148. decom_df['opendate_date'] = decom_df['open-date'].map(lambda x: self.datetime_deal(x))
  149. if 'add-delete' in decom_df.columns:
  150. decom_df['add-delete'] = decom_df['add-delete'].astype('string', errors='ignore')
  151. if 'will-ship-internationally' in decom_df.columns:
  152. decom_df['will-ship-internationally'] = decom_df['will-ship-internationally'].astype('string',errors='ignore')
  153. if 'expedited-shipping' in decom_df.columns:
  154. decom_df['expedited-shipping'] = decom_df['expedited-shipping'].astype('string',errors='ignore')
  155. decom_df['updateTime'] = datetime.now()
  156. decom_df['timezone'] = "UTC"
  157. decom_df['seller_id'] = seller_id
  158. #
  159. decom_df['item-description'] = decom_df['item-description'].str.slice(0,500)
  160. decom_df[decom_df.select_dtypes(float).columns] = decom_df[decom_df.select_dtypes(float).columns].fillna(0.0)
  161. decom_df[decom_df.select_dtypes(int).columns] = decom_df[decom_df.select_dtypes(int).columns].fillna(0)
  162. decom_df[decom_df.select_dtypes(datetime).columns] = decom_df[decom_df.select_dtypes(datetime).columns].astype(
  163. 'string')
  164. decom_df.fillna('', inplace=True)
  165. # print(decom_df.info())
  166. return decom_df
  167. def GET_MERCHANT_LISTINGS_ALL_DATA(self,limit=None):
  168. start = time.time()
  169. para = {"reportType":ReportType.GET_MERCHANT_LISTINGS_ALL_DATA}
  170. reportid = self.create_report(**para)
  171. decom_df = self.decompression(reportid)
  172. print("连接数据库")
  173. conn = self.mysql_connect()
  174. print("连接成功")
  175. cursor = conn.cursor()
  176. timezone = "UTC" #pytz.timezone(self.timezone)
  177. bondary_date = (datetime.now()).strftime("%Y-%m-%d") #+ timedelta(days=-28)
  178. cursor.execute(f"""select * from amz_sp_api.productInfo where (mainImageUrl is not null and mainImageUrl not in ('', ' ')) and
  179. (`seller-sku` not in ('',' ') and `seller-sku` is not null) and
  180. `updateTime`>='{bondary_date}'""") #`seller-sku`,`updateTime`,`mainImageUrl`
  181. col = [i[0] for i in cursor.description]
  182. query_rel = cursor.fetchall()
  183. if len(query_rel)!=0:
  184. print(query_rel[0])
  185. df = pd.DataFrame(query_rel,columns=col)
  186. listingid = df['listing-id'].to_numpy().tolist()
  187. decom_df = decom_df.query("`listing-id` not in @listingid")
  188. print("数据条数: ",len(decom_df))
  189. # print(f"delete * from amz_sp_api.productInfo where `listing-id` not in {tuple(listingid)}")
  190. # conn.commit()
  191. if len(decom_df)==0:
  192. return "Done"
  193. if limit != None:
  194. decom_df = decom_df.iloc[:limit,:]
  195. print("getting mainImageInfo...")
  196. rowcount = 0
  197. while rowcount < len(decom_df):
  198. df_insert = decom_df.copy()
  199. df_insert = df_insert.iloc[rowcount:rowcount + 200, :]
  200. df_insert = self.data_deal(df_insert)
  201. list_df = df_insert.to_numpy().tolist()
  202. # print(list(conn.query("select * from amz_sp_api.orderReport")))
  203. sql = f"""
  204. insert into amz_sp_api.productInfo
  205. values (%s,%s,%s,%s,%s,%s,%s, %s,%s,%s,%s,%s,%s,%s, %s,%s,%s,%s,%s,%s,%s, %s,%s,%s,%s,%s,%s,%s,%s)
  206. """ #ok
  207. # print(sql)
  208. conn = self.mysql_connect()
  209. cursor = conn.cursor()
  210. try:
  211. conn.begin()
  212. cursor.executemany(sql, list_df)
  213. conn.commit()
  214. print("插入中...")
  215. insert_listingid = df_insert['listing-id'].to_numpy().tolist()
  216. cursor.execute(f"delete from amz_sp_api.productInfo where `listing-id` not in {tuple(insert_listingid)} and `updateTime`<'{bondary_date}'")
  217. conn.commit()
  218. rowcount += 200
  219. except Exception as e:
  220. conn.rollback()
  221. print(e)
  222. try:
  223. conn = self.mysql_connect()
  224. cursor = conn.cursor()
  225. conn.begin()
  226. cursor.executemany(sql, list_df)
  227. conn.commit()
  228. insert_listingid = df_insert['listing-id'].to_numpy().tolist()
  229. cursor.execute(f"delete from amz_sp_api.productInfo where `listing-id` not in {tuple(insert_listingid)} and `updateTime`<'{bondary_date}'")
  230. conn.commit()
  231. except Exception as e:
  232. conn.rollback()
  233. print(e)
  234. break
  235. # break
  236. conn.close()
  237. print("全部完成")
  238. end =time.time()
  239. print("duration:",end-start)
  240. return decom_df
  241. def get_listing_info(self, sku,seller_id):
  242. listingClient = ListingsItems(credentials=self.credentials, marketplace=self.marketplace)
  243. try:
  244. r1 = listingClient.get_listings_item(sellerId=seller_id, sku=sku)
  245. # print(r1.payload)
  246. json_content = r1.payload.get("summaries")[0]
  247. item_name = json_content.get("itemName")
  248. item_name ='###' if item_name==None else item_name
  249. img = json_content.get("mainImage")
  250. img_url = '###' if img is None else img.get("link")
  251. # print(str(img_url)+"-----"+ str(item_name))
  252. return str(img_url)+"-----"+ str(item_name)
  253. except Exception as e:
  254. try:
  255. print("获取图片url过程错误重试, 错误message: ",e)
  256. time.sleep(3)
  257. r1 = listingClient.get_listings_item(sellerId=seller_id, sku=sku)
  258. print(r1.payload)
  259. json_content = r1.payload.get("summaries")[0]
  260. item_name = json_content.get("itemName")
  261. item_name = '###' if item_name == None else item_name
  262. img = json_content.get("mainImage")
  263. img_url = '###' if img is None else img.get("link")
  264. return str(img_url)+"-----"+ str(item_name)
  265. except Exception as e:
  266. print(e)
  267. return "###-----###"
  268. def datetime_deal(self,timestring):
  269. timezone_ = {"AEST":"Australia/Sydney",
  270. "AEDT":"Australia/Sydney",
  271. "PST":"America/Los_Angeles",
  272. "PDT":"America/Los_Angeles",
  273. "CST":"America/Chicago",
  274. "CDT":"America/Chicago",
  275. "MET":"MET",
  276. "MEST":"MET",
  277. "BST":"Europe/London",
  278. "GMT":"GMT",
  279. "CET":"CET",
  280. "CEST":"CET",
  281. "JST":"Asia/Tokyo",
  282. "BRT":"America/Sao_Paulo"}
  283. date_list = str.split(timestring,sep = ' ')
  284. if len(date_list)<3:
  285. try:
  286. return datetime.strptime(date_list[0],"%Y-%m-%d")
  287. except:
  288. try:
  289. return datetime.strptime(date_list[0], "%Y/%m/%d")
  290. except:
  291. try:
  292. return datetime.strptime(date_list[0], "%d/%m/%Y")
  293. except Exception as e:
  294. print(e)
  295. return datetime(1999, 12, 31, 0, 0, 0)
  296. try:
  297. time_date = datetime.strptime(date_list[0]+date_list[1],"%Y-%m-%d%H:%M:%S")
  298. timezone = pytz.timezone(timezone_[date_list[2]])
  299. time_ = timezone.localize(time_date)
  300. return time_.astimezone(pytz.UTC)
  301. except:
  302. try:
  303. time_date = datetime.strptime(date_list[0] + date_list[1], "%d/%m/%Y%H:%M:%S")
  304. timezone = pytz.timezone(timezone_[date_list[2]])
  305. time_ = timezone.localize(time_date)
  306. return time_.astimezone(pytz.UTC)
  307. except :
  308. try:
  309. time_date = datetime.strptime(date_list[0] + date_list[1], "%Y/%m/%d%H:%M:%S")
  310. timezone = pytz.timezone(timezone_[date_list[2]])
  311. time_ = timezone.localize(time_date)
  312. return time_.astimezone(pytz.UTC)
  313. except Exception as e1:
  314. print(e1)
  315. return datetime(1999,12,31,0,0,0)
  316. def update_data(self,df,seller_id,country_code,conn):
  317. conn = SpApiRequest.mysql_connect_auth_lst()
  318. cursor = conn.cursor()
  319. columns = ['listing-id', 'seller_id',
  320. 'asin1', 'seller-sku', 'title', 'image_link', 'country_code',
  321. 'marketplace_id', 'quantity', 'fulfillment_channel',
  322. 'price', 'opendate', 'status', 'update_datetime', 'product-id', 'product-id-type'
  323. ]
  324. if country_code=='GB':
  325. country_code="UK"
  326. df['country_code'] = "UK"
  327. df_data = pd.DataFrame(columns=columns)
  328. delete_list = []
  329. marketplace_id = self.marketplace.marketplace_id
  330. try:
  331. cursor.execute(f"""select * from
  332. amz_sp_api.seller_listings where seller_id='{seller_id}' and marketplace_id='{marketplace_id}'""")
  333. col = [i[0] for i in cursor.description]
  334. query_rel = cursor.fetchall()
  335. df_rel = pd.DataFrame(query_rel, columns=col)
  336. df_rel['quantity'] = df_rel['quantity'].fillna(0).astype('int64')
  337. df_rel['price'] = df_rel['price'].fillna(0.0).astype('float64')
  338. df_rel['product_id_type'] = df_rel['product_id_type'].astype('int64')
  339. df['update_datetime'] =df['update_datetime'].astype('datetime64[ns]')
  340. df['quantity'] = df['quantity'].fillna(0).astype('int64')
  341. df['price']= df['price'].fillna(0.0).astype('float64')
  342. # print(df_rel.dtypes)
  343. # print(df[columns].dtypes)
  344. row = 0
  345. while row < len(df):
  346. temp_df = df.iloc[row, :]
  347. listing_id = temp_df['listing-id']
  348. asin = temp_df['asin1']
  349. sku = temp_df['seller-sku']
  350. quantity = temp_df['quantity']
  351. fulfillment_channel = temp_df['fulfillment_channel']
  352. price = temp_df['price']
  353. product_id = temp_df['product-id']
  354. title = temp_df['title']
  355. imageurl = temp_df['image_link']
  356. temp = df_rel.query("""listing_id==@listing_id and asin==@asin and sku==@sku and quantity==@quantity and fulfillment_channel==@fulfillment_channel and price==@price and product_id==@product_id and country_code==@country_code and seller_id==@seller_id and title==@title and image_link==@imageurl""")
  357. print("需要关注数据(是否异常):",len(temp),temp.to_numpy().tolist()) if len(temp)>1 else 1
  358. if len(temp)>1:
  359. temp = temp.head(1).to_numpy().tolist()
  360. df_data = df_data.append(temp_df, ignore_index=True)
  361. delete_list.append((seller_id, marketplace_id, sku, listing_id, product_id))
  362. # print(len(temp))
  363. if len(temp)==0:
  364. df_data = df_data.append(temp_df,ignore_index=True)
  365. delete_list.append((seller_id,marketplace_id,sku,listing_id,product_id))
  366. row += 1
  367. print("判断不同数据条数",len(delete_list))
  368. print("预计更新数据条数",len(df_data))
  369. try:
  370. # print(tuple(delete_list))
  371. if len(delete_list)>0:
  372. query = f"""delete from amz_sp_api.seller_listings
  373. where (seller_id,marketplace_id,sku,listing_id,product_id) in %s""" #where (seller_id,country_code) in %s"""
  374. cursor.execute(query,(delete_list,))
  375. conn.commit()
  376. print(delete_list)
  377. print("进行中...")
  378. except Exception as e:
  379. print(e)
  380. conn.rollback()
  381. return df_data
  382. except Exception as e:
  383. print("错误:", e)
  384. return df
  385. def GET_FLAT_FILE_OPEN_LISTINGS_DATA(self,conn=None,seller_id=None):
  386. para = {"reportType": ReportType.GET_MERCHANT_LISTINGS_ALL_DATA}
  387. reportid = self.create_report(**para)
  388. df = self.decompression(reportid)
  389. if len(df)>0:
  390. if self.marketplace.marketplace_id =='A1VC38T7YXB528':
  391. df.columns = ['item-name','listing-id','seller-sku','price','quantity','open-date','product-id-type','item-description',
  392. 'item-condition','overseas shipping','fast shipping','asin1','stock_number','fulfillment-channel','merchant-shipping-group','status']
  393. df['seller_id'] = seller_id
  394. df['marketplace_id'] = self.marketplace.marketplace_id
  395. df['country_code'] = str(self.marketplace)[-2:]
  396. if 'fulfilment-channel' in df.columns:
  397. print("changed fulfilment-channel:")
  398. print(seller_id,self.marketplace)
  399. df['fulfillment-channel'] = df['fulfilment-channel'].copy()
  400. df['fulfillment_channel'] = df['fulfillment-channel'].map(lambda x:"FBA" if not pd.isna(x) and len(x)>0 and str(x)[1:4] in "AMAZON" else x)
  401. df['fulfillment_channel'] = df['fulfillment_channel'].map(lambda x: "FBM" if not pd.isna(x) and len(x)>0 and str(x)[1:4] in "DEFAULT" else x)
  402. if 'asin1' not in df.columns:
  403. df['asin1'] = ''
  404. if 'product-id' not in df.columns:
  405. df['product-id'] = ''
  406. # 空值处理
  407. df['quantity'] = df['quantity'].fillna(0).astype('int64',errors='ignore')
  408. df[['listing-id','seller_id','asin1','seller-sku','country_code','marketplace_id','fulfillment_channel','status','product-id']] = df[['listing-id','seller_id','asin1','seller-sku','country_code','marketplace_id','fulfillment_channel','status','product-id']].fillna('').astype('string',errors='ignore')
  409. df['price'] = df['price'].fillna(0.0).astype('float64',errors='ignore')
  410. df.fillna('',inplace=True)
  411. # 时间处理
  412. df['opendate'] = df['open-date'].map(lambda x: self.datetime_deal(x))
  413. df['update_datetime'] = datetime.now(pytz.UTC).date()
  414. origin_columns = ['listing-id','seller_id',
  415. 'asin1','seller-sku','title','image_link','country_code',
  416. 'marketplace_id','quantity','fulfillment_channel',
  417. 'price','opendate','status','update_datetime','product-id','product-id-type'
  418. ]
  419. conn = SpApiRequest.mysql_connect_auth_lst()
  420. cursor = conn.cursor()
  421. cursor.execute("""select product_id,asin from (select * from amz_sp_api.seller_listings where asin is not null
  422. and asin<>'' and product_id is not null and product_id <>'') t1 group by product_id,asin""")
  423. query_ = cursor.fetchall()
  424. col_name = [i[0] for i in cursor.description]
  425. df_datatable = pd.DataFrame(query_, columns=col_name)
  426. merged_df = df.merge(df_datatable[['product_id','asin']],how='left',left_on='product-id',right_on='product_id')
  427. print(merged_df.head())
  428. def func_(asin,asin1,product_id,cred,market_p,seller_id,sku):
  429. if 'B0' in str(product_id)[:3]:
  430. return str(product_id)
  431. if (pd.isna(asin1) or asin1=='') and (pd.isna(asin)==False and asin !=''):
  432. if 'B0' in asin[:3]:
  433. return asin
  434. elif (pd.isna(asin1)==False and asin1!=''):
  435. if 'B0' in asin1[:3]:
  436. return asin1
  437. listingClient = ListingsItems(credentials=cred, marketplace=market_p)
  438. try:
  439. r1 = listingClient.get_listings_item(sellerId=seller_id, sku=sku)
  440. print(r1.payload)
  441. asin = r1.payload.get("summaries")[0].get("asin")
  442. return asin
  443. except Exception as e:
  444. print("获取图片url过程错误重试, 错误message: ", e)
  445. time.sleep(3)
  446. r1 = listingClient.get_listings_item(sellerId=seller_id, sku=sku)
  447. print(r1.payload)
  448. asin = r1.payload.get("summaries")[0].get("asin")
  449. return asin
  450. merged_df['asin1'] = merged_df.apply(lambda x:func_(x['asin'],x['asin1'],x['product-id'],self.credentials,self.marketplace,seller_id,x['seller-sku']),axis=1) #x['asin'] if pd.isna(x['asin1']) or x['asin1']=='' else x['asin1']
  451. # merged_df.to_csv("tmp.csv")
  452. # merged_df = merged_df.loc[:10,:].copy()
  453. print("获取listing Info...")
  454. merged_df['temp_columns'] = merged_df.apply(lambda x: self.get_listing_info(x['seller-sku'],seller_id),axis=1)
  455. merged_df[['image_link','title']] = merged_df['temp_columns'].str.split("-----",expand=True)
  456. # merged_df['image_link'] = ''
  457. # merged_df['title'] = ''
  458. merged_df.fillna('',inplace=True)
  459. df1 = merged_df.copy()
  460. print(df1[origin_columns].head(1))
  461. update_df = self.update_data(df1,seller_id,str(self.marketplace)[-2:],conn)
  462. if len(update_df)==0:
  463. return '无更新数据插入'
  464. # update_df['country_code'] = update_df['country_code'].map({"GB":"UK"})
  465. conn = SpApiRequest.mysql_connect_auth_lst()
  466. cursor = conn.cursor()
  467. try:
  468. insertsql = """insert into
  469. amz_sp_api.seller_listings(listing_id,seller_id,asin,sku,title,image_link,country_code,marketplace_id,quantity,
  470. fulfillment_channel,price,launch_datetime,status,update_datetime,product_id,product_id_type)
  471. values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"""
  472. conn.begin()
  473. cursor.executemany(insertsql,tuple(update_df[origin_columns].to_numpy().tolist()))
  474. conn.commit()
  475. print("插入完成")
  476. return '插入完成'
  477. except Exception as e:
  478. print("插入错误:",e)
  479. conn.rollback()
  480. return '出错回滚'
  481. @staticmethod
  482. def auth_info():
  483. auth_conn = SpApiRequest.mysql_connect_auth()
  484. cursor = auth_conn.cursor()
  485. cursor.execute("select * from amazon_sp_report.amazon_sp_auth_info;")
  486. columns_name = [i[0] for i in cursor.description]
  487. rel = cursor.fetchall()
  488. df = pd.DataFrame(rel, columns=columns_name)
  489. return df
  490. @classmethod
  491. def get_orders_allShops(cls):
  492. pass
  493. @staticmethod
  494. def data_judge_secondTry(sp_api,data_type,seller_id,auth_conn):
  495. try:
  496. SpApiRequest.data_judge(sp_api, data_type, seller_id, auth_conn)
  497. except:
  498. time.sleep(3)
  499. SpApiRequest.data_judge(sp_api, data_type, seller_id, auth_conn)
  500. @staticmethod
  501. def data_judge(sp_api,data_type,seller_id,auth_conn):
  502. if data_type == "GET_FLAT_FILE_OPEN_LISTINGS_DATA":
  503. return sp_api.GET_FLAT_FILE_OPEN_LISTINGS_DATA(auth_conn,seller_id)
  504. elif data_type =="GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL":
  505. return sp_api.GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL(seller_id)
  506. elif data_type =="GET_FLAT_FILE_RETURNS_DATA_BY_RETURN_DATE":
  507. return sp_api.GET_FLAT_FILE_RETURNS_DATA_BY_RETURN_DATE(seller_id)
  508. else:
  509. return ""
  510. @classmethod
  511. def get_refreshtoken(cls):
  512. df = cls.auth_info()
  513. refreshtoken_list = (df['refresh_token'].to_numpy().tolist())
  514. return refreshtoken_list
  515. @classmethod
  516. def get_allShops(cls,data_type=Literal["GET_FLAT_FILE_OPEN_LISTINGS_DATA","GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL"]):
  517. df = cls.auth_info()
  518. refreshtoken_list = (df['refresh_token'].to_numpy().tolist())
  519. refreshtoken_list.reverse()
  520. for refresh_token in refreshtoken_list:
  521. aws_credentials = {
  522. 'refresh_token': refresh_token,
  523. 'lwa_app_id': 'amzn1.application-oa2-client.1f9d3d4747e14b22b4b598e54e6b922e', # 卖家中心里面开发者资料LWA凭证
  524. 'lwa_client_secret': 'amzn1.oa2-cs.v1.3af0f5649f5b8e151cd5bd25c10f2bf3113172485cd6ffc52ccc6a5e8512b490',
  525. 'aws_access_key': 'AKIARBAGHTGOZC7544GN',
  526. 'aws_secret_key': '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',
  527. 'role_arn': 'arn:aws:iam::070880041373:role/Amazon_SP_API_ROLE'
  528. }
  529. single_info = df.query("refresh_token==@refresh_token")
  530. region_circle = single_info['region'].values[0]
  531. seller_id = single_info['selling_partner_id'].values[0]
  532. account_name = single_info['account_name'].values[0]
  533. if region_circle == 'NA':
  534. pass
  535. for marketplace in [Marketplaces.US, Marketplaces.BR, Marketplaces.CA,Marketplaces.MX]:
  536. sp_api = SpApiRequest(aws_credentials, marketplace)
  537. try:
  538. auth_conn = SpApiRequest.mysql_connect_auth()
  539. cls.data_judge_secondTry(sp_api, data_type, seller_id, auth_conn)
  540. ## sp_api.GET_FLAT_FILE_OPEN_LISTINGS_DATA(auth_conn, seller_id)
  541. except Exception as e:
  542. print(e)
  543. elif region_circle == 'EU':
  544. pass
  545. for marketplace in [Marketplaces.DE,Marketplaces.AE, Marketplaces.BE, Marketplaces.PL,
  546. Marketplaces.EG,Marketplaces.ES, Marketplaces.GB, Marketplaces.IN, Marketplaces.IT,
  547. Marketplaces.NL, Marketplaces.SA, Marketplaces.SE, Marketplaces.TR,Marketplaces.UK,Marketplaces.FR,
  548. ]:
  549. sp_api = SpApiRequest(aws_credentials, marketplace)
  550. try:
  551. auth_conn = SpApiRequest.mysql_connect_auth()
  552. cls.data_judge_secondTry(sp_api, data_type, seller_id, auth_conn)
  553. ## sp_api.GET_FLAT_FILE_OPEN_LISTINGS_DATA(auth_conn, seller_id)
  554. except Exception as e:
  555. print(e)
  556. else:
  557. # if region_circle not in ['NA','EU']:
  558. auth_conn = SpApiRequest.mysql_connect_auth()
  559. print(region_circle)
  560. marketplace = eval(f'Marketplaces.{region_circle}')
  561. sp_api = SpApiRequest(aws_credentials, marketplace)
  562. cls.data_judge_secondTry(sp_api, data_type, seller_id, auth_conn)
  563. ## sp_api.GET_FLAT_FILE_OPEN_LISTINGS_DATA(auth_conn, seller_id)
  564. def timeDeal(self, orgTime):
  565. orgTime = parse(orgTime)
  566. timezone = pytz.timezone("UTC")
  567. shopTime = orgTime.astimezone(timezone)
  568. shopTime_datetime = datetime(shopTime.year, shopTime.month, shopTime.day, shopTime.hour, shopTime.minute,
  569. shopTime.second)
  570. return shopTime_datetime
  571. def GET_FLAT_FILE_RETURNS_DATA_BY_RETURN_DATE(self,seller_id):
  572. shopReportday = (datetime.now() + timedelta(days=-2)).strftime("%Y-%m-%d")
  573. # print(shopReportday)
  574. para = {"reportType": ReportType.GET_SELLER_FEEDBACK_DATA,
  575. "dataStartTime": shopReportday, "dataEndTime": shopReportday,
  576. }
  577. reportid = self.create_report(**para) # {"ShowSalesChannel":"true"}
  578. decom_df = self.decompression(reportid)
  579. print(decom_df)
  580. # print(decom_df.columns)
  581. def GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL(self,seller_id):
  582. # timezone_ = pytz.timezone(self.timezone)
  583. shopReportday = (datetime.now() + timedelta(days=-1)).strftime("%Y-%m-%d")
  584. # print(shopReportday)
  585. para = {"reportType":ReportType.GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL,"dataStartTime":shopReportday,"dataEndTime":shopReportday,"reportOptions":{"ShowSalesChannel":"true"}}
  586. reportid = self.create_report(**para) #{"ShowSalesChannel":"true"}
  587. decom_df = self.decompression(reportid)
  588. decom_df[decom_df.select_dtypes(float).columns] = decom_df[decom_df.select_dtypes(float).columns].fillna(0.0)
  589. decom_df[decom_df.select_dtypes(int).columns] = decom_df[decom_df.select_dtypes(int).columns].fillna(0)
  590. decom_df[decom_df.select_dtypes(datetime).columns] = decom_df[decom_df.select_dtypes(datetime).columns].astype('string')
  591. if "purchase-order-number" in decom_df.columns:
  592. decom_df['purchase-order-number'] = decom_df['purchase-order-number'].astype("string")
  593. decom_df.fillna('',inplace=True)
  594. # decom_df.to_csv('order.csv')
  595. decom_df["ReportDate"] = parse(shopReportday)
  596. # decom_df['timezone'] = decom_df["purchase-date"].map(lambda x: parse(x).tzname()).fillna(method='bfill')
  597. decom_df['timezone'] = "UTC"
  598. print("==========================================================")
  599. decom_df[["purchase-date", "last-updated-date"]] = decom_df[["purchase-date", "last-updated-date"]].applymap(
  600. lambda x: self.timeDeal(x) if pd.isna(x) == False or x != None else x)
  601. if 'is-business-order' not in decom_df.columns:
  602. decom_df['is-business-order'] = None
  603. if 'purchase-order-number' not in decom_df.columns:
  604. decom_df['purchase-order-number'] = '-'
  605. if 'price-designation' not in decom_df.columns:
  606. decom_df['price-designation'] = '-'
  607. decom_df['seller_id'] = seller_id
  608. country_code = str(self.marketplace)[-2:]
  609. if country_code=='GB':
  610. country_code="UK"
  611. # decom_df['country_code'] = "UK"
  612. decom_df['country_code'] = country_code
  613. # print(decom_df[])
  614. reserve_columns = ["amazon-order-id","merchant-order-id","purchase-date","last-updated-date","order-status",
  615. "fulfillment-channel","sales-channel","order-channel","ship-service-level","product-name",
  616. "sku","asin","item-status","quantity","currency","item-price","item-tax","shipping-price",
  617. "shipping-tax","gift-wrap-price","gift-wrap-tax","item-promotion-discount",
  618. "ship-promotion-discount","ship-city","ship-state","ship-postal-code","ship-country",
  619. "promotion-ids","is-business-order","purchase-order-number","price-designation","ReportDate",
  620. "timezone","seller_id","country_code"
  621. ]
  622. list_df = decom_df[reserve_columns].to_numpy().tolist()
  623. # print(list_df)
  624. # print(list_df[0])
  625. # tuple_data = [tuple(i) for i in list_df]
  626. conn = self.mysql_connect()
  627. cursor = conn.cursor()
  628. # print(list(conn.query("select * from amz_sp_api.orderReport")))
  629. sql = f"""
  630. insert into amz_sp_api.orderreport_renew1
  631. values (%s,%s,%s,%s,%s,%s,%s, %s,%s,%s,%s,%s,%s,%s, %s,%s,%s,%s,%s,%s,%s, %s,%s,%s,%s,%s,%s,%s, %s,%s,%s,%s,%s,%s,%s)
  632. """ #ok
  633. # print(sql)
  634. try:
  635. conn.begin()
  636. cursor.executemany(sql,list_df)
  637. conn.commit()
  638. print("插入完成")
  639. except Exception as e:
  640. conn.rollback()
  641. print(e)
  642. if __name__ == '__main__':
  643. SpApiRequest.get_allShops("GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL")
  644. # rel = SpApiRequest.get_catelog(account_name='ANLAPUS_US',country=Marketplaces.US,asin='B0BVXB4KT9')
  645. # print(rel)
  646. """
  647. create database amz_sp_api;
  648. """
  649. """
  650. create table amz_sp_api.productInfo
  651. (
  652. `item-name` VARCHAR(300),
  653. `item-description` VARCHAR(1000),
  654. `listing-id` VARCHAR(50),
  655. `seller-sku` VARCHAR(50),
  656. `price` FLOAT,
  657. `quantity` INT,
  658. `open-date` VARCHAR(70),
  659. `image-url` VARCHAR(300),
  660. `item-is-marketplace` VARCHAR(50),
  661. `product-id-type` INT,
  662. `item-note` VARCHAR(300),
  663. `item-condition` INT,
  664. `asin1` VARCHAR(50),
  665. `asin2` VARCHAR(50),
  666. `asin3` VARCHAR(50),
  667. `will-ship-internationally` VARCHAR(50),
  668. `expedited-shipping` VARCHAR(50),
  669. `product-id` VARCHAR(50),
  670. `bid-for-featured-placement` FLOAT,
  671. `add-delete` VARCHAR(50),
  672. `pending-quantity` INT,
  673. `fulfillment-channel` VARCHAR(50),
  674. `merchant-shipping-group` VARCHAR(50),
  675. `status` VARCHAR(50),
  676. `mainImageUrl` VARCHAR(300),
  677. `opendate_date` Date,
  678. `updateTime` Date,
  679. `timezone` VARCHAR(30)
  680. )
  681. """
  682. """
  683. create table amz_sp_api.orderReport
  684. (`amazon-order-id` VARCHAR(40),
  685. `merchant-order-id` VARCHAR(40),
  686. `purchase-date` DATETIME,
  687. `last-updated-date` DATETIME,
  688. `order-status` VARCHAR(40),
  689. `fulfillment-channel` VARCHAR(40),
  690. `sales-channel` VARCHAR(40),
  691. `order-channel` VARCHAR(40),
  692. `ship-service-level` VARCHAR(40),
  693. `product-name` VARCHAR(250),
  694. `sku` VARCHAR(50),
  695. `asin` VARCHAR(40),
  696. `item-status` VARCHAR(40),
  697. `quantity` INT,
  698. `currency` VARCHAR(40),
  699. `item-price` FLOAT,
  700. `item-tax` FLOAT,
  701. `shipping-price` FLOAT,
  702. `shipping-tax` FLOAT,
  703. `gift-wrap-price` FLOAT,
  704. `gift-wrap-tax` FLOAT,
  705. `item-promotion-discount` FLOAT,
  706. `ship-promotion-discount` FLOAT,
  707. `ship-city` VARCHAR(40),
  708. `ship-state` VARCHAR(40),
  709. `ship-postal-code` VARCHAR(40),
  710. `ship-country` VARCHAR(40),
  711. `promotion-ids` VARCHAR(50),
  712. `cpf` VARCHAR(40),
  713. `is-business-order` BOOL,
  714. `purchase-order-number` VARCHAR(50),
  715. `price-designation` VARCHAR(40),
  716. `signature-confirmation-recommended` BOOL,
  717. `ReportDate` DATE not null,
  718. `timezone` VARCHAR(20) not null
  719. );
  720. """