cpp-compiler / app.py
blogsupport's picture
Initial upload via HfApi
95c8cc1 verified
Raw
History Blame Contribute Delete
2.91 kB
import os
import stat
import subprocess
from flask import Flask, request, jsonify
from flask_cors import CORS
import uuid # Import the uuid library to create unique filenames
app = Flask(__name__)
CORS(app)
@app.route('/')
def home():
return jsonify({
"status": "ok",
"message": "C++ compiler backend is running. Send POST requests to /api/run-cpp"
})
@app.route('/api/run-cpp', methods=['POST'])
def run_cpp():
code = request.json.get('code', '')
user_input = request.json.get('input', '')
if not code:
return jsonify({'error': 'No code provided.'}), 400
# **CRITICAL FIX: Use the /tmp directory for all file operations.**
# This directory is guaranteed to be writable in Linux container environments.
# A unique name prevents conflicts if two requests happen at once.
unique_name = str(uuid.uuid4())
temp_dir = "/tmp"
source_file_path = os.path.join(temp_dir, f"{unique_name}.cpp")
executable_path = os.path.join(temp_dir, unique_name)
try:
# Write the user's code to the temporary .cpp file in /tmp
with open(source_file_path, "w") as f:
f.write(code)
# --- Compilation Step ---
compile_process = subprocess.run(
['g++', '-std=c++17', source_file_path, '-o', executable_path],
capture_output=True, text=True, timeout=10
)
if compile_process.returncode != 0:
return jsonify({'compileErrors': compile_process.stderr})
# --- Set Execute Permissions ---
# This is still necessary for the compiled file in /tmp.
st = os.stat(executable_path)
os.chmod(executable_path, st.st_mode | stat.S_IEXEC)
# --- Execution Step ---
# Execute the program using its full, absolute path.
run_process = subprocess.run(
[executable_path], # No './' is needed when using the full path
input=user_input,
capture_output=True, text=True, timeout=15
)
if run_process.returncode != 0:
return jsonify({'runErrors': run_process.stderr})
else:
return jsonify({'output': run_process.stdout})
except subprocess.TimeoutExpired:
return jsonify({'error': 'Execution timed out. Your program took too long to run or has an infinite loop.'})
except Exception as e:
# This will catch any other unexpected errors.
return jsonify({'error': f"An unexpected server error occurred: {str(e)}"})
finally:
# --- Cleanup Step ---
# Always clean up the files from the /tmp directory to be a good citizen.
if os.path.exists(source_file_path):
os.remove(source_file_path)
if os.path.exists(executable_path):
os.remove(executable_path)
if __name__ == '__main__':
app.run(host="0.0.0.0", port=7860)