From b3fce88c987f8dd96ffe41da8dec243629d538c2 Mon Sep 17 00:00:00 2001 From: cellarspoon Date: Mon, 6 Dec 2021 10:57:59 +0100 Subject: [PATCH] upload is maybe working --- .gitignore | 1 + app.py | 24 +++++++++++++++++++++--- templates/index.html | 13 ++++++++++--- 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/.gitignore b/.gitignore index 82adb58..b94e2b5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ __pycache__ venv +pdfs diff --git a/app.py b/app.py index bbe37d6..59157b8 100644 --- a/app.py +++ b/app.py @@ -1,7 +1,11 @@ -from flask import Flask, render_template +import os +from pathlib import Path + +from flask import Flask, redirect, render_template, url_for from flask_wtf import FlaskForm from flask_wtf.csrf import CSRFProtect -from flask_wtf.file import FileField, FileRequired +from flask_wtf.file import FileAllowed, FileField, FileRequired +from werkzeug.utils import secure_filename from wtforms import StringField from wtforms.validators import DataRequired @@ -10,11 +14,25 @@ app.config["SECRET_KEY"] = "foo" app.config["WTF_CSRF_SECRET_KEY"] = "bar" +CWD = Path().resolve() + + class UploadForm(FlaskForm): - pdf = FileField(validators=[FileRequired()]) + pdf = FileField(validators=[FileAllowed(["pdf"], "PDFs only!"), FileRequired()]) @app.route("/") def home(): form = UploadForm() return render_template("index.html", form=form) + + +@app.route("/upload", methods=["POST"]) +def upload(): + form = UploadForm() + if form.validate_on_submit(): + f = form.pdf.data + filename = secure_filename(f.filename) + f.save(os.path.join(CWD, "pdfs", filename)) + return redirect(url_for("home")) + return render_template("index.html", form=form) diff --git a/templates/index.html b/templates/index.html index bafc157..5617433 100644 --- a/templates/index.html +++ b/templates/index.html @@ -6,10 +6,17 @@ THIS IS A TITLE -
- {{ form.csrf_token }} - + + {{ form.csrf_token }} {{ form.pdf }}
+ + {% if form.pdf.errors %} + + {% endif %}