MCPcopy
hub / github.com/USArmyResearchLab/Dshell / HTTPResponse

Class HTTPResponse

dshell/plugins/httpplugin.py:142–198  ·  view source on GitHub ↗

A class for HTTP responses Attributes: blob : the Blob instance of the request errors : a list of caught exceptions from parsing version : the HTTP version (e.g. "1.1" for "HTTP/1.1") status : the status code of the response (e.g. "200" or "304")

Source from the content-addressed store, hash-verified

140
141
142class HTTPResponse(object):
143 """
144 A class for HTTP responses
145
146 Attributes:
147 blob : the Blob instance of the request
148 errors : a list of caught exceptions from parsing
149 version : the HTTP version (e.g. "1.1" for "HTTP/1.1")
150 status : the status code of the response (e.g. "200" or "304")
151 reason : the status text of the response (e.g. "OK" or "Not Modified")
152 headers : a dictionary containing the headers and values
153 body : bytestring of the reassembled body, after the headers
154 """
155 def __init__(self, blob):
156 self.errors = []
157 self.headers = {}
158 self.body = b''
159 self.blob = blob
160 data = io.BytesIO(blob.data)
161 rawline = data.readline()
162 try:
163 line = rawline.decode('utf-8')
164 except UnicodeDecodeError:
165 line = ''
166 l = line.strip().split(None, 2)
167 if len(l) < 2 or not l[0].startswith("HTTP") or not l[1].isdigit():
168 self.errors.append(dshell.core.DataError('invalid HTTP response: {!r}'.format(rawline)))
169 self.version = ''
170 self.status = ''
171 self.reason = ''
172 return
173 else:
174 self.version = l[0][5:]
175 self.status = l[1]
176 self.reason = l[2]
177 self.headers = parse_headers(self, data)
178 self.body = parse_body(self, data, self.headers)
179
180 def decompress_gzip_content(self):
181 """
182 If this response has Content-Encoding set to something with "gzip",
183 this function will decompress it and store it in the body.
184 """
185 if "gzip" in self.headers.get("content-encoding", ""):
186 try:
187 iobody = io.BytesIO(self.body)
188 except TypeError as e:
189 # TODO: Why would body ever not be bytes? If it's not bytes, then that means
190 # we have a bug somewhere in the code and therefore should just allow the
191 # original exception to be raised.
192 self.errors.append(dshell.core.DataError("Body was not a byte string ({!s}). Could not decompress.".format(type(self.body))))
193 return
194 try:
195 self.body = gzip.GzipFile(fileobj=iobody).read()
196 except OSError as e:
197 self.errors.append(OSError("Could not gunzip body. {!s}".format(e)))
198 return
199

Callers 1

connection_handlerMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected