-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
134 lines (114 loc) · 4.87 KB
/
server.py
File metadata and controls
134 lines (114 loc) · 4.87 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
from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
from os.path import exists
import flask
import sqlite3
import base64
import os
current_directory = os.getcwd()
app = Flask(__name__)
def get_cursor():
sqliteConnection = sqlite3.connect("ImageRepository.db")
cursor = sqliteConnection.cursor()
return sqliteConnection, cursor
"""Initialize the sqlite database and fill up the `products` table with sample data."""
def initialize_db():
db_exists = exists(
f"{current_directory}\ImageRepository.db")
if db_exists:
print('DB DOES EXIST')
if not db_exists:
print('DB DOES NOT EXIST')
# Create initial table
sqliteConnection = sqlite3.connect('ImageRepository.db')
cursor = sqliteConnection.cursor()
cursor.execute('''CREATE TABLE photos
(id INTEGER PRIMARY KEY, filename VARCHAR, photo BLOB NOT NULL);''')
sqliteConnection.commit()
print("Initialized database")
def convert_to_binary_data(filename):
# Convert digital data to binary format
with open(filename, 'rb') as file:
blobData = file.read()
return blobData
@app.route("/")
def home_page():
(sqliteConnection, cursor) = get_cursor()
print("Connected to SQLite")
cursor.execute("SELECT rowid, * FROM photos")
rows = cursor.fetchall()
print("Retrieved %d database entries" % len(rows))
# For HTML Display
images = []
for row in rows:
images.append({
"id": row[1],
"filename": row[2],
"image": row[3].decode()
})
cursor.close()
return render_template("index.html", images=images)
@app.route("/add_photo/", methods=['GET', 'POST'])
def add_photo():
if flask.request.method == 'GET':
return render_template("add_photo.html", message="No pic uploaded! Press the 'Main Page' button (or your browser's"
" 'Back' button) and refresh the page."), 400
pics = request.files['files']
pic_list = request.files.getlist('files')
if not pics:
return render_template("add_photo.html", message="No pic uploaded! Press the 'Main Page' button (or your browser's"
" 'Back' button) and refresh the page."), 400
filenameList = []
for i in pic_list:
filename = secure_filename(i.filename)
filenameList.append(filename)
mimetype = pics.mimetype
file = secure_filename(pics.filename)
if not file or not mimetype:
return render_template("add_photo.html", message="Bad upload! Press the 'Main Page' button (or your browser's"
" 'Back' button) and refresh the page."), 400
(sqliteConnection, cursor) = get_cursor()
print("Connected to SQLite")
# Grabbing final row from db for ID numbering reasons
cursor.execute("SELECT id FROM photos ORDER BY id DESC LIMIT 1")
finalEntryID = cursor.fetchone()
for count, i in enumerate(pic_list, 1):
photoBytes = i.read()
photoData = base64.b64encode(photoBytes)
if finalEntryID is None:
finalEntryID = [0]
data_tuple = (count + finalEntryID[0], filenameList[count-1], photoData)
sqlite_addPhoto_query = """ INSERT INTO photos
(id, filename, photo) VALUES ( ?, ?, ?)"""
cursor.execute(sqlite_addPhoto_query, data_tuple)
sqliteConnection.commit()
print("Images inserted successfully as a BLOB into a table")
cursor.close()
# return 'Image(s) Uploaded! Press the back button and refresh the page.', 200
return render_template("add_photo.html",
message="Image(s) Uploaded! Press the 'Main Page' button (or your browser's"
" 'Back' button) and refresh the page."), 200
@app.route("/delete_pic/<image_id>")
def delete_pic(image_id):
if not image_id:
return render_template("delete_pic.html", message="Invalid image ID!"), 400
(sqliteConnection, cursor) = get_cursor()
cursor.execute("DELETE FROM photos WHERE id = ?", (image_id,))
sqliteConnection.commit()
cursor.execute("VACUUM")
sqliteConnection.commit()
return render_template("delete_pic.html", message="Image deletion successful!"), 200
@app.route("/reset")
def reset():
(sqliteConnection, cursor) = get_cursor()
cursor.execute("DROP TABLE IF EXISTS photos")
cursor.execute("VACUUM")
cursor.execute('''CREATE TABLE photos
(id INTEGER PRIMARY KEY, filename VARCHAR, photo BLOB NOT NULL);''')
sqliteConnection.commit()
cursor.close()
return render_template("reset.html", message="Database reset. Press the 'Main Page' button (or your browser's 'Back"
"' button) and refresh the page."), 200
if __name__ == '__main__':
initialize_db()
app.run(debug=False)