You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Python循环读取CSV每行客户名并调用对应API处理

改造后完整代码
import json
import getpass
import csv
import requests
import warnings
from requests.auth import HTTPBasicAuth

# 关闭verify=False带来的不安全请求警告
warnings.filterwarnings("ignore", message="Unverified HTTPS request")

# 账号密码仅输入一次,放在循环外部
username = input("Enter GTAX username: ")
password = getpass.getpass('Enter GTAX Password: ')

# 替换为你的CSV文件实际路径
csv_path = "clients.csv"

# 遍历CSV每一行读取client
with open(csv_path, 'r', encoding='utf-8', newline='') as f:
    reader = csv.reader(f)
    # 如果CSV第一行是表头(比如列名为client),取消下面一行的注释跳过表头
    # next(reader)
    for row in reader:
        # 跳过空行,去除首尾空白字符
        if not row:
            continue
        client = row[0].strip()
        if not client:
            continue

        try:
            # 查询client ID逻辑
            query = {'name': client}
            response_API = requests.get(
                'https://example.com/api/v1/clients',
                auth=HTTPBasicAuth(username, password),
                timeout=10,
                params=query
            )
            response_API.raise_for_status() # 请求状态码非200时直接抛出异常
            parse_json = response_API.json() # 直接用requests内置的json解析更方便

            if not parse_json.get('data'):
                print(f"客户【{client}】未查询到匹配ID,跳过")
                continue
            client_id = parse_json['data'][0]['id']

            # 更新属性逻辑
            properties = {
                "qualifier": {
                    "value": "qualify",
                    "required": True,
                    "active": True
                },
                "presi": {
                    "value": True,
                    "required": True,
                    "active": True
                },
                "pool": {
                    "value": "VM",
                    "required": False,
                    "active": True
                }
            }
            putproperties = requests.put(
                f'https://example.com/api/v1/clients/{client_id}/properties/user',
                auth=HTTPBasicAuth(username, password),
                timeout=10,
                verify=False,
                data=json.dumps(properties)
            )
            print(f"客户【{client}】处理完成,状态码:{putproperties.status_code}")
        except requests.exceptions.RequestException as e:
            print(f"客户【{client}】请求失败,错误信息:{str(e)}")
        except Exception as e:
            print(f"客户【{client}】处理异常,错误信息:{str(e)}")
关键修改说明
  • 账号密码输入逻辑放在循环外部,无需每次循环重复输入
  • 调用csv.reader逐行读取CSV文件内容,每行第一个单元格的值作为client参数,若CSV文件带表头,取消代码中next(reader)的注释即可跳过表头行
  • 新增异常捕获逻辑,单个客户处理失败不会中断整个循环,同时打印错误信息方便定位问题
  • 新增空行、空白值判断逻辑,自动跳过CSV中的无效行
  • 替换原手动json.loads解析响应为requests内置的response.json()方法,代码更简洁
  • 注意将代码中csv_path的值替换为你本地CSV文件的实际路径

内容的提问来源于stack exchange,提问作者Alex Hoopes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 14:39:04