C$50 Finance / register

C$50 Finance / register

December 14, 2019 4 By Kailee Schamberger


ZAMYLA CHAN: In register,
we’ll want to display a form to the user that allows them
to register and sign up for the site. We’ll want to check to see whether
the passwords that they’ve submitted are valid, and if so, we’ll
add that user to the database and log them in so that they can
start buying and selling their stocks. Let’s start by adding a template
for the registration process. And we can borrow from
login.HTML because the forms are going to look very similar,
but when you register we’ll want to add a password
confirmation field so that the user has to enter their password in one more
time to ensure that they haven’t made any typos as they’re typing it in. And all of this will be
submitted via post request, so check back into your
notes about get versus post and see that you can understand why. Now that we’ve completed the
register template as an HTML file, we can move to the register route in
the Python file of application.py. In our Python code, we’ll want to
manipulate and at very least access the information that
the user has submitted. In order to do this, we
use the very same name that we’ve specified
in the HTML template. In this case if the input name
of my box is quite simply “name,” then I reference that in Python
with a request.form.get name. So now that we can retrieve this we
want to make sure that all of the fields are filled in, so if any of
the fields are left blank then you’ll want to apologize by
returning apology with a relevant error message. Then we’ll also want to make sure
that the password and the confirmation match. Otherwise, you should apologize again. Finally if all of this is valid, then
you’ll want to protect their password a little bit, so we won’t actually
store the password that they typed in but rather a hash of that password
using this encrypt function that I’ve shown here. Once we’ve done that, let’s add the user
to our database so that they’re stored and can log in again. Usernames will be a unique field in
the database, as will be their user ID but what if the username
already exists in the database? then database execute will fail, so
you check for that failure as follows. So what’s the query that we
actually want to execute? Well the insert query will allow us
to insert into a particular table particular values. So here I’ve used placeholders for
the user name and for the hash. This is important to protect
against SQL injection attacks. Here I have the username
and the hash as placeholders and then I fill it in later on. After successfully adding
a user to the database, let’s log them in automatically
by storing their ID number within the session user ID. Now that they’ve registered,
they can start looking up stocks.