Python- Pass control flow back to top of the script - python

I am trying to fetch the contents of a page using Requests.The URL has 3 parameters:
Unique page ID
Username
Password
My initial block of code looks like this :
import requests
id = raw_input("Enter the unique id:")
user = raw_input("Enter your username:")
password = raw_input("Enter corresponding password:")
try:
r = requests.get('http://test.com/request.pl?id=' + id, auth=(user, password))
if r.status_code == 404:
print "No such page exists.Please check the ID and try again"
## Ask for input again
else:
print r.text
except requests.ConnectionError:
print "Server is refusing connections.Please try after sometime"
sys.exit(1)
My issue is on the commented line wherein i want the user to be prompted for the input again.How do I pass the control flow back to the top of the script.
I have a vague feeling that I might be doing this in a very crude way and there might be more elegant solutions using functions.If there are any,please do enlighten me.

This will do what actually you want.
import requests
def user_input():
id1 = raw_input("Enter the unique id:")
user = raw_input("Enter your username:")
password = raw_input("Enter corresponding password:")
try:
r = requests.get('http://test.com/request.pl?id='+ id1 + user + password)
if r.status_code == 404:
print "No such page exists.Please check the ID and try again"
## Ask for input again
user_input()
else:
print r.text
except requests.ConnectionError:
print "Server is refusing connections.Please try after sometime"
sys.exit(1)
user_input()

The simplest (but not necessarily the most extensible) way is to put everything in a while True loop.
import requests
while True:
id = raw_input("Enter the unique id:")
user = raw_input("Enter your username:")
password = raw_input("Enter corresponding password:")
try:
r = requests.get('http://test.com/request.pl?id=' + id, auth=(user, password))
if r.status_code == 404:
print "No such page exists.Please check the ID and try again"
## control flow will reach the bottom and return to the top
else:
print r.text
break
except requests.ConnectionError:
print "Server is refusing connections.Please try after sometime"
sys.exit(1) ## Exit condition of the loop

I would place this code in a while loop that always executes while True: and have a flag that allows you to break out of the loop appropriately.

Related

Why am I getting this error? (KeyError: 'username')

I'm asking the user for an email, and then sending it to an email verification api, which I then get certain bits of info from. I'm getting a KeyError: 'username' and I have no idea why I'm getting that error. It's also annoying to test since they ratelimit after ~5 attempts
import json, requests, sys
emailInput = ""
def printHelp():
print("Proper usage is: python test.py [email]")
if len(sys.argv) < 2:
printHelp()
sys.exit()
elif len(sys.argv) == 2 and sys.argv[1] == "--help":
printHelp()
sys.exit()
elif len(sys.argv) == 2 and sys.argv[1] != "--help":
emailInput = str(sys.argv[1])
url = 'https://api.trumail.io/v2/lookups/json?email=' + str(emailInput)
res = requests.get(url)
res.raise_for_status()
resultText = res.text
emailInfo = json.loads(resultText)
print("\nEmail Analyzer 1.0\n\nInformation for email: " + sys.argv[1])
print("=====================================================")
print("Username: " + str(emailInfo["username"]))
print("Domain: " + str(emailInfo["domain"]))
print("Valid Format: " + str(emailInfo["validFormat"]))
print("Deliverable: " + str(emailInfo["deliverable"]))
print("Full Inbox: " + str(emailInfo["fullInbox"]))
print("Host Exists: " + str(emailInfo["hostExists"]))
print("Catch All: " + str(emailInfo["catchAll"]))
print("Disposable: " + str(emailInfo["disposable"]))
print("Free: " + str(emailInfo["free"]))
The reason is because a user enters an email that might seem valid - i.e. it's a valid email address with an # symbol etc. - but the email likely does not exist or is not in use.
For example, I ran your script with the following dummy input:
emailInput = 'acdefg#gmail.com'
After I added a print(emailInfo) statement for debugging purposes, this is what I found to be the output from the server:
{'Message': 'No response received from mail server'}
Therefore, your goal here will be to validate the server output. That is, in the case of a valid email that does not exist, you will receive an HTTP 200 (OK) response from the server with a Message field alone populated in the JSON response object. The task here will be to correctly detect the presence of this key, and then run a separate logic other than the happy path, which was already being handled above.
Your error is coming from the fact that emailInfo does not have a key username. Perhaps use emailInfo.get("username", default_value), where default_value is any value you would like if there is no username.
The line with the error is print("Username: " + str(emailInfo["username"]))

Enter and Save username and password into same file

