Handling Streaming Responses
In addition to receiving responses
with :meth:`IResponse.deliverBody`, treq provides a helper function
:py:func:`treq.collect` which takes a
response and a single argument function which will be called with all new
data available from the response. Much like :meth:`IProtocol.dataReceived`,
:py:func:`treq.collect` knows nothing about the framing of your data and will
simply call your collector function with any data that is currently available.
Here is an example which simply a file object's write method to :py:func:`treq.collect` to save the response body to a file.
Full example: :download:`download_file.py <examples/download_file.py>`
:py:func:`treq.request` supports a
params keyword argument which will
be URL-encoded and added to the
url argument in addition to any query
parameters that may already exist.
params argument may be either a
dict or a
(key, value) tuples.
If it is a
dict then the values in the dict may either be a
Full example: :download:`query_params.py <examples/query_params.py>`
HTTP Basic authentication as specified in RFC 2617 is easily supported by
auth keyword argument to any of the request functions.
auth argument should be a tuple of the form
Full example: :download:`basic_auth.py <examples/basic_auth.py>`
treq handles redirects by default.
The following will print a 200 OK response.
Full example: :download:`redirects.py <examples/redirects.py>`
You can easily disable redirects by simply passing allow_redirects=False to any of the request methods.
You can even access the complete history of treq response objects by calling the :meth:`~treq.response._Response.history()` method on the response.
Cookies can be set by passing a
cookies keyword argument. Later cookies set by the server can be
retrieved using the :py:meth:`~treq.response._Response.cookies()` method.
Full example: :download:`using_cookies.py <examples/using_cookies.py>`
treq creates its own twisted.web.client.Agent
with reasonable defaults, but you may want to provide your own custom agent.
A custom agent can be passed to the various treq request methods using the
agent keyword argument.
custom_agent = Agent(reactor, connectTimeout=42) treq.get(url, agent=custom_agent)