mamweb/brainfuck/views.py
2025-05-07 16:32:51 +02:00

48 lines
1.4 KiB
Python

from django.template.response import TemplateResponse
from django.http import JsonResponse as JSONResponse
from .interpreter import Interpreter
from urllib.parse import parse_qsl, unquote_plus, unquote
from typing import Dict
def index(request):
args = {}
return TemplateResponse(request, 'brainfuck/index.html', args)
def process_code(request):
qs = request.META['QUERY_STRING']
params: Dict[str, str] = {}
for pair in qs.split('&'):
if not pair:
continue
key, sep, val = pair.partition('=')
# decode key (still treat '+'→space in parameter names)
decoded_key = unquote_plus(key)
# decode value: unquote (leaves '+' intact), then percent-decode
decoded_val = unquote(val)
params[decoded_key] = decoded_val
print('params:', params)
code = params.get('code', '')
input_data = params.get('user_input', '')
# interpreter
interpreter = Interpreter(commands_per_second=1_000_000_000_000, debug=True, comma_standart_input=False)
interpreter.user_input = input_data
interpreter.load_code_from_string(code)
# TODO kill the process if it takes too long?
try:
interpreter.execute_loaded_code()
out = interpreter.saved_output
except Exception as e:
print('Error:', e)
out = 'Error: Code execution failed - ' + str(e)
end_state = interpreter.print_data(interpreter.last_step)
return JSONResponse({
'code': code,
'input_data': input_data,
'output': out,
'end_state': end_state,
})