-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
357 lines (270 loc) · 11.7 KB
/
server.py
File metadata and controls
357 lines (270 loc) · 11.7 KB
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
from flask import Flask, render_template, redirect, request, session, flash
from flask_bcrypt import Bcrypt
import re # the regex module
# create a regular expression object that we'll use later
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
from MySQLconnection import connectToMySQL
# import the function that will return an instance of a connection
app = Flask(__name__)
app.secret_key = "keep it secret"
app.secret_key ="keep it secret"
bcrypt = Bcrypt(app)
#flash require a secret key as well as session
# show a page with a form to create a new user
@app.route('/', methods=['GET'])
@app.route('/index', methods=['GET'])
def index_total():
return render_template('/index-total.html')
@app.route('/register', methods=['POST'])
def register():
is_valid = True
mysql = connectToMySQL('books')
query = 'SELECT * FROM users_table WHERE email = %(em)s;'
data = {
'em': request.form['email']
}
email_result = mysql.query_db(query, data)
if len(email_result) >= 1:
is_valid = False
flash("email already registered in database")
print(email_result)
if len(request.form['fname']) < 1:
is_valid = False
flash("Please enter a first name")
if len(request.form['lname']) < 1:
is_valid = False
flash("Please enter a last name")
if len(request.form['email']) < 1:
is_valid = False
flash("Email cannot be blank.")
if len(request.form['pw']) < 8:
is_valid = False
flash('Password must be atleast 8 characters')
if (request.form['pw'] != request.form['cpw']):
is_valid = False
flash('Passwords do NOT match')
if not EMAIL_REGEX.match(request.form['email']):
# test whether a field matches the pattern. If it does not fit the pattern, then redirect. if email fits pattern, continue.
is_valid = False
flash("email cannot be blank or invalid")
##### at this point, I have checked every field
##### if any of the fields weren't valid, is_valid will be False
##### if all the fields are valid, is_valid will be True
if not is_valid:
return redirect('/')
# return render_template('/') could use also in this case
else:
pw_hash = bcrypt.generate_password_hash(request.form['pw'])
# pw_hash can be called anything including mickey
print(pw_hash)
# put the pw_hash in our data dictionary, NOT the password the user provided
# prints something like b'$2b$12$sqjyok5RQccl9S6eFLhEPuaRaJCcH3Esl2RWLm/cimMIEnhnLb7iC'
# be sure you set up your database so it can store password hashes this long (60 characters)
mysql = connectToMySQL("books")
query = "INSERT INTO users_table (first_name,last_name, email, password) VALUES (%(fn)s, %(ln)s, %(em)s, %(pw)s);"
# put the pw_hash in our data dictionary, NOT the password the user provided
data = {
"fn": request.form['fname'],
"ln": request.form['lname'],
"em": request.form['email'],
"pw": pw_hash
}
#make the call of the function to the database.
result = mysql.query_db(query, data)
session['id_mickey_user']=result
# never render on a post, always redirect!
flash("Login info successfuly added. Please login!")
# either way the application should return to the index and display the messag
# never render on a post, always redirect!
return redirect("/")
# login the database
@app.route('/login', methods = ['POST'])
def login():
mysql = connectToMySQL('books')
query = 'SELECT * FROM users_table WHERE email = %(em)s;'
data = {
'em': request.form['email']
}
result = mysql.query_db(query, data)
if len(result)>0:
if bcrypt.check_password_hash(result[0]['password'], request.form['pw']):
session['id_mickey_user'] = result[0]['id_user']
# This is setting id_mickey_user to session which is equal the id_user logged in.
session['mickeys_first_name'] = result[0]['first_name']
#look in session and result the first name at login
return redirect('/dashboard')
flash("You could not be logged in")
return redirect ('/')
@app.route('/logout')
def logout():
print(session)
session.clear()
flash("You've been logged out")
return redirect('/')
@app.route('/dashboard', methods=['GET'])
def show_all_books_dashboard():
if 'id_mickey_user' not in session:
flash("You need to be logged in to view this page")
return redirect('/')
else:
flash("welcome to the dashboard")
MySQL = connectToMySQL('books')
query_show_books = 'SELECT * FROM books_table JOIN users_table ON books_table.id_contributor = users_table.id_user ORDER By books_table.book_title;'
# Add DESC to order in reverse order backwards
# toorderbyid_bookuseORDERBYbooks_table.id_book;
books = MySQL.query_db(query_show_books)
print('show page hitting 0')
return render_template('dashboard.html', all_books=books)
print('show page before Hitting 1')
@app.route('/add_book', methods = ['POST'])
def process_book_dashboard():
print("Hitting 1")
print(request.form)
print(session['id_mickey_user'])
print("Hitting 2")
print(request.form)
if len(request.form['book_name']) < 2:
if len(request.form['book_summary']) < 2:
# post_content is the name in the form on the dashboard.html
print("Hitting if")
flash('Input Needs to be longer')
return redirect('/dashboard')
else:
print(request.form)
db = connectToMySQL('books')
print("Hitting 4")
# # # #this is telling the computer to find the table name posts
query = 'INSERT INTO books_table (book_title, book_description,id_contributor, created_at, updated_at) VALUES (%(bt)s, %(bd)s, %(id_cont)s, NOW(), NOW());'
print("Hitting 5")
data = {
'bt': request.form['book_name'],
'bd': request.form['book_summary'],
'id_cont':session['id_mickey_user'],
}
print("hitting 6")
add_book = db.query_db(query, data)
# print(request.form)
print("hitting 7")
return redirect ('/dashboard')
# # # # show the form to show user added books
@app.route('/show_one_book/<id>', methods=["GET"])
def show_one_book(id):
print(id)
# showthebooktitle
# showaddedbyuserx
# addedoncreated_at
# lastupdated_at
# description:
# if session: ['id_mickey_user'] != 'id_contributor';
# return redirect('/dashboard');
# flash("You can not edit this entry");
# else:
MySQL = connectToMySQL ("books")
query = "SELECT * FROM books_table JOIN users_table ON books_table.id_contributor = users_table.id_user WHERE id_book=%(idb)s;"
print(id)
data = {
'idb': id
}
one_book = MySQL.query_db(query, data)
return render_template('show_one_book.html', book=one_book)
# DO NOT NEED TO USE THE STR(ID) for render template
# ONly pass in the str(ID) when doing a url or redirect
# @app.route('/show_one_user/<id>', methods=['GET'])
# def show_one_user(id):
#to get info about a specific user, you need to pass in an id through the browser
# return render_template (show_one_user.html)
#for temporary solution use this render_template
# MySQL = connectToMySQL("quotes")
#connect to to the MySQL schema name
# query = "(SELECT * FROM users_table WHERE id_user= %(mickey_id)s);"
# id_user is the variable name found in the database that intiates a user_id
# print(id)
#printing the blue id in shown above is id passed in through the browser and not the database.
# data = {
# 'mickey_id': session['id_mickey_user']
# } #data is required when we need to define specific data.
# In this case, id_user in table users_table, there is data for the query to get and this is this data called id which is in blue and it is passed through the both the URL as well as the function above.
# data_id_call = MySQL.query_db(query, data)
# this is the call to run the function to get the ID in the database where the database will then pass results to the browser page. This database_id is database_id and it will be set to the browswer in orange which will be written in jinja
# MySQL = connectToMySQL('quotes')
# query_show_quotes = 'SELECT * FROM quotes_table JOIN users_table ON quotes_table.user_added_by = users_table.id_user;'
# quotes = MySQL.query_db(query_show_quotes)
# print('show page hitting 0')
# print('show page before Hitting 1')
# return render_template ("show_one_user.html", all_users=data_id_call, all_quotes=quotes)
@app.route('/edit/<id>', methods=["GET", "POST"])
def show_edit_form(id):
MySQL = connectToMySQL("books")
# query = 'SELECT * FROM books_table JOIN users_table ON books_table.id_contributor = users_table.id_user;'
query = "(SELECT * FROM books_table JOIN users_table ON books_table.id_contributor = users_table.id_user WHERE id_book = %(idb)s);"
print(id)
data = {
'idb': id
}
# # # # #run query
books = MySQL.query_db(query, data)
print('hitting show edit page')
print(books)
return render_template("edit.html", book=books)
@app.route('/update_book/<id>', methods=['POST'])
def process_edit_form(id):
print(id)
# #connect to db to show users info in the form
print('hittingprocessingeditpage')
MySQL = connectToMySQL("books")
# # # # # #write query for getting specific users
print('connecting to the server')
query = "UPDATE books_table SET book_title = %(bt)s,book_description=%(bd)s, id_contributor=%(idc)s, created_at = NOW(), updated_at = NOW() WHERE id_book = %(idb)s;"
#
data = {
'bt': request.form['book_name'],
'bd': request.form['book_summary'],
'idc': session['id_mickey_user'],
'idb': id
}
# #possibly a value from the url,
print('hitting query')
MySQL.query_db(query, data)
print("hitting 6")
# #possibly a value from the url,
# where to go after this is complete
return redirect('/edit/' + str(id))
@app.route('/delete/<id>', methods=['GET'])
def delete_book(id):
# print('user to ??')
MySQL = connectToMySQL("books")
# #write an UPDATE query
query = "DELETE from books_table WHERE id_book = %(idb)s;"
print(id)
data = {
'idb': id
}
MySQL.query_db(query, data)
flash("removed")
return redirect('/dashboard')
if __name__ == "__main__":
app.run(debug=True)
# data={
# "id_user": session['id_mickey_user'],
# # 'bd': ['book_description'],
# # "addby":session['id_mickey_user']
# }
# all_recipients = MySQL.query_db(query_all_recipients, data)
# MySQL=connectToMySQL('books')
# query_count_incoming_posts = 'SELECT COUNT(*) FROM posts_table WHERE id_receiver = %(id_rec)s'
# data = {
# 'id_rec': session['id_mickey_user']
# }
# print('your id is', id)
# total_message_count = MySQL.query_db(query_count_incoming_posts, data)
# print('You have messages', total_message_count)
# db = connectToMySQL('books')
# query_inbox_messages = 'SELECT * FROM posts_table JOIN users_table ON posts_table.id_sender = users_table.id_user WHERE id_receiver= %(id_rec)s;'
# data = {
# 'id_rec': session['id_mickey_user']
# }
# print('id_rec')
# print('id_sender says', {query_inbox_messages})
# incoming_messages = db.query_db(query_inbox_messages, data)
# print('id_sender says', incoming_messages)
# return render_template('/dashboard.html', id_receivers=all_recipients,counts=total_message_count, all_messages=incoming_messages)