sync_get_open_listing_data.py 38 KB

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