Skip to content

Instantly share code, notes, and snippets.

@Zheaoli
Created November 12, 2023 14:10
Show Gist options
  • Save Zheaoli/9321dab58a156df4150390ef6e8cd023 to your computer and use it in GitHub Desktop.
Save Zheaoli/9321dab58a156df4150390ef6e8cd023 to your computer and use it in GitHub Desktop.
from flask import Flask, request, render_template_string, jsonify
from flask_caching import Cache
app = Flask(__name__)
cache = Cache(app, config={"CACHE_TYPE": "SimpleCache"})
# The HTML template as a string
html_template = """
<!doctype html>
<html>
<head><title>Monitor - {{ title }}</title></head>
<body>
{% if action == 'edit' %}
<div>
<form method='post'>
<div>
<p>Key:</p>
<p>
<input name='key' type='text' value='{{ key }}' />
</p>
</div>
<div>
<p>Content:</p>
<p>
<textarea name='value' cols=80 rows=24>{{ value }}</textarea>
</p>
<p>
<span><input name='markdown' type='checkbox' {% if markdown %}checked{% endif %}/> </span>
<span>Markdown</span>
</p>
</div>
<div>
<p>
<input type='submit' value="Submit (Ctrl+Enter)" />
</p>
</div>
</form>
</div>
{% elif action == 'display' %}
<div id='monitor'>{{ value }}</div>
<script type='module'>
// Your JavaScript code for refreshing content goes here
</script>
{% elif action == 'qrcode' %}
<div>
<p>url: {{ display_url }}</p>
</div>
<div id="qrcode"></div>
<script src='https://unpkg.com/qrcodejs@1.0.0/qrcode.min.js'></script>
<script>
new QRCode(document.getElementById("qrcode"), "{{ display_url }}");
</script>
{% endif %}
</body>
</html>
"""
@app.route("/", methods=["GET", "POST"])
def index():
action = request.args.get("action", "")
key = request.args.get("key", "default")
value = ""
markdown = False
if action == "set":
if "value" in request.form:
value = request.form["value"]
cache.set(key, value)
return jsonify(status="OK")
elif action == "get":
value = cache.get(key)
if value is None:
return jsonify(content="empty content")
return jsonify(content=value)
elif action == "display":
value = cache.get(key) or ""
return render_template_string(html_template, action=action, value=value)
elif action == "qrcode":
display_url = request.host_url.rstrip("/") + "/?action=display&key=" + key
return render_template_string(
html_template, action=action, display_url=display_url
)
elif action == "edit":
if "value" in request.form:
value = request.form["value"]
markdown = "markdown" in request.form
cache.set(key, value)
# Handle markdown conversion if needed
# This is where you'd add your markdown to HTML conversion logic
value = cache.get(key) or ""
return render_template_string(
html_template, action=action, key=key, value=value, markdown=markdown
)
# Default action for root URL
return render_template_string(
html_template, action="edit", key=key, value=value, markdown=markdown
)
if __name__ == "__main__":
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment