1 #!/usr/bin/env python 2 3 """ 4 Request helper classes. 5 """ 6 7 class MessageBodyStream: 8 9 """ 10 A naive stream class, providing a non-blocking stream for transactions when 11 reading the message body. According to the HTTP standard, the following 12 things decide how long the message is: 13 14 * Use of the Content-Length header field (see 4.4 Message Length). 15 * Use of the Transfer-Coding header field (see 3.6 Transfer Codings), 16 particularly when the "chunked" coding is used. 17 18 NOTE: For now, we don't support the Transfer-Coding business. 19 """ 20 21 def __init__(self, stream, headers): 22 23 """ 24 Initialise the object with the given underlying 'stream'. The supplied 25 'headers' in a dictionary-style object are used to examine the nature of 26 the request. 27 """ 28 29 self.stream = stream 30 self.headers = headers 31 self.length = int(headers.get("Content-Length") or 0) 32 33 def read(self, limit=None): 34 35 "Reads all remaining data from the message body." 36 37 if limit is not None: 38 limit = min(limit, self.length) 39 else: 40 limit = self.length 41 data = self.stream.read(limit) 42 self.length = self.length - len(data) 43 return data 44 45 def readline(self): 46 47 "Reads a single line of data from the message body." 48 49 data = [] 50 while self.length > 0: 51 data.append(self.read(1)) 52 if data[-1] == "\n": 53 break 54 return "".join(data) 55 56 def readlines(self): 57 58 """ 59 Reads all remaining data from the message body, splitting it into lines 60 and returning the data as a list of lines. 61 """ 62 63 lines = self.read().split("\n") 64 for i in range(0, len(lines) - 1): 65 lines[i] = lines[i] + "\n" 66 return lines 67 68 def close(self): 69 70 "Closes the stream." 71 72 self.stream.close() 73 74 # vim: tabstop=4 expandtab shiftwidth=4