Skip to content

Commit

Permalink
added the wall
Browse files Browse the repository at this point in the history
  • Loading branch information
jacobsaw committed Aug 10, 2016
1 parent 16464c8 commit 9f7a13c
Show file tree
Hide file tree
Showing 10 changed files with 567 additions and 0 deletions.
40 changes: 40 additions & 0 deletions AdamJacobs/the_wall/mysqlconnection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
""" import the necessary modules """
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import text
# Create a class that will give us an object that we can use to connect to a database
class MySQLConnection(object):
def __init__(self, app, db):
config = {
'host': 'localhost',
'database': db, # we got db as an argument
'user': 'root',
'password': 'root',
'port': '8889' # change the port to match the port your SQL server is running on
}
# this will use the above values to generate the path to connect to your sql database
DATABASE_URI = "mysql://{}:{}@127.0.0.1:{}/{}".format(config['user'], config['password'], config['port'], config['database'])
app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# establish the connection to database
self.db = SQLAlchemy(app)
# this is the method we will use to query the database
def query_db(self, query, data=None):
result = self.db.session.execute(text(query), data)
if query[0:6].lower() == 'select':
# if the query was a select
# convert the result to a list of dictionaries
list_result = [dict(r) for r in result]
# return the results as a list of dictionaries
return list_result
elif query[0:6].lower() == 'insert':
# if the query was an insert, return the id of the
# commit changes
self.db.session.commit()
# row that was inserted
return result.lastrowid
else:
# if the query was an update or delete, return nothing and commit changes
self.db.session.commit()
# This is the module method to be called by the user in server.py. Make sure to provide the db name!
def MySQLConnector(app, db):
return MySQLConnection(app, db)
Binary file added AdamJacobs/the_wall/mysqlconnection.pyc
Binary file not shown.
131 changes: 131 additions & 0 deletions AdamJacobs/the_wall/server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
from flask import Flask, render_template, request, redirect, session, flash
from mysqlconnection import MySQLConnector
from flask_bcrypt import Bcrypt
app = Flask(__name__)
app.secret_key = 'sexyorange'
bcrypt = Bcrypt(app)
mysql = MySQLConnector(app,'thewall')

import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
NAME = re.compile(r'.[a-zA-Z]')

@app.route('/')
def index():
return render_template('index.html')

@app.route('/thewall')
def displaywall():
session['messages'] = mysql.query_db("SELECT users.first_name, messages.created_at, messages.message, messages.id as messageid FROM users JOIN messages ON users.id=messages.user_id ORDER BY messages.created_at DESC")
session['comments'] = mysql.query_db("SELECT users.first_name, comments.message_id as comment_message_id, comments.comment, comments.created_at FROM users JOIN comments ON users.id=comments.user_id ORDER BY comments.created_at ASC")
return render_template('wall.html')

@app.route('/register', methods = ['POST'])
def create():
if len(request.form['first_name']) < 2:
flash('Please type your first name')
return redirect('/')
elif not NAME.match(request.form['first_name']):
flash('Please only use alphabetical characters')
return redirect('/')
elif len(request.form['last_name']) < 2:
flash('Please type your last name')
return redirect('/')
elif not NAME.match(request.form['last_name']):
flash('Please only use alphabetical characters')
return redirect('/')
elif len(request.form['email']) < 1:
flash('Please provide a valid email address')
return redirect('/')
elif not EMAIL_REGEX.match(request.form['email']):
flash('Invalid Email Address!')
return redirect('/')
elif len(request.form['password']) < 8:
flash('Password must be at least 8 characters')
return redirect('/')
elif request.form['confirm_password'] != request.form['password']:
flash('Password and confirmation must match')
return redirect('/')
else:
password = request.form['password']
pw_hash = bcrypt.generate_password_hash(password)
query = "INSERT INTO users (first_name, last_name, email, pw_hash, created_at) VALUES (:first_name, :last_name, :email, :pw_hash, NOW())"
data = {
'first_name': request.form['first_name'],
'last_name': request.form['last_name'],
'email': request.form['email'],
'pw_hash': pw_hash
}
mysql.query_db(query, data)
email = request.form['email']
query2 = "SELECT first_name, id FROM users WHERE email = :email LIMIT 1"
data2 = {'email': email}
session['user'] = mysql.query_db(query2, data2)
session['messages'] = mysql.query_db("SELECT users.first_name, messages.created_at, messages.message, messages.id as messageid FROM users JOIN messages ON users.id=messages.user_id ORDER BY messages.created_at DESC")
session['comments'] = mysql.query_db("SELECT users.first_name, comments.message_id as comment_message_id, comments.comment, comments.created_at FROM users JOIN comments ON users.id=comments.user_id ORDER BY comments.created_at ASC")
return redirect('/thewall')

