循环文件并执行api请求

时间:2016-08-02 09:53:55

标签: python api loops batch-file for-loop

我正在尝试用Python编写一个Web服务(相当新的)。我有权访问需要特定格式网址的API:

http://api.company-x.com/api/publickey/string/0/json

逐个执行GET请求不是问题,但我想批量执行。所以我有一个包含字符串的文本文件。例如:

string1,
string2,
string3,

我想编写一个Python脚本,它遍历该文件,以特定格式生成,执行请求并将批处理的响应写入新的文本文件。我已经阅读了请求的文档,它提到了为您的网址添加参数,但它并没有按照此API所需的特定格式执行此操作。

到目前为止,没有循环的基本代码如下所示:

import requests
r = requests.get('http://api.company-x.com/api/publickey/string/0/json')

print(r.url)
data = r.text

text_file = open("file.txt", "w")
text_file.write(data)
text_file.close()

2 个答案:

答案 0 :(得分:0)

首先打开包含字符串的文件

import requests

with open(filename) as file:
    data = file.read()
split_data = data.split(',')

然后遍历列表,

for string in split_data:
    r = requests.get(string)
    (...your code...)

这是你想要的吗?

答案 1 :(得分:0)

我已经玩了更多,这就是我想要的:

#requests to talk easily with API's
import requests

#to use strip to remove spaces in textfiles.
import sys

#two variables to squeeze a string between these two so it will become a full uri
part1 = 'http://api.companyx.com/api/productkey/'
part2 = '/precision/format'

#open the outputfile before the for loop
text_file = open("uri.txt", "w")

#open the file which contains the strings
with open('strings.txt', 'r') as f:
for i in f:    
    uri = part1 + i.strip(' \n\t') + part2
    print uri
    text_file.write(uri)
    text_file.write("\n")

text_file.close()

#open a new file textfile for saving the responses from the api
text_file = open("responses.txt", "w")

#send every uri to the api and write the respsones to a textfile
with open('uri.txt', 'r') as f2:
   for i in f2:
     uri = i.strip(' \n\t')
     batch = requests.get(i)
     data = batch.text
     print data
     text_file.write(data)
     text_file.write('\n')

text_file.close()