0

私は次のことを行うプログラムを作ろうとしています:

  • 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の初心者であり、ここでいくつかの重要な要素を見逃していると確信しています:(

4

2 に答える 2

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'}

私が提案するいくつかの改善:

  1. ログインをテストし(引数:user、pwd)、True/Falseを返す関数があります
  2. req_dataは、データが正しくない/欠落している場合にのみ呼び出されるため、req_data内にデータを保存します
  3. オプションの引数tries=0をreq_dataに追加し、それに対して最大試行回数をテストします

(1):

def check_login(user,pwd):
    r = requests.get(url, auth=(user, pwd), headers=headers)
    return r.reason == 'OK':

(2)の場合、json(上記のとおり)、csvなどを使用できます。どちらも非常に簡単ですが、jsonは既に使用しているので、より理にかなっている場合があります。

(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..."
于 2012-10-06T03:16:15.967 に答える
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())
于 2012-10-06T03:03:17.233 に答える