@app.route('/login', methods = ['POST'])
def login():
email = request.form['email']
password = request.form['password']
if len(email) < 2:
flash('Come on man, at least put in an email or something')
return redirect('/')
else:
user_query = "SELECT email, pw_hash FROM users WHERE email = :email LIMIT 1"
user_data = {'email': email}
user = mysql.query_db(user_query, user_data)
if bcrypt.check_password_hash(user[0]['pw_hash'], password):
email = request.form['email']
query = "SELECT first_name, id FROM users WHERE email = :email LIMIT 1"
data = {'email': email}
session['user'] = mysql.query_db(query, data)
session['messages'] = mysql.query_db("SELECT users.first_name, messages.created_at, messages.message, messages.id as messageid FROM users JOIN messages ON users.id=messages.user_id ORDER BY messages.created_at DESC")
session['comments'] = mysql.query_db("SELECT users.first_name, comments.message_id as comment_message_id, comments.comment, comments.created_at FROM users JOIN comments ON users.id=comments.user_id ORDER BY comments.created_at ASC")
return render_template('wall.html')
else:
flash('Incorrect username and password. Please try again.')
return redirect('/')

@app.route('/logout', methods = ['POST'])
def logout():
session.clear()
return redirect('/')

@app.route('/message/<id>', methods = ['POST'])
def message(id):
query = "INSERT INTO messages (user_id, message, created_at) VALUES (:id, :message, NOW())"
data = {
'id': id,
'message' : request.form['message']
}
mysql.query_db(query, data)
return redirect('/thewall')

@app.route('/delete_message/<id>', methods = ['POST'])
def delete(id):
query2 = "DELETE FROM comments WHERE message_id = :id"
data2 = {
'id': id,
}
mysql.query_db(query2, data2)
query1 = "DELETE FROM messages WHERE id = :id"
data1 = {
'id': id,
}
mysql.query_db(query1, data1)
return redirect('/thewall')

@app.route('/comment/<message_id>', methods = ['POST'])
def comment(message_id):
query = "INSERT INTO comments (user_id, message_id, comment, created_at) VALUES (:user_id, :message_id, :comment, NOW())"
data = {
'user_id' : session['user'][0]['id'],
'message_id': message_id,
'comment' : request.form['comment']
}
mysql.query_db(query, data)
return redirect('/thewall')

app.run(debug=True)
61 changes: 61 additions & 0 deletions AdamJacobs/the_wall/sql_files/thewall_comments.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
CREATE DATABASE IF NOT EXISTS `thewall` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `thewall`;
-- MySQL dump 10.13 Distrib 5.6.13, for osx10.6 (i386)
--
-- Host: 127.0.0.1 Database: thewall
-- ------------------------------------------------------
-- Server version 5.5.34

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `comments`
--

DROP TABLE IF EXISTS `comments`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`message_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`comment` text,
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_comments_messages1_idx` (`message_id`),
KEY `fk_comments_users1_idx` (`user_id`),
CONSTRAINT `fk_comments_messages1` FOREIGN KEY (`message_id`) REFERENCES `messages` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_comments_users1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `comments`
--

