Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python在以正确格式编写/读取和测试时遇到问题_Python - Fatal编程技术网

Python在以正确格式编写/读取和测试时遇到问题

Python在以正确格式编写/读取和测试时遇到问题,python,Python,我正在尝试制作一个程序,该程序将执行以下操作: 检查验证文件是否存在 如果是->读取文件并尝试使用该文件中的数据登录 -如果数据错误->请求新数据 如果否->请求一些数据,然后创建文件并用请求的数据填充它 到目前为止: import json import getpass import os import requests filename = ".auth_data" auth_file = os.path.realpath(filename) url = 'http://exampl

我正在尝试制作一个程序,该程序将执行以下操作:

  • 检查验证文件是否存在
    • 如果是->读取文件并尝试使用该文件中的数据登录 -如果数据错误->请求新数据
    • 如果否->请求一些数据,然后创建文件并用请求的数据填充它
到目前为止:

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
我有以下问题(理解和应用正确的方法):

  • 我找不到一种正确的方法来将从req_auth()返回的数据以一种可以在load_auth file中读取和使用的格式存储到auth_文件中

PS:当然我是Python的初学者,我肯定我错过了这里的一些关键元素:(

有几件事我会用不同的方法来处理,但是你已经有了一个好的开始

我不会一开始就试图打开该文件,而是检查它是否存在:

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())

要读取和写入数据,可以使用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'}

我建议进行一些改进:

  • 有一个测试登录名(参数:user,pwd)并返回True/False的函数
  • 将数据保存在req_数据中,因为只有在数据不正确/缺失时才会调用req_数据
  • 在req_数据中添加一个可选参数
    trys=0
    ,并根据该参数测试最大尝试次数
  • (1) :

    对于(2),您可以使用json(如上所述),等等。这两种方法都非常简单,尽管json可能更有意义,因为您已经在使用它了

    第(3)款:

    def req_auth(trys=0)#接受一个可选参数,表示尝试次数
    #您的现有代码在这里
    如果检查\u登录(用户、密码):
    #在此处保存数据
    其他:
    
    如果triestry/except在open()中是必需的,那么在Python的咒语之一是“与其请求许可,不如请求原谅”之前调用isfile()是没有意义的;首先检查存在性会违反这一点,并导致检查时间到使用时间错误。
    def check_login(user,pwd):
        r = requests.get(url, auth=(user, pwd), headers=headers)
        return r.reason == 'OK':
    
    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..."