【发布时间】:2017-09-28 08:42:01
【问题描述】:
我正在尝试使用两种方法构建一个类:第一种方法是检查文件是否下载时没有错误,第二种方法是保存下载的文件。此代码按我的意愿工作,但它会下载文件两次。我想在第二种方法中使用第一种方法中的r变量,而无需再次下载文件。
发送电子邮件的功能很好用。
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)
所以第二种方法应该是这样的:
# 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)
但是,我得到这个错误:
AttributeError: 'checkGet_and_loads' 对象没有属性 'r'
我在 SO 和其他网站上尝试了所有解决方案,但没有弄明白...
【问题讨论】:
标签: json python-3.x class methods