Flask Tutorial Web Development with Python 16 - User Registration cont'd

sentdex · Beginner ·🛠️ AI Tools & Apps ·11y ago

Key Takeaways

This video tutorial covers user registration in Flask web development using Python, including password hashing with passlib and SQL injection prevention with mysequel.db. The tutorial demonstrates how to create a user registration system, check for existing usernames, and insert new users into the database.

Full Transcript

what is going on everybody welcome to part 16 of our practical flash tutorial uh series in this video what we're going to be doing is actually adding our registration form to our register page function here in the last video i did say that we were probably going to have a full registration process done in this video unlikely sorry i lied we've got to cover this adding it to our html page and password hashing all um all before we can actually do this so it's going to take a while but anyways let's jump in and see how far we can get so to our register page let me go ahead and make the font uh bigger because i made it small so i could read everything real quick before but now we're ready to continue along so uh we've got all this so far and then we'll come down here we'll leave the trine except we'll leave the connection um actually let's get rid of the connection we'll we'll come back to that in a little bit so first we want to try and the first thing we're going to say is form equals registration form and then in uh uh parentheses request dot form okay so that's just giving us this form that we're gonna inject into our page here in a minute uh so when we return the render template we're going to pass through this form variable into our html page and then we can actually render the form based on the information contained in our form variable so we'll still be passing passing it through but we won't actually be building the forum as we normally would have to but you'll see what i mean in a minute well in a few minutes okay so form equals that now if request dot method equals all caps post and form dot validate so what this is asking is first of all if the method is a post i.e they hit register you know the register button uh so they're making an attempt to make a registration and the form has been validated i.e we have two passwords filled in they match uh they have a you know a username field all that kind of stuff okay right they have to have a minimum of four a maximum of 20 so this also not only does that mean that the minimum is for the maximum is 20 it also means you have to have something in that field same thing with the email password it's required confirm is also required to match passwords so by uh the transitive property both of these are required and then this is also required so if request that method equals post and form in the form is validated we're ready to uh continue along so first we're going to say their username so the attempted username is going to be equal to what well it's going to be equal to form.usernameusername.data so form is in reference up here well it's reference to this which is in reference to this class so form dot username is this right here and then text field returns some information and dot data is going to be the data that the user put in so dot data will be whatever they fill into this username variable okay so that's username and then email is going to be form dot email dot data and then we have down here password now at no point uh besides when you cl just right when you collect that password they're going to have to you know send a password over but immediately before you start playing with any passwords using them or whatever your immediate reaction needs to be to um encrypt that password so password is going to be equal to um well we're not right we don't have it just yet but we'll have to grab that real quick but sha 256 underscore crypt dot encrypt encrypt uh and then we want to encrypt the uh basically altogether the string version of form dot password dot data so first we need sha 256 crypt and then we're also going to need um really probably one more thing but we'll get there so first let's go ahead and get shot 256 crypt so let me go here so back to our uh console here let's do pip install sha 256 underscore crypt um actually you know what hold on let me go yeah actually what we need is paslip pip install pass lib okay so we have paslib now what we want to do is go to the top of our init script here and we're going to go from passlib.hash import sha 256 underscore crypt so this is a big um just the it's pass lib which is a library for handling passwords you hash passwords and we're going to hash them with sha 256 also while we're up in our imports we're going to import one more thing and that's going to be from my sequel db import escape underscore string underscore oops escape string as and we're going to call it thwart and the reason why we're importing this and calling it thwart is escape string is going to escape any sort of uh sql injection type stuff so generally an sql exception is going to start with say i can't speak uh like an apostrophe basically uh and then they might do some stuff and then they're gonna start at you know injecting sql queries so the the way sql injection works just for really quick is when we actually run let's say an insert query you can run the insert query and then you could append more queries to the end like if you the programmer could do it that way so what people do when they do sql injection is they're going to say you know my username equals something seemingly legitimate and then they're going to close off the sql query and then they're going to add an sql query literally within the username field or the password field or the email field so you don't want people being able to do that so to get around that we can use escape string now that's not 100 uh perfect but it's pretty good so we do that and we also obviously need to hash the password so we've got those and now we're ready hold on my mouse is super sensitive anyway uh so we have that now ready to go back to our register page so coming on down the password equals this now i'm going to show you guys just what this does this is actually really cool um even if you don't really understand encryption that much uh this should be very impressive so probably in the next video i'll show that i'm just hoping to get through this register page but we'll see anyway c and then con equals uh connection which oops connection which is what we imported above from db connect and port connection now we're going to actually execute a query so we're going to say x for xq you actually don't have to assign anything to variables especially if you're just executing an insert the only thing you would have to assign to a variable is say a select query or something that would actually return something but i like to assign it to variables anyway so c dot execute so this is cursor.execute now we're going to execute a sql query and what we want to do is select all i i guess i actually misspoke there so we are actually selecting and what we're actually going to do here is we're checking the database to see if the username already exists otherwise you might wind up with users with the same username right you can't have that so select all from users so select everything from the table of users asterix asterisk means all where username equals and then we have some logic here or some variable basically and what this is just doing is where it equals some variable and then we do comma and then you put the variables in order of your percent s's so you'll see that later on you might have where username equals percent s and i don't know email equals percent s so you would put them in username email order in these parentheses but and also if you want to learn more about again sql queries i do have some mysql tutorials with python but you should learn quite a few here anyway and then again we want to thwart remember we imported uh this escape string as thwart because we're thwarting jerks so thwart and then what are we trying to thwart while we're thwarting um the username username let me make sure i did that right yeah okay and then that so just make sure that all clears out then we're gonna have an if statement if int x is greater than um zero we're going to say um we're going to flash and if x if int hold on that doesn't make any sense we'll have to check that in a second that's what that's what my code actually says but that's not quite quite what we want actually you would want i believe the length of x uh we'll have to check that out when i get through uh that's a pretty silly error if that's the case uh but if that's the case we're gonna flash that username is already taken please choose another x equals select all i just find it really hard to believe if the end of len of x i'm just not even gonna go with that it must be just a typo or something anyway that username is already taken please try another and then we will return render underscore template register.html and form equals form and we still need to make that register.html template as well so that's if this is greater than zero so basically if the length of rows because x is going to execute the select query and then the select query um basically is going to return in order or basically rows right each row of data so if the length of that of those rows is is greater than zero that means there's already that username in existence so that user can't have that username else we'll actually want to run an execution so else we would say c dot execute and we will insert insert into users and then here we put the columns so username password email and tracking so you insert into users and then these are the columns that we're going to insert and in the order that we will be inserting stuff so insert into users that information and then we're going to now have values and that's going to be what are we inserting and we have one two three four things so that's percent s uh comma percent s comma percent s comma and one more percent s and then that's basically the end of the query but now we throw in our actual variables here and the variables again is going to be a tuple for long in the order of username password email and tracking so what do we need to actually thwart again well that's anything the user input so username password and email those three need to be thwarted okay so we're gonna have uh the first one will be thwart uh username comma thwarts password comma thwarts email comma and then the tracking will just be our version of tracking but just in case we're stupid for some reason and we have tracking that actually corresponds to some sort of injection by mistake we'll thwart that as well you might as well and uh and for now the first bit of tracking that we throw in here is actually going to be introduction to python programming so again tracking is what are the topics the user has viewed so in our case as soon as someone registers this is the page that we're going to send them to so we're going to go ahead and say that they've done that tutorial so this page is like a landing page that just kind of explains how pythonprogramming.net works and it's a you know basic introduction to python as well so that's this page here so this would be the landing page that they're sent to on my site uh so it's got you know some information here some stuff on console how this page is working we've even got a little embedded console here what does python do what is a wrapper we check this stuff anyway it's a nice little introduction page so moving along uh so that's what we want to insert with our query and that's our whole query there and then anytime you are doing inserting into a database it's kind of like modifying a file right when you have a text file you might write in that text file but if you write in that text file and you pull the power plug to your computer is that text saved no if you're using maybe google drive or something it is but is that text generally saved no it's the same thing with database you you insert into that database but until you do the following con.commit it will not save to that database you'll actually have kind of like a little temporary kind of thing there and it won't actually save once we've committed we're gonna do we're gonna flash and the message that will flash to the user is just gonna be you know thanks for registering okay easy enough now the other thing that you'll want to do is c dot close and then um so that closes your cursor then we're going to run a conduct close and the idea here is that you're going to close your connection because sql or just database connections in general are going to take memory now we're going to have one more thing which we actually have not imported and that is gc and gc stands for garbage collector and then dot collect now sadly you've probably never needed this code in your life you've probably never seen it thought about it or anything python is pretty darn good at garbage collection by garbage collection we mean clearing out unused cached memory for the most part but for whatever reason when we make a web server with python and flask it suddenly does not just collect its garbage okay so i use gc.collect and that kind of helps us keep a rain in on uh the memory usage or the memory waste basically so now we need to go to the very very top and just import gc okay and that's just again garbage collector it's python and for whatever reason we it's useful i find that it's the connections to the database that causes the trouble so every time i have a connection to a database at right after closing i do gc.collect maybe it's not the best way the most elite way ever but it works so that's what i'll teach so anyway uh we've done that now we have a couple more things that we want to add i forgot about a session so we come to the very very top now let's go from flask import all this so we're going to import one more thing and that's going to be session and what this is is it's a good way to track your uh user session via cookies the other thing that you can have is g i don't really tend to use g but g has a lot of fancy stuff definitely look into it um i tend to do everything via just using session but g is pretty good it's good for tracking what your user is doing so anyway coming back down to our function here gc.collect after we've collected we want to do session and session is basically a dictionary so we're going to do session logged in equals true and you can actually add your own stuff to this dictionary so that's why i like session you can basically save anything to the session and the session again is like a cookie so you can save all kinds of neat information to this session uh and then so so session logged in equals true and then we're also going to set this user sessions username we want this username to equal whatever the username actually was at the time and then we are going to return the redirect redirect and then url underscore four and normally we would do the url for uh that intro.hi page but it doesn't exist so we're just for now we're just we'll return them to the dashboard until we have that intro page i'm not really probably in this tutorial i won't add it uh but maybe we will just for kicks or something but probably not so we do that uh otherwise uh outside of this elf else statement we have or outside of this else right here we have we still have this if way way up there uh and if that runs great we've done a lot of cool stuff otherwise really nothing has happened so we just want to let me make sure i get this right so we've got try if scrolling down okay if nothing else runs we'll just return render template and the template we want to render is register.html the parameter one of the variables rather that we want to pass through is going to be form and again we're using the scripting or the line by line nature of python to to basically uh we're using that as a form of logic here we run this if statement if this if statement runs we either render the template here or we're under the template here period otherwise we will pass along and we'll render this template okay so that's how we're kind of getting away with that and we also return the string e here if that happens to fail which is very messy returning straight up string e is a bad idea you should return something that looks a little better than that but hopefully you're not hitting that string e and eventually you would actually want to hide that error again we put them there for debugging purposes but once you're done debugging take those errors out because the only reason people should be seeing those errors if they're is if they're up to no good so you don't want to always leave those so uh that should be it for our register page we might have some typos here but we'll we'll end up finding them soon enough now i believe the only major thing left is to actually create the register html page so we'll probably do that in the next video and then we really will have a full uh registration process and then in the video after that i'm going to show you guys this password hashing because it's important that you understand what's going on there that way if you choose to do it your own way or something stupid like that you can understand how password hashing ought to work so anyways stay tuned for those two things as always if you have any questions or comments please feel free to leave them below i don't really expect too many other questions anyways because you won't really know if this works or not until the next video so anyway but if you do have questions or comments leave them below otherwise as always thanks for watching thanks for all the support and subscriptions until next time

