CSV & Manual Upload is working! Fixed both features.

This commit is contained in:
Norm Rasmussen
2023-03-09 15:15:42 -05:00
parent 030c5541cf
commit 43cdcff115
6 changed files with 89 additions and 83 deletions

View File

@ -37,7 +37,7 @@ def download_csv():
def key_response(response): def key_response(response):
if "402" in str(response): if "402" in str(response):
error = response.text error = response.text
return render_template("index.html", title="Error Home", errors=error) return render_template("index.html", title="Error Home", error=error)
if "401" in str(response): if "401" in str(response):
error = [ error = [
"Unauthorized access error.", "Unauthorized access error.",
@ -45,26 +45,20 @@ def key_response(response):
"such as the key being changed.", "such as the key being changed.",
"Remember, they are paired to each educator!", "Remember, they are paired to each educator!",
] ]
return render_template("index.html", title="Error Home", errors=error) return render_template("index.html", title="Error Home", error=error)
return correct_key(response) return correct_key(response)
def correct_key(response): def correct_key(response):
data = response.json() data = response.json()
session["school"] = data["data"]["attributes"]["properties"]["name"] session["school"] = data["data"]["attributes"]["properties"]["name"]
print(session["school"]) return render_template("bulk_add.html", title="Active Session")
return render_template("options.html", title="Options")
def allowed_file(filename): def allowed_file(filename):
return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route("/dev", methods=["GET", "POST"])
def dev_test():
return render_template("options.html", title="Dev Test")
# DONE: Remove header for main page. # DONE: Remove header for main page.
# DONE: Leave boxes but change outcome depending if file has been uploaded. # DONE: Leave boxes but change outcome depending if file has been uploaded.
@ -75,35 +69,45 @@ def ask_key():
Without this key, no other functions will work. Without this key, no other functions will work.
It also assigns the api key to the session and clears the session upon each reload. It also assigns the api key to the session and clears the session upon each reload.
""" """
if session.get("key"): specials = '"!@#$%^&*()-+?_=,<>/"'
return render_template("options.html", title="Options Home") #if session.get("key"):
# return render_template("bulk_add.html", title="Options Home")
if request.method == "POST": if request.method == "POST":
session["key"] = request.form.get("apikey") session["key"] = request.form.get("apikey")
# if re.search(r"\s", session["key"]): if (any(char in specials for char in session["key"]) or
# error = "Hm. That doesn't seem right" re.search(r"[\s]", session["key"])):
# return render_template("index.html", title="Home", errors=error) error = "Invalid Key."
session.clear()
return render_template("index.html", title="Home", error=error)
if session["key"] is not None and len(session["key"]) > 10: if session["key"] is not None and len(session["key"]) > 10:
endpoint = "/v2/properties/school" endpoint = "/v2/properties/school"
headers = {"accept": "application/json", "X-Api-Key": session["key"]} headers = {"accept": "application/json", "X-Api-Key": session["key"]}
response = requests.get(url + endpoint, headers=headers) response = requests.get(url + endpoint, headers=headers)
return key_response(response) return key_response(response)
error = "Hm. That doesn't seem right" error = "Hm. That doesn't seem right"
session.clear()
return render_template("index.html", title="Home", error=error) return render_template("index.html", title="Home", error=error)
session.clear()
return render_template("index.html", title="Home") return render_template("index.html", title="Home")
@app.route("/", methods=["GET", "POST"]) @app.route("/", methods=["GET", "POST"])
def render_home(): def render_home():
if session.get("key"): if session.get("key"):
return render_template("options.html", title="Home") return render_template("bulk_add.html", title="Home")
return render_template("index.html", title="Enter Key") return render_template("index.html", title="Enter Key")
@app.route("/options", methods=["GET", "POST"]) #@app.route("/options", methods=["GET", "POST"])
@app.route("/", methods=["GET", "POST"]) #@app.route("/bulk_add", methods=["GET", "POST"])
@app.route("/clear_session", methods=["GET", "POST"])
def clear_session(): def clear_session():
session.clear() if session.get("key"):
print("Session Formula")
# [session.pop(key) for key in list(session.keys())]
session.clear()
error="Session Cleared!"
return render_template("index.html", error=error, title="Home, New session")
return render_template("index.html", title="Home, New session") return render_template("index.html", title="Home, New session")
@ -111,19 +115,9 @@ def clear_session():
def table(): def table():
return render_template("table.html", tables=[session["dfhtml"]], titles=["Table"]) return render_template("table.html", tables=[session["dfhtml"]], titles=["Table"])
"""
uploaded_file = request.files['file']
if uploaded_file.filename != '':
print("File has name")
uploaded_file.save(uploaded_file.filename)
return render_template("options.html", title="Home, Now with CSV!")
"""
@app.route("/upload_file", methods=["GET", "POST"]) @app.route("/upload_file", methods=["GET", "POST"])
@app.route("/bulk_add", methods=["GET", "POST"])
def upload_file(): def upload_file():
print("Uploading CSV") print("Uploading CSV")
csvData = pd.DataFrame()
if request.method == "POST": if request.method == "POST":
if "file" not in request.files: if "file" not in request.files:
flash("No file found or uploaded") flash("No file found or uploaded")
@ -136,51 +130,51 @@ def upload_file():
# return redirect(request.url) # return redirect(request.url)
if file and allowed_file(file.filename): if file and allowed_file(file.filename):
filename = secure_filename(file.filename) filename = secure_filename(file.filename)
session["file"] = filename
file_path = os.path.join(app.config["UPLOAD_FOLDER"], filename) file_path = os.path.join(app.config["UPLOAD_FOLDER"], filename)
session["file"] = filename
session["filepath"] = file_path session["filepath"] = file_path
file.save(file_path) file.save(file_path)
# csvData = pd.read_csv(file_path)
file = list(csv.reader(open(file_path, "r"))) file = list(csv.reader(open(file_path, "r")))
emails = [] return divide_values(file)
groups = [] return render_template("bulk_add.html", title="Bulk Add")
for col in file:
emails.append(col[0])
#groups.append(col(range(1,20)))
print(emails)
#print(groups)
#print(emails) def divide_values(file):
# for item in data: emails = []
# print(item[0]) groups = []
# lines = reader(csvData) selection = request.form.get('learner-groups')
# csvData = list(lines) if request.form['submit']:
# print(csvData) if selection == "all-groups":
selection = request.form.get('learner-groups') for item in file[1:]:
if selection == "all-groups": emails.append(item[0])
if request.form['preview']: groups.append(item[1:])
return api_csv_all_groups(csvData) # FEAT: These two extract the groups and emails into two lists
elif request.form['submit']: groups = [item for group in groups for item in group]
return "Submitted Selection" groups = list(set(groups))
elif selection == "some-groups": print(emails)
return api_csv_some_groups(csvData) print(groups)
return render_template( return api_csv_parse(emails, groups)
"bulk_add.html", table=html_data, title="Uploaded File" # We're good here. This can now be sent to the api functions with emails and groups.
) elif selection == "some-groups":
return render_template("options.html", title="Home, now with a CSV Table!") submissions = []
for item in file[1:]:
# FEAT: This extracts each row as a list. Perfect for Learners in Specific Groups.
submissions.append(item)
for item in submissions:
emails.append(item[0])
print(type(emails))
groups = item[1:]
return api_csv_parse(emails, groups)
return emails
if request.form['preview']:
error="Preview Button Still Under Construction. Try again later."
return render_template("bulk_add.html", error=error, title="Preview Not Yet")
def api_csv_all_groups(csvData): return render_template(
# htmlcsv = csvData.to_html() "bulk_add.html", title="Uploaded File"
# for items in csvData: )
# emails = csvData['Email'].values.tolist()
# emails = [nan for nan in emails if str(nan) != 'nan']
# groups = csvData['Groups'].values.tolist()
# groups = [nan for nan in groups if str(nan) != 'nan']
def api_csv_parse(emails, groups):
if emails and groups: if emails and groups:
return api_add_ppl_groups(emails, groups) return api_add_ppl_groups(emails, groups)
elif emails: elif emails:
@ -189,7 +183,16 @@ def api_csv_all_groups(csvData):
return api_add_groups(groups) return api_add_groups(groups)
return render_template("bulk_add.html", table=htmlcsv, title="CSV Submission") return render_template("bulk_add.html", table=htmlcsv, title="CSV Submission")
def api_csv_some_groups(csvData): def api_csv_all_groups(emails, groups):
if emails and groups:
return api_add_ppl_groups(emails, groups)
elif emails:
return api_add_ppl(emails)
elif groups:
return api_add_groups(groups)
return render_template("bulk_add.html", table=htmlcsv, title="CSV Submission")
def api_csv_some_groups(emails, groups):
htmlcsv = csvData.to_html() htmlcsv = csvData.to_html()
emails = csvData['Email'].values.tolist() emails = csvData['Email'].values.tolist()

View File

@ -134,7 +134,7 @@ img {
.instructions-list{ .instructions-list{
display:flex; display:flex;
justify-content: center; justify-content: space-around;
width: 100%; width: 100%;
} }

View File

@ -3,15 +3,16 @@
{% include 'header.html' %} {% include 'header.html' %}
{% include 'logo.html' %} {% include 'logo.html' %}
{% block content %} {% block content %}
<h4>Please find your options below. Some things to note:</h4> <h2>You're currently accessing {{ session.school }}.</h2>
<h2>Instructions</h2>
<div class="instructions-list"> <div class="instructions-list">
<div class="instructions-left"> <div class="instructions-left">
<ul> <ul>
<li> Left side - Manual entry: <li> <h3>Left side - Manual entry:</h3>
<ul> <ul>
<li> Both fields <em>don't</em> need to be filled out!</li> <li> Both fields don't need to be filled out!</li>
<li> You can add just people or just groups.</li> <li> You can add just people or just groups.</li>
<li> Adding both Emails and Groups will add all people to all groups.</li> <li> Using both fields will add all people to all groups.</li>
</ul> </ul>
</li> </li>
</ul> </ul>
@ -19,19 +20,19 @@
<div class="instructions-right"> <div class="instructions-right">
<ul> <ul>
<li> Right side - CSV Upload: <li> <h3>Right side - CSV Upload:</h3>
<ul> <ul>
<li> The CSV will only look for one or both columns with the exact wording as the header row! </li>
<li> The Header rows must be <strong>Email</strong> and/or <strong>Groups</strong></li> <li> The Header rows must be <strong>Email</strong> and/or <strong>Groups</strong></li>
<li> You can easily add people to multiple groups.</li> <li> Please format the csv like this:</li>
<li> To add every person to every group, simply upload the CSV and select option 1 below. </li> <li> Email,Groups</li>
<li> For adding people to specific groups, format the csv as | Name | Group 1 | Group 2 | and select option 2 below. </li> <li> email@email.com, group1, group2, group3 </li>
<li> There are no limits the number of people or groups that can be added.</li> <li> email2@email.com, group5, group1 </li>
</ul> </ul>
</li> </li>
</ul> </ul>
</div> </div>
</div> </div>
<p>&nbsp;</p>
{% if error %} {% if error %}
<p class=error><strong> </strong>{{ error }}</p> <p class=error><strong> </strong>{{ error }}</p>
{% endif %} {% endif %}
@ -43,7 +44,7 @@
<form action="{{ url_for("bulk_add")}}" method="post"> <form action="{{ url_for("bulk_add")}}" method="post">
<p>Emails</p> <p>Emails</p>
<textarea id="emails" name="emails" rows="4" cols="50"></textarea> <textarea id="emails" name="emails" rows="4" cols="50"></textarea>
<p>Please paste in the Group Names which these learners should be added to.</p> <p>Group Names</p>
<textarea id="groups" name="groups" rows="4" cols="50"></textarea> <textarea id="groups" name="groups" rows="4" cols="50"></textarea>
<p></p> <p></p>
<input type="submit" value="Submit"></input> <input type="submit" value="Submit"></input>

View File

@ -14,7 +14,7 @@
<input type="radio" id="some-groups" name="learner-groups" value="some-groups"> <input type="radio" id="some-groups" name="learner-groups" value="some-groups">
<label for="learner-groups">Learners Only in Adjacent Groups</label> <label for="learner-groups">Learners Only in Adjacent Groups</label>
</div> </div>
<p><input type="submit" name="preview" value="Preview"></p> <input type="submit" name="preview" value="Preview"></input>
<input type="submit" name="submit" value="Submit to Academy"></input> <input type="submit" name="submit" value="Submit to Academy"></input>
</form> </form>
</div> </div>

View File

@ -3,9 +3,11 @@
{% include 'logo.html' %} {% include 'logo.html' %}
{% block content %} {% block content %}
<h4>Hello! Please click below to enter your key.</h4> <h4>Hello! Please click below to enter your key.</h4>
{% for error in errors %} <h2 class=error><strong>
<h2 class=error><strong> {{ error }} </strong></h2> {% if error %}
{% endfor %} {{ error }}
{% endif %}
</strong></h2>
<p> <p>
</p> </p>
<form action="{{ url_for("ask_key")}}" method="post"> <form action="{{ url_for("ask_key")}}" method="post">