1
0
mirror of https://github.com/binary-kitchen/doorlockd synced 2024-12-22 10:24:26 +01:00

EventClient.py: implement small reads an refactor

use read1() for smaller latency. Refactor message parsing

Signed-off-by: Thomas Schmid <tom@lfence.de>
This commit is contained in:
Thomas 2020-10-08 21:08:34 +02:00
parent 7153eecd57
commit 90c4e9f6cf

View File

@ -3,31 +3,43 @@ import threading
import json import json
class EventClient: class EventClient:
def __init__(self,url): def __init__(self,url, chunk_size = 1024):
self.chunk_size = chunk_size
self.r = requests.get(url,stream=True) self.r = requests.get(url,stream=True)
if self.r.encoding is None: if self.r.encoding is None:
self.r.encoding = 'utf8' self.r.encoding = 'utf8'
def parseEvent(self,line_buf): def parseEvent(self, raw):
ret = dict() lines = raw.splitlines()
for line in line_buf: data = dict()
if line: for line in lines:
k,v = line.decode().split(':',1) k,v = line.split(":",1)
ret[k] = v if data.get(k):
return ret data[k] += v
data[k] = v
return data
def events(self): def events(self):
lines = self.r.iter_lines() def generate():
line_buf = [] sbuf = ""
while True: while True:
line_buf.append(next(lines)) bbuf = self.r.raw._fp.fp.read1(self.chunk_size)
if line_buf:
if not line_buf[-1].decode(): if not bbuf:
yield self.parseEvent(line_buf) break
line_buf = []
sbuf += bbuf.decode('utf8')
parts = sbuf.split('\n\n')
if len(parts) > 1:
for p in parts[0:-1]:
yield self.parseEvent(p)
sbuf = parts[-1]
return generate()
if __name__ == "__main__": if __name__ == "__main__":
e = EventClient("http://localhost:8080/push") while True:
for evt in e.events(): e = EventClient("http://localhost:5000/push")
print(json.loads(evt['data'])) for evt in e.events():
print(json.loads(evt['data']))