1. Matthew Turk
  2. yt.web_interactors

Source

yt.web_interactors / interact.py

from var_types import VariableType
from disp_types import DisplayType
import yt.utilities.bottle as bottle

template = r"""
<HTML><BODY>
<TABLE>
<TR>
    <TD>%(rv)s</TD>
</TR>
<TR>
    <TD>%(iv)s</TD>
</TR>
</TABLE>
</BODY></HTML>
"""

class Interactor(object):
    _setup = False
    _value = None
    def __init__(self, *args, **kwargs):
        self.setup_arguments(*args, **kwargs)

    def __call__(self, *args, **kwargs):
        if self._setup is False:
            assert(len(args) == 1)
            assert(len(kwargs) == 0)
            self.func = args[0]
            self._setup = True
            return self
        else:
            return self.func(*args, **kwargs)

    def setup_arguments(self, *args, **kwargs):
        print "Setting up", args, kwargs
        assert(len(args) == 0)
        self.parameters = {}
        self.returns = None
        for name, val in kwargs.items():
            if isinstance(val, VariableType):
                print "    %s = %s" % (name, val.name)
                self.parameters[name] = val
            elif isinstance(val, DisplayType):
                print "    %s = %s" % (name, val.name)
                self.returns = val
            else:
                raise RuntimeError

    def serve(self):
        print "Serving"
        bottle.debug(True)
        app = bottle.Bottle()
        app.route("/call", method="POST")(self.respond)
        app.route("/", method="GET")(self.index)
        app.route("/bootstrap/:path#.+#")(self.static_bootstrap)
        bottle.run(app, host = "0.0.0.0")
        print "Terminating serving."

    def static_bootstrap(self, path):
        return bottle.static_file(path, "bootstrap/")

    def respond(self):
        arglist = {}
        print "Hello, responding"
        for name in self.parameters:
            fv = bottle.request.forms.get(name)
            print "NAME %s : %s" % (name, fv)
            arglist[name] = self.parameters[name].cast(fv)
        print arglist
        self._value = self.func(**arglist)
        print self._value
        bottle.redirect("/")

    def index(self):
        template = open("index.html").read()
        tpl = bottle.SimpleTemplate(template)
        tr = tpl.render(return_value = self.returns,
                        input_values = self.parameters,
                        func_value = self._value
                        )
        self._value = None
        return tr