Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagecell
Path: blob/master/tests/multimechanize/test_scripts/client.py
447 views
1
import urllib2
2
import websocket
3
import json
4
import uuid
5
6
root = "http://localhost:8888"
7
8
class SageCellSession(object):
9
def __init__(self):
10
f = urllib2.urlopen("%s/kernel" % (root,), "")
11
data = json.loads(f.read())
12
f.close()
13
self.kernel_id = data["kernel_id"]
14
self.ws_url = data["ws_url"]
15
self.iopub = websocket.create_connection("%skernel/%s/iopub" % (self.ws_url, self.kernel_id))
16
self.shell = websocket.create_connection("%skernel/%s/shell" % (self.ws_url, self.kernel_id))
17
self.session_id = str(uuid.uuid4())
18
19
def __del__(self):
20
self.close()
21
22
def __enter__(self):
23
return self
24
25
def __exit__(self, etype, value, traceback):
26
self.close()
27
28
def execute(self, code):
29
content = {"code": code,
30
"silent": False,
31
"user_variables": [],
32
"user_expressions": {"_sagecell_files": "sys._sage_.new_files()"},
33
"allow_stdin": False}
34
self.send_msg("execute_request", content)
35
36
def update_interact(self, interact_id, values):
37
self.execute("sys._sage_.update_interact(%r, %r)" % (interact_id, values))
38
39
def send_msg(self, msg_type, content):
40
msg = {"header": {"msg_id": str(uuid.uuid4()),
41
"username": "username",
42
"session": self.session_id,
43
"msg_type": msg_type
44
},
45
"metadata": {},
46
"content": content,
47
"parent_header":{}
48
}
49
self.shell.send(json.dumps(msg))
50
51
def close(self):
52
self.iopub.close()
53
self.shell.close()
54
55
def iopub_recv(self):
56
return json.loads(self.iopub.recv())
57
58
def shell_recv(self):
59
return json.loads(self.shell.recv())
60
61
def load_root():
62
resources = ["/", "/static/root.css", "/static/jquery.min.js",
63
"/static/embedded_sagecell.js",
64
"/static/jquery-ui/css/sagecell/jquery-ui-1.8.21.custom.css",
65
"/static/colorpicker/css/colorpicker.css",
66
"/static/all.min.css", "/static/mathjax/MathJax.js",
67
"/static/sagelogo.png", "/static/spinner.gif",
68
"/sagecell.html", "/static/all.min.js",
69
"/static/mathjax/config/TeX-AMS-MML_HTMLorMML.js",
70
"/static/mathjax/images/MenuArrow-15.png",
71
"/static/jquery-ui/css/sagecell/images/ui-bg_highlight-hard_60_99bbff_1x100.png",
72
"/static/mathjax/extensions/jsMath2jax.js",
73
"/static/jquery-ui/css/sagecell/images/ui-bg_highlight-hard_90_99bbff_1x100.png"]
74
for r in resources:
75
f = urllib2.urlopen(root + r)
76
assert f.code == 200, "Bad response: HTTP %d" % (f.code,)
77
78