So close! I'm able to use syntax highlighting AND grab the content with js (which then adds to a textarea), but the Flask for loop is only noticed on the first iteration. I can't grab the subsequent values. I need to find a way to dynamically find IDs.

This commit is contained in:
Norm Rasmussen
2023-03-13 17:23:56 -04:00
parent a435a66b81
commit 8afdec139b
16 changed files with 160 additions and 95 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

Binary file not shown.

View File

@ -5,7 +5,9 @@ app = Flask(__name__)
app.config.from_object(Config) app.config.from_object(Config)
# Upload folder # Upload folder
UPLOAD_FOLDER = 'static/files' UPLOAD_FOLDER = "/Users/normrasmussen/Documents/Projects/CSM_webapp/app/static/files"
app.config['UPLOAD_FOLDER'] =UPLOAD_FOLDER # UPLOAD_FOLDER = 'static/files'
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
ALLOWED_EXTENSIONS = {"csv"}
from app import routes from app import routes, forms

Binary file not shown.

View File

@ -1,8 +1,10 @@
from flask_wtf import FlaskForm from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField from wtforms.fields import SubmitField
from wtforms.validators import DataRequired from flask_codemirror.fields import CodeMirrorField
class TemplateForm(FlaskForm):
template_code = CodeMirrorField(
language='htmlembedded',
config={'lineNumbers': 'true'})
submit = SubmitField('Submit')
class RequestForm(FlaskForm):
apikey = StringField("Academy API Key", validators=[DataRequired()])
submit = SubmitField("Submit")

View File

