|
1 | 1 | import requests |
2 | 2 | import json |
3 | 3 | import warnings |
| 4 | +import httplib |
4 | 5 |
|
5 | 6 | from .version import __version__ |
6 | 7 |
|
@@ -250,5 +251,53 @@ def __makecall(self, args, un, key, origin, kwargs): |
250 | 251 |
|
251 | 252 | return r |
252 | 253 |
|
| 254 | +class stream: |
| 255 | + def __init__(self, token): |
| 256 | + ''' plotly stream constructor |
| 257 | + token found at https://plot.ly/settings |
| 258 | + ''' |
| 259 | + self.token = token |
| 260 | + self.connected = False |
| 261 | + |
| 262 | + def init(self): |
| 263 | + ''' Initialize a streaming connection to plotly |
| 264 | + ''' |
| 265 | + self.conn = httplib.HTTPConnection('stream.plot.ly', 80) |
| 266 | + self.conn.putrequest('POST', '/') |
| 267 | + self.conn.putheader('Host', 'stream.plot.ly') |
| 268 | + self.conn.putheader('User-Agent', 'Python-Plotly') |
| 269 | + self.conn.putheader('Transfer-Encoding', 'chunked') |
| 270 | + self.conn.putheader('Connection', 'close') |
| 271 | + self.conn.putheader('plotly-streamtoken', self.token) |
| 272 | + self.conn.endheaders() |
| 273 | + self.connected=True |
| 274 | + |
| 275 | + def write(self, data): |
| 276 | + ''' Write data to plotly's streaming servers |
253 | 277 |
|
| 278 | + data is a plotly formatted data dict |
| 279 | + with data keys 'x', 'y', 'text', 'z', 'marker', 'line' |
| 280 | + 'x', 'y', 'text', and 'z' can have values of strings, numbers, or lists |
| 281 | + 'marker', and 'line' have dicts as values with keys 'size', 'color', 'symbol' |
254 | 282 |
|
| 283 | + Examples: |
| 284 | + {'x': 1, 'y': 2} |
| 285 | + {'x': [1, 2, 3], 'y': [10, 20, 30]} |
| 286 | + {'x': 1, 'y': 3, 'text': 'hover text'} |
| 287 | + {'x': 1, 'y': 3, 'marker': {'color': 'blue'}} |
| 288 | + {'z': [[1,2,3], [4,5,6]]} |
| 289 | + ''' |
| 290 | + if not self.connected: |
| 291 | + self.init() |
| 292 | + # plotly's streaming API takes new-line separated json objects |
| 293 | + msg = json.dumps(data)+'\n' |
| 294 | + msglen = format(len(msg), 'x') |
| 295 | + # chunked encoding requests contain the messege length in hex, \r\n, and then the message |
| 296 | + self.conn.send('{msglen}\r\n{msg}\r\n'.format(msglen=msglen, msg=msg)) |
| 297 | + |
| 298 | + def close(self): |
| 299 | + ''' Close connection to plotly's streaming servers |
| 300 | + ''' |
| 301 | + self.conn.send('0\r\n\r\n') |
| 302 | + self.conn.close() |
| 303 | + self.connected=False |
0 commit comments