Ich versuche, eine Klasse mit zwei Methoden zu erstellen: erste Methode, um zu überprüfen, ob die Datei ohne Fehler heruntergeladen wurde und die zweite Methode, um die heruntergeladene Datei zu speichern . Dieser Code funktioniert so, wie ich es möchte, aber er lädt die Datei zweimal herunter. Ich möchte die r
Variable von der ersten Methode in der zweiten Methode verwenden, ohne die Datei erneut herunterzuladen.Python 3. Verwenden Sie Variable von einer Methode in einer anderen Methode innerhalb der gleichen Klasse
Die Funktion zum Senden von E-Mails funktioniert gut.
from collections import OrderedDict
import requests
class checkGet_and_loads:
# check if the get is successfull or not
def get(self, url, file):
# download the file
self.r = requests.get(url)
# check if file was downloaded with no errors
if self.r.status_code != 200:
# send email to gmail
# emailBody = 'Sending email. Error with downloading the ' + file + ' file.'
# send_email(fromaddr = emailFrom, pwd = password, toaddr = emailTo, Subject = emailSubject, body = emailBody)
print('Error: Unexpected response {}'.format(self.r))
else:
print(' Not sending email. No errors found when downloading the ' + file + ' file.')
# loads the json file
def loads(self, url, file):
# download the file
self.r = requests.get(url)
# loads the json file
self.to_loads = json.loads(self.r.text, object_pairs_hook = OrderedDict)
return(self.to_loads)
# Check if test file is downloaded without errors. If errors found while downloading then send email; otherwise, don't email
# link for test file
url = 'http://mysafeinfo.com/api/data?list=englishmonarchs&format=json'
file = 'test'
checkGet_and_loads().get(url, file)
test_json = checkGet_and_loads().loads(url, file)
So ist die zweite Methode sollte wie folgt aussehen:
# loads the json file
def loads(self):
# loads the json file
to_loads = json.loads(self.r.text, object_pairs_hook = OrderedDict)
return(to_loads)
Aber ich bekomme diese Fehlermeldung:
AttributeError: 'checkGet_and_loads' object has no attribute 'r'
Ich habe versucht, alle Lösungen auf SO und anderen Websites und tat es nicht es herauszufinden ...
es funktioniert. Vielen Dank. ein wenig edit: es sollte sein 'test_json = data_source.loads()' anstelle von 'test_json = data_source.loads (url, datei)' – nick
@nick Sicher. Fest. – m0nhawk