请求帮助:将Flask版Python在线编译器适配至Django项目
Hey there! As a Django newbie, let's walk through how to port your Flask-based Python code runner into your Django project. We'll build on the core logic from your runcode.py snippet and integrate it smoothly into Django's standard workflow.
Original Flask-Based runcode.py Snippet
import subprocess import sys import os class RunPyCode(object): def __init__(self, code=None): self.code = code if not os.path.exists('running'): os.mkdir('running') def _run_py_prog(self, cmd="a.py"): cmd = [sys.executable, ...] # Rest of your command logic here
Step 1: Set Up Your Django App
First, create a dedicated app for this functionality (if you haven’t already):
python manage.py startapp code_runner
Don’t forget to add code_runner to the INSTALLED_APPS list in your project’s settings.py.
Step 2: Adapt the Code Runner Class for Django
We’ll update the RunPyCode class to follow Django best practices—like using managed temporary directories and adding critical safety guards (running user-submitted code is risky!).
Here’s an improved version:
# code_runner/utils.py import subprocess import sys import os from django.conf import settings from tempfile import NamedTemporaryFile class RunPyCode: def __init__(self, code=None): self.code = code # Use a project-specific temp directory instead of hardcoding self.temp_dir = os.path.join(settings.BASE_DIR, "temp_code") os.makedirs(self.temp_dir, exist_ok=True) def run_code(self): if not self.code: return "Error: No code provided." # Create a temporary Python file safely with NamedTemporaryFile(mode='w', suffix='.py', dir=self.temp_dir, delete=False) as f: f.write(self.code) temp_file_path = f.name try: # Run code with a timeout to prevent infinite loops result = subprocess.run( [sys.executable, temp_file_path], capture_output=True, text=True, timeout=10 # Adjust timeout as needed ) # Combine stdout and stderr for full output output = result.stdout + result.stderr except subprocess.TimeoutExpired: output = "Error: Execution timed out." except Exception as e: output = f"Error: {str(e)}" finally: # Clean up the temporary file os.unlink(temp_file_path) return output
Important note: Running user-submitted code directly on your server is unsafe for production. For live apps, use a sandboxed environment like Docker containers to isolate code execution.
Step 3: Create a Django View for Code Submission
Build a view that handles POST requests with user code, runs it, and returns results. We’ll use a function-based view for simplicity:
# code_runner/views.py from django.shortcuts import render from django.http import JsonResponse from .utils import RunPyCode def code_compiler(request): if request.method == 'POST': code = request.POST.get('code', '') runner = RunPyCode(code) output = runner.run_code() # Return JSON for AJAX, or render a template with results return JsonResponse({'output': output}) # For GET requests, render the code input form return render(request, 'code_runner/compiler.html')
Step 4: Build the Frontend Template
Create a template where users can input code and view results. Save this as code_runner/templates/code_runner/compiler.html:
<!DOCTYPE html> <html> <head> <title>Python Code Compiler</title> <style> .container { max-width: 800px; margin: 20px auto; } textarea { width: 100%; height: 200px; padding: 10px; font-family: monospace; } button { padding: 10px 20px; margin-top: 10px; cursor: pointer; } #output { margin-top: 20px; padding: 10px; background: #f5f5f5; border-radius: 4px; font-family: monospace; } </style> </head> <body> <div class="container"> <h1>Python Code Compiler</h1> <form id="codeForm"> <textarea name="code" placeholder="Enter your Python code here...">print("Hello, Django!")</textarea> <br> <button type="submit">Run Code</button> </form> <div id="output"></div> </div> <script> document.getElementById('codeForm').addEventListener('submit', function(e) { e.preventDefault(); const code = this.code.value; fetch('', { method: 'POST', headers: { 'X-CSRFToken': '{{ csrf_token }}', 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'code=' + encodeURIComponent(code) }) .then(response => response.json()) .then(data => { document.getElementById('output').textContent = data.output; }); }); </script> </body> </html>
Step 5: Map URLs to the View
Add a URL pattern in your project’s urls.py:
# your_project/urls.py from django.urls import path from code_runner.views import code_compiler urlpatterns = [ # ... other project URLs path('compiler/', code_compiler, name='code_compiler'), ]
Step 6: Test the Compiler
Start your Django server:
python manage.py runserver
Visit http://localhost:8000/compiler/—you should see the code editor. Enter some Python code, click "Run Code", and view the output!
内容的提问来源于stack exchange,提问作者Andurnache Alexandru

