Building an Online Code Compiler with Django

Creating an online code compiler using Django can be a rewarding project that showcases your ability to build a web-based tool for compiling and executing code in various programming languages. This guide by The Coding College outlines the steps to create a basic online compiler in Django.

Prerequisites

Before starting, ensure you have the following:

  • Basic knowledge of Django.
  • Python installed on your system.
  • Django installed (pip install django).
  • Knowledge of using external libraries like subprocess for running commands securely.

Steps to Build the Online Compiler

1. Create a Django Project

Start by creating a Django project and an app for your compiler.

django-admin startproject OnlineCompiler
cd OnlineCompiler
python manage.py startapp compiler

2. Configure the Project

  • Add the compiler app to your INSTALLED_APPS in settings.py:
INSTALLED_APPS = [
    ...
    'compiler',
]
  • Create the database:
python manage.py migrate

3. Define Models (Optional)

If you want to store submitted code or results, create models in models.py.

from django.db import models

class CodeSubmission(models.Model):
    code = models.TextField()
    language = models.CharField(max_length=50)
    created_at = models.DateTimeField(auto_now_add=True)

Run migrations:

python manage.py makemigrations
python manage.py migrate

4. Create a Form for Code Submission

In forms.py (create this file in the compiler app), define a form for users to input their code.

from django import forms

class CodeForm(forms.Form):
    LANGUAGE_CHOICES = [
        ('python', 'Python'),
        ('javascript', 'JavaScript'),
        ('c', 'C'),
        ('cpp', 'C++'),
    ]
    language = forms.ChoiceField(choices=LANGUAGE_CHOICES)
    code = forms.CharField(widget=forms.Textarea)

5. Create Views to Process Code

In views.py, define a view to handle code submission and execution. Use subprocess to execute the code.

from django.shortcuts import render
from django.http import JsonResponse
from .forms import CodeForm
import subprocess

def compile_code(request):
    if request.method == 'POST':
        form = CodeForm(request.POST)
        if form.is_valid():
            language = form.cleaned_data['language']
            code = form.cleaned_data['code']

            # Define how to run the code based on the language
            if language == 'python':
                file_name = 'temp.py'
                command = ['python', file_name]
            elif language == 'javascript':
                file_name = 'temp.js'
                command = ['node', file_name]
            elif language == 'c':
                file_name = 'temp.c'
                command = ['gcc', file_name, '-o', 'temp.out', '&&', './temp.out']
            elif language == 'cpp':
                file_name = 'temp.cpp'
                command = ['g++', file_name, '-o', 'temp.out', '&&', './temp.out']
            else:
                return JsonResponse({'error': 'Unsupported language'})

            # Write the code to a temporary file
            with open(file_name, 'w') as file:
                file.write(code)

            try:
                # Run the code
                result = subprocess.run(command, capture_output=True, text=True, check=True)
                output = result.stdout
            except subprocess.CalledProcessError as e:
                output = e.stderr

            return JsonResponse({'output': output})

    else:
        form = CodeForm()

    return render(request, 'compiler/compiler.html', {'form': form})

6. Create Templates

In templates/compiler/compiler.html, create the UI for submitting code.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Online Compiler</title>
</head>
<body>
    <h1>Online Code Compiler</h1>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Run Code</button>
    </form>
</body>
</html>

7. Configure URLs

In compiler/urls.py, define a URL pattern for the compiler view.

from django.urls import path
from . import views

urlpatterns = [
    path('', views.compile_code, name='compile_code'),
]

Include this in the project’s urls.py:

from django.urls import path, include

urlpatterns = [
    path('compiler/', include('compiler.urls')),
]

8. Test the Compiler

Run the development server and visit http://127.0.0.1:8000/compiler/. Input your code and see the results.

python manage.py runserver

Security Considerations

  1. Sandboxing: Use tools like Docker to sandbox the execution environment, preventing malicious code from affecting your server.
  2. Resource Limits: Limit execution time and memory usage to prevent abuse.
  3. Input Validation: Sanitize inputs to avoid injection attacks.

Enhancements

  • Add support for more programming languages.
  • Implement real-time output using WebSockets.
  • Store and display user code submissions and outputs.

For more detailed guides and tutorials, visit The Coding College.

Leave a Comment