def create(): #this will print in the terminal since its a post request print (request.form['name']) print (request.form['type']) #when inserting/ adding into data base follow these steps: mysql = connectToMySQL("crpets") # connect to your db first! query = "INSERT INTO pets (name, type, created_at, updated_at) VALUES(%(name)s, %(type)s, NOW(), NOW())" data = { 'name': request.form['name'], 'type': request.form['type'] } #call on query_db mysql.query_db(query, data) return redirect("/")
def root(): #display information to client: #step one: connect to db mysql = connectToMySQL("crpets") #step two: make query query = "SELECT * FROM pets" #this query will return us a list of dictionaries # the variable "pets" will hold a list of dictionaries that we # can loop through to display all of our data pets = mysql.query_db(query) # now we can pass pets to the front end to display to user # pets in blue is referenced in our HTML! # pets in white comes from our server! return render_template("index.html", pets=pets)
def unique_email(email): # check from db if that email is already excist mysql = connectToMySQL('first_flask') # call the function, passing in the name of our db # select count(id) from friends where email like '[email protected]%'; notUnique = mysql.query_db( f"SELECT count(*) FROM friends where email like '{email}';") # {friend[0]['first_name'] print(notUnique[0]["count(*)"]) if notUnique[0]["count(*)"] > 0: print("your email is not unique", "%" * 50) return False else: print("your email is unique", "%" * 50) return True
def edit(): print (request.form ['full_name']) print (request.form ['email']) query = "UPDATE users SET full_name = %(name)s, email=%(email)s, updated_at=NOW() WHERE id=%(id)s" data = { 'name': request.form['full_name'], 'email': request.form['email'], 'id': request.form['id'] } mysql = connectToMySQL('users_assignment') mysql.query_db(query, data) return redirect('/users/'+data['id'])
def edit(): #first thing we want to do when first route # lets print the date to make sure we are getting the correct data print(request.form['name']) print(request.form['type']) print(request.form['id']) #update the table name then column and then value query = "UPDATE pets SET name=%(name)s, type=%(type)s, updated_at=NOW() WHERE id =%(id)s" data = { 'name': request.form['name'], 'type': request.form['type'], 'id': request.form['id'] } mysql = connectToMySQL('crpets') mysql.query_db(query,data) return redirect('/')
def login_validate(): mysql = connectToMySQL('got_db') query = "SELECT * FROM users WHERE email = %(email)s" data = {"email": request.form['email_login']} loggedin = mysql.query_db(query, data) # check = mysql.query_db(query,data) # if len(check)>0: #if the len of check is greater than 0: then it exist in db if loggedin: if bcrypt.check_password_hash(loggedin[0]['password'], request.form['log_in_pw']): print("bcrypt matched!") session['id'] = loggedin[0]['id'] return redirect('/success') else: flash('Invalid Credentials: Login denied!') return redirect('/') else: flash("Log In Failed. Log in Error.") return redirect('/')
def create(): is_valid = True #if email is left blank if request.form['email'] == " ": flash("Email cannot be left blank") is_valid = False elif not emailRegex.match(request.form['email']): flash("Invalid email address") else: email = request.form['email'] session['email'] = email query = "INSERT INTO emails (email, created_at, updated_at) VALUES ('{}', NOW(), NOW())".format(session['email']) print(query) mysql = connectToMySQL('email_validation') mysql.query_db(query) return redirect('results')
def edit_process(): is_valid = True if len(request.form['title']) < 3: is_valid = False flash("Title must be at least 3 or more characters long") if len(request.form['author']) < 3: is_valid = False flash("Author must be at least 3 or more characters long") if is_valid == False: return redirect('/edit/' + request.form['bookID']) else: mysql = connectToMySQL('fave_books') query = "UPDATE books SET title=%(title)s,author=%(author)s,updated_at=NOW() WHERE id =" + request.form[ 'bookID'] data = { 'title': request.form['title'], 'author': request.form['author'] } mysql.query_db(query, data) return redirect('/show')
def login_validate(): mysql = connectToMySQL('login_reg') query = "SELECT * FROM users WHERE email = %(email)s" data = {"email": request.form['email_login']} check = mysql.query_db(query, data) if len(check ) > 0: #if the len of check is greater than 0: then it exist in db # if check[0]['email'] == request.form['email_login'] if bcrypt.check_password_hash(check[0]['password'], request.form['log_in_pw']): session['id'] = check[0]['id'] return redirect('/success') else: flash('Invalid Credentials: Login denied') return redirect('/') else: flash('Invalid Credentials: Login denied') return redirect('/')
def validuser(): # check if this user does exist in db mysql = connectToMySQL('first_flask') # call the function, passing in the name of our db # select count(id) from friends where email like '[email protected]%'; query = "SELECT * FROM users where email = %(email)s;" data = {"email": request.form["email"]} result = mysql.query_db(query, data) print(result, "-" * 80) if len(result) > 0: if bcrypt.check_password_hash(result[0]['pass'], request.form['password']): # if we get True after checking the password, we may put the user id in session # its a valid user # setsession set_session(result[0]['id'], result[0]['first_name']) return redirect('/home') else: flash("You could not be logged in") return redirect("/login")
def login_validate(): mysql = connectToMySQL("handy_helper") query = "SELECT * FROM users WHERE email = %(email)s" data = {"email": request.form['email_login']} logged_in = mysql.query_db(query, data) if logged_in: if bcrypt.check_password_hash(logged_in[0]['password'], request.form['log_in_pw']): print('BCRYPT MATCHED!') session['userid'] = logged_in[0]['id'] return redirect('/dashboard') else: flash("Invalid Credentials. Login denied", "login_error") return redirect('') else: flash("Log In Failed. Log In Error", "login_error") return redirect('/')
def process(): print(request.form['name']) print(request.form['house']) print(request.form['sigil']) create_is_valid = True #need to validate if len(request.form['name']) < 3: flash("Name must be 3 or more characters!", 'gotName') create_is_valid = False if len(request.form['house']) < 3: flash("House must be 3 or more characters!", 'gotHouse') create_is_valid = False if len(request.form['sigil']) < 3: flash("Name must be 3 or more characters!", 'gotSigil') create_is_valid = False if not create_is_valid: return redirect('/show-create') mysql = connectToMySQL('got_db') query = "INSERT INTO characters (name, house, sigil, create_at, updated_at, user_id) VALUES (%(name)s, %(house)s,%(sigil)s, NOW(), NOW(),%(userid)s);" data = { 'name': request.form['name'], 'house': request.form['house'], 'sigil': request.form['sigil'], 'userid': session[ 'userid'] #when we need the logged in users id we get it in using session! } mysql.query_db(query, data) return redirect('/success')
def edit_process(): is_valid = True if len(request.form['job']) < 3: is_valid = False flash("Title must be at least 3 or more characters long", "job_error") if len(request.form['location']) < 3: is_valid = False flash("Author must be at least 3 or more characters long", "loc_error") if is_valid == False: return redirect('/edit/' + request.form['jobID']) else: mysql = connectToMySQL('handy_helper') query = "UPDATE jobs SET job=%(job)s,location=%(location)s,updated_at=NOW() WHERE id=%(id)s" data = { 'job': request.form['job'], 'location': request.form['location'], 'id': request.form['jobID'] } mysql.query_db(query, data) return redirect("/dashboard")
def remove(job_id): mysql = connectToMySQL('handy_helper') query = "DELETE FROM userjobs WHERE job_posted_id =" + job_id mysql.query_db(query) return redirect('/dashboard')
def show(id): mysql = connectToMySQL('survey') query = "SELECT * FROM users WHERE id=" + id users = mysql.query_db(query) return render_template('results.html', users=users)
def ShowOneJob(job_id): mysql = connectToMySQL('handy_helper') query = "SELECT * FROM jobs WHERE id=" + job_id job = mysql.query_db(query) return render_template("show.html", job=job)
def deleter(id): print(id) mysql = connectToMySQL("users_assignment") query = "DELETE FROM users WHERE id="+id mysql.query_db(query) return redirect('/users')
def showEdit(id): query = "SELECT * FROM users WHERE id="+id mysql = connectToMySQL('users_assignment') users = mysql.query_db(query) return render_template("edit.html", users = users[0])
def show_all(): mysql = connectToMySQL('users_assignment') users = mysql.query_db('SELECT * FROM users;') print(users) return render_template('showall.html', all_users = users)
def show_user(id): mysql = connectToMySQL('users_assignment') users = mysql.query_db("SELECT * FROM users WHERE ID="+id) print(users) return render_template("show.html", one_us = users)
def create(): mysql = connectToMySQL("got_db") if not EMAIL_REGEX.match(request.form['email']): flash("Invalid email address") is_valid = True # assume True ######## FIRST NAME VALIDATION ########## ############################################ if len(request.form['first_name']) < 3: is_valid = False # display validation error using flash flash("First Name must have 3 or more characters", "fchar_error") #check if first name contains a number def num_there(s): return any(i.isdigit() for i in s) if num_there(request.form['first_name']) == True: flash("First name cannot contain any numbers", "fnum_error") is_valid = False ######### LAST NAME VALIDATION ############# ############################################ if len(request.form['last_name']) < 1: is_valid = False # display validation error using flash flash("Invalid last name.") def numberPresent(s): return any(i.isdigit() for i in s) if numberPresent(request.form['last_name']) == True: flash("Last name cannot contain any numbers", "fnum_error") is_valid = False ############ EMAIL VALIDATION ############ ########################################## # if len(request.form['email']) <1: # flash("Email cannot be left blank.") # return redirect('/') if not EMAIL_REGEX.match(request.form['email']): flash( "Invalid email address. Please have email in proper email format.") return redirect('/') ######### Password Validation ########### ########################################## if len(request.form['password']) < 8: is_valid = False # display validation error using flash flash("Password needs to be 8 or more characters") if request.form['password'] != request.form['confirm']: is_valid = False flash("Passwords don't match") if not is_valid: return redirect("/") mysql = connectToMySQL("got_db") query = "SELECT * FROM users WHERE email =%(email)s" data = {"email": request.form['email']} result = mysql.query_db(query, data) if len(result) > 0: is_valid = False flash('username already exist') return redirect('/') else: pw_hash = bcrypt.generate_password_hash(request.form['password']) print(pw_hash) # prints something like b'$2b$12$sqjyok5RQccl9S6eFLhEPuaRaJCcH3Esl2RWLm/cimMIEnhnLb7iC' # be sure you set up your database so it can store password hashes this long (60 characters) mysql = connectToMySQL("got_db") query = "INSERT INTO users (first_name, last_name, email, password) VALUES (%(first_name)s, %(last_name)s, %(email)s, %(password_hash)s);" # put the pw_hash in our data dictionary, NOT the password the user provided data = { "first_name": request.form['first_name'], "last_name": request.form['last_name'], "email": request.form['email'], "password_hash": pw_hash, } id = mysql.query_db(query, data) session['id'] = id flash("You've been successfully added, you may now log in.") # never render on a post, always redirect! return redirect("/")
def delete(book_id): print(book_id) mysql = connectToMySQL('fave_books') #connect to mysql query = "Delete from books where id=" + book_id mysql.query_db(query) return redirect("/show")
def createUser(): # include some logic to validate user input before adding them to the database! # create the hash mysql = connectToMySQL("handy_helper") if not EMAIL_REGEX.match(request.form['email']): flash("Invalid email address", "reg_error") is_valid = True # assume True if len(request.form['first_name']) < 2: is_valid = False # display validation error using flash flash("Please enter first name", "reg_error") if len(request.form['last_name']) < 1: is_valid = False # display validation error using flash flash("Please enter last name.", "reg_error") if not EMAIL_REGEX.match(request.form['email']): flash( "Invalid email address. Please have email in proper email format.") return redirect('/') if len(request.form['password']) < 8: is_valid = False # display validation error using flash flash("Password needs to be 8 or more characters", "reg_error") if request.form['password'] != request.form['confirm']: is_valid = False flash("Passwords don't match", "reg_error") if not is_valid: return redirect("/") mysql = connectToMySQL("handy_helper") query = "SELECT * FROM users WHERE email =%(email)s" data = {"email": request.form['email']} result = mysql.query_db(query, data) if len(result) > 0: is_valid = False flash('username already exist') return redirect("/") else: pw_hash = bcrypt.generate_password_hash(request.form['password']) print(pw_hash) # prints something like b'$2b$12$sqjyok5RQccl9S6eFLhEPuaRaJCcH3Esl2RWLm/cimMIEnhnLb7iC' # be sure you set up your database so it can store password hashes this long (60 characters) mysql = connectToMySQL("handy_helper") query = "INSERT INTO users (first_name, last_name, email, password) VALUES (%(first_name)s, %(last_name)s, %(email)s, %(password_hash)s);" # put the pw_hash in our data dictionary, NOT the password the user provided data = { "first_name": request.form['first_name'], "last_name": request.form['last_name'], "email": request.form['email'], "password_hash": pw_hash, } id = mysql.query_db(query, data) session['userid'] = id flash("You've been successfully added, you may now log in", "success") # never render on a post route, always redirect! return redirect("/")
def index(): mysql = connectToMySQL('first_flask') # call the function, passing in the name of our db friends = mysql.query_db('SELECT * FROM friends;') # call the query_db function, pass in the query as a string print(friends) return render_template("index.html", friends = friends)
def showOneBook(book_id): mysql = connectToMySQL('fave_books') query = "SELECT * FROM books WHERE id=" + book_id book = mysql.query_db(query) return render_template("show.html", book=book)
from flask import Flask, render_template, redirect, request, session, flash # import the function connectToMySQL from the file mysqlconnection.py from myconnection import connectToMySQL from flask_bcrypt import Bcrypt app = Flask(__name__) app.secret_key = 'keep it secret' bcrypt = Bcrypt(app) import re EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') # invoke the connectToMySQL function and pass it the name of the database we're using # connectToMySQL returns an instance of MySQLConnection, which we will store in the variable 'mysql' mysql = connectToMySQL('login_registration') # now, we may invoke the query_db method # print("all the users", mysql.query_db("SELECT * FROM users;")) # ROOT ROUTE @app.route('/') def index(): return render_template('index.html') @app.route('/results') def results(): # CHECKS IF THERE IS A USER IS IN SESSION if 'userid' in session: id = session['userid'] # QUERIES FOR THE USER ID IN SESSION namequery = "SELECT first_name FROM users WHERE id = %(id)s" data = {'id': id}
from flask import Flask, render_template, redirect, request, flash, session import re from myconnection import connectToMySQL #add this email Regex emailRegex = re.compile(r'^[a-zA-Z0-9\.\+_-]+@[a-zA-Z0-9\._-]+\.[a-zA-Z]*$') app = Flask(__name__) app.secret_key = 'Secret Key' mysql = connectToMySQL('email_validation') ############## INDEX ############## @app.route('/') def index(): return render_template('index.html') ############# CREATE ######## @app.route('/create', methods=["POST"]) def create(): is_valid = True #if email is left blank if request.form['email'] == " ": flash("Email cannot be left blank") is_valid = False elif not emailRegex.match(request.form['email']): flash("Invalid email address")