Skip to content
This repository was archived by the owner on Jan 13, 2021. It is now read-only.

Commit 841ecfa

Browse files
committed
Add methods to HTTP20Response for trailers.
Right now these methods match the `httplib` API, but with 'headers' replaced with 'trailers'. I'm not happy about this, and one day I hope to be able to abandon the `httplib` API, but right now we just can't.
1 parent 06b5d10 commit 841ecfa

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

hyper/http20/response.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,9 @@ def __init__(self, headers, stream):
111111
# once, and never assigned again.
112112
self._headers = Headers(headers)
113113

114+
# The response trailers. These are always intially ``None``.
115+
self._trailers = None
116+
114117
# The stream this response is being sent over.
115118
self._stream = stream
116119

@@ -198,6 +201,48 @@ def getheaders(self):
198201
"""
199202
return list(self._headers.items())
200203

204+
def gettrailer(self, name, default=None):
205+
"""
206+
Return the value of the trailer ``name``, or ``default`` if there is no
207+
trailer matching ``name``. If there is more than one trailer with the
208+
value ``name``, return all of the values joined by ', '. If ``default``
209+
is any iterable other than a single string, its elements are similarly
210+
returned joined by commas.
211+
212+
.. warning:: Note that this method requires that the stream is
213+
totally exhausted. This means that, if you have not
214+
completely read from the stream, all stream data will be
215+
read into memory.
216+
217+
:param name: The name of the trailer to get the value of.
218+
:param default: (optional) The return value if the trailer wasn't sent.
219+
:returns: The value of the trailer.
220+
"""
221+
# We need to get the trailers.
222+
if self._trailers is None:
223+
trailers = self.stream.gettrailers() or []
224+
self._trailers = Headers(trailers)
225+
226+
return self._trailers.getheader(name, default)
227+
228+
def gettrailers(self):
229+
"""
230+
Get all the trailers sent on the response.
231+
232+
.. warning:: Note that this method requires that the stream is
233+
totally exhausted. This means that, if you have not
234+
completely read from the stream, all stream data will be
235+
read into memory.
236+
237+
:returns: A list of ``(header, value)`` tuples.
238+
"""
239+
# We need to get the trailers.
240+
if self._trailers is None:
241+
trailers = self.stream.gettrailers() or []
242+
self._trailers = Headers(trailers)
243+
244+
return list(self._trailers.items())
245+
201246
def fileno(self):
202247
"""
203248
Return the ``fileno`` of the underlying socket. This function is

0 commit comments

Comments
 (0)