Ionut
Ionut

Reputation: 536

Python having problems writing/reading and testing in a correct format

I’m trying to make a program that will do the following:

So far:

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

I have the following problems(understanding and applying the correct way):

PS: Of course I'm a beginner in Python and I'm sure I have missed some key elements here :(

Upvotes: 0

Views: 107

Answers (2)

Anuj Gupta
Anuj Gupta

Reputation: 10526

To read and write data, you can use 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'}

A few improvements I'd suggest:

  1. Have a function that tests login (arguments: user,pwd) and returns True/False
  2. Save data inside req_data, because req_data is called only when you have incorrect/missing data
  3. Add an optional argument tries=0 to req_data, and test against it for a maximum number of tries

(1):

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

for (2), you can use json (as described above), csv, etc. Both of those are extremely easy, though json might make more sense since you're already using it.

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..."

Upvotes: 1

g.d.d.c
g.d.d.c

Reputation: 48028

There are a couple of things I would approach differently, but you're off to a good start.

Instead of trying to open the file initially I'd check for it's existence:

if not os.path.isfile(auth_file):

Next, when you're working with writing the output you should use context managers:

with open(auth_file, 'w') as fh:
    fh.write(data)

And finally, as a storage open (not terribly secure), it might work well to put the information you're saving in json format:

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

Upvotes: 0

Related Questions