from flask import Flask, request, render_template_string, send_file import subprocess import sys import os app = Flask(__name__) HTML_TEMPLATE = """
{{ warning }}{% endif %} {% if output %}
{{ output }}{% endif %} {% if error %}
{{ error }}{% endif %} {{ iframe | safe }} """ @app.route("/", methods=["GET", "POST"]) def run_code(): code = "" output = "" error = "" warning = "" iframe = "" if request.method == "POST": code = request.form.get("code", "") if "import toga" in code or "from toga" in code: warning = ("Toga apps create GUI windows, which run on the server's virtual display. " "View the GUI below (may take a moment to load). Download the code to run locally.") iframe = '' temp_file = "temp_code.py" with open(temp_file, "w") as f: f.write(code) try: result = subprocess.run( [sys.executable, temp_file], capture_output=True, text=True, timeout=5 ) output = result.stdout error = result.stderr except subprocess.TimeoutExpired: error = "Execution timed out after 5 seconds." except Exception as e: error = f"An error occurred: {str(e)}" finally: if os.path.exists(temp_file): os.remove(temp_file) return render_template_string(HTML_TEMPLATE, code=code, output=output, error=error, warning=warning, iframe=iframe) @app.route("/download") def download_code(): code = request.args.get("code", "") temp_file = "toga_app.py" with open(temp_file, "w") as f: f.write(code) return send_file(temp_file, as_attachment=True) if __name__ == "__main__": app.run(debug=False, host="0.0.0.0", port=5000)