-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
175 lines (148 loc) · 6.54 KB
/
app.py
File metadata and controls
175 lines (148 loc) · 6.54 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
# app.py
from flask import Flask, render_template, request, redirect, url_for, flash, send_from_directory, jsonify
from config import Config
from models import db, Item
import base64
from werkzeug.utils import secure_filename
from flask_wtf.csrf import CSRFProtect
from sqlalchemy import or_
from flask_wtf.csrf import generate_csrf
from flask_wtf import FlaskForm
from PIL import Image
import io
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
app.config['SECRET_KEY'] = 'your-secret-key-here' # Replace with secure key
csrf = CSRFProtect(app)
db.init_app(app)
@app.context_processor
def utility_processor():
return dict(csrf_token=generate_csrf)
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']
def process_image(image_file):
# Read the image
image = Image.open(image_file)
# Convert to RGB if needed (for PNG transparency)
if image.mode in ('RGBA', 'LA'):
background = Image.new('RGB', image.size, (255, 255, 255))
background.paste(image, mask=image.split()[-1])
image = background
# Calculate new dimensions
aspect_ratio = image.size[0] / image.size[1]
new_height = min(800, image.size[1]) # Updated to 800px
new_width = int(aspect_ratio * new_height)
# Resize image
image = image.resize((new_width, new_height), Image.Resampling.LANCZOS)
# Save as WebP
webp_buffer = io.BytesIO()
image.save(webp_buffer, format='WebP', quality=85, method=6)
return webp_buffer.getvalue()
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
try:
title = request.form['title']
description = request.form['description']
location = request.form['location']
image_file = request.files['image']
if image_file and allowed_file(image_file.filename):
image_data = process_image(image_file)
else:
image_data = None
quantity = int(request.form['quantity']) # Get quantity
new_item = Item(title=title, description=description, location=location, image=image_data)
db.session.add(new_item)
db.session.commit()
flash('Item added successfully!', 'success')
return redirect(url_for('index'))
except Exception as e:
print(f"Error adding item: {e}")
flash('Error adding item. Please try again.', 'danger')
return redirect(url_for('index'))
page = request.args.get('page', 1, type=int)
items = Item.query.order_by(Item.created_at.desc()).paginate(page=page, per_page=10)
return render_template('index.html', items=items, base64=base64)
@app.route('/item/<int:item_id>')
def item(item_id):
item = Item.query.get_or_404(item_id)
return render_template('item.html', item=item, base64=base64)
@app.route('/delete/<int:item_id>', methods=['POST'])
def delete(item_id):
item_to_delete = Item.query.get_or_404(item_id)
try:
db.session.delete(item_to_delete)
db.session.commit()
flash('Item deleted successfully!', 'success')
return redirect(url_for('index'))
except Exception as e:
print(f"Error deleting item: {e}")
flash('Error deleting item. Please try again.', 'danger')
return redirect(url_for('index'))
@app.route('/search')
def search():
query = request.args.get('q', '')
if query:
items = Item.query.filter(
or_(
Item.title.ilike(f'%{query}%'),
Item.description.ilike(f'%{query}%'),
Item.location.ilike(f'%{query}%')
)
).all()
return jsonify([{
'id': item.id,
'title': item.title,
'location': item.location
} for item in items])
return jsonify([])
@app.route('/item/<int:item_id>/edit', methods=['GET', 'POST'])
def edit_item(item_id):
item = Item.query.get_or_404(item_id)
if request.method == 'POST':
try:
item.title = request.form['title']
item.description = request.form['description']
item.location = request.form['location']
item.quantity = int(request.form['quantity'])
# Add debug logging
print("Processing image upload in edit route")
image_file = request.files.get('image')
if image_file and image_file.filename:
print(f"Image file received: {image_file.filename}")
if allowed_file(image_file.filename):
print("File type allowed, processing image")
image_data = process_image(image_file)
item.image = image_data
print("Image processed and saved")
else:
print(f"File type not allowed: {image_file.filename}")
db.session.commit()
flash('Item updated successfully!', 'success')
return redirect(url_for('item', item_id=item.id))
except Exception as e:
print(f"Error updating item: {str(e)}")
db.session.rollback()
flash('Error updating item. Please try again.', 'danger')
return redirect(url_for('edit_item', item_id=item.id))
return render_template('edit_item.html', item=item)
@app.route('/item/<int:item_id>/update_quantity', methods=['POST'])
def update_quantity(item_id):
item = Item.query.get_or_404(item_id)
try:
data = request.get_json()
new_quantity = int(data.get('quantity', 1))
item.quantity = new_quantity
db.session.commit()
return jsonify({'quantity': item.quantity})
except Exception as e:
db.session.rollback()
return jsonify({'error': str(e)}), 500
return app
if __name__ == '__main__':
app = create_app()
with app.app_context():
db.create_all()
app.run(debug=True, host='0.0.0.0')