From c2e9f27a50ecd648d95e5fd242d9c5749397dd02 Mon Sep 17 00:00:00 2001 From: Tomasz Fluxid Kowalczyk Date: Sun, 29 Jan 2012 19:34:42 +0100 Subject: [PATCH] Add reponse handling utils for MPC --- syncplay/network_utils.py | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/syncplay/network_utils.py b/syncplay/network_utils.py index 04252e6..07cbd11 100644 --- a/syncplay/network_utils.py +++ b/syncplay/network_utils.py @@ -1,6 +1,14 @@ #coding:utf8 -from twisted.internet.protocol import ProcessProtocol +try: + from cStringIO import StringIO +except ImportError: + from StringIO import StringIO + +from twisted.internet.protocol import ( + ProcessProtocol, + Protocol, +) from twisted.protocols.basic import LineReceiver class CommandProtocol(LineReceiver): @@ -79,3 +87,28 @@ class LineProcessProtocol(ProcessProtocol): for line in lines: self.transport.write(line+'\n') + +class BodyGetter(Protocol): + def __init__(self, length, callback): + self.length = length + self.callback = callback + self.body = StringIO() + + def dataReceived(self, data): + if self.length > 0: + data = data[:self.length] + self.body.write(data) + self.length -= len(length) + + def connectionLost(self, reason): + self.callback(self.body.getvalue()) + +def handle_response(callback): + def defer_callback(response): + status = response.code + headers = response.headers.getAllRawHeaders() + def body_callback(body): + callback(status, headers, body) + response.deliverBody(BodyGetter(response.length, body_callback)) + return defer_callback +