Files
function/app.py
2023-12-16 00:24:36 +11:00

71 lines
2.1 KiB
Python

import os
from flask import Flask, Response, jsonify, render_template, request
import jinja_partials
from jinja2_fragments import render_block
from flask_htmx import HTMX
import minify_html
import requests
app = Flask(__name__)
app.config.from_pyfile('config.py')
jinja_partials.register_extensions(app)
htmx = HTMX(app)
API_URL = 'https://isolator.peterstockings.com/execute'
def map_isolator_response_to_flask_response(response):
"""
Maps a Node.js response to a Flask response.
:param nodejs_response: The response from Node.js, expected to be a dictionary
with keys 'body', 'headers', and 'status'.
:return: Flask Response object
"""
result = response.get('result', {})
body = result.get('body', '')
headers = result.get('headers', {})
status = result.get('status', 200)
# Convert body to JSON if it's a dictionary
body = str(body)
return Response(response=body, status=status, headers=headers)
@ app.route("/", methods=["GET"])
def index():
return render_template("index.html")
@app.route('/execute', methods=['POST'])
def execute_code():
try:
# Extract code and convert request to a format acceptable by Node.js app
code = request.json.get('code')
request_obj = {
'method': request.method,
'headers': dict(request.headers),
'body': request.json,
'url': request.url,
# Add other request properties as needed
}
# Call the Node.js API
response = requests.post(API_URL, json={'code': code, 'request': request_obj})
response_data = response.json()
# Map the Node.js response to Flask response
flask_response = map_isolator_response_to_flask_response(response_data)
return flask_response
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='127.0.0.1', port=port)