salt = binascii.b2a_hex(os.urandom(15)) hashed_pw = md5.new(password + salt).hexdigest() if error == 0: insert_query = "INSERT INTO users (first_name,last_name, email, password,salt, created_at, updated_at) VALUES(:fn,:ln,:em,:hashed_pw,:salt,NOW(),NOW() );" data = { 'fn': first_name, 'ln': last_name, 'em': email, 'hashed_pw': hashed_pw, 'salt': salt } newid = mysql.query_db(insert_query, data) session['id'] = newid print "Print new id", newid return redirect('/wall') # if int(user) == 0: # flash('Unexpected error!!!!!!') # return redirect('/') # else: # session['first_name']= user['first_name'] # session['last_name']= user['last_name']
bcrypt = Bcrypt(app) app.secret_key = "TheAnswerToLifeTheUniverseAndEverything=42" db = MySQLConnector(app,'login_db') EMAIL_REGEX = re.compile(r'^[\w\.+_-]+@[\w\._-]+\.[\w]*$') queries = { 'create' : "INSERT INTO users (first_name, last_name, email, password, created_at, updated_at) VALUES (:first_name, :last_name, :email, :password, NOW(), NOW())", 'index' : "SELECT * FROM users", 'delete' : "DELETE FROM users WHERE id=:id", 'select_id' : "SELECT * FROM users WHERE id=:id", 'update' : "UPDATE users SET first_name = :first_name, last_name=:last_name, email=:email, updated_at=NOW() WHERE id=:id", 'select_email' : "SELECT id, password FROM users WHERE email=:email" } print db.query_db("SELECT * FROM users") # ROUTING @app.route('/') # '/' (GET) login/registration form def index(): if 'user' in session: return redirect('/welcome') return render_template('index.html') @app.route('/logout') def logout(): session.pop('user') return redirect('/')
from flask import Flask, render_template, flash, request, redirect from mysqlconnection import MySQLConnector import re app = Flask(__name__) app.secret_key = "secret" mysql = MySQLConnector(app, 'email') EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9\.\+_-]+@[a-zA-Z0-9\._-]+\.[a-zA-Z]*$') queries = { 'create' : 'INSERT INTO emails (email, created_at) VALUES (:email, NOW());', 'index' : "SELECT * FROM emails", 'delete' : "DELETE FROM emails WHERE id = :id" } print mysql.query_db("SELECT email FROM emails") @app.route('/', methods = ["GET", "POST"]) def index(): if request.method == "POST": if(validateEmail(request.form['email'])): query = queries['create'] data = { 'email' : request.form['email']} mysql.query_db(query, data) flash("Successfully created email record!") return redirect('/success') else: flash("Email is not valid!") return render_template('index.html') @app.route('/success', methods = ['GET'])
from flask import Flask from mysqlconnection import MySQLConnector app = Flask(__name__) mysql = MySQLConnector(app, 'users') query = "SELECT * FROM users" print(mysql.query_db(query, data)) app.run(debug=True)
from flask import Flask from mysqlconnection import MySQLConnector app = Flask(__name__) mysql = MySQLConnector(app, 'world') print mysql.query_db( "SELECT countries.region FROM countries WHERE countries.name LIKE '%key'")
from flask import Flask from mysqlconnection import MySQLConnector app = Flask(__name__) mysql = MySQLConnector(app, 'mydb') # An example of running sql query print mysql.query_db("SELECT * FROM users LIMIT 5") app.run(debug=True)
from flask import Flask from mysqlconnection import MySQLConnector app = Flask(__name__) mysql = MySQLConnector(app, 'twitter') print(mysql.query_db("SELECT * FROM users")) print(mysql.query_db("SELECT * FROM users WHEN ")) app.run(debug=True)
else: # raw data ok / check for email match query = "SELECT * FROM users WHERE email=:email_to_check" data = {'email_to_check':email} email_check = mysql.query_db(query, data) if (email_check): #found a match so don't add / check password print "==================== email already exists ==========================" return redirect('/thewall') else: #add new email/user print "==================insert==================" #list of dictionary pairs for sqlalchemy query = "INSERT INTO users (first_name, last_name, email, password, created_at, updated_at) VALUES (:first_name, :last_name, :email, :password, NOW(), NOW())" data = {'first_name': f_name, 'last_name': l_name, 'email': email, 'password': p_word} mysql.query_db(query, data) current_id = user.id session['user_id'] = mysql.query_db(users_query, users_data) return redirect('/thewall') # hashed_password = md5.new(password + salt).hexdigest() #encrypt password # #add the user # users_query = "INSERT INTO users VALUES (null, :first_name, :last_name, :email, :password, NOW(), NOW(), :salt)" # users_data = { # 'first_name': first_name, # 'last_name': last_name, # 'email': email, # 'password': hashed_password, # 'salt': salt # }
from flask import Flask, render_template, redirect, request, flash # import the Connector function from mysqlconnection import MySQLConnector app = Flask(__name__) app.secret_key = 'ThisIsSecret' # import datetime # connect and store the connection in "mysql" note that you pass the database name to the function mysql = MySQLConnector(app, 'makefriendsdb') # an example of running a query print mysql.query_db("SELECT * FROM makefriends") @app.route('/') def index(): return render_template('index.html') @app.route('/create_friends', methods=['POST']) def create_friend(): error = True first_name = request.form['first_name'] if len(request.form['first_name']) < 1: error = False flash('You need to fill out your first name') last_name = request.form['last_name'] if len(request.form['last_name']) < 1: error = False flash('You need to fill out your last name') occupation = request.form['occupation'] if len(request.form['occupation']) < 1: error = False
query = "DELETE FROM friends WHERE id = :id" data = {'id': friend_id} mysql.query_db(query, data) return redirect('/') app.run(debug=True) username = request.form['username'] email = request.form['email'] password = request.form['password'] salt = binascii.b2a_hex(os.urandom(15)) hashed_pw = md5.new(password + salt).hexdigest() insert_query = "INSERT INTO users (username, email, password, salt, created_at, updated_at) VALUES (:username, :email, :hashed_pw, :salt, NOW(), NOW())" query_data = { 'username': username, 'email': email, 'hashed_pw': hashed_pw, 'salt': salt} mysql.query_db(insert_query, query_data) email = request.form['email'] password = request.form['password'] user_query = "SELECT * FROM users WHERE users.email = :email LIMIT 1" query_data = {'email': email} user = mysql.query_db(user_query, query_data) if len(user) != 0: encrypted_password = md5.new(password + user[0]['salt']).hexdigest() if user[0]['password'] == encrypted_password: # this means we have a successful login! else: # invalid password! else: # invalid email!
from flask import Flask, render_template, redirect, request, flash # import the Connector function from mysqlconnection import MySQLConnector import datetime import time #possible delete later app = Flask(__name__) app.secret_key = 'KeepItSecretKeepItSafe' mysql = MySQLConnector(app, 'mydb') print mysql.query_db("SELECT * FROM logreg") @app.route('/') def index(): all_logreg = mysql.query_db("SELECT * FROM logreg") return render_template('index.html', logreg=all_logreg) @app.route('/process', methods=["POST"]) def registration(): username = request.form['username'] # check if password matches = re.match(validation check) first_name = request.form['first_name'] last_name = request.form['last_name'] password = request.form['password'] password_conf = request.form['password'] #danger here? # delare a success to be true if (len(request.form['first_name']) < 2 and ['first_name'].isalpha()): flash("First Name must be more than 2 characters long") return redirect('/')
import re app = Flask(__name__) app.secret_key = "somesecret" db = MySQLConnector(app,'friends_db') EMAIL_REGEX = re.compile(r'^[\w\.+_-]+@[\w\._-]+\.[\w]*$') queries = { 'create' : "INSERT INTO friends (first_name, last_name, email, created_at) VALUES (:first_name, :last_name, :email, NOW())", 'index' : "SELECT * FROM friends", 'delete' : "DELETE FROM friends WHERE id=:id", 'select' : "SELECT * FROM friends WHERE id=:id", 'update' : "UPDATE friends SET first_name = :first_name, last_name=:last_name, email=:email WHERE id=:id" } print db.query_db("SELECT * FROM friends") # ROUTING @app.route('/') #Show All Friends def index(): query = queries['index'] data = {} all_friends = db.query_db(query, data) return render_template('index.html', all_friends = all_friends) @app.route('/friends', methods=["POST"]) #Create A Friend def create(): if is_email_valid(request.form['email']): query = queries['create'] data = {
friends = mysql.query_db(query) # run query with query_db() return render_template('index.html', all_friends=friends) # pass data to our template @app.route('/friends', methods=['POST']) def create(): # Write query as a string. Notice how we have multiple values # we want to insert into our query. query = "INSERT INTO friends (first_name, last_name, occupation, created_at, updated_at) VALUES (:first_name, :last_name, :occupation, NOW(), NOW())" # We'll then create a dictionary of data from the POST data received. data = { 'first_name': request.form['first_name'], 'last_name': request.form['last_name'], 'occupation': request.form['occupation'] } # Run query, with dictionary values injected into the query. mysql.query_db(query, data) return redirect('/') @app.route('/friends/<friend_id>') def show(friend_id): # Write query to select specific user by id. At every point where # we want to insert data, we write ":" and variable name. query = "SELECT * FROM friends WHERE id = :specific_id" # Then define a dictionary with key that matches :variable_name in query. data = {'specific_id': friend_id} # Run query with inserted data. friends = mysql.query_db(query, data) # Friends should be a list with a single object, # so we pass the value at [0] to our template under alias one_friend. return render_template('index.html', one_friend=friends[0]) @app.route('/update_friend/<friend_id>', methods=['POST']) def update(friend_id):
} # Run query, with dictionary values injected into the query. mysql.query_db(query, data) return redirect('/') # Updating Records # Say we wanted to update a specific record, we could create another page and add a form that would submit to the following route. @app.route('/update_friend/<friend_id>', methods=['POST']) def update(friend_id): query = "UPDATE friends SET first_name = :first_name, last_name = :last_name, occupation = :occupation WHERE id = :id" data = { 'first_name': request.form['first_name'], 'last_name': request.form['last_name'], 'occupation': request.form['occupation'], 'id': friend_id } mysql.query_db(query, data) return redirect('/') # Deleting Records @app.route('/remove_friend/<friend_id>', methods=['POST']) def delete(friend_id): query = "DELETE FROM friends WHERE id = :id" data = {'id': friend_id} mysql.query_db(query, data) return redirect('/') app.run(debug=True)
from flask import Flask # import the Connector function from mysqlconnection import MySQLConnector app = Flask(__name__) # connect and store the connection in "mysql" note that you pass the database name to the function mysql = MySQLConnector(app, 'mydb') # an example of running a query print mysql.query_db("SELECT * FROM states") app.run(debug=True)
from flask import Flask # import the Connector function from mysqlconnection import MySQLConnector app = Flask(__name__) # connect and store the connection in "mysql" note that you pass the database name to the function mysql = MySQLConnector(app, 'mydb') # an example of running a query print "*"*8 print mysql.query_db("SELECT * FROM users") app.run(debug=True)
from flask import Flask from mysqlconnection import MySQLConnector app=Flask(__name__) mysql = MySQLConnector(app,'sakila') print(mysql.query_db("SELECT * FROM actor")) app.run(debug=True)
from flask import Flask, render_template, request, redirect, flash, session from mysqlconnection import MySQLConnector # import the Connector function from flask.ext.bcrypt import Bcrypt # import Bcrypt to hash password import re EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9\.\+_-]+@[a-zA-Z0-9\._-]+\.[a-zA-Z]*$') NAME_REGEX = re.compile(r'^[a-zA-Z ]+$') # Case insensitive "a" to "z" and "space" allowed PASSWORD_REGEX = re.compile(r'^([^0-9]*|[^A-Z]*)$') # number and upper case letter allowed app = Flask(__name__) bcrypt = Bcrypt(app) app.secret_key = 'KeepItSecretKeepItSafe' mysql = MySQLConnector(app, 'login') # connect and store the connection in "mysql" note that you pass the database name to the function print mysql.query_db("SELECT * FROM users") # an example of running a query # this will load a page that has 2 forms one for registration and login @app.route('/', methods=['GET']) def index(): error=1 # assume there could be register error by default return render_template('index.html', error=error) @app.route('/register', methods=['POST']) def register(): print "Got Post Info" error = 1 # assume there could be register error by default if len(request.form['first_name']) < 2 or not NAME_REGEX.match(request.form['first_name']): flash("Invalid First Name. (Letters only, at least 2 characters.)") elif len(request.form['last_name']) < 2 or not NAME_REGEX.match(request.form['last_name']): flash("Invalid Last Name. (Letters only, at least 2 characters.)") elif len(request.form['email']) < 1 or not EMAIL_REGEX.match(request.form['email']): flash("Invalid Email Address.") # check if email already exists which is required as unique value for users to log in elif mysql.query_db("SELECT * FROM users WHERE email = '"+request.form['email']+"'") != [] : flash("Account already exists with this email. Please choose different email to register.")
from flask import Flask # import the Connector function from mysqlconnection import MySQLConnector app = Flask(__name__) # connect and store the connection in "mysql"; note that you pass the database name to the function mysql = MySQLConnector(app, 'mydb') # an example of running a query print(mysql.query_db("SELECT * FROM clients")) app.run(debug=True)
from flask import Flask # import the Connector function from mysqlconnection import MySQLConnector app = Flask(__name__) # connect and store the connection in "mysql" note that you pass the database name to the function mysql = MySQLConnector(app, 'sakila') # an example of running a query query = 'SELECT city.city_id, city.city, customer.first_name, customer.last_name, customer.email, address.address' query += ' FROM city' query += ' LEFT JOIN address' query += ' ON city.city_id = address.city_id' query += ' LEFT JOIN customer' query += ' ON address.address_id = customer.address_id' query += ' WHERE city.city_id = 312;' print mysql.query_db(query) app.run(debug=True)
from flask import Flask # import the Connector function from mysqlconnection import MySQLConnector app = Flask(__name__) # connect and store the connection in "mysql"; note that you pass the database name to the function mysql = MySQLConnector(app, 'erd_demo') # an example of running a query print mysql.query_db("SELECT * FROM authors") app.run(debug=True)
from flask import Flask, render_template, redirect, session, flash, request from datetime import datetime from mysqlconnection import MySQLConnector import re from flask_bcrypt import Bcrypt app = Flask(__name__) app.secret_key = 'I<3Secrets' mysql = MySQLConnector(app, 'usersdb') bcrypt = Bcrypt(app) rightnow = datetime.now() EMAIL_REG = re.compile(r'^[a-zA-Z0-9.-_+]+@[a-zA-Z0-9.-_]+\.[a-zA-Z]*$') print mysql.query_db('SELECT * FROM usersdb.users') @app.route('/') def hello(): query_all = 'SELECT * FROM usersdb.users' all_users = mysql.query_db(query_all) return render_template('index.html', all_users=all_users) @app.route('/user', methods=['POST']) def addUser(): user_info = { 'fname': request.form["fname"], 'lname': request.form["lname"], 'email': request.form["email"],
from mysqlconnection import MySQLConnector import datetime import md5 # import os, binascii password = '******' hashed_password = md5.new(password).hexdigest() print hashed_password EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') app = Flask(__name__) app.secret_key = "ThisisSecret" mysql = MySQLConnector(app, 'mydb') print mysql.query_db("SELECT * FROM registers") @app.route('/', methods=['GET']) def index(): print mysql.query_db("SELECT * FROM registers") return render_template("index.html") @app.route('/process', methods=['POST']) def create_user(): print request.form['first_name'] print request.form['last_name'] print request.form['email'] print request.form['password'] print request.form['confirm_password']
# this is data where you assign the value in your server.py and then pass it to the html file as a parameter of render_template # (see JINJA section below) ## add session display data (if needed) # if you need to display session data, set some session data to a hardcoded number in your server.py method and then # display that session data in you html file using jinja, and make sure that works before adding more complicated session data # (see session section below) ## add database data (if needed) # add and configure mysqlconnection.py file # add mysql code for server.py file # Example from mysqlconnection import MySQLConnector app.secret_key = 'ThisIsSecret' mysql = MySQLConnector(app,'emailvaliddb') all_emails = mysql.query_db("SELECT * FROM emails") @app.route('/friends/<id>/edit') def edit(id): query = "SELECT * FROM friends WHERE id = :id" data = {'id': id} #the blue id here matches to the orange id passed in the parameter of the method friend_array = mysql.query_db(query, data) # be aware of what datatype is being returned - in this case it is an array if len(friend_array) == 0: friend = None else: friend = friend_array[0] return render_template('edit.html', friend = friend) # run a basic select SQL query and print out the result to your terminal to make sure everything is connected and working # run the specific select SQL query you need, and again check that the result is what you want through the terminal # display that data on your view page using JINJA and for loops as needed
elif not NAME_REGEX.match(request.form['lname']): flash("Last name can only contain letters!") elif len(request.form['occ'])< 1: flash("Occupation cannot be empty!") elif not NAME_REGEX.match(request.form['occ']): flash("Occupation can only contain letters!") else: valOK = True #Update the record if fields pass all validation. if (valOK): try: query = "UPDATE friends SET first_name = '" + request.form['fname'] +'", last_name='" + request.form['lname'] + "', occupation='" + request.form['occ'] + "' session['view'] = "success" flash("Successfully changed ID " + id) mysql.query_db(query) except Exception as e: session['view'] = "alert" flash("Unable to change your friend!") return redirect('/friends/' + id + '/edit') else: return redirect('/friends/' + id + '/edit') return redirect('/') # DELETE RECORD - *** IS WORKING! DO NOT TOUCH THIS *** @app.route('/friends/<id>/delete') def destroy(id): try: query = "DELETE FROM friends WHERE ID: :id" data = {'id': id}
from flask import Flask # import the Connector function from mysqlconnection import MySQLConnector app = Flask(__name__) # connect and store the connection in "mysql"; note that you pass the database name to the function mysql = MySQLConnector(app, 'mydb') # an example of running a query data = mysql.query_db("SELECT * FROM users") for x in range(0, len(data)): print data[x]['first_name'] + " " + data[x]['last_name'] app.run(debug=True)
if len(data['first_name'])<1 or len(data['last_name'])<1 or len(data['username'])<1 or len(data['password'])<8 or data['passowrd'] != data['confirm_password']: print "Wassuuuuuuuuuuuup!!!!///// Error!! Error!! Error!!, Try again :)" if not EMAIL_REGEX.match(data['username']): print "Invalid Character" value=mysql.query_db(query, data) return render_template('success.html') @app.route('/login_a', methods=[POST]) def login(): query= 'SELECT users.username,users.password FROM users' data = { 'username': request.form['username'], 'password': request.form['password'], } user=mysql.query_db(query, data)[0] if data['username']==user.username and data[password]==user.password: print "True" return render_template('success.html') app.run(debug=True)
email_l = len(email) if not EMAIL_REGEX.match(email) or email_l < 1: flash("Email is not valid!") return render_template("index.html", notValid=True, color="red", emails=emails) else: flash(email + " is a valid email address! The Prince of Nigeria thanks you!") query = "INSERT INTO emails (email, created_at) VALUES (:email, NOW())" data = { 'email': email, } mysql.query_db(query, data) query = "SELECT * FROM emails" emails = mysql.query_db(query) return render_template("index.html", Valid=True, color="green", emails=emails) print mysql.query_db("SELECT * FROM emails") app.run(debug=True) # run our server
print '2' return redirect('/success') @app.route('/success') def success(): print "blue" query = 'SELECT * FROM users' users = mysql.query_db(query) print "blick" return render_template('success.html', email=session['email'], all_users=users) @app.route('/remove', methods=['POST']) def delete(): users = mysql.query_db(query) query = "DELETE FROM users WHERE id = :id" data = {'id': users.id} mysql.query_db(query, data) return redirect('/success') @app.route("/remove/<id>", methods=["POST"]) def remove(id): query = "DELETE FROM users (id, email, created_at, updated_at) VALUES({}, :email, NOW(), NOW());".format(id) mysql.query_db(query, request.form) return redirect("/user/{}".format(id)) user = mysql.query_db("SELECT * FROM users WHERE id={};".format(id)) users = mysql.query_db("SELECT * FROM users;") delete = mysql.query_db("DELETE email, users.created_at, users.updated_at WHERE users.id = {};".format(id)) app.run(debug=True) # run our server
from flask import Flask # import the Connector function from mysqlconnection import MySQLConnector app = Flask(__name__) # connect and store the connection in "mysql" note that you pass the database name to the function mysql = MySQLConnector(app, 'mydb') # an example of running a query print mysql.query_db("SELECT * FROM users") app.run(debug=True)
errors=1 if request.form['password'] != request.form['pswdcon']: flash("Passwords must match!") errors=1 if len(request.form['email']) < 1: flash("Email cannot be blank!") errors=1 elif not EMAIL_REGEX.match(request.form['email']): flash("Invalid Email Addres!") errors=1 if (user !=[] and errors == 0): mysql.query_db(query, data) user = mysql.query_db(user_query, query_data) session['user_id'] = user[0]["id"] return render_template('success.html', success = 'Successful Registration') # else: # flash( "User Already Exists!" ) return redirect('/') @app.route('/logout', methods=['POST']) def logout(): print 'logout button' session.clear() return redirect('/') app.run(debug=True) # run our server
from flask import Flask # import the Connector function from mysqlconnection import MySQLConnector app = Flask(__name__) # connect and store the connection in "mysql" note that you pass the database name to the function mysql = MySQLConnector(app, 'mydb') # an example of running a query print "I am here" print mysql.query_db("SELECT * FROM cities") app.run(debug=True)
from flask import Flask # import the Connector function from mysqlconnection import MySQLConnector app = Flask(__name__) # connect and store the connection in "mysql" note that you pass the database name to the function mysql = MySQLConnector(app, 'sakila') # an example of running a query print mysql.query_db("SELECT * FROM store") app.run(debug=True)
import datetime import re app = Flask(__name__) app.secret_key = 'ShushKabob' mysql = MySQLConnector(app, 'full_friends') EMAIL_REGEX = re.compile(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)") @app.route('/') def index(): <<<<<<< HEAD query_all = 'SELECT first_name, last_name, email FROM full_friends.friends' ======= query_all = 'SELECT * FROM full_friends.friends' >>>>>>> e4de77c6658cc96ede9876b91759915171675027 all_users = mysql.query_db(query_all) return render_template('index.html', all_users=all_users) @app.route('/friends', methods=['POST']) def create(): data = { 'fname': request.form['fname'], 'lname': request.form['lname'], 'email': request.form['email'], } if len(data['fname']) < 2: flash('First name must be longer than 2 characters', 'error') if len(data['lname']) < 2: flash('Last name must be longer than 2 characters', 'error') if not EMAIL_REGEX.match(data['email']) or len(data['email']) < 5: flash('Email not valid', 'error')
from flask import Flask # import the Connector function from mysqlconnection import MySQLConnector app = Flask(__name__) # connect and store the connection in "mysql" note that you pass the database name to the function mysql = MySQLConnector(app, 'sakila') # an example of running a query print mysql.query_db("SELECT * FROM customer LIMIT 1") app.run(debug=True)
from flask import Flask,jsonify import json # import the Connector function from mysqlconnection import MySQLConnector app = Flask(__name__) # connect and store the connection in "mysql" note that you pass the database name to the function mysql = MySQLConnector(app, 'fullfriendsdb') # an example of running a query print(mysql.query_db("SELECT * FROM friends")) @app.route('/') def index(): answers= mysql.query_db("SELECT * FROM friends WHERE friends.id=10") print(answers) if answers== None: print("none") elif answers==[]: print("empty list") else: print("maybe empty list") #print(jsonify(answers)) return "hi" app.run(debug=True,port=9000,host='0.0.0.0')
from flask import Flask, request, redirect, render_template, session, flash from mysqlconnection import MySQLConnector app = Flask(__name__) mysql = MySQLConnector(app,'friendsdb') print mysql.query_db("SELECT * FROM friends") @app.route('/') def index(): query = "SELECT * FROM friends" # define your query friends = mysql.query_db(query) # run query with query_db() return render_template('index.html', all_friends=friends) # pass data to our template @app.route('/friends', methods=['POST']) def create(): # add a friend to the database! return redirect('/') app.run(debug=True)