LOCK TABLES `comments` WRITE;
/*!40000 ALTER TABLE `comments` DISABLE KEYS */;
INSERT INTO `comments` VALUES (1,4,1,'You crazy paul!','2016-08-09 18:48:41',NULL),(2,4,1,'You crazy paul!','2016-08-09 18:57:05',NULL),(3,4,1,'work!!!','2016-08-09 19:09:25',NULL),(5,4,1,'This is a new comment!','2016-08-10 08:18:23',NULL),(6,5,6,'I\'m a new person','2016-08-10 08:37:09',NULL),(14,13,10,'Boring!','2016-08-10 13:06:19',NULL),(15,13,11,'So is el fuego! ','2016-08-10 13:07:10',NULL);
/*!40000 ALTER TABLE `comments` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2016-08-10 14:04:43
58 changes: 58 additions & 0 deletions AdamJacobs/the_wall/sql_files/thewall_messages.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
CREATE DATABASE IF NOT EXISTS `thewall` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `thewall`;
-- MySQL dump 10.13 Distrib 5.6.13, for osx10.6 (i386)
--
-- Host: 127.0.0.1 Database: thewall
-- ------------------------------------------------------
-- Server version 5.5.34

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `messages`
--

DROP TABLE IF EXISTS `messages`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `messages` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`message` text,
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_messages_users_idx` (`user_id`),
CONSTRAINT `fk_messages_users` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `messages`
--

LOCK TABLES `messages` WRITE;
/*!40000 ALTER TABLE `messages` DISABLE KEYS */;
INSERT INTO `messages` VALUES (4,5,'wiggidy whack attack','2016-08-09 18:19:22',NULL),(5,1,'New Message!','2016-08-10 08:16:22',NULL),(13,9,'Winter is coming!','2016-08-10 13:05:33',NULL);
/*!40000 ALTER TABLE `messages` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2016-08-10 14:04:43
58 changes: 58 additions & 0 deletions AdamJacobs/the_wall/sql_files/thewall_users.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
CREATE DATABASE IF NOT EXISTS `thewall` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `thewall`;
-- MySQL dump 10.13 Distrib 5.6.13, for osx10.6 (i386)
--
-- Host: 127.0.0.1 Database: thewall
-- ------------------------------------------------------
-- Server version 5.5.34

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `users`
--

DROP TABLE IF EXISTS `users`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(255) DEFAULT NULL,
`last_name` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`pw_hash` varchar(255) DEFAULT NULL,
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `users`
--

LOCK TABLES `users` WRITE;
/*!40000 ALTER TABLE `users` DISABLE KEYS */;
INSERT INTO `users` VALUES (1,'Adam','Jacobs','adamj@gmail.com','$2b$12$Rv9MkkwkAzrVvwolkGC71.FhS1QhY4BnZBxkeYYph82Q4tXXxtjC.','2016-08-09 16:27:36',NULL),(2,'Allison','Johnson','aj26@gmail.com','$2b$12$irqghPzUzmsMqOMFyqKaaufGNgrcBmQLf3ZlsPbE/0Vj.Mq12fBoy','2016-08-09 16:34:11',NULL),(3,'Allison','Johnson','aj26@gmail.com','$2b$12$3TJrpq96.te0tqog..RDDOiQTmLh6OoiUMpa3bh2aQNF6WNKH0T0y','2016-08-09 18:06:41',NULL),(4,'James','Smith','jsmith@gmail.com','$2b$12$UoyAzFhuPSGHuJl49oKfkegeZm3s5k7c2vxqU4u2ODJRQ8TqoChlO','2016-08-09 18:07:47',NULL),(5,'paul','bluth','funkedelic@user.net','$2b$12$WxvQ/34kZcRnuUQEVLBPg.pj9gzusfpxXggQfJI3qH8Ux5dF1/8gK','2016-08-09 18:18:50',NULL),(6,'New','Person','newperson@new.com','$2b$12$JSAyy0NAbIHrK0tGAdd83.l3NB2x3wytSzLh7xGalkxV8wHXNN/Y2','2016-08-10 08:32:58',NULL),(7,'second','newperson','secondnew@new.com','$2b$12$PwmHt3oy9TOkEcT1P/HeuOs07umJER3Bk/PAYyfeWaY6vKXxD9WwK','2016-08-10 08:34:27',NULL),(8,'Jon','Snow','jonsnow@got.com','$2b$12$B19flg4UcSlacm/EHE2kue2cPfY3BsPQ2WcOVNlhWRVh00U3TM8gi','2016-08-10 08:40:05',NULL),(9,'Ned','Stark','nedstark@gmail.com','$2b$12$iIEA1UJx1Ylw3789IRkTEOvJlwT2rGeC3mUvtufJ08O7e7/ATyt3a','2016-08-10 13:05:27',NULL),(10,'Tyrion ','Lannister','tyrion@gmail.com','$2b$12$PyFigI5CBfbIGNCt2Tjfi.YghGetjo/7VH.AFb/Mkii4jsPMb.nSG','2016-08-10 13:06:09',NULL),(11,'Green','Dragon','gdragon@gmail.com','$2b$12$AZEc.DZlX7qIyoD09R3WyeD8q2s9tguvdqsoC.HgT8mFSj2VYvzTS','2016-08-10 13:06:42',NULL);
/*!40000 ALTER TABLE `users` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2016-08-10 14:04:43
Loading

0 comments on commit 9f7a13c

Please sign in to comment.