views.py 2.03 KB
Newer Older
1
import json
2
import os
3 4 5

import xml.etree.ElementTree

6 7 8
from django.conf import settings
from django.http import Http404
from django.http import HttpResponse
9
from django.shortcuts import redirect
10
from mitxmako.shortcuts import render_to_response, render_to_string
11 12

from models import ServerCircuit
13

14

15
def circuit_line(circuit):
16
    ''' Returns string for an appropriate input element for a circuit.
17
        TODO: Rename. '''
18 19 20 21 22 23 24 25 26 27 28 29 30 31
    if not circuit.isalnum():
        raise Http404()
    try:
        sc = ServerCircuit.objects.get(name=circuit)
        schematic = sc.schematic
    except:
        schematic = ''

    circuit_line = xml.etree.ElementTree.Element('input')
    circuit_line.set('type', 'hidden')
    circuit_line.set('class', 'schematic')
    circuit_line.set('width', '640')
    circuit_line.set('height', '480')
    circuit_line.set('name', 'schematic')
32 33
    circuit_line.set('id', 'schematic_' + circuit)
    circuit_line.set('value', schematic)  # We do it this way for security -- guarantees users cannot put funny stuff in schematic.
34 35
    return xml.etree.ElementTree.tostring(circuit_line)

36

37 38 39 40 41 42 43 44
def edit_circuit(request, circuit):
    try:
        sc = ServerCircuit.objects.get(name=circuit)
    except:
        sc = None

    if not circuit.isalnum():
        raise Http404()
45 46
    response = render_to_response('edit_circuit.html', {'name': circuit,
                                                        'circuit_line': circuit_line(circuit)})
47 48 49
    response['Cache-Control'] = 'no-cache'
    return response

50

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
def save_circuit(request, circuit):
    if not circuit.isalnum():
        raise Http404()
    print dict(request.POST)
    schematic = request.POST['schematic']
    print schematic
    try:
        sc = ServerCircuit.objects.get(name=circuit)
    except:
        sc = ServerCircuit()
        sc.name = circuit
    sc.schematic = schematic
    print ":", sc.schematic
    sc.save()
    json_str = json.dumps({'results': 'success'})
    response = HttpResponse(json_str, mimetype='application/json')
    response['Cache-Control'] = 'no-cache'
    return response