I want a user to be able to enter a new username and password and it saves it into the same file so it can be used for the login process that would come after. The user should be able to enter a new username into an input and the same for the password then it is saved to the file to be used later. I would do this myself but i don't know how to save it to the same file.
import time
import sys
uun = "test"
uun01 = "test01"
uun02 = "test02"
usernames = (uun+uun01+uun02)
upw = "test"
upw01 = "test01"
upw02 = "test02"
passwords = (upw+upw01+upw02)
max_attempts = 3
attempts = 0
while True:
print("Username")
username = input("")
print("Password")
password = input("")
if username in usernames and password in passwords:
print("Access Granted")
else:
attempts+=1
if attempts >= max_attempts:
print(f"reached max attempts of {attempts} ")
sys.exit()
print("Try Again (10 sec)")
time.sleep(10)
continue
break
First thing I do when deciding how to file data is think about how I want to access it later - this determines the data structure. A couple examples are, just straight key : value dictionary (username : password) to search by username or maybe entrytime : (username, password) to search by when the entry was made.
Once that is decided, format into a string and write to file. A simple print() of your data structure will show how it looks 'in the raw' and how you might want to format it for easy access later.

Error on Python Json.load: Extra data line 10 column 2 (char 194)

I am new to python and am working on a project that require appending json data to a file data.txt after which i need to iterate over the data and filter email and password.
Here is my code
import json
from main import *
from jobs import *
def registration():
''' Register a user.'''
print('''Welcome! \nRegister to get started \n''')
data = {} # Container that wil hold user details before writing to a file
fullname = input('Full name: ')
email = input('Email address: ')
phone_number = input('Phone number: ')
password = input('Password: ')
# append to users dictionary
data['users'] = []
data['users'].append({
'Fullname': fullname,
'Email': email,
'Phonenumber': phone_number,
'Password': password
})
# appending to a file
with open('data.txt', 'a') as users_file:
json.dump(data, users_file, indent=4)
login()
def login():
''' Check if a user has registered and login the user after authentication'''
print('''Don't have an account yet?\n 1. Create account\n 2. Continue to login ''')
user_response = input()
if user_response == '1':
return registration()
with open('data.txt') as users_file:
data = json.load(users_file)
Email = input("email: ")
Password =input("Password: ")
for foo in data['users']:
if foo["Email"] == Email and foo["Password"] == Password:
x = foo["Email"]
y = foo["Password"]
x == y is True
#Creates a login session for a staff and saves it to session.txt
print (f"Welcome! logged in as {Email}")
keyword_post = input('1. Search job by keyword\n 2. Register a job')
if keyword_post == '1':
return keywords()
return job_list()
else:
print('Invalid email or password.')
return login()
I am getting raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 10 column 2 (char 194) error message whenever more than one user registered. Please i need help on how to resolve this.
You need a comma between each entry. It also doesnt make sense to have the key "users" repeated. That should be your key, then within that key, your list of user parameters/info
Couple of other things:
I'm not sure what this is doing for you:
x = foo["Email"]
y = foo["Password"]
x == y is True
I took it out as x == y will always return False, so I'm not sure why store as x and y variables, and x == y is True just doesn't make sense.
Another thing to consider is emails (unlike passwords) are not case sensitive, so you need to anticipate that. so someone should not be able to register USER#email.com and user#email.com...it's the same email address. So store emails as either all upper or lower case.
I made a few minor changes as well, doesn't change the logic, but added a few prints (If wrong password, if email already exists, etc.) You can also continue to add some checks in there too using regex. So things like, email address needs to be in the form of xxxx#xxxxxxx.com So if it doesn't have the # or .com, .edu, dot whatever, it'll not accept the email address. Or phone number needs to follow a certain pattern. But that you can do later, if needed.
You also don't NEED to 'user' key in there (unless you'll be adding some other key into the json later??) I'm not sure as I don't know what your end is to look like or be used for. It doesn't hurt to have it there though, so not a big deal, but it just adds another level that may or may not be needed.
Try this:
import json
import os
from main import *
from jobs import *
def registration():
#### Register a user ####
print('Welcome!\nRegister to get started\n')
inputdata = {} # Container that will hold user details before writing to a file
fullname = input('Full name: ')
email = input('Email address: ').lower()
phone_number = input('Phone number: ')
password = input('Password: ')
# append to users dictionary
inputdata['users'] = {}
inputdata['users'][email] = {}
inputdata['users'][email].update({
'Fullname': fullname,
'Phonenumber': phone_number,
'Password': password
})
# appending to a file
if os.path.isfile('data.txt'):
with open('data.txt', 'r') as users_file:
dataFile = json.load(users_file)
# Check if email already exists
if email in dataFile['users'].keys():
print ('Can not register this email. Email already in use.')
return login()
dataFile['users'].update(inputdata['users'])
with open('data.txt', 'w') as users_file:
json.dump(dataFile, users_file, indent=4)
else:
with open('data.txt', 'w') as users_file:
json.dump(inputdata, users_file, indent=4)
login()
def login():
''' Check if a user has registered and login the user after authentication'''
print('''Don't have an account yet?\n 1. Create account\n 2. Continue to login ''')
user_response = input()
if user_response == '1':
return registration()
with open('data.txt') as users_file:
data = json.load(users_file)
Email = input("Email: ").lower()
Password =input("Password: ")
userEmailList = list(data['users'].keys())
if Email not in userEmailList:
print ('Email is not registered.')
return login()
fooPassword = data['users'][Email]['Password']
if fooPassword == Password:
x = Email
y = fooPassword
x == y is True
#Creates a login session for a staff and saves it to session.txt
print (f"Welcome! logged in as {Email}")
keyword_post = input('1. Search job by keyword\n2. Register a job')
if keyword_post == '1':
return keywords()
return job_list()
else:
print('Invalid password.')
return login()

