1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/WebStack/Helpers/Request.py Sun Feb 08 18:16:05 2004 +0000
1.3 @@ -0,0 +1,74 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +"""
1.7 +Request helper classes.
1.8 +"""
1.9 +
1.10 +class MessageBodyStream:
1.11 +
1.12 + """
1.13 + A naive stream class, providing a non-blocking stream for transactions when
1.14 + reading the message body. According to the HTTP standard, the following
1.15 + things decide how long the message is:
1.16 +
1.17 + * Use of the Content-Length header field (see 4.4 Message Length).
1.18 + * Use of the Transfer-Coding header field (see 3.6 Transfer Codings),
1.19 + particularly when the "chunked" coding is used.
1.20 +
1.21 + NOTE: For now, we don't support the Transfer-Coding business.
1.22 + """
1.23 +
1.24 + def __init__(self, stream, headers):
1.25 +
1.26 + """
1.27 + Initialise the object with the given underlying 'stream'. The supplied
1.28 + 'headers' in a dictionary-style object are used to examine the nature of
1.29 + the request.
1.30 + """
1.31 +
1.32 + self.stream = stream
1.33 + self.headers = headers
1.34 + self.length = int(headers.get("Content-Length") or 0)
1.35 +
1.36 + def read(self, limit=None):
1.37 +
1.38 + "Reads all remaining data from the message body."
1.39 +
1.40 + if limit is not None:
1.41 + limit = min(limit, self.length)
1.42 + else:
1.43 + limit = self.length
1.44 + data = self.stream.read(limit)
1.45 + self.length = self.length - len(data)
1.46 + return data
1.47 +
1.48 + def readline(self):
1.49 +
1.50 + "Reads a single line of data from the message body."
1.51 +
1.52 + data = []
1.53 + while self.length > 0:
1.54 + data.append(self.read(1))
1.55 + if data[-1] == "\n":
1.56 + break
1.57 + return "".join(data)
1.58 +
1.59 + def readlines(self):
1.60 +
1.61 + """
1.62 + Reads all remaining data from the message body, splitting it into lines
1.63 + and returning the data as a list of lines.
1.64 + """
1.65 +
1.66 + lines = self.read().split("\n")
1.67 + for i in range(0, len(lines) - 1):
1.68 + lines[i] = lines[i] + "\n"
1.69 + return lines
1.70 +
1.71 + def close(self):
1.72 +
1.73 + "Closes the stream."
1.74 +
1.75 + self.stream.close()
1.76 +
1.77 +# vim: tabstop=4 expandtab shiftwidth=4