This repository was archived by the owner on Dec 31, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathexecutor.py
55 lines (44 loc) · 1.58 KB
/
executor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import json
import marshal
import os
from base64 import b64decode
from contextlib import redirect_stderr, redirect_stdout
from http.server import HTTPServer, SimpleHTTPRequestHandler
from io import StringIO
from .namekeeper import NameKeeper
MARSHAL_RAISES = (KeyError, ValueError, TypeError, EOFError)
nk = NameKeeper()
def execute(code):
global nk
out = StringIO()
err = StringIO()
with redirect_stdout(out), redirect_stderr(err):
_exec = exec
with nk.secure_scope():
_exec(code)
return {"out": out.getvalue(), "err": err.getvalue()}
class Handler(SimpleHTTPRequestHandler):
def do_POST(self, *args, **kwargs):
content_length = int(self.headers["Content-Length"])
raw_body = self.rfile.read(content_length).decode()
print(raw_body)
body = json.loads(raw_body)
try:
code = marshal.loads(b64decode(body["code"]))
self.respond(self.execute(code), 200)
except MARSHAL_RAISES as exc:
print(exc)
self.respond("FAIL", 400)
except Exception as exc:
print(exc)
self.respond("FAIL", 500)
def respond(self, result, code):
self.send_response(code)
self.end_headers()
self.wfile.write(json.dumps({"result": result}).encode())
class Executor:
def __init__(self, host="", port=18888, handler=Handler):
self._httpd = HTTPServer((host, port), handler)
self._httpd.serve_forever()
if __name__ == "__main__":
executor = Executor(port=os.environ.get("EXECUTOR_PORT", 18888), handler=Handler)