【问题标题】:How to effectively manage multiple URL responses in python 3?如何在 python 3 中有效地管理多个 URL 响应?
【发布时间】:2019-10-24 17:27:37
【问题描述】:

背景

我有一个针对一系列 URL 响应对象 (json) 运行分析的脚本。为此,我遍历包含 URL 的字典,然后动态创建文件名并将这些文件写入磁盘,在将文件打开到内存时执行分析。

我想消除脚本中的 IO 并将其推送给我的用户,他们可以使用 pandas 数据帧在 Jupyter 笔记本中自己运行它来进行表格展示/逻辑

这是我不确定如何修改的代码sn-p:

for key, value in url_dict.items():
    print("Issuing query for {}".format(key))
    json_response = s.get(value, verify=cert_authority)
    data = json_response.json()
    jsonfilename = 'query_' + key + '.json'
    jsonfile = os.path.join(query_output_directory, jsonfilename)
    with open(jsonfile, 'wb') as outfile:
        json.dump(data, outfile)

我想弄清楚的是如何将各种 json 响应对象通过管道传输到它们自己的变量中;例如,我需要 data1data2 等,而不仅仅是 data。感觉就像我需要动态变量,但我确信必须有一个不那么笨拙的解决方案。

【问题讨论】:

  • 为什么不追加到 json 响应列表中?
  • 天哪,这个推荐太简单了,我完全错过了。如果您想将示例折腾并作为答案提交,我将其标记为正确。
  • 哈哈,没问题!它一直在发生,通常是在早上第一杯咖啡之前。

标签: python-3.x pandas python-requests jupyter-notebook


【解决方案1】:

您可以在循环时将响应附加到列表中。

alljsonvariables=[]
for key, value in url_dict.items():
    print("Issuing query for {}".format(key))
    json_response = s.get(value, verify=cert_authority)
    alljsonvariables.append(json_response.json())
#the rest of your code goes here

【讨论】:

    猜你喜欢
    • 2010-10-04
    • 2019-12-22
    • 1970-01-01
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多