私は次のことを行うプログラムを作ろうとしています:
- auth_fileが存在するかどうかを確認します
- はいの場合->ファイルを読み取り、そのファイルのデータを使用してログインを試みます-データが間違っている場合->新しいデータを要求します
- いいえの場合->データを要求してから、ファイルを作成し、要求されたデータを入力します
ここのところ:
import json
import getpass
import os
import requests
filename = ".auth_data"
auth_file = os.path.realpath(filename)
url = 'http://example.com/api'
headers = {'content-type': 'application/json'}
def load_auth_file():
try:
f = open(auth_file, "r")
auth_data = f.read()
r = requests.get(url, auth=auth_data, headers=headers)
if r.reason == 'OK':
return auth_data
else:
print "Incorrect login..."
req_auth()
except IOError:
f = file(auth_file, "w")
f.write(req_auth())
f.close()
def req_auth():
user = str(raw_input('Username: '))
password = getpass.getpass('Password: ')
auth_data = (user, password)
r = requests.get(url, auth=auth_data, headers=headers)
if r.reason == 'OK':
return user, password
elif r.reason == "FORBIDDEN":
print "Incorrect login information..."
req_auth()
return False
私は次の問題を抱えています(正しい方法を理解して適用する):
- load_authファイルで読み取って使用できる形式でreq_auth()からauth_fileに返されたデータを保存する正しい方法が見つかりません
PS:もちろん、私はPythonの初心者であり、ここでいくつかの重要な要素を見逃していると確信しています:(