我正在尝试制作一个能够执行以下操作的程序:
到目前为止:
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
我有以下问题(理解和应用正确的方法):
答案 0 :(得分:1)
要读取和写入数据,您可以使用json:
>>> with open('login.json','w') as f:
f.write(json.dumps({'user': 'abc', 'pass': '123'}))
>>> with open('login.json','r') as f:
data=json.loads(f.read())
>>> print data
{u'user': u'abc', u'pass': u'123'}
我建议的一些改进:
tries=0
,并针对最大尝试次数进行测试(1):
def check_login(user,pwd):
r = requests.get(url, auth=(user, pwd), headers=headers)
return r.reason == 'OK':
对于(2),你可以使用json(如上所述),csv等。这两个都非常容易,虽然json可能更有意义,因为你已经在使用它了。
for(3):
def req_auth(tries = 0) #accept an optional argument for no. of tries
#your existing code here
if check_login(user, password):
#Save data here
else:
if tries<3: #an exit condition and an error message:
req_auth(tries+1) #increment no. of tries on every failed attempt
else:
print "You have exceeded the number of failed attempts. Exiting..."
答案 1 :(得分:0)
我会采用不同的方式处理一些事情,但是你有一个良好的开端。
我没有尝试打开文件,而是检查它是否存在:
if not os.path.isfile(auth_file):
接下来,当您正在编写输出时,您应该使用上下文管理器:
with open(auth_file, 'w') as fh:
fh.write(data)
最后,作为一个存储打开(非常安全),将您保存的信息放在json
格式中可能会很好:
userdata = dict()
userdata['username'] = raw_input('Username: ')
userdata['password'] = getpass.getpass('Password: ')
# saving
with open(auth_file, 'w') as fho:
fho.write(josn.dumps(userdata))
# loading
with open(auth_file) as fhi:
userdata = json.loads(fhi.read())