OLD | NEW |
(Empty) | |
| 1 import BaseHTTPServer |
| 2 import base64 |
| 3 import json |
| 4 import logging |
| 5 import string |
| 6 import subprocess |
| 7 |
| 8 HOST_NAME = 'localhost' |
| 9 PORT_NUMBER = 8765 |
| 10 |
| 11 def runCode(usercode): |
| 12 f = open('template.cpp', 'rb') |
| 13 template = string.Template(f.read()) |
| 14 f.close() |
| 15 |
| 16 code = template.substitute(usercode=usercode) |
| 17 |
| 18 f = open('result.cpp', 'wb') |
| 19 f.write(code) |
| 20 f.close() |
| 21 |
| 22 msg = "" |
| 23 img = "" |
| 24 try: |
| 25 logging.info("compiling") |
| 26 msg = subprocess.check_output('ninja -C ../../out/Debug webtry'.split()) |
| 27 try: |
| 28 logging.info("running") |
| 29 msg = subprocess.check_output('../../out/Debug/webtry'.split()) |
| 30 f = open('foo.png', 'rb') |
| 31 img = base64.b64encode(f.read()) |
| 32 f.close() |
| 33 except subprocess.CalledProcessError as e: |
| 34 logging.info(e) |
| 35 msg = e.output |
| 36 except subprocess.CalledProcessError as e: |
| 37 logging.info(e) |
| 38 msg = e.output |
| 39 |
| 40 retval = { |
| 41 'message': msg |
| 42 } |
| 43 if img: |
| 44 retval['img'] = img |
| 45 return retval |
| 46 |
| 47 class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler): |
| 48 def do_POST(self): |
| 49 logging.info("POST") |
| 50 body = "" |
| 51 l = self.rfile.readline() |
| 52 while l.strip() != "EOF": |
| 53 body += l |
| 54 l = self.rfile.readline() |
| 55 self.send_response(200) |
| 56 self.send_header("Content-type", "application/json") |
| 57 self.end_headers() |
| 58 resp = runCode(body) |
| 59 self.wfile.write(json.dumps(resp)) |
| 60 self.end_headers() |
| 61 |
| 62 def do_GET(self): |
| 63 """Respond to a GET request.""" |
| 64 self.send_response(200) |
| 65 self.send_header("Content-type", "text/html") |
| 66 self.end_headers() |
| 67 f = open('index.html', 'rb') |
| 68 self.wfile.write(f.read()) |
| 69 f.close() |
| 70 |
| 71 if __name__ == '__main__': |
| 72 server_class = BaseHTTPServer.HTTPServer |
| 73 httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler) |
| 74 logging.info("Server Start: %s:%s" % (HOST_NAME, PORT_NUMBER)) |
| 75 try: |
| 76 httpd.serve_forever() |
| 77 except KeyboardInterrupt: |
| 78 pass |
| 79 httpd.server_close() |
OLD | NEW |