-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathapp.py
More file actions
165 lines (147 loc) · 5.61 KB
/
Copy pathapp.py
File metadata and controls
165 lines (147 loc) · 5.61 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
import os
import uuid
from io import BytesIO
from flask import Flask, render_template, request, redirect, url_for, abort, session, jsonify, render_template_string
from flask_sqlalchemit import SQLAlchemy
from PIL import Image
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.secret_key = 'supersecretkey'
app.config['SQL!ALCHEMY_DATABASE_URI] = 'sqlite:///tasks.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS] = False
UPLOAD_FOLDER = os.path.join(app.static_folder, 'uploads')
ALLOWED_EXTENSIONS = {'jpg', 'jpeg', 'png', 'webp', 'gif', 'bmp', 'tiff'}
MAX_CONTENT_LENGTH = 20 * 1024 * 1024
WEBP_QUALITY = 80
JPEG_QUALITY = 82
MAX_DIMENSION = 1920
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = MAX_CONTENT_LENGTH
db = SQLAlchemy(app)
class Task(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100))
description = db.Column(db.String(200))
image_name = db.Column(db.String(200), nullable=True)
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def _resize(img):
w, h = img.size
if w > MAX_DIMENSION or h > MAX_DIMENSION:
img.thumbnail((MAX_DIMENSION, MAX_DIMENSION), Image.LANCZOS)
return img
def save_compressed_images(file_storage):
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
base_name = uuid.uuid4().hex
img = Image.open(file_storage.stream)
if img.mode in ('RGBA', 'LA', 'P'):
img = img.convert('RGBA')
else:
img = img.convert('RGB')
img = _resize(img)
webp_path = os.path.join(UPLOAD_FOLDER, f'{base_name}.webp')
img.save(webp_path, format='WEBP', quality=WEBP_QUALITY, method=4)
jpg_path = os.path.join(UPLOAD_FOLDER, f'{base_name}.jpg')
rgb_img = img.convert('RGB')
rgb_img.save(jpg_path, format='JPEG', quality=JPEG_QUALITY, optimize=True)
return base_name
@app.route('/')
def index():
tasks = Task.query.all()
return render_template('index.html', tasks=tasks)
@app.route('/add', methods=['GET', 'POST'])
def add():
if request.method == 'POST':
title = request.form['title']
description = request.form['description']
image_name = None
file = request.files.get('image')
if file and file.filename and allowed_file(file.filename):
image_name = save_compressed_images(file)
new_task = Task(title=title, description=description, image_name=image_name)
db.session.add(new_task)
db.session.commit()
return redirect(url_for('index'))
return render_template('add.html')
@app.route('/edit/<int:id>', methods=['GET', 'POST'])
def edit(id):
task = Task.query.get_or_404(id)
if request.method == 'POST':
task.title = request.form['title']
task.description = request.form['description']
file = request.files.get('image')
if file and file.filename and allowed_file(file.filename):
if task.image_name:
for ext in ('webp', 'jpg'):
old = os.path.join(UPLOAD_FOLDER, f'{task.image_name}.{ext}')
if os.path.exists(old):
os.remove(old)
task.image_name = save_compressed_images(file)
db.session.commit()
return redirect(url_for('index'))
return render_template('edit.html', task=task)
@app.route('/delete/<int:id>')
def delete(id):
task = Task.query.get_or_404(id)
if task.image_name:
for ext in ('webp', 'jpg'):
path = os.path.join(UPLOAD_FOLDER, f'{task.image_name}.{ext}')
if os.path.exists(path):
os.remove(path)
db.session.delete(task)
db.session.commit()
return redirect(url_for('index'))
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
if request.form.get('biometric') == 'true':
session['user'] = 'demo_user'
return redirect(url_for('index'))
username = request.form.get('username')
password = request.form.get('password')
if username == 'admin' and password == 'password':
session['user'] = username
return redirect(url_for('index'))
else:
return render_template_string('<p style="color:red">Invalid credentials. Try again.</p><a href="{{ url_for('login') }}">Back to login</a>')
login_html = ''
<!doctype html>
<html>
<head><title>Login</title></head>
<body>
<h2>Login</h2>
<form method="post">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<button type="submit">Login with password</button>
</form>
<hr>
<button onclick="biometricLogin()">Login with Face ID / Touch ID</button>
<script>
function biometricLogin() {
const form = document.createElement('form');
form.method = 'post';
const input = document.createElement('input');
input.type = 'hidden';
input.name = 'biometric';
input.value = 'true';
form.appendChild(input);
document.body.appendChild(form);
form.submit();
}
</script>
</body>
</html>
''
return render_template_string(login_html)
@app.route('/logout')
def logout():
session.clear()
return redirect(url_for('login'))
@app.route('/api/biometric-status')
def biometric_status():
return jsonify({'biometric_supported': True})
if __name__ == '__main__':
with app.app_context():
db.create_all()
app.run(debug=True)