In [3]:
import json
import pytest
import requests
import uuid

import aiohttp
import socket
import asyncio
import async_timeout
In [2]:
binder_url = 'https://binder.pangeo.io'
repo = 'pangeo-data/pangeo-ocean-examples'
ref = 'f73b92a'


build_url = binder_url + '/build/gh/{repo}/{ref}'.format(repo=repo, ref=ref)
r = requests.get(build_url, stream=True)
r.raise_for_status()
for line in r.iter_lines():
    line = line.decode('utf8')
    if line.startswith('data:'):
        data = json.loads(line.split(':', 1)[1])
        if data.get('phase') == 'ready':
            notebook_url = data['url']
            token = data['token']
            break
else:
    # This means we never got a 'Ready'!
    assert False

headers = {
    'Authorization': 'token {}'.format(token)
}
r = requests.get(notebook_url + '/api', headers=headers)
assert r.status_code == 200
assert 'version' in r.json()
In [3]:
notebook_url
Out[3]:
'https://hub.binder.pangeo.io/user/pangeo-data-pan--ocean-examples-hvj3tn0e/'
In [4]:
r = requests.post(notebook_url + '/api/kernels', headers=headers)
r.raise_for_status()
r.json()
Out[4]:
{'connections': 0,
 'execution_state': 'starting',
 'id': '856a5eb4-0cc3-4182-b4fa-83e631f85dce',
 'last_activity': '2019-08-23T22:26:59.938798Z',
 'name': 'python3'}
In [5]:
kernel_id = r.json()['id']
kernel_id
Out[5]:
'856a5eb4-0cc3-4182-b4fa-83e631f85dce'
In [6]:
r_kernels = requests.get(notebook_url + '/api/kernels', headers=headers)
r_kernels.raise_for_status()
r_kernels.json()
Out[6]:
[{'connections': 0,
  'execution_state': 'starting',
  'id': '856a5eb4-0cc3-4182-b4fa-83e631f85dce',
  'last_activity': '2019-08-23T22:26:59.938798Z',
  'name': 'python3'}]
In [7]:
channel_url =  f'{notebook_url}api/kernels/{kernel_id}/channels'
channel_url
Out[7]:
'https://hub.binder.pangeo.io/user/pangeo-data-pan--ocean-examples-hvj3tn0e/api/kernels/856a5eb4-0cc3-4182-b4fa-83e631f85dce/channels'
In [8]:
ws_url = channel_url.replace('https', 'wss')
ws_url
Out[8]:
'wss://hub.binder.pangeo.io/user/pangeo-data-pan--ocean-examples-hvj3tn0e/api/kernels/856a5eb4-0cc3-4182-b4fa-83e631f85dce/channels'
In [9]:
headers
Out[9]:
{'Authorization': 'token FCMKpu2XSSaJsav8Je_kww'}
In [10]:
import websocket
ws = websocket.WebSocket()
ws.connect(ws_url, header=headers)
ws
Out[10]:
<websocket._core.WebSocket at 0x10dd141d0>
In [11]:
ws.getstatus()
Out[11]:
101
In [13]:
def request_execute_code(msg_id, code):
    message = {
        "header": {
            "msg_id": msg_id,
            "username": "jovyan",
            "msg_type": "execute_request",
            "version": "5.2"
        },
        "metadata": {},
        "content": {
            "code": code,
            "silent": False,
            "store_history": True,
            "user_expressions": {},
            "allow_stdin": True,
            "stop_on_error": True
        },
        "buffers": [],
        "parent_header": {},
        "channel": "shell"
    }
    return json.dumps(message)
    
