Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- db = MySQLdb.connect("localhost", "root", "7May1996", "login_sys")
- # Check if username is valid
- # @param username {String} - Username to be checked for existance
- # @returns {Boolean} - If there are multiple table records
- # with matching username then user exists and function returns TRUE, otherwise FALSE.
- def usernameExists(username)
- cursor = db.cursor()
- cursor.execute('SELECT COUNT(*) FROM users WHERE user_name = %s', (username,))
- username_match_count = cursor.fetchone()
- db.close()
- return username_match_count[0] > 0
- # Inserts user into a table
- # @param username {String} - Username
- # @param password {String} - Password
- def insertUser(username, password)
- cursor = db.cursor()
- cursor.execute('INSERT INTO users (user_name, user_password) VALUES ("%s", "%s")', (username, password))
- db.commit()
- db.close()
- # Getting an input value. Input can be anything and this needs to be validated
- # to suit a particular criteria. Unput must be 1 or 2.
- # Username and password can also be retrieved because they are both required down the line
- # for both options.
- user_choice = input("Test login system\noptions(press and enter)\n1. Login\n2. signup")
- input_username = input('Username: ')
- input_password = input('Password: ')
- # Everything inside a try ... except block
- try:
- # If choice is not 1 and not 2 then error out.
- # You could build a looping mechanism here for retries
- if user_choice != '1' or user_choice != '2':
- raise Exception('Invalid choice')
- # Since we know that choice is 1 or 2 and both require username validation
- # and database acces. We can preform this here
- username_exists = usernameExists(input_username)
- # If logging in the username must exist. If it doesn't then we error or do something else
- if user_choice == '1': # Login
- if !username_exists:
- raise Exception('Username does not exist')
- # Login Success
- # For signup we need to have a unique username. If it exists we can't use it.
- elif user_choice == '2': # Signup
- if username_exists:
- raise Exception('Username is already taken')
- # Login Success
- # We can also insert username with password
- insertUser(input_username, input_password)
- # All error handling for code under try can be preformed here
- except Exception as error:
- print(error.message)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement