• 调用api接口获取token


    1. import os
    2. import pyodbc
    3. import requests
    4. import openpyxl
    5. from openpyxl.utils import get_column_letter
    6. import base64
    7. import time
    8. import hmac
    9. import hashlib
    10. import json
    11. import urllib
    12. import random
    13. import pandas as pd
    14. import datetime
    15. # 获取当前日期和时间
    16. current_datetime = datetime.datetime.now()
    17. # 将日期和时间格式化为字符串
    18. formatted_datetime1= current_datetime.strftime("%Y-%m-%d")
    19. # 生成新的文件名
    20. new_filename = xxx_{}.xlsx".format(formatted_datetime1)
    21. class SecretRobot:
    22. def __init__(self, secret='', webhook=''):
    23. self.secret = secret
    24. self.webhook = webhook
    25. self.timestamp = str(round(time.time() * 1000))
    26. self.headers = {"Content-Type": "application/json"}
    27. def send(self, message):
    28. self.get_sign()
    29. webhook = self.webhook + '×tamp=' + self.timestamp + '&sign=' + self.sign
    30. data = {
    31. "msgtype": "text",
    32. "text": {
    33. "content": message
    34. }
    35. }
    36. resp = requests.post(webhook, data=json.dumps(data), headers=self.headers)
    37. resp.close()
    38. def get_sign(self):
    39. secret_enc = self.secret.encode('utf-8')
    40. string_to_sign = '{}\n{}'.format(self.timestamp, self.secret)
    41. string_to_sign_enc = string_to_sign.encode('utf-8')
    42. hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    43. self.sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    44. def send_dingding_message1(message, secret):
    45. webhook = 'xxx'
    46. # 创建 SecretRobot 对象
    47. robot = SecretRobot(secret=secret, webhook=webhook)
    48. # 发送消息
    49. robot.send(message)
    50. def get_order_source_name(order_source_id):
    51. # 连接数据库
    52. conn = pyodbc.connect('DRIVER={SQL Server};SERVER=xxx;DATABASE=metabase;UID=xxx;PWD=xxx')
    53. cursor = conn.cursor()
    54. # 执行查询语句,获取order_source_name
    55. cursor.execute(f"SELECT xxx FROM xxx WHERE xxx = '{xxx}'")
    56. row = cursor.fetchone()
    57. # 关闭数据库连接
    58. conn.close()
    59. if row is not None:
    60. return row[0]
    61. else:
    62. return ""
    63. # 设置计数器和暂停时间
    64. count = 0
    65. pause_time = random.randint(10, 12)
    66. username = 'xxx'
    67. password = 'xxx'
    68. # 编码用户名和密码为 Base64 字符串
    69. credentials = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("utf-8")
    70. authorization = f"Basic {credentials}"
    71. # 连接数据库
    72. conn = pyodbc.connect('DRIVER={SQL Server};SERVER=xxx;DATABASE=xxx;UID=xxx;PWD=xxx')
    73. cursor = conn.cursor()
    74. url_template = 'xxx'
    75. # 执行查询语句,获取数据
    76. cursor.execute("SELECT order_source_id, user_token_secret_access_key, order_source_country FROM rb_mercadolibre_site_user_info")
    77. rows = cursor.fetchall()
    78. order_source_names = []
    79. processed_order_ids = [] # 存储已处理过的 order_source_id
    80. # 遍历每行数据
    81. for row_idx, row in enumerate(rows, 2):
    82. order_source_id = row[0]
    83. if order_source_id in processed_order_ids:
    84. continue
    85. ACCESS_TOKEN = row[1]
    86. order_source_country = row[2]
    87. processed_order_ids.append(order_source_id)
    88. order_source_id = int(order_source_id)
    89. # 构建接口入参
    90. payload = {
    91. "language": "zh_CN",
    92. "input": {
    93. "customerId": 1,
    94. "orderSourceType": 70,
    95. "orderSourceId": order_source_id
    96. }
    97. }
    98. # 发送请求获取通token
    99. response = requests.post("xxx", json=payload, headers={"Authorization": authorization})
    100. if response.ok:
    101. json_data = response.json()
    102. data = json_data.get('data', {})
    103. ACCESS_TOKEN = data.get('userTokenSecretAccessKey', '')
    104. print(ACCESS_TOKEN)
    105. headers = {'Authorization': f'Bearer {ACCESS_TOKEN}'}
    106. # 计数器加一
    107. count += 1
    108. # 如果计数器达到了 5,则暂停 3 秒
    109. if count == 3:
    110. time.sleep(pause_time)
    111. count = 0
    112. #调用目标接口
    113. response_target = requests.get(url_template, headers=headers)
    114. if response_target.ok:
    115. # 处理返回结果
    116. response_data = response_target.json()
    117. print(response_data)
    118. # 判断是否满足条件
    119. if not response_data['status']['sell']['allow']:
    120. order_source_name = get_order_source_name(order_source_id) # 根据order_source_id获取对应的order_source_name
    121. # 将店铺名称添加到列表中
    122. order_source_names.append(order_source_name)
    123. else:
    124. print(f"由于token失效原因 failed {response_target.status_code}: {response_target.reason}")
    125. time.sleep(3)
    126. #调用目标接口
    127. response_target = requests.get(url_template, headers=headers)
    128. if response_target.ok:
    129. # 处理返回结果
    130. response_data = response_target.json()
    131. print(response_data)
    132. # 判断是否满足条件
    133. if not response_data['status']['sell']['allow']:
    134. order_source_name = get_order_source_name(order_source_id) # 根据order_source_id获取对应的order_source_name
    135. # 将店铺名称添加到列表中
    136. order_source_names.append(order_source_name)
    137. else:
    138. print(f"由于其它原因 failed {response.status_code}: {response.reason}")
    139. # 关闭数据库连接
    140. conn.close()
    141. shop_count = len(order_source_names)
    142. msg1 = f"今天有{shop_count}家 KYC 店铺,分别是:\n"
    143. msg1 += "\n".join([f" {order_source_name}" for order_source_name in order_source_names])
    144. secret1 = 'xxx'
    145. send_dingding_message1(msg1,secret1)
    146. # 读取Excel文件
    147. df = pd.read_excel(new_filename)
    148. # 获取"账号全程"列中与被KYC店铺列表相同的行索引
    149. shop_rows = df[df['账号全称'].isin(order_source_names)].index
    150. # 修改对应行的"站点状态"列的值为"KYC"
    151. df.loc[shop_rows, '站点状态'] = 'KYC'
    152. # 保存修改后的Excel文件
    153. df.to_excel(new_filename, index=False)
    1. 导入所需的库,包括os、pyodbc、requests、openpyxl等。
    2. 定义一个名为SecretRobot的类,用于发送钉钉消息。其中包含了签名算法的实现。
    3. 定义一个函数send_dingding_message1,用于发送钉钉消息。该函数创建了一个SecretRobot对象,并调用其send方法发送消息。
    4. 定义一个函数get_order_source_name,用于从数据库中获取订单来源名称。
    5. 初始化计数器和暂停时间。
    6. 将数据库连接信息和授权信息存储在变量中。
    7. 连接数据库并执行查询语句,获取订单来源信息。
    8. 遍历获取的数据行,对每个订单来源进行验证操作。
    9. 根据订单来源信息构建接口入参,并发送请求获取令牌。
    10. 判断请求是否成功,如果成功则处理返回结果。
    11. 判断是否满足条件,如果不满足则获取订单来源名称并添加到列表中。
    12. 如果请求失败,则等待一段时间后重新发送请求。
    13. 遍历完所有订单来源信息后,关闭数据库连接。
    14. 统计满足条件的KYC店铺数量,并生成钉钉消息内容。
    15. 发送钉钉消息通知相关人员。
    16. 读取Excel文件。
    17. 获取与KYC店铺列表相匹配的行索引。
    18. 修改对应行的"站点状态"列的值为"KYC"。
    19. 保存修改后的Excel文件。
  • 相关阅读:
    python模块下载
    Python大数据之PySpark
    Comparison method violates its general contract解决办法
    Java OA系统任务协作模块
    升级 Xcode 15模拟器 iOS 17.0 Simulator(21A328) 下载失败
    OpenCL编程指南-11.1OpenCL嵌入式简档
    微服务架构笔记
    Java 实例:删除字符串中的一个字符和字符串替换
    【C语言】数据类型之结构体
    国产5G手机的影响在扩大,美芯面临阴霾,两家美企被抛售
  • 原文地址:https://blog.csdn.net/EaSoNgo111/article/details/133067034