Original Description

Welcome to part 16 of our Flask web development tutorial, in this video we discuss further how to create our user registration system. sample code: http://pythonprogramming.net http://seaofbtc.com http://sentdex.com http://hkinsley.com https://twitter.com/sentdex Bitcoin donations: 1GV7srgR4NJx4vrk7avCmmVQQrqmv87ty6
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from sentdex · sentdex · 0 of 60

← Previous Next →
1 Matplotlib Python Tutorial Part 1: Basics and your first Graph!
Matplotlib Python Tutorial Part 1: Basics and your first Graph!
sentdex
2 Python Encryption Tutorial with PyCrypto
Python Encryption Tutorial with PyCrypto
sentdex
3 Python's Logging Function
Python's Logging Function
sentdex
4 wxPython Tutorials 1: Making Windows GUIs with Python : Installing + 1st window!
wxPython Tutorials 1: Making Windows GUIs with Python : Installing + 1st window!
sentdex
5 wxPython Tutorials 2: Making Windows GUIs with Python: Customizing Window Parameters
wxPython Tutorials 2: Making Windows GUIs with Python: Customizing Window Parameters
sentdex
6 wxPython Programming Tutorial 3: Menu Bar and Menu Button
wxPython Programming Tutorial 3: Menu Bar and Menu Button
sentdex
7 wxPython Programming Tutorial 4: Panels
wxPython Programming Tutorial 4: Panels
sentdex
8 wxPython Programming Tutorial 5: User Input Saved To Variables
wxPython Programming Tutorial 5: User Input Saved To Variables
sentdex
9 wxPython Programming Tutorial 6: Multiple Choice Input
wxPython Programming Tutorial 6: Multiple Choice Input
sentdex
10 wxPython Programming Tutorial 7: Adding Static Text and Colors
wxPython Programming Tutorial 7: Adding Static Text and Colors
sentdex
11 wxPython Programming Tutorial 8: Custom Button Images
wxPython Programming Tutorial 8: Custom Button Images
sentdex
12 wxPython Programming Tutorial 9: Tool Bar Items and Sub Menus!
wxPython Programming Tutorial 9: Tool Bar Items and Sub Menus!
sentdex
13 Basic PHP Tutorial 13: Multi-dimensional Array
Basic PHP Tutorial 13: Multi-dimensional Array
sentdex
14 Basic PHP Tutorial 15: Functions and Global Variables
Basic PHP Tutorial 15: Functions and Global Variables
sentdex
15 Basic PHP Tutorial 12: Associative Array
Basic PHP Tutorial 12: Associative Array
sentdex
16 Basic PHP Tutorial 14: Foreach loop
Basic PHP Tutorial 14: Foreach loop
sentdex
17 Basic PHP Tutorial 16: Include and Require
Basic PHP Tutorial 16: Include and Require
sentdex
18 Basic PHP Tutorial 7: Assignment, comparison and Logical operators
Basic PHP Tutorial 7: Assignment, comparison and Logical operators
sentdex
19 Basic PHP Tutorial 4: Variables and Comments
Basic PHP Tutorial 4: Variables and Comments
sentdex
20 Basic PHP Tutorial 11: Arrays part 1, basic array
Basic PHP Tutorial 11: Arrays part 1, basic array
sentdex
21 Basic PHP Tutorial 6: If else and else if conditionals cont'd
Basic PHP Tutorial 6: If else and else if conditionals cont'd
sentdex
22 Basic PHP Tutorial 1: Intro to PHP
Basic PHP Tutorial 1: Intro to PHP
sentdex
23 Basic PHP Tutorial 3: HTML with PHP
Basic PHP Tutorial 3: HTML with PHP
sentdex
24 Basic PHP Tutorial 9: While Loop
Basic PHP Tutorial 9: While Loop
sentdex
25 Basic PHP Tutorial 10: Switch Statement
Basic PHP Tutorial 10: Switch Statement
sentdex
26 Basic PHP Tutorial 2: Print and Echo
Basic PHP Tutorial 2: Print and Echo
sentdex
27 Basic PHP Tutorial 5: If else and else if conditional statements
Basic PHP Tutorial 5: If else and else if conditional statements
sentdex
28 Basic PHP Tutorial 8: Arithmatic Operators: Doing math with php
Basic PHP Tutorial 8: Arithmatic Operators: Doing math with php
sentdex
29 Basic PHP Tutorial 17: User Input Form Example / String Manipulation
Basic PHP Tutorial 17: User Input Form Example / String Manipulation
sentdex
30 Basic PHP Tutorial 18: HTML Entities and forms cont'd
Basic PHP Tutorial 18: HTML Entities and forms cont'd
sentdex
31 Basic PHP Tutorial 19: Finding words in strings
Basic PHP Tutorial 19: Finding words in strings
sentdex
32 Basic PHP Programming Tutorial 20: Saving to a File / writing and appending
Basic PHP Programming Tutorial 20: Saving to a File / writing and appending
sentdex
33 Basic PHP Programming Tutorial 22: Hashing part 2: salting
Basic PHP Programming Tutorial 22: Hashing part 2: salting
sentdex
34 Basic PHP Programming Tutorial 23: Variables in Strings and tokenizing
Basic PHP Programming Tutorial 23: Variables in Strings and tokenizing
sentdex
35 Basic PHP Programming Tutorial 21: MD5 Hashing For Security
Basic PHP Programming Tutorial 21: MD5 Hashing For Security
sentdex
36 Basic PHP Programming Tutorial 24: String similarity
Basic PHP Programming Tutorial 24: String similarity
sentdex
37 Basic PHP Programming Tutorial 25: Time and Time stamps
Basic PHP Programming Tutorial 25: Time and Time stamps
sentdex
38 Basic PHP Programming Tutorial 26: Die and Exit
Basic PHP Programming Tutorial 26: Die and Exit
sentdex
39 Basic PHP Programming Tutorial 27: MySQL Databases Part 1
Basic PHP Programming Tutorial 27: MySQL Databases Part 1
sentdex
40 Basic PHP Programming Tutorial 28: MySQL Database Part 2: Reading From Database
Basic PHP Programming Tutorial 28: MySQL Database Part 2: Reading From Database
sentdex
41 Basic PHP Programming Tutorial 29: MySQL Database Part 3: Inputting Data
Basic PHP Programming Tutorial 29: MySQL Database Part 3: Inputting Data
sentdex
42 Basic PHP Programming Tutorial 30: MySQL database in Use
Basic PHP Programming Tutorial 30: MySQL database in Use
sentdex
43 Django Tutorial Web Development with Python Part 1: Installing Django
Django Tutorial Web Development with Python Part 1: Installing Django
sentdex
44 Python Tutorial: File Deletion and Folder Deletion / directory deletion
Python Tutorial: File Deletion and Folder Deletion / directory deletion
sentdex
45 Python Tutorial: How to Rename Files and Move Files with Python
Python Tutorial: How to Rename Files and Move Files with Python
sentdex
46 3D Graphs in Matplotlib for Python: Basic 3D Line
3D Graphs in Matplotlib for Python: Basic 3D Line
sentdex
47 3D Plotting in Matplotlib for Python: 3D Scatter Plot
3D Plotting in Matplotlib for Python: 3D Scatter Plot
sentdex
48 3D Charts in Matplotlib for Python: Multiple datasets scatter plot
3D Charts in Matplotlib for Python: Multiple datasets scatter plot
sentdex
49 Sikuli Tutorial 1: Visually programming in python!
Sikuli Tutorial 1: Visually programming in python!
sentdex
50 Sikuli Tutorial 2: Program visually in python!
Sikuli Tutorial 2: Program visually in python!
sentdex
51 Sikuli Tutorial 3: Program visually in python!
Sikuli Tutorial 3: Program visually in python!
sentdex
52 3D Bar Charts in Python and Matplotlib
3D Bar Charts in Python and Matplotlib
sentdex
53 3D Plane wire frame Graph Chart in Python
3D Plane wire frame Graph Chart in Python
sentdex
54 Raspberry Pi Part 1 Introduction
Raspberry Pi Part 1 Introduction
sentdex
55 Raspberry Pi Part 8: First Download and Update! (Firmware)
Raspberry Pi Part 8: First Download and Update! (Firmware)
sentdex
56 Raspberry Pi Part 10: How to set up a Linux Web Server on your Pi
Raspberry Pi Part 10: How to set up a Linux Web Server on your Pi
sentdex
57 Raspberry Pi Part 11: Remote Desktop
Raspberry Pi Part 11: Remote Desktop
sentdex
58 Twitter Analysis: How to rank a user's influence
Twitter Analysis: How to rank a user's influence
sentdex
59 GPIO Tutorial for Pi Part 2 - Programming the GPIO
GPIO Tutorial for Pi Part 2 - Programming the GPIO
sentdex
60 GPIO Tutorial for Raspberry Pi Part 1 - Setting up
GPIO Tutorial for Raspberry Pi Part 1 - Setting up
sentdex

This video tutorial covers user registration in Flask web development using Python. It demonstrates how to create a user registration system, check for existing usernames, and insert new users into the database. The tutorial also covers password hashing with passlib and SQL injection prevention with mysequel.db.

Key Takeaways
  1. Install passlib using pip install passlib
  2. Import sha256_crypt from passlib.hash
  3. Use escape_string from mysequel.db to thwart SQL injection
  4. Hash passwords with sha256_crypt
  5. Execute a SQL query to check if a username already exists in the database
  6. Check if username already exists in database
  7. Flash message saying username is already taken if it exists
  8. Insert new user into database with username, password, email, and tracking information
💡 Password hashing is crucial for secure user registration, and using a library like passlib can simplify the process.

Related AI Lessons

Up next
AI in Care - Katie Furey, Pairly.com
The Access Group
Watch →