4
# python-console <port> <magic>
15
from threading import Thread
17
class StdinFromWeb(object):
18
def __init__(self, cmdQ, lineQ):
25
self.cmdQ.put({"input":None})
29
# Some of our 5 seconds may have elapsed, but never mind.
33
class PythonRunner(Thread):
34
def __init__(self, cmdQ, lineQ):
41
compiler = codeop.CommandCompiler()
47
if self.curr_cmd == '':
48
self.curr_cmd = ln['chat']
50
self.curr_cmd = self.curr_cmd + '\n' + ln['chat']
52
cmd = compiler(self.curr_cmd)
54
# The command was incomplete,
55
# so send back a None, so the
56
# client can print a '...'
57
self.cmdQ.put({"more":None})
59
# The command was complete,
61
sys.stdin = StdinFromWeb(self.cmdQ, self.lineQ)
62
self.out = cStringIO.StringIO()
66
res = eval(cmd, globs, locls)
68
self.cmdQ.put({"okay":(self.out.getvalue(),res)})
70
except Exception, exc:
72
self.cmdQ.put({"exc":(self.out.getvalue(),str(exc))})
75
# throw away a partial command.
78
cmd = compile(ln['block'], "<web session>", 'exec');
80
sys.stdin = StdinFromWeb(self.cmdQ, self.lineQ)
81
self.out = cStringIO.StringIO()
85
res = eval(cmd, globs, locls)
87
self.cmdQ.put({"okay":(self.out.getvalue(),res)})
89
except Exception, exc:
91
self.cmdQ.put({"exc":(self.out.getvalue(),str(exc))})
95
self.globs['__builtins__'] = globals()['__builtins__']
103
# The global 'magic' is the secret that the client and server share
104
# which is used to create and md5 digest to authenticate requests.
105
# It is assigned a real value at startup.
114
digest = md5.new(inp.text + magic).digest().encode('hex')
115
if inp.digest != digest:
116
web.output("401 Unauthorized")
117
web.ctx.status = '401 Unauthorized'
120
# Okay, so the authentication succeeded,
121
# so now we have the trivial matter of actually
122
# executing the python....
123
lineQ.put({'chat':inp.text})
125
sys.__stderr__.write(cjson.encode(r) + "\n")
126
web.output(cjson.encode(r))
134
digest = md5.new(inp.text + magic).digest().encode('hex')
135
if inp.digest != digest:
136
web.output("401 Unauthorized")
137
web.ctx.status = '401 Unauthorized'
140
# Okay, so the authentication succeeded,
141
# so now we have the trivial matter of actually
142
# executing the python....
143
lineQ.put({'block':inp.text})
145
sys.__stderr__.write(cjson.encode(r) + "\n")
146
web.output(cjson.encode(r))
149
lineQ = Queue.Queue()
150
interpThread = PythonRunner(cmdQ, lineQ)
152
if __name__ == "__main__":
154
interpThread.setDaemon(True)
156
web.run(urls, globals())