Skip to content

Commit

Permalink
database.py component working
Browse files Browse the repository at this point in the history
  • Loading branch information
techwithtim committed Feb 5, 2020
1 parent b958a7e commit 508bb29
Show file tree
Hide file tree
Showing 20 changed files with 205 additions and 124 deletions.
3 changes: 3 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
TESTING=False
DEBUG=True
SECRET_KEY=youwontguessthiskey
62 changes: 46 additions & 16 deletions .idea/workspace.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Empty file added old_msg_server/__init__.py
Empty file.
File renamed without changes.
File renamed without changes.
2 changes: 1 addition & 1 deletion website/client/test.py → old_msg_server/client/test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from client import Client
from old_msg_server.client import Client
import time
from threading import Thread

Expand Down
File renamed without changes.
File renamed without changes.
12 changes: 4 additions & 8 deletions website/__init__.py → website/application/__init__.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,22 @@
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()
from os import environ


def create_app():
"""Construct the core application."""
app = Flask(__name__, instance_relative_config=False)
db.init_app(app)
app.config.from_object('config.Config')
app.secret_key = "no"

# APP ROUTES

with app.app_context():
# Imports
from .views import view
from .filters import filter
from .models import Message
from .database import DataBase

app.register_blueprint(view, url_prefix="/")
app.register_blueprint(filter, url_prefix="/filter")

# Create tables for our models
db.create_all()

return app
61 changes: 61 additions & 0 deletions website/application/database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import sqlite3
from sqlite3 import Error
import os
from datetime import datetime
import pickle


cwd = os.getcwd()

FILE = "messages.db"
PLAYLIST_TABLE = "Messages"


class DataBase:
def __init__(self):
self.conn = None
try:
self.conn = sqlite3.connect(FILE)
except Error as e:
print(e)

self.cursor = self.conn.cursor()
self._create_table()

def close(self):
self.conn.close()

def _create_table(self):
query = f"""CREATE TABLE IF NOT EXISTS {PLAYLIST_TABLE}
(name TEXT, content TEXT, time Date, id INTEGER PRIMARY KEY AUTOINCREMENT)"""
self.cursor.execute(query)
self.conn.commit()

def get_all_messages(self, limit=100):
"""
returns all messages
"""
query = f"SELECT * FROM {PLAYLIST_TABLE} LIMIT {limit}"
self.cursor.execute(query)
result = self.cursor.fetchall()

results = []
for r in result:
name, content, date, _id = r
data = {"name":name, "message":content, "time":date}
results.append(data)

return results

def save_message(self, name, msg, time):
"""
saves the given message
:param name: str
:param msg: str
:param time: datetime
:return:
"""
query = f"INSERT INTO {PLAYLIST_TABLE} VALUES (?, ?, ?, ?)"
self.cursor.execute(query, (name, msg,time, None))
self.conn.commit()

1 change: 0 additions & 1 deletion website/filters.py → website/application/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

filter = Blueprint("filter", __name__)


# JINJA TEMPLATE FILTERS
@filter.context_processor
def slice():
Expand Down
70 changes: 70 additions & 0 deletions website/application/static/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
async function load_name(){
return await fetch('/get_name')
.then(async function (response) {
return await response.json();
}).then(function (text) {
return text["name"]
});
};

async function load_messages() {
return await fetch('/get_messages')
.then(async function (response) {
return await response.json();
}).then(function (text) {
console.log(text)
return text
});
}

var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on( 'connect', function() {
socket.emit( 'event', {
data: 'User Connected'
} )
var form = $( 'form#msgForm' ).on( 'submit', async function( e ) {
e.preventDefault()

// get input from message box
let msg_input = document.getElementById("msg")
let user_input = msg_input.value
let user_name = await load_name()

// clear msg box value
msg_input.value = ""

// send message to other users
socket.emit( 'event', {
message : user_input,
name: user_name
} )
} )
} )
socket.on( 'message response', function( msg ) {
add_messages(msg)
})

window.onload = async function() {
var msgs = await load_messages()
for (msg of msgs){
add_messages(msg)
}
}

async function add_messages(msg){
if( typeof msg.name !== 'undefined' ) {
var d = new Date()
var n = d.toLocaleTimeString()
if ( typeof msg.time !== "undefined") {
}
var global_name = await load_name()

var content = '<div class="container">' + '<b style="color:#000" class="right">'+msg.name+'</b><p>' + msg.message +'</p><span class="time-right">' + n + '</span></div>'
if (global_name == msg.name){
content = '<div class="container darker">' + '<b style="color:#000" class="left">'+msg.name+'</b><p>' + msg.message +'</p><span class="time-left">' + n + '</span></div>'
}
// update div
var messageDiv = document.getElementById("messages")
messageDiv.innerHTML += content
}
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
18 changes: 13 additions & 5 deletions website/views.py → website/application/views.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from flask import Blueprint
from flask import Flask, render_template, url_for, redirect, request, session, jsonify, flash, Blueprint
from .database import DataBase

view = Blueprint("views", __name__)

Expand All @@ -8,7 +9,7 @@

# GLOBAL VARS
client = None
messages = []
MSG_LIMIT = 20


@view.route("/login", methods=["POST","GET"])
Expand All @@ -23,7 +24,7 @@ def login():
if len(name) >= 2:
session[NAME_KEY] = name
flash(f'You were successfully logged in as {name}.')
return redirect(url_for("home"))
return redirect(url_for("views.home"))
else:
flash("1Name must be longer than 1 character.")

Expand All @@ -38,7 +39,7 @@ def logout():
"""
session.pop(NAME_KEY, None)
flash("You were logged out.")
return redirect(url_for("login"))
return redirect(url_for("views.login"))


@view.route("/")
Expand All @@ -51,7 +52,7 @@ def home():
global client

if NAME_KEY not in session:
return redirect(url_for("login"))
return redirect(url_for("views.login"))

return render_template("index.html", **{"session": session})

Expand All @@ -61,4 +62,11 @@ def get_name():
data = {"name": ""}
if NAME_KEY in session:
data = {"name": session[NAME_KEY]}
return jsonify(data)
return jsonify(data)


@view.route("/get_messages")
def get_messages():
db = DataBase()
msgs = db.get_all_messages(MSG_LIMIT)
return jsonify(msgs)
4 changes: 0 additions & 4 deletions website/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,3 @@ class Config:
TESTING = environ.get('TESTING')
FLASK_DEBUG = environ.get('FLASK_DEBUG')
SECRET_KEY = environ.get('SECRET_KEY')

# Database
SQLALCHEMY_DATABASE_URI = environ.get('SQLALCHEMY_DATABASE_URI')
SQLALCHEMY_TRACK_MODIFICATIONS = environ.get('SQLALCHEMY_TRACK_MODIFICATIONS')
Loading

0 comments on commit 508bb29

Please sign in to comment.