import cs304dbi as dbi import pymysql import bcrypt def insert_user(conn, username, password): '''inserts given username & password into the userpass table.''' hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) curs = dbi.cursor(conn) try: curs.execute('''INSERT INTO userpass(username, hashed) VALUES(%s, %s)''', [username, hashed.decode('ascii')]) curs.execute('select last_insert_id()') row = curs.fetchone() return row[0] except pymysql.err.IntegrityError as err: details = err.args print('error',details) if details[0] == pymysql.constants.ER.DUP_ENTRY: print('duplicate key for username {}'.format(username)) else: print('some other error!') return err if __name__ == '__main__': conn = dbi.connect() for username in ['fred', 'george', 'fred']: print(username, insert_user(conn, username, 'secret'))