2016-08-02 34 views
0

Ich versuche, einen Web-Service in Python zu schreiben (ziemlich neu dazu). Ich habe Zugang zu einer API, die eine URL in einem bestimmten Format will:Datei durchlaufen und eine API-Anfrage ausführen

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

Es ist kein Problem, eine GET-Anfrage nacheinander auszuführen, aber ich möchte es in einer Charge tun. Also habe ich eine Textdatei mit Strings drin. Zum Beispiel:

string1, 
string2, 
string3, 

Ich mag würde ein Python-Skript schreiben, die iteriert durch die Datei, es in dem spezifischen Format macht, führt die Anfragen und schreibt die Antworten der Charge in eine neue Textdatei. Ich habe die Dokumente der Anfragen gelesen und erwähnt, dass Sie Parameter zu Ihrer URL hinzugefügt haben, aber dies geschieht nicht in dem spezifischen Format, das ich für diese API benötige.

Mein Grund Code bisher ohne die Schleife sieht wie folgt aus:

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

In welchem ​​Format möchten Sie tun? – Jeril

Antwort

0

Ich habe um etwas mehr gespielt und das ist, was ich wollte:

#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

zuerst die Datei öffnen, die die Saiten hat,

import requests 

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

Dann durch die Liste iterieren,

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

Wolltest du das?

+0

Danke für Hilfe, es führte mich zur Antwort! – Donald