Mercurial > code > home > repos > homeauto
comparison lib/twisted_sse_demo/sse_client.py @ 1156:ee168d55524a
reasoning & collector move into docker images
Ignore-this: 67e97d307eba96791cbe77e57c57ad57
darcs-hash:47056d579a870b473e95f4eb7897aae0a97c03cc
author | drewp <drewp@bigasterisk.com> |
---|---|
date | Mon, 03 Sep 2018 00:45:34 -0700 |
parents | |
children | 81ab17e377b7 |
comparison
equal
deleted
inserted
replaced
1155:3d478b05f9b1 | 1156:ee168d55524a |
---|---|
1 from twisted.protocols.basic import LineReceiver | |
2 | |
3 | |
4 class EventSourceProtocol(LineReceiver): | |
5 def __init__(self): | |
6 self.MAX_LENGTH = 1 << 20 | |
7 self.callbacks = {} | |
8 self.finished = None | |
9 # Initialize the event and data buffers | |
10 self.event = 'message' | |
11 self.data = '' | |
12 | |
13 def lineLengthExceeded(self, line): | |
14 print "line too long" | |
15 raise NotImplementedError | |
16 | |
17 def setFinishedDeferred(self, d): | |
18 self.finished = d | |
19 | |
20 def addCallback(self, event, func): | |
21 self.callbacks[event] = func | |
22 | |
23 def lineReceived(self, line): | |
24 if line == '': | |
25 # Dispatch event | |
26 self.dispatchEvent() | |
27 else: | |
28 try: | |
29 field, value = line.split(':', 1) | |
30 # If value starts with a space, strip it. | |
31 value = lstrip(value) | |
32 except ValueError: | |
33 # We got a line with no colon, treat it as a field(ignore) | |
34 return | |
35 | |
36 if field == '': | |
37 # This is a comment; ignore | |
38 pass | |
39 elif field == 'data': | |
40 self.data += value + '\n' | |
41 elif field == 'event': | |
42 self.event = value | |
43 elif field == 'id': | |
44 # Not implemented | |
45 pass | |
46 elif field == 'retry': | |
47 # Not implemented | |
48 pass | |
49 | |
50 def connectionLost(self, reason): | |
51 if self.finished: | |
52 self.finished.callback(None) | |
53 | |
54 def dispatchEvent(self): | |
55 """ | |
56 Dispatch the event | |
57 """ | |
58 # If last character is LF, strip it. | |
59 if self.data.endswith('\n'): | |
60 self.data = self.data[:-1] | |
61 if self.event in self.callbacks: | |
62 self.callbacks[self.event](self.data) | |
63 self.data = '' | |
64 self.event = 'message' | |
65 | |
66 def lstrip(value): | |
67 return value[1:] if value.startswith(' ') else value |