-
Notifications
You must be signed in to change notification settings - Fork 0
/
image.py
71 lines (62 loc) · 2.2 KB
/
image.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
# image.py
import os
from werkzeug.utils import secure_filename
from database import connect_to_database
from datetime import datetime
UPLOAD_FOLDER = 'uploads/'
def allowed_file(filename):
"""Check if the file has an allowed extension."""
return '.' in filename and filename.rsplit('.', 1)[1].lower() in {'png', 'jpg', 'jpeg'}
def upload_image(user_id, username, image_file):
"""Upload image for the user."""
user_folder = os.path.join(UPLOAD_FOLDER, str(user_id))
if not os.path.exists(user_folder):
os.makedirs(user_folder)
if image_file and allowed_file(image_file.filename):
filename = secure_filename(image_file.filename)
filepath = os.path.join(user_folder, filename)
image_file.save(filepath)
db = connect_to_database()
cursor = db.cursor()
try:
cursor.execute("INSERT INTO images (user_id, username, filename, created_at) VALUES (%s, %s, %s, %s)",
(user_id, username, filename, datetime.now()))
db.commit()
return True
except Exception as e:
print("Error:", e)
db.rollback()
return False
finally:
cursor.close()
db.close()
else:
return False
def retrieve_images(user_id):
"""Retrieve images for the user."""
db = connect_to_database()
cursor = db.cursor()
cursor.execute("SELECT filename FROM images WHERE user_id = %s", (user_id,))
images = cursor.fetchall()
cursor.close()
db.close()
return images
def delete_image(user_id, filename):
"""Delete image for the user."""
user_folder = os.path.join(UPLOAD_FOLDER, str(user_id))
filepath = os.path.join(user_folder, filename)
if os.path.exists(filepath):
os.remove(filepath)
db = connect_to_database()
cursor = db.cursor()
try:
cursor.execute("DELETE FROM images WHERE user_id = %s AND filename = %s", (user_id, filename))
db.commit()
return True
except Exception as e:
print("Error:", e)
db.rollback()
return False
finally:
cursor.close()
db.close()