CS50 Finance : Issue with code for Register - cs50

I am unable to execute Register. Everytime i try to Register, it moves me to Apology.html even when the credentials are correct. Can anyone please review below excerpt from my application.py and help me resolve this?
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("username"):
return apology("must provide username", 400)
# Ensure password was submitted
elif not request.form.get("password"):
return apology("must provide password", 400)
# Ensure password and confirmation match
elif not request.form.get("password") == request.form.get("confirmation"):
return apology("passwords do not match", 400)
# hash the password and insert a new user in the database
hash = generate_password_hash(request.form.get("password"))
new_user_id = db.execute("INSERT INTO users (username, hash) VALUES(:username, :hash)",
username=request.form.get("username"),
hash=hash)
# unique username constraint violated?
if not new_user_id:
return apology("username taken", 400)
# Remember which user has logged in
session["user_id"] = new_user_id
# Display a flash message
flash("Registered!")
# Redirect user to home page
return redirect(url_for("index"))
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("register.html")

It looks like your confirm password has a space in it. If a request is coming via HTML, this may be causing you trouble (as it will have to convert to HTML URL encoding, which is %20 for a space).
Try changing your HTML and your code to use a hyphen, or an underscore, or simply make it one word.
HTH

Hey I think that your code is meant to say
elif not request.form.get("password") **!=** request.form.get("confirmation"):
However currently it says
elif not request.form.get("password") **==** request.form.get("confirmation"):
Therefore even when it matches it is still returning an apology

Related

Django - How do I set default value to primary key

