【问题标题】:Python API Call IterationPython API 调用迭代
【发布时间】:2021-05-06 21:46:26
【问题描述】:

我正在使用 meraki api 创建一个 l7 防火墙批量更新 python 脚本,但遇到了问题。我需要脚本来遍历 .txt 文件中的每个行项目。 .txt 文件中的每个行项目都是一个网络 ID。目前,我设置代码的方式仅使用列表顶部的网络 ID 运行一次。我该如何解决这个问题?

import requests
import json
import os
from dotenv import load_dotenv

load_dotenv()
api_key = os.environ.get("API_Key")

with open('testnetids.txt') as file:
    for line in file:
        line = line.rstrip("\n")

url = "https://api.meraki.com/api/v0/networks/%s/l7FirewallRules" % line

with open("layer7rules.json") as f:
    payload = json.load(f)

headers = {
    'X-Cisco-Meraki-API-Key': api_key,
    'Content-Type': 'application/json',
}

response = requests.put(url, data=json.dumps(payload), headers=headers)

print(response.text)

【问题讨论】:

    标签: python json python-requests meraki-api


    【解决方案1】:

    为了对文件中的每一行进行一些处理,您需要将实际处理移入while循环:

    import requests
    import json
    import os
    from dotenv import load_dotenv
    
    load_dotenv()
    api_key = os.environ.get("API_Key")
    
    with open('testnetids.txt') as file:
        for line in file:
            line = line.rstrip("\n")
    
            url = "https://api.meraki.com/api/v0/networks/%s/l7FirewallRules" % line
    
            with open("layer7rules.json") as f:
                payload = json.load(f)
    
                headers = {
                    'X-Cisco-Meraki-API-Key': api_key,
                    'Content-Type': 'application/json',
                }
    
                response = requests.put(url, data=json.dumps(payload), headers=headers)
    
                print(response.text)
    

    【讨论】:

    • 感谢您的帮助!简单的格式问题!
    猜你喜欢
    • 1970-01-01
    • 2011-03-21
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 2011-11-22
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    相关资源
    最近更新 更多