sp_api_client.py 37 KB

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