image_upload/upload.py

65 lines
1.6 KiB
Python
Raw Normal View History

2024-11-16 09:47:07 +01:00
import os
from flask import Flask, render_template, redirect, request
from flask_wtf import FlaskForm
from flask_wtf.file import FileAllowed, FileField
from wtforms import (
SubmitField,
)
2024-11-16 10:10:30 +01:00
# config me here
2024-11-16 09:47:07 +01:00
APP = Flask(__name__, static_folder="static")
APP.config["IMAGE_FOLDER"] = "static/images"
2024-11-16 10:10:30 +01:00
ALLOWED_FILES = ["jpg", "png", "gif", "webp"]
2024-11-16 09:47:07 +01:00
# don't config these lines
APP.config["SECRET_KEY"] = os.urandom(24)
2024-11-16 10:32:31 +01:00
2024-11-16 09:47:07 +01:00
class ImageUploadForm(FlaskForm):
"""Image upload form."""
allowed = ", ".join(ALLOWED_FILES)
2024-11-16 09:47:07 +01:00
image = FileField(
2024-11-16 10:10:30 +01:00
"image:",
2024-11-16 10:32:31 +01:00
validators=[
FileAllowed(
ALLOWED_FILES,
f"Images only, please use any of the following file extensions: {allowed}",
2024-11-16 10:32:31 +01:00
)
],
2024-11-16 09:47:07 +01:00
)
submit = SubmitField("Submit")
def saveimage(image):
"""Save the image to the folder"""
image.save(os.path.join(APP.config["IMAGE_FOLDER"], image.filename))
@APP.route("/", methods=["GET", "POST"])
def index():
"""Upload route, a page to upload an image"""
imageuploadform = ImageUploadForm()
if request.method == "POST":
if imageuploadform.validate_on_submit():
saveimage(imageuploadform.image.data)
2024-11-16 10:32:31 +01:00
uploaded_files = sorted(
[
os.path.join(APP.config["IMAGE_FOLDER"], file)
for file in os.listdir(APP.config["IMAGE_FOLDER"])
],
key=os.path.getctime,
)
2024-11-16 10:32:31 +01:00
return render_template(
"upload.html",
imageuploadform=imageuploadform,
uploaded_files=uploaded_files
)
2024-11-16 09:47:07 +01:00
if __name__ == "__main__":
APP.debug = True
APP.run(port=5000)