I have made custom User model with AbstractBaseUser.
and I'm trying to make the primary key of the class to start from certain numbers as new users sign up to the site.
Such as '2022001' - '2022002' - '2022003' and so on.
I have searched on stack overflow and other sources, and some people suggest define function within the custom user's class model, but i have failed to do that.
is there a simple way to generate auto_increment number starting with the custom number from models.py ?
or Is it possible for me to give that certain number in views.py as new users sign up?.
here is my register function. from views.py
def register_user(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
messages.success(request, ("You have successfully registered."))
return redirect('home')
else:
form = RegistrationForm()
return render(request, 'register/register_user.html', {'form' : form})
Thank you
user = authenticate(id=2022001 ,username=username, password=password)
if you want to modify your primary key this method may help.
try this.....
add following field to your model:
id = models.BigIntegerField(primary_key=True)
now you give it what ever value you'd like

When I try to get a quote for nflx my code tells me symbol does not exist. Below is my code. I can not find my error. Thoughts?

Here is the code to check symbol inputed correctly, then to show name, price and symbol on the quoted template.
#app.route("/quote", methods=["GET", "POST"])
#login_required
def quote():
"""Get stock quote."""
if request.method == "POST":
# Ensure ticker was submitted
if not request.form.get("symbol"):
return apology("must input stock symbol")
# Get symbol and make sure it exists
quote = lookup(request.form.get("symbol"))
if not quote:
return apology("symbol does not exist")
# to show company name, price, symbol
else:
return render_template("quoted.html", quote=quote)
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("quote.html")
IEX changed the API. You can find the new code for lookup function in helpers.py at this reddit post
No, lookup() is correct in helpers.py. And I could get a quote from CS50 answer. Is there some way to check if my token is correct? I can log on to my finance app, but can't get a quote.

How do I print back specific data from a list using user input?

In summary I'm trying to create a password manager. The Idea is that the program would ask the user input.
If user writes "new", the program asks input on the website, username and password and then store this data in a text file in the form of a List.
Now the main problem:
I want to be able to access selected data and have the program print said data from the text file to me.
For example:
I input into the program the website "google" along with username: "potato" and password: "potato"
After that, the program asks me what else I want to do. And if I write "access google", I want to program to give me back the website, username and password that are SPECIFIC to the google input.
This is necessary, as I will be adding several different inputs.
I have no idea how to do this and have no tutor. I hope someone can give a solution I can learn from.
Below you will find the base code I have come up with.
Keep in mind that I am a beginner. Thank you.
vault = open("Passvault.txt", "r+")
list = []
action = input("What do you want to do? ")
def tit():
global title
title = input("Add website: ")
return title
def user():
global username
username = input("Create username: ")
return username
def passw():
global password
password = input("Create password: ")
return password
running = True
while running:
creation = True
tit()
user()
passw()
if action == "new":
tit()
user()
passw()
#I added a class here hoping that i could create a class with an argument referencing the title
#so that when i type access "title" in the next if statement it would print back the data
#relevant to the selected title
class new(str(title)):
list.append(tit)
list.append(user)
list.append(passw)
vault.close()
if action == "access" + title:
creation = False
print(title)
print("Username: " + username)
print("Password: " + password)
vault.close()
Here is the code. This code stores the username, password, and website name in the txt file and also prints the username and password w.r.t website name.
import re # used to search patterns.
file_name = 'Passvault.txt'
while True:
action = input("What do you want to do? ")
if action == 'new':
title = input("Add website: ")
username = input("Create username:")
password = input('Create password')
#writing data into the file
with open (file_name,'a') as f:
data = f.write(f'{title} {username} {password}\n')
if 'access' in action:#if input contains access word
website = action.split()[1].strip() #storing website name which is written after access
#reading the data
with open(file_name,'r') as f:
data = f.read()
#searching for all username password related to website
username_pass = re.findall(f'{website}\s+(.*?)\n',data,re.S)#example google sachin 1234
print('Website: ',website)
print('Username, Password',username_pass)
I'm going to give you a more conceptual answer than code, because this is a more long term type of deal.
What you're going to want to do is use json files and dictionaries to store your data so you can search by keys (see the dictionaries link).
Once you've done that you're going to want to wrap everything in a while loop inside a def that gets user input like so:
def get_input():
permitted_actions = ['new', 'access', 'exit']
while True:
action = input("What do you want to do? Valid actions: new, access or type EXIT to end the program.").strip().lower()
if action not in permitted_actions:
print(f"{action} is not a valid action!")
elif action == 'new':
#call another function to do stuff here
elif action == 'access':
#call another function to do stuff here
elif action == 'exit':
print("Shutting down...")
break
I would highly recommend against creating your own actual vault for a password manager until you're much more experienced if you actually intend to use this, otherwise feed it fake passwords and whatnot and learn.
Now when you're adding website data you'll read your dictionary (see the dictionary link) and get the key associated with said website if it exists and then update the info that the user gives.
When you're accessing a website's data you just go to the dictionary (see the dictionary link) and grab the info relating to that website key if it exists.
Remember, you're going to be loading that dictionary from a json file (see the json link).
If you were to make this program an actual program someone would use you'd use a proper database of some sort (python3 has sqlite support natively) and use a database with encryption and master passwords.
I hope this points you in the right direction.
You can save the values as a dictionary with a list as the username and password then use literal_eval to convert the string dict into a dict and access the username and password as well as storing other websites with its own usernames and passwords.
website = 'google'
username,password = 'potato', 'potato'
filename = "yourfilehere"
with open(filename, w) as f:
f.write(str({website: [username,password]}))
#This will save your data as a string dictionary will the data above
#then read the file, get the dictionary and convert it then use its values
from ast import literal_eval
with open(filename, 'r') as f:
data = f.read()
data = literal_eval(data)
#Then search dictionary for website
found = data.get(website)
#Then if it was successful get the username and password
username = found[0]
password = found[1]
As long as you only have the dictionary created as a string in the file you are reading you can use this ethod to save as many website with the allocated username and password saved with it.
You can add a input() into the code to check which site the user wants the username and password for and then search for it in your dictionary.
search = input("Enter the website: ")
try:
found = data.get(search)
#add code here to get username and password
except:
print("failed to find a website matching: %s" % search")

Username and Password in Python 3.6

I am trying to make a Python script where users can create an account and log in. I need to save their account details (Name, DoB, etc.) so they can close the program and log in again next time.
#username:Password
account = {"Admin":["Pog"],"Hughes":["Hughes"], "E": ["Echo"], "C": ["Charlie"], "B": ["Bravo"], "D": ["Delta"], "A": ["Alpha"]}
#Check Credentials
name=input("Username: ") #Ask for name
if name in account: #Check name exists
print (account[name][0]) #Error test - print expected password
if passw==account[name][0]: #Check for password match
print("welcome,", name) #Welcome message
else:
print ("Failed Authentication") #Wrong Password
else:
print("Username Not Known") #Unknown Username
The above code works, I can authenticate users but how do I add new users/Passwords so that they will be added to the program?
I have been experimenting with writing/reading to/from txt files but without success. Is this the right approach?
Any help would be much appreciated!
Thanks
(I have tried searching but can't find what I'm looking for. How to create a python dictionary that will store the username and password for multiple accounts was close)
yep you will need to either use an external file as a constant storage or else use a database of some sort to store that data. Otherwise when you restart the script, it'll drop everything thats currently in memory (stored during the last script run)
I solved my problem using Pickle:
...
account = pickle.load(open("accounts.pkl","rb")) #Load Accounts file
#Check Credentials
name=input("Username: ") #Ask for name
if name in account: #Check name exists
print (account[name][0]) #Error test - print expected password
passw=input("Password: ") #Ask for Password
if passw==account[name][0]: #Check for password match
print("welcome,", name) #Welcome message
print("your Favourite Artist is: ",account[name][2])
menu(name,account)
else:
print ("Failed Authentication") #Wrong Password
users()
else:
print("Username Not Known") #Unknown Username
new_user(account)
Where the account details are stored like this:
{'Name': ['Password', 'Detail_1', 'Detail_2', 'Detail_3'],'Name2': ['Password', 'Detail_12', 'Detail_22', 'Detail_32']}

In this context, is there anyway I can use requests.post() without also using BeautifulSoup?

I've spent the day day and-a-half (I'm a beginner) trying to work out how to do something simple: Fill in an ID code and hit 'search'. I've read the requests docs and scoured stack overflow for examples, but none seem to help me.
What I want to do is run through a list of IDs that I have and check off which one's are valid and which are invalid. (This is for academic research)
Here's my code:
import requests
url = 'https://ndber.seai.ie/pass/ber/search.aspx'
payload = {'ctl00$DefaultContent$BERSearch$dfSearch$txtBERNumber':'100000000'
}
#the above dictionary key corresponds to the name , found using Firefox inspector in the source code.
#I have tried using input ID too with no difference in outcome
#enter in arbitrary number of '100000000'- expect to see 'Invalid ID Number' printed
r = requests.post(url, data = payload)
print(r.status_code, r.reason)
print(r.text)
if 'Number.'in r.text: #'Number' is an arbitrary word that happens to be in the page if a correct ID code is entered
print('Valid ID Number')
elif 'No results found.' in r.text: #as above, 'No results found' is in the page if an incorrect ID is entered
print('Invalid ID Number') #with the aboove number entered, I would expect this line to be printed
else:
print('Code Failure') #this line gets printed
I've tried to comment it as much as possible, so you can see what I'm at.
The output I get is Code Failure
The reason why BeautifulSoup comes into all this is because I asked for help on Reddit's excellent 'learn python' subreddit yesterday. A Redditor generously took the time to try to explain where I went wrong and what I should do differently. Here's what (s)he suggested I do:
enter image description here, which involves BS4.
So, is the Redditor right, or can this be done in a simple and 'light' way using the requests library?
Cheers!
Make sure to simulate exact same post with parameters, you can use firefox's firebug to see what parameters are beeing sent.
Below you can see the parameters, I've seen.
__EVENTARGUMENT=
__EVENTTARGET=
__EVENTVALIDATION=/wEdAAUFK13s0OHvBcOmXYSKCCYAA5nYY19nD30S2PPC/bgb6yltaY6CwJw6+g9S5X73j5ccPYOXbBJVHSWhVCIjHWYlwa4c5fa9Qdw0vorP2Y9f7xVxOMmbQICW5xMXXERtE7U18lHqXqDZVqJ8R/A9h66g
__SCROLLPOSITIONX=0
__SCROLLPOSITIONY=114
__VIEWSTATE=/wEPDwULLTE2MDEwODU4NjAPFgIeE1ZhbGlkYXRlUmVxdWVzdE1vZGUCARYCZg9kFgICAw9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earch$Bottomsearch=Search
ctl00$DefaultContent$BERSearch$dfSearch$txtBERNumber=2313131
ctl00$DefaultContent$BERSearch$dfSearch$txtMPRN=11111111111
And belowe code just worked,
from __future__ import unicode_literals
import requests
url = 'https://ndber.seai.ie/pass/ber/search.aspx'
payload = {'__EVENTVALIDATION':'/wEdAAUFK13s0OHvBcOmXYSKCCYAA5nYY19nD30S2PPC/bgb6yltaY6CwJw6+g9S5X73j5ccPYOXbBJVHSWhVCIjHWYlwa4c5fa9Qdw0vorP2Y9f7xVxOMmbQICW5xMXXERtE7U18lHqXqDZVqJ8R/A9h66g',
'__VIEWSTATE':'/wEPDwULLTE2MDEwODU4NjAPFgIeE1ZhbGlkYXRlUmVxdWVzdE1vZGUCARYCZg9kFgICAw9kFgICAw8WAh4FY2xhc3MFC21haW53cmFwcGVyFgQCBQ8PFgIeB1Zpc2libGVnZGQCCQ9kFgICAQ9kFgxmD2QWAgIBD2QWAgIBD2QWAmYPZBYCZg9kFgQCAQ8WAh4JaW5uZXJodG1sZWQCAw9kFgICAg9kFgJmD2QWBAIBD2QWAgIDDw8WCh4EXyFTQgKAAh4MRGVmYXVsdFdpZHRoHB4EVGV4dAUFY3RsMDAeB1Rvb2xUaXAFPlBsZWFzZSBlbnRlciBhIHZhbHVlLCB3aXRoIG5vIHNwZWNpYWwgY2hhcmFjdGVycywgd2l0aCBubyB0ZXh0HgVXaWR0aBxkZAIDD2QWAgIDDw8WCh8EAoACHwUcHwYFCTEwMDAwMDAwMB8HBT5QbGVhc2UgZW50ZXIgYSB2YWx1ZSwgd2l0aCBubyBzcGVjaWFsIGNoYXJhY3RlcnMsIHdpdGggbm8gdGV4dB8IHGRkAgQPFCsAAmQQFgAWABYAFgJmD2QWAgICD2QWAmYPPCsAEQIBEBYAFgAWAAwUKwAAZAIGDxYCHwJoFgQCAQ8WAh8CaGQCAw9kFgJmD2QWAmYPZBYCAgMPZBYCZg9kFgJmD2QWAgIBDxYCHwJoZAIIDxYCHwJoFgQCAQ8WAh8CaGQCAw9kFgJmD2QWAmYPZBYCAgMPZBYCZg9kFgJmD2QWAgIBDxYCHwJoZAIKDxYCHwJoFgQCAQ8WAh8CaGQCAw9kFgJmD2QWAmYPZBYCAgMPZBYCZg9kFgJmD2QWAgIBDxYCHwJoZAIMDxYCHwJoFgQCAQ8WAh8CaGQCAw9kFgJmD2QWAmYPZBYCAgMPZBYCZg9kFgJmD2QWAgIBDxYCHwJoZBgBBTNjdGwwMCREZWZhdWx0Q29udGVudCRCRVJTZWFyY2gkZ3JpZFJhdGluZ3MkZ3JpZHZpZXcPZ2QPHVcTs3MrN3SZqli/KiHgWASd1DRvCLPuS7Rs+GRQAQ==',
'__VIEWSTATEGENERATOR':'1F9CCB97',
'ctl00$DefaultContent$BERSearch$dfSearch$Bottomsearch':'Search',
'ctl00$DefaultContent$BERSearch$dfSearch$txtBERNumber':'2313131',
'ctl00$DefaultContent$BERSearch$dfSearch$txtMPRN':'11111111111'
}
session = requests.session()
r = requests.post(url, data=payload)
if 'Number.'in r.text: #'Number' is an arbitrary word that happens to be in the page if a correct ID code is entered
print('Valid ID Number')
elif 'No results found.' in r.text: #as above, 'No results found' is in the page if an incorrect ID is entered
print('Invalid ID Number') #with the aboove number entered, I would expect this line to be printed
else:
print('Code Failure') #this line gets printed"""
Just put your parameters in the payload dictionary, rest of the parameters can stay they I think
BER/DEC Number > ctl00$DefaultContent$BERSearch$dfSearch$txtBERNumber
MPRN > ctl00$DefaultContent$BERSearch$dfSearch$txtMPRN

Resources