2016-08-02 43 views
0

我正在尝试在Python中编写一个Web服务(相当新)。我有存取权限想要在一个特定格式的URL的API:循环遍历文件并执行api请求

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

它不是为执行GET请求一个接一个的问题,但我想这样做的一个批次。所以我有一个包含字符串的文本文件。例如:

string1, 
string2, 
string3, 

我想编写一个Python脚本,通过该文件迭代,使得它在特定的格式,执行请求,并写入到一个新的文本文件的批处理的响应。我已经阅读了请求的文档,它提到给你的url添加参数,但是它并没有以我需要的这个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() 
+0

在什么格式,你想要什么? – Jeril

回答

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() 
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...) 

这是你想要的吗?

+0

谢谢你的帮助,它引导我走向答案! – Donald