Permalink
Fetching contributors…
Cannot retrieve contributors at this time
118 lines (80 sloc) 3.65 KB

Use Cases

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>`

Query Parameters

: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.

The params argument may be either a dict or a list of (key, value) tuples.

If it is a dict then the values in the dict may either be a str value or a list of str values.

Full example: :download:`query_params.py <examples/query_params.py>`

Auth

HTTP Basic authentication as specified in RFC 2617 is easily supported by passing an auth keyword argument to any of the request functions.

The auth argument should be a tuple of the form ('username', 'password').

Full example: :download:`basic_auth.py <examples/basic_auth.py>`

Redirects

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.

Full example: :download:`disable_redirects.py <examples/disable_redirects.py>`

You can even access the complete history of treq response objects by calling the :meth:`~treq.response._Response.history()` method on the response.

Full example: :download:`response_history.py <examples/response_history.py>`

Cookies

Cookies can be set by passing a dict or cookielib.CookieJar instance via the cookies keyword argument. Later cookies set by the server can be retrieved using the :py:meth:`~treq.response._Response.cookies()` method.

The object returned by :py:meth:`~treq.response._Response.cookies()` supports the same key/value access as requests cookies.

Full example: :download:`using_cookies.py <examples/using_cookies.py>`

Agent Customization

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)