Trying to make a simple login system using a dictionary in python

def getlogins():
from requests import get
url = "https://raw.githubusercontent.com/Ezb2661/lol/master/loginstest"
return get(url).text
logins = getlogins()
logins = logins[:-1]
username = input("Username:")
username = str(username)
password = input("Password: ")
password = str(password)
if password == logins[username]:
print("Logged in!")
else:
print("Wrong password or username")
Whenever I run this, it does prompt for username and password, but then it says there is an error on line 15 of :
TypeError: string indices must be integers
Fixed this by fixing my json format to {"ezb2661": "test"} rather than {"ezb2661:test"}, and then using
return loads( get(url).text )

Python Login Script; Usernames and Passwords in a separate file

I'm looking for assistance to get my Python script to imitate a log-in feature while the credentials are stored in a separate file.
I got it to work from hard-coded Username and Password, and it also reads in a file, but I'm having some difficulty finding out how to link the two together.
Any assistance is appreciated.
The Python script is as follows:
print "Login Script"
import getpass
CorrectUsername = "Test"
CorrectPassword = "TestPW"
loop = 'true'
while (loop == 'true'):
username = raw_input("Please enter your username: ")
if (username == CorrectUsername):
loop1 = 'true'
while (loop1 == 'true'):
password = getpass.getpass("Please enter your password: ")
if (password == CorrectPassword):
print "Logged in successfully as " + username
loop = 'false'
loop1 = 'false'
else:
print "Password incorrect!"
else:
print "Username incorrect!"
I found this somewhere else that helped me read the file in, and it does print the contents of the text file, but I am unsure on how to progress from this:
with open('Usernames.txt', 'r') as f:
data = f.readlines()
#print data
for line in data:
words = line.split()
The text file contains the Usernames and Passwords in a format of: Test:TestPW Chris:ChrisPW Admin:AdminPW with each credential on a new line.
As I said previously, any help is appreciated!
Thanks.
You could start having a dictionary of usernames and passwords:
credentials = {}
with open('Usernames.txt', 'r') as f:
for line in f:
user, pwd = line.strip().split(':')
credentials[user] = pwd
Then you have two easy tests:
username in credentials
will tell you if the username is in the credentials file (ie. if it's a key in the credentials dictionary)
And then:
credentials[username] == password
import hashlib ,os
resource_file = "passwords.txt"
def encode(username,password):
return "$%s::%s$"%(username,hashlib.sha1(password).hexdigest())
def add_user(username,password):
if os.path.exists(resource_file):
with open(resource_file) as f:
if "$%s::"%username in f.read():
raise Exception("user already exists")
with open(resource_file,"w") as f:
print >> f, encode(username,password)
return username
def check_login(username,password):
with open(resource_file) as f:
if encode(username,password) in f.read():
return username
def create_username():
try:
username = add_user(raw_input("enter username:"),raw_input("enter password:"))
print "Added User! %s"%username
except Exception as e:
print "Failed to add user %s! ... user already exists??"%username
def login():
if check_login(raw_input("enter username:"),raw_input("enter password:")):
print "Login Success!!"
else:
print "there was a problem logging in"
while True:
{'c':create_username,'l':login}.get(raw_input("(c)reate user\n(l)ogin\n------------\n>").lower(),login)()
You should not use 2 loops. It would just tell the person that they guessed the username. Just saying. use one loop.
also check my repl.it it page for a better sso that can have like 100 people at once without else if statements
Here it is: https://repl.it/#AmazingPurplez/CatSSO
Has errors. Was developed only by me so +rep to me.
rep to: Joran Beasley
Could not post code here because of "indention errors" like frick it! but I will still try a simpler version
import getpass
username = "username"
password = "password"
loop = True
while loop == True:
userinput = input("question")
passinput = getpass.getpass("question")
if userinput == username and passinput == password:
statements
break
else:
statements
username = raw_input("Username:")
password = raw_input("Password:")
if password == "CHANGE" and username == "CHANGE":
print "Logged in as CHANGE"
else:
print "Incorrect Password. Please try again."

Categories