From c8de190303204ed119afc1054720a54b159b6dc8 Mon Sep 17 00:00:00 2001 From: jonager Date: Sat, 2 Sep 2017 23:53:53 -0400 Subject: [PATCH] working on adding upload/download file --- app.py | 2 ++ main.py | 36 ++++++++++++++++++++++++++++++++++++ templates/edit_student.html | 7 +++++++ templates/students.html | 12 ++++++++++++ 4 files changed, 57 insertions(+) diff --git a/app.py b/app.py index f235943..151342c 100644 --- a/app.py +++ b/app.py @@ -4,5 +4,7 @@ app = Flask(__name__) app.config["DEBUG"] = True app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://lc-attendance:root@localhost:8889/lc-attendance" +ALLOWED_EXTENSIONS = set(['xlsx']) # only allows .xlsx files to be uploaded + db = SQLAlchemy(app) app.secret_key = "y337kGcys&zP3D4" \ No newline at end of file diff --git a/main.py b/main.py index 813b96e..8490d6c 100644 --- a/main.py +++ b/main.py @@ -6,6 +6,10 @@ from models import Student, Teacher, Attendance from hash_tools import make_hash, check_hash import val +import pandas as pd +from io import BytesIO # built-in in python, no need to install +import xlsxwriter +from werkzeug.utils import secure_filename # Main View @app.route('/') @@ -265,5 +269,37 @@ def editStudent(): return render_template("edit_student.html", student=student) +# Adds all the cohorts students at once into the student table +# only accepts .xlsx files +@app.route('/upload_file', methods = ['POST']) +def upload_file(): + + if request.method == 'POST': + # TODO add validation, in case user didn't select any file to upload + # TODO checks if only accepts .xlsx files + + file = request.files['file'] + file = secure_filename(file.filename) # prevents people from uploading + # malicious code + + # ----------- Reads Files and pushes to student table ------------- + df = pd.read_excel(file) + # df.columns is a list of all the table headings, 'First Name' and 'Last Name' + # in this case. + first_name = list(df[df.columns[0]]) + last_name = list(df[df.columns[1]]) + # names is a list of tupples in the form of (first_name, last_name) + names = zip(first_name,last_name) + + # creates a record for row in students.xlsx into the student table. + for name in names: + student = Student(name[0].title(), name[1].title()) + db.session.add(student) + db.session.commit() + return render_template("students.html") + + + + if __name__ == "__main__": app.run() \ No newline at end of file diff --git a/templates/edit_student.html b/templates/edit_student.html index bf04cfa..b702902 100644 --- a/templates/edit_student.html +++ b/templates/edit_student.html @@ -41,5 +41,12 @@

Edit Student

+ +
+

+ +
+ {% endblock %} diff --git a/templates/students.html b/templates/students.html index 6761a98..3c1ed2f 100644 --- a/templates/students.html +++ b/templates/students.html @@ -39,4 +39,16 @@

Add Student

+ + +
+
+

Add roster for this cohort.

+
+

+ +
+
+
{% endblock %} \ No newline at end of file