faflask / app.py
getad72493's picture
Update app.py
97c207d verified
raw
history blame
1.88 kB
from flask import Flask, render_template, request, redirect, url_for, flash
import os
from werkzeug.utils import secure_filename
from math import ceil
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'
app.config['STATIC_FOLDER'] = 'static/images'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16 MB file upload limit
app.config['ALLOWED_EXTENSIONS'] = {'jpg', 'jpeg', 'png', 'gif'}
# Create folder if doesn't exist
os.makedirs(app.config['STATIC_FOLDER'], exist_ok=True)
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
# Check allowed file extensions
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']
# Route for the homepage (gallery)
@app.route('/')
def index():
image_files = os.listdir(app.config['STATIC_FOLDER'])
images_per_page = 6
page = request.args.get('page', 1, type=int)
total_images = len(image_files)
total_pages = ceil(total_images / images_per_page)
image_files = image_files[(page-1) * images_per_page : page * images_per_page]
return render_template('index.html', images=image_files, total_pages=total_pages, page=page)
# Route for the upload page
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
files = request.files.getlist('file')
for file in files:
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['STATIC_FOLDER'], filename))
flash('Images successfully uploaded')
return redirect(url_for('index'))
return render_template('upload.html')
if __name__ == '__main__':
app.run(debug=True)