@ -3,8 +3,8 @@ import itertools
import re import re
import os import os
import csv import csv
from .forms import TemplateForm
from functools import wraps from functools import wraps
from app import app
from flask import ( from flask import (
redirect, redirect,
flash, flash,
@ -15,9 +15,7 @@ from flask import (
url_for, url_for,
) )
from werkzeug.utils import secure_filename from werkzeug.utils import secure_filename
from app import app, forms
# Global Variables
url = "https://api.northpass.com/"
# Upload folder # Upload folder
UPLOAD_FOLDER = "/Users/normrasmussen/Documents/Projects/CSM_webapp/app/static/files" UPLOAD_FOLDER = "/Users/normrasmussen/Documents/Projects/CSM_webapp/app/static/files"
@ -25,6 +23,8 @@ UPLOAD_FOLDER = "/Users/normrasmussen/Documents/Projects/CSM_webapp/app/static/f
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
ALLOWED_EXTENSIONS = {"csv"} ALLOWED_EXTENSIONS = {"csv"}
# Global Variables
url = "https://api.northpass.com/"
def download_csv(): def download_csv():
if request.method == "GET": if request.method == "GET":
@ -200,7 +200,6 @@ def bulk_add():
emails = emails.split() emails = emails.split()
if groups: if groups:
print(groups)
if "\n" in groups: if "\n" in groups:
groups = groups.split("\n") groups = groups.split("\n")
groups = [group.strip() for group in groups] groups = [group.strip() for group in groups]
@ -305,7 +304,8 @@ def load_templates():
data = response.json() data = response.json()
nextlink = data["links"] nextlink = data["links"]
for response in data["data"]: for response in data["data"]:
name, body = (response["attributes"]["name"], response["attributes"]["body"]) name, body = (
response["attributes"]["name"], response["attributes"]["body"])
templates.append((name,body)) templates.append((name,body))
if "next" not in nextlink: if "next" not in nextlink:
@ -313,7 +313,7 @@ def load_templates():
return render_template("templates.html", return render_template("templates.html",
title="Templates", title="Templates",
templates=templates templates=templates,
) )
return render_template("options.html") return render_template("options.html")
@ -322,32 +322,41 @@ def load_templates():
@key_required @key_required
def templates(): def templates():
if request.method == "POST": if request.method == "POST":
name = request.form.get('template_name') if request.form['submit-template']:
body = request.form.get('body') name = request.form.get('template_name')
print(name) body = request.form.get("loaded-content")
endpoint = "v2/custom_templates" if body == "":
headers = { error = "Ooph. Looks like you didn't load the changes before submitting."
"accept": "application/json", return render_template("templates.html", error=error)
"content-type": "application/json", else:
"X-Api-Key": session["key"], endpoint = "v2/custom_templates"
} headers = {
payload = {"custom_template": { "accept": "application/json",
"name":name, "content-type": "application/json",
"body":body "X-Api-Key": session["key"],
}} }
response = requests.post(url+endpoint, json=payload, headers=headers) payload = {"custom_template": {
return check_templates(response) "name":name,
return render_template("templates.html", error="Uh oh!") "body":body
}}
response = requests.post(url+endpoint, json=payload, headers=headers)
return check_templates(response)
return load_templates()
def check_templates(response): def check_templates(response):
print(response) print(response)
response = str(response) response = str(response)
if "201" in response: if "201" in response:
error = "Success! Templates Uploaded." error = "Success! Templates Uploaded."
return render_template("templates.html", title="People Added", error=error) return render_template("templates.html",
title="Templates Added",
error=error)
elif "403" in response: elif "403" in response:
error = "Uh oh. Looks like you don't have appropriate privileges." error = "Uh oh. Looks like you don't have appropriate privileges."
return render_template("templates.html", error=error) return render_template("templates.html", error=error)
elif "404" in response:
error = "Hm. Looks like something was wrong in the templates."
return render_template("templates.html", error=error)
else: else:
error = "Something went wrong, but I'm not sure what." error = "Something went wrong, but I'm not sure what."
return render_template("templates.html", title="Shrug", error=error) return render_template("templates.html", title="Shrug", error=error)
@ -364,10 +373,17 @@ def bulk_courses_to_groups():
def bulk_invite_ppl(): def bulk_invite_ppl():
pass pass
@app.route('/cmtest', methods = ['GET', 'POST'])
def cmtest():
form = TemplateForm()
if form.validate_on_submit():
text = form.template_code.data
return render_template('templates.html', form=form)
app.secret_key = "@&I\x1a?\xce\x94\xbb0w\x17\xbf&Y\xa2\xc2(A\xf5\xf2\x97\xba\xeb\xfa" app.secret_key = "@&I\x1a?\xce\x94\xbb0w\x17\xbf&Y\xa2\xc2(A\xf5\xf2\x97\xba\xeb\xfa"
if __name__ == "__main__": #if __name__ == "__main__":
ask_key() # ask_key()

BIN
app/static/.DS_Store vendored Normal file

Binary file not shown.

4
app/static/css/prism.css Normal file
View File

@ -0,0 +1,4 @@
/* PrismJS 1.29.0
https://prismjs.com/download.html#themes=prism-tomorrow&languages=markup+clike+javascript&plugins=line-numbers */
code[class*=language-],pre[class*=language-]{color:#ccc;background:0 0;font-family:Consolas,Monaco,'Andale Mono','Ubuntu Mono',monospace;font-size:1em;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none}pre[class*=language-]{padding:1em;margin:.5em 0;overflow:auto}:not(pre)>code[class*=language-],pre[class*=language-]{background:#2d2d2d}:not(pre)>code[class*=language-]{padding:.1em;border-radius:.3em;white-space:normal}.token.block-comment,.token.cdata,.token.comment,.token.doctype,.token.prolog{color:#999}.token.punctuation{color:#ccc}.token.attr-name,.token.deleted,.token.namespace,.token.tag{color:#e2777a}.token.function-name{color:#6196cc}.token.boolean,.token.function,.token.number{color:#f08d49}.token.class-name,.token.constant,.token.property,.token.symbol{color:#f8c555}.token.atrule,.token.builtin,.token.important,.token.keyword,.token.selector{color:#cc99cd}.token.attr-value,.token.char,.token.regex,.token.string,.token.variable{color:#7ec699}.token.entity,.token.operator,.token.url{color:#67cdcc}.token.bold,.token.important{font-weight:700}.token.italic{font-style:italic}.token.entity{cursor:help}.token.inserted{color:green}
pre[class*=language-].line-numbers{position:relative;padding-left:3.8em;counter-reset:linenumber}pre[class*=language-].line-numbers>code{position:relative;white-space:inherit}.line-numbers .line-numbers-rows{position:absolute;pointer-events:none;top:0;font-size:100%;left:-3.8em;width:3em;letter-spacing:-1px;border-right:1px solid #999;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.line-numbers-rows>span{display:block;counter-increment:linenumber}.line-numbers-rows>span:before{content:counter(linenumber);color:#999;display:block;padding-right:.8em;text-align:right}

7
app/static/css/prism.js Normal file

File diff suppressed because one or more lines are too long

View File

@ -170,7 +170,7 @@ li {
.man-csv-opts { .man-csv-opts {
display: flex; display: flex;
justify-content: space-evenly; justify-content: space-evenly;
} }
.csv-upload { .csv-upload {
@ -182,6 +182,15 @@ li {
text-decoration: none; text-decoration: none;
} }
.window-body {
display: flex;
justify-content: space-around;
}
#templates {
width: 75%;
}
#currentDate { #currentDate {
color: var(--primary); color: var(--primary);
} }

View File

@ -1,40 +0,0 @@
document.addEventListener("DOMContentLoaded", function() {
getAllGroups();
});
const apiKey = 'session["key"]';
const groups= [];
const getAllGroups = async (num) => {
if(num === 1){
}
let page = num;
await axios({
method: 'get',
url: `https://api.northpass.com/v2/groups?page=${page}`,
headers: {
'accept': '*/*',
'x-api-key': apiKey,
'content-type': 'application/json'
}
})
.then(async (res) => {
if (res.data.links.next != null) {
page++;
for (let i = 0; i < res.data.data.length; i++) {
let groupName = res.data.data[i].attributes.name;
selectInput = '<option value='+ groupName +'>'+ groupName+'</option>';
$('#groups').append(selectInput);
groups.push(res.data.data[i].attributes.name);
}
await getAllGroups(page);
} else {
for (let i = 0; i < res.data.data.length; i++) {
groups.push(res.data.data[i].attributes.name);
}
}
})
.catch(err => {
console.log(err);
})
}

View File

@ -15,15 +15,20 @@
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&display=swap" <link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&display=swap"
rel="stylesheet"> rel="stylesheet">
<link rel="stylesheet" href="{{ url_for('static', filename="css/styles.css") }}" /> <link rel="stylesheet" href="{{ url_for('static', filename="css/styles.css") }}" />
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script> <script src="https://cdn.jsdelivr.net/gh/WebCoder49/code-input@1.2/code-input.min.js"></script>
if ( window.history.replaceState ) { <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/WebCoder49/code-input@1.2/code-input.min.css">
window.history.replaceState( null, null, window.location.href ); <link href="{{ url_for('static', filename='css/prism.css')}}" rel="stylesheet" />
}
</script>
</head> </head>
<body> <body>
{% block content %} {% endblock %} {% block content %} {% endblock %}
<script src="{{ url_for('static', filename='css/prism.js' )}}"></script>
<script src="//cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.7.0/build/highlight.min.js"></script>
<script>
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
</body> </body>
</html> </html>

View File

@ -7,12 +7,13 @@
<h3>{{ error }}</h4> <h3>{{ error }}</h4>
{% endif %} {% endif %}
{% if templates %} {% if templates %}
<h2> Here are the liquid templates </h2> <h2> Here are the liquid templates for </h2>
<h2 style="color:#F05323"><strong> {{ session.school }} </strong></h2>
{% endif %} {% endif %}
<div class="templates_display" > <div class="templates_display" >
{% for templates in templates %} {% for templates in templates %}
<p>&nbsp;</p> <p>&nbsp;</p>
<div class="html_code"> <div class="window-body">
<form <form
id="templates" id="templates"
action="{{ url_for('templates')}}" action="{{ url_for('templates')}}"
@ -20,17 +21,20 @@
<h2> <h2>
{{ templates[0] }} {{ templates[0] }}
</h2> </h2>
<textarea <code-input
placeholder={{ templates[0] }} lang="HTML"
id="body" value="{{ templates[1] }}"
name="body" id="editor"
rows="35" name="body"
cols="100"> template="code-input">
{{ templates[1] }} {{ templates[1] }}
</textarea> </code-input>
<p>&nbsp;</p> <textarea
name="loaded-content"
id="loaded-content"
style="width:100%;"></textarea>
<label for="template_name"> <label for="template_name">
Create New Template (optional): Create New Template Name (optional):
</label> </label>
<input <input
type="text" type="text"
@ -38,10 +42,67 @@
value="{{ templates[0] }}"> value="{{ templates[0] }}">
</input> </input>
<p>&nbsp;</p> <p>&nbsp;</p>
<input type="submit" name="submit_template" value="Submit Template"</input> <div
name="load-template"
value="Load Changes"
onclick="copyToTextArea()"
style="cursor:pointer"
>Click here to load changes</div>
<input
type="submit"
name="submit-template"
value="Submit Template">
</input>
</form> </form>
</div> </div>
</div> </div>
<p>&nbsp;</p> <p>&nbsp;</p>
{% endfor %} {% endfor %}
<!--
<h3> Advanced users only: create new template </h3>
<p>&nbsp;</p>
<div class="html_code">
<form
id="templates"
action="{{ url_for('templates')}}"
method="post">
<h2>
Enter the code below
</h2>
<textarea
id="body"
name="body"
rows="35"
cols="100">
</textarea>
<p>&nbsp;</p>
<label for="template_name">
Template Name:
</label>
<input
type="text"
name="template_name">
</input>
<p>&nbsp;</p>
<input type="submit" name="submit_template" value="Submit Template"</input>
</form>
</div> -->
<script>
codeInput.registerTemplate("code-input", codeInput.templates.hljs(hljs,
[
]));
</script>
<script>
codeInput.registerTemplate("code-input", codeInput.templates.prism(Prism, []));
</script>
<script>
function copyToTextArea() {
var code = document.getElementById("editor").value;
let textarea = document.getElementById("loaded-content");
textarea.textContent = code;
console.log(code);
}
</script>

View File

@ -1,5 +1,4 @@
import os import os
class Config(object): class Config(object):
SECRET_KEY = os.environ.get("NORTHPASS") or "north-pass" SECRET_KEY = os.environ.get("NORTHPASS") or "north-pass"