-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
140 lines (92 loc) · 3.7 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
from config import *
from time import localtime, strftime
from flask import (Flask, flash, redirect, render_template, request, session,
url_for)
from flask_socketio import SocketIO, emit
from flask_sqlalchemy import SQLAlchemy
from flask_session import Session
app = Flask(__name__)
socketio = SocketIO(app)
#loading the config file
if app.config["ENV"] == "production":
app.config.from_object("config.ProductionConfig")
else:
app.config.from_object("config.DevelopmentConfig")
#with this can leave code alone and control the config environment outside of the application
#using the terminal
app.static_folder = "static"
#print(app.config)
db = SQLAlchemy(app)
Session(app)
class Users(db.Model):
""" Class that stores the user's usernames"""
id = db.Column("id", db.Integer, primary_key=True)
user_name = db.Column("username", db.String(100))
#id is automatically created as it is the primary key
def __init__(self, user_name):
"""Initialises a new user"""
self.user_name = user_name
#creating the routes
@app.route('/')
def login_form():
"""returns the login page """
return render_template('login.html')
@app.route('/chat-page', methods=["POST", "GET"])
def chat_page():
"""Adds new users to the db, checks if existing users are in teh db, and redirects all
these usersto the chatting page"""
if request.method == "POST":
username = request.form.get("user_name")
session["user"] = username
new_user = Users(user_name=username)
#checking if the user is in the database. There will only be one user with
#that name so hence why we are only interested in grabbing the first entry of the db
found_user = Users.query.filter_by(user_name=username).first()
if found_user:
flash("username already exists, please pick another one")
return redirect(url_for("login_form"))
else:
#push user to database:
try:
db.session.add(new_user)
db.session.commit()
return render_template('chat-page.html', Uname=username)
except:
return "there was an error adding the user"
#request method = GET
else:
if "user" in session:
flash("already logged in")
return render_template("chat-page.html", Uname= session["user"])
else:
flash("You are not logged in!")
return render_template("login.html")
@app.route("/logout")
def logout():
"""Logs out users from the chatpage and deletes them from the database"""
if "user" in session:
username = session.pop("user")
#deleting the user from the database:
delete_user = Users.query.filter_by(user_name=username).first_or_404()
db.session.delete(delete_user)
db.session.commit()
flash("You have been logged out!")
return redirect(url_for("login_form"))
@app.route("/view")
def view():
"""Displays the list of users that are logged into the database"""
return render_template("views.html", values=Users.query.all())
@app.route("/delete")
def delete():
"""A temporary route that clears the database whilst I work on fixing the session bug."""
Users.query.delete()
db.session.commit()
return render_template("delete_db.html")
@socketio.on('text')
def text(message):
username = session.get('user')
emit('message', {'msg': username + ' : ' + message['msg'], "time_stamp": strftime("%b-%d %I:%M%p", localtime())}, broadcast= True)
if __name__ == "__main__":
#this will create the database if it doesn't already exist when we the run the program
db.create_all()
socketio.run(app)