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)
# Upload folder
UPLOAD_FOLDER = 'static/files'
app.config['UPLOAD_FOLDER'] =UPLOAD_FOLDER
UPLOAD_FOLDER = "/Users/normrasmussen/Documents/Projects/CSM_webapp/app/static/files"
# 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 wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired
from wtforms.fields import SubmitField
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 os
import csv
from .forms import TemplateForm
from functools import wraps
from app import app
from flask import (
redirect,
flash,
@ -15,9 +15,7 @@ from flask import (
url_for,
)
from werkzeug.utils import secure_filename
# Global Variables
url = "https://api.northpass.com/"
from app import app, forms
# Upload folder
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
ALLOWED_EXTENSIONS = {"csv"}
# Global Variables
url = "https://api.northpass.com/"
def download_csv():
if request.method == "GET":
@ -200,7 +200,6 @@ def bulk_add():
emails = emails.split()
if groups:
print(groups)
if "\n" in groups:
groups = groups.split("\n")
groups = [group.strip() for group in groups]
@ -305,7 +304,8 @@ def load_templates():
data = response.json()
nextlink = data["links"]
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))
if "next" not in nextlink:
@ -313,7 +313,7 @@ def load_templates():
return render_template("templates.html",
title="Templates",
templates=templates
templates=templates,
)
return render_template("options.html")
@ -322,9 +322,13 @@ def load_templates():
@key_required
def templates():
if request.method == "POST":
if request.form['submit-template']:
name = request.form.get('template_name')
body = request.form.get('body')
print(name)
body = request.form.get("loaded-content")
if body == "":
error = "Ooph. Looks like you didn't load the changes before submitting."
return render_template("templates.html", error=error)
else:
endpoint = "v2/custom_templates"
headers = {
"accept": "application/json",
@ -337,17 +341,22 @@ def templates():
}}
response = requests.post(url+endpoint, json=payload, headers=headers)
return check_templates(response)
return render_template("templates.html", error="Uh oh!")
return load_templates()
def check_templates(response):
print(response)
response = str(response)
if "201" in response:
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:
error = "Uh oh. Looks like you don't have appropriate privileges."
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:
error = "Something went wrong, but I'm not sure what."
return render_template("templates.html", title="Shrug", error=error)
@ -364,10 +373,17 @@ def bulk_courses_to_groups():
def bulk_invite_ppl():
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"
if __name__ == "__main__":
ask_key()
#if __name__ == "__main__":
# 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

@ -182,6 +182,15 @@ li {
text-decoration: none;
}
.window-body {
display: flex;
justify-content: space-around;
}
#templates {
width: 75%;
}
#currentDate {
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

@ -17,13 +17,18 @@
<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://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/WebCoder49/code-input@1.2/code-input.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/WebCoder49/code-input@1.2/code-input.min.css">
<link href="{{ url_for('static', filename='css/prism.css')}}" rel="stylesheet" />
</head>
<body>
{% 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>
</head>
<body>
{% block content %} {% endblock %}
</body>
</html>

View File

@ -7,12 +7,13 @@
<h3>{{ error }}</h4>
{% endif %}
{% 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 %}
<div class="templates_display" >
{% for templates in templates %}
<p>&nbsp;</p>
<div class="html_code">
<div class="window-body">
<form
id="templates"
action="{{ url_for('templates')}}"
@ -20,17 +21,20 @@
<h2>
{{ templates[0] }}
</h2>
<textarea
placeholder={{ templates[0] }}
id="body"
<code-input
lang="HTML"
value="{{ templates[1] }}"
id="editor"
name="body"
rows="35"
cols="100">
template="code-input">
{{ templates[1] }}
</textarea>
<p>&nbsp;</p>
</code-input>
<textarea
name="loaded-content"
id="loaded-content"
style="width:100%;"></textarea>
<label for="template_name">
Create New Template (optional):
Create New Template Name (optional):
</label>
<input
type="text"
@ -38,10 +42,67 @@
value="{{ templates[0] }}">
</input>
<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>
</div>
</div>
<p>&nbsp;</p>
{% 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
class Config(object):
SECRET_KEY = os.environ.get("NORTHPASS") or "north-pass"