forked from UChicagoWebDev/2023-winter-exercise-5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
169 lines (133 loc) · 4.83 KB
/
app.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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import logging
import string
import traceback
import random
import sqlite3
from datetime import datetime
from flask import * # Flask, g, redirect, render_template, request, url_for
from functools import wraps
app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect('db/watchparty.sqlite3')
db.row_factory = sqlite3.Row
setattr(g, '_database', db)
return db
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
def query_db(query, args=(), one=False):
db = get_db()
cursor = db.execute(query, args)
print("query_db")
print(cursor)
rows = cursor.fetchall()
print(rows)
db.commit()
cursor.close()
if rows:
if one:
return rows[0]
return rows
return None
def new_user():
name = "Unnamed User #" + ''.join(random.choices(string.digits, k=6))
password = ''.join(random.choices(string.ascii_lowercase + string.digits, k=10))
api_key = ''.join(random.choices(string.ascii_lowercase + string.digits, k=40))
u = query_db('insert into users (name, password, api_key) ' +
'values (?, ?, ?) returning id, name, password, api_key',
(name, password, api_key),
one=True)
return u
def get_user_from_cookie(request):
user_id = request.cookies.get('user_id')
password = request.cookies.get('user_password')
if user_id and password:
return query_db('select * from users where id = ? and password = ?', [user_id, password], one=True)
return None
def render_with_error_handling(template, **kwargs):
try:
return render_template(template, **kwargs)
except:
t = traceback.format_exc()
return render_template('error.html', args={"trace": t}), 500
# ------------------------------ NORMAL PAGE ROUTES ----------------------------------
@app.route('/')
def index():
print("index") # For debugging
user = get_user_from_cookie(request)
if user:
rooms = query_db('select * from rooms')
return render_with_error_handling('index.html', user=user, rooms=rooms)
return render_with_error_handling('index.html', user=None, rooms=None)
@app.route('/rooms/new', methods=['GET', 'POST'])
def create_room():
print("create room")
user = get_user_from_cookie(request)
if user is None: return {}, 403
if (request.method == 'POST'):
name = "Unnamed Room " + ''.join(random.choices(string.digits, k=6))
room = query_db('insert into rooms (name) values (?) returning id', [name], one=True)
return redirect(f'{room["id"]}')
else:
return app.send_static_file('create_room.html')
@app.route('/signup', methods=['GET', 'POST'])
def signup():
print("signup")
user = get_user_from_cookie(request)
if user:
return render_with_error_handling('signup.html', user=user) # redirect('/')
if request.method == 'POST':
u = new_user()
print("u")
print(u)
for key in u.keys():
print(f'{key}: {u[key]}')
resp = make_response(render_with_error_handling('signup.html', user=u))
resp.set_cookie('user_id', str(u['id']))
resp.set_cookie('user_password', u['password'])
return resp
return redirect('/login')
@app.route('/login', methods=['GET', 'POST'])
def login():
print("login")
user = get_user_from_cookie(request)
if user:
return redirect('/')
if request.method == 'POST':
name = request.form['name']
password = request.form['name']
u = query_db('select * from users where name = ? and password = ?', [name, password], one=True)
if user:
resp = make_response(redirect("/"))
resp.set_cookie('user_id', u.id)
resp.set_cookie('user_password', u.password)
return resp
return render_with_error_handling('login.html', failed=True)
@app.route('/logout')
def logout():
resp = make_response(redirect('/'))
resp.set_cookie('user_id', '')
resp.set_cookie('user_password', '')
return resp
@app.route('/rooms/<int:room_id>')
def room(room_id):
user = get_user_from_cookie(request)
if user is None: return redirect('/')
room = query_db('select * from rooms where id = ?', [room_id], one=True)
return render_with_error_handling('room.html',
room=room, user=user)
# -------------------------------- API ROUTES ----------------------------------
# POST to change the user's name
# POST to change the user's password
# POST to change the name of a room
# GET to get all the messages in a room
# POST to post a new message to a room
# Change username
# Change room name
# Get messages in a room
# Post a message in a room