In [14]:
msg_id = str(uuid.uuid4())
code = "print('hello world')"
payload = request_execute_code(msg_id, code)
payload
Out[14]:
'{"header": {"msg_id": "79018a6b-14a8-47a8-9317-1b4d8864379a", "username": "jovyan", "msg_type": "execute_request", "version": "5.2"}, "metadata": {}, "content": {"code": "print(\'hello world\')", "silent": false, "store_history": true, "user_expressions": {}, "allow_stdin": true, "stop_on_error": true}, "buffers": [], "parent_header": {}, "channel": "shell"}'
In [15]:
len(payload)
Out[15]:
358
In [16]:
ws.send(payload)
Out[16]:
366
In [18]:
ws.recv?
Signature: ws.recv()
Docstring:
Receive string data(byte array) from the server.

return value: string(byte array) value.
File:      ~/miniconda3/envs/geo_scipy/lib/python3.6/site-packages/websocket/_core.py
Type:      method
In [17]:
result = ws.recv()
result
---------------------------------------------------------------------------
BrokenPipeError                           Traceback (most recent call last)
<ipython-input-17-5987a911995d> in <module>()
----> 1 result = ws.recv()
      2 result

~/miniconda3/envs/geo_scipy/lib/python3.6/site-packages/websocket/_core.py in recv(self)
    298         """
    299         with self.readlock:
--> 300             opcode, data = self.recv_data()
    301         if six.PY3 and opcode == ABNF.OPCODE_TEXT:
    302             return data.decode("utf-8")

~/miniconda3/envs/geo_scipy/lib/python3.6/site-packages/websocket/_core.py in recv_data(self, control_frame)
    315         return  value: tuple of operation code and string(byte array) value.
    316         """
--> 317         opcode, frame = self.recv_data_frame(control_frame)
    318         return opcode, frame.data
    319 

~/miniconda3/envs/geo_scipy/lib/python3.6/site-packages/websocket/_core.py in recv_data_frame(self, control_frame)
    346             elif frame.opcode == ABNF.OPCODE_PING:
    347                 if len(frame.data) < 126:
--> 348                     self.pong(frame.data)
    349                 else:
    350                     raise WebSocketProtocolException(

~/miniconda3/envs/geo_scipy/lib/python3.6/site-packages/websocket/_core.py in pong(self, payload)
    289         if isinstance(payload, six.text_type):
    290             payload = payload.encode("utf-8")
--> 291         self.send(payload, ABNF.OPCODE_PONG)
    292 
    293     def recv(self):

~/miniconda3/envs/geo_scipy/lib/python3.6/site-packages/websocket/_core.py in send(self, payload, opcode)
    238 
    239         frame = ABNF.create_frame(payload, opcode)
--> 240         return self.send_frame(frame)
    241 
    242     def send_frame(self, frame):

~/miniconda3/envs/geo_scipy/lib/python3.6/site-packages/websocket/_core.py in send_frame(self, frame)
    263         with self.lock:
    264             while data:
--> 265                 l = self._send(data)
    266                 data = data[l:]
    267 

~/miniconda3/envs/geo_scipy/lib/python3.6/site-packages/websocket/_core.py in _send(self, data)
    428 
    429     def _send(self, data):
--> 430         return send(self.sock, data)
    431 
    432     def _recv(self, bufsize):

~/miniconda3/envs/geo_scipy/lib/python3.6/site-packages/websocket/_socket.py in send(sock, data)
    115 
    116     try:
--> 117         return sock.send(data)
    118     except socket.timeout as e:
    119         message = extract_err_message(e)

~/miniconda3/envs/geo_scipy/lib/python3.6/ssl.py in send(self, data, flags)
    942                     "non-zero flags not allowed in calls to send() on %s" %
    943                     self.__class__)
--> 944             return self._sslobj.write(data)
    945         else:
    946             return socket.send(self, data, flags)

~/miniconda3/envs/geo_scipy/lib/python3.6/ssl.py in write(self, data)
    640         The 'data' argument must support the buffer interface.
    641         """
--> 642         return self._sslobj.write(data)
    643 
    644     def getpeercert(self, binary_form=False):

BrokenPipeError: [Errno 32] Broken pipe
In [ ]: