2017-04-30 5 views
1

2つのメソッドでクラスを構築しようとしています:ファイルがエラーなしでダウンロードされたかどうかを確認する最初のメソッドと、 。このコードは私が望むように動作しますが、ファイルを2回ダウンロードします。 2番目の方法で最初のメソッドの変数rを使用し、ファイルをもう一度ダウンロードしないでください。python 3.一つのメソッドの変数を同じクラス内の別のメソッドで使う

電子メールを送信する機能はうまく動作します。

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) 

ので、第2の方法は、次のようになります。

# 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' object has no attribute 'r' 

私はSOと他のサイト上のすべてのソリューションを試してみましたが、ありませんでしたそれを把握してください...

答えて

1

一時オブジェクトを作成してから新しいオブジェクトを作成するため、

checkGet_and_loads().get(url, file) 
test_json = checkGet_and_loads().loads(url, file) 

それはこのようになります。そして、あなたは.loads機能でrequests.getを呼び出す必要はありません

data_source = checkGet_and_loads() 
data_source.get(url, file) 
test_json = data_source.loads() 

+0

を読むことをお勧めします。ありがとう。 ちょっとした編集: 'test_json = data_source.loads(url、file)'の代わりに 'test_json = data_source.loads()'にする必要があります。 – nick

+1

@nick一定。 – m0nhawk

1

私はあなたが必要とするものがはるかに簡単に達成できると思います。メソッドが2つしかなく、そのうちの1つが__init__のクラスがある場合は、functionにする必要があります。あなたの場合、initを持っていなくても。 statusが、その後200ではなく、場合

def load_file(url, filename): 
    response = r.get(url) 
    if response.status == 200: 
     with open(filename, 'w') as f: 
      json.dump(f, response.json(object_pairs_hook=OrderedDict)) 

あなたはraise CustomException()それをキャッチし、エラーを記録することができます。

私はまた、Pythonコードスタイル(PEP8)

関連する問題