# coding: utf-8


import json
import sys
import code

from io import BytesIO
from tornado import ioloop, web, template, gen

@gen.coroutine
def _eval(request):
    ns = {}
    to_eval = json.loads(request.body)['toEval']
    out, err = sys.stdout, sys.stderr
    fake_stdout, fake_stderr = BytesIO(), BytesIO()
    sys.stdout, sys.stderr = fake_stdout, fake_stderr
    console = code.InteractiveConsole(locals=ns)
    for statement in to_eval.split("\n"):
        if statement:
            console.push(statement)
        else:
            console.push('\n')
    sys.stdout, sys.stderr = out, err

    out_result, err_result = fake_stdout.getvalue(), fake_stderr.getvalue()

    return {"out": out_result,
           "err": err_result
           }


loader = template.Loader('templates')

class MainHandler(web.RequestHandler):
    def get(self):
        self.write(loader.load("main.html").generate())


class EvalHandler(web.RequestHandler):

    @gen.coroutine
    def post(self):
        response = yield _eval(self.request)
        self.write(response)


def make_app():
    return web.Application([
        (r"/", MainHandler),
        (r"/eval", EvalHandler),
        (r'/static/(.*)', web.StaticFileHandler, {'path': 'static/'}),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8080)
    ioloop.IOLoop.current().start()

@@ -69,16 +69,26 @@
  BytesIO
+, StringIO
 %0Afrom to
@@ -212,16 +212,32 @@
 est.body
+.decode('utf-8')
 )%5B'toEva
@@ -313,24 +313,26 @@
 r = 
-BytesIO(), Bytes
+StringIO(), String
 IO()

fix things that broke on python3