faflask / app.py
getad72493's picture
Update app.py
bfb8a4e verified
from flask import Flask, render_template, request, redirect, url_for, flash
import os
from werkzeug.utils import secure_filename
from math import ceil
# Initialize the Flask app
app = Flask(__name__)
# Set up configurations
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'}
app.config['SECRET_KEY'] = os.urandom(24) # Secret key for session management and flash messages
# Create necessary directories if they don't exist
os.makedirs(app.config['STATIC_FOLDER'], exist_ok=True)
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
# Function to check if the uploaded file has a valid extension
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():
# Get the list of image files in the static folder
image_files = os.listdir(app.config['STATIC_FOLDER'])
# Pagination setup
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)
# Slice the image list to show only the images for the current 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':
# Check if the file part exists
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
files = request.files.getlist('file')
for file in files:
# Check if the file is allowed
if file and allowed_file(file.filename):
# Secure the filename and save the file
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['STATIC_FOLDER'], filename))
# Flash a success message and redirect to the index page
flash('Images successfully uploaded')
return redirect(url_for('index'))
# Render the upload page template
return render_template('upload.html')
# Start the Flask app in production mode (Hugging Face will handle WSGI)
if __name__ == '__main__':
app.run(debug=False, host='0.0.0.0', port=7860)