API Reference

This page lists all of the interfaces exposed by the treq package.

Making Requests

treq.request(method, url, **kwargs)[source]

Make an HTTP request.

Parameters:
  • method (str) – HTTP method. Example: 'GET', 'HEAD'. 'PUT', 'POST'.
  • url (str) – http or https URL, which may include query arguments.
  • headers (Headers or None) – Optional HTTP Headers to send with this request.
  • params (dict w/ str or list/tuple of str values, list of 2-tuples, or None.) – Optional parameters to be append as the query string to the URL, any query string parameters in the URL already will be preserved.
  • data (str, file-like, IBodyProducer, or None) – Optional request body.
  • json (dict, list/tuple, int, string/unicode, bool, or None) – Optional JSON-serializable content to pass in body.
  • reactor – Optional twisted reactor.
  • persistent (bool) – Use persistent HTTP connections. Default: True
  • allow_redirects (bool) – Follow HTTP redirects. Default: True
  • auth (tuple of ('username', 'password').) – HTTP Basic Authentication information.
  • cookies (dict or cookielib.CookieJar) – Cookies to send with this request. The HTTP kind, not the tasty kind.
  • timeout (int) – Request timeout seconds. If a response is not received within this timeframe, a connection is aborted with CancelledError.
  • browser_like_redirects (bool) – Use browser like redirects (i.e. Ignore RFC2616 section 10.3 and follow redirects from POST requests). Default: False
  • unbuffered (bool) – Pass True to to disable response buffering. By default treq buffers the entire response body in memory.
Return type:

Deferred that fires with an IResponse provider.

treq.get(url, headers=None, **kwargs)[source]

Make a GET request.

See treq.request()

treq.head(url, **kwargs)[source]

Make a HEAD request.

See treq.request()

treq.post(url, data=None, **kwargs)[source]

Make a POST request.

See treq.request()

treq.put(url, data=None, **kwargs)[source]

Make a PUT request.

See treq.request()

treq.patch(url, data=None, **kwargs)[source]

Make a PATCH request.

See treq.request()

treq.delete(url, **kwargs)[source]

Make a DELETE request.

See treq.request()

Accessing Content

treq.collect(response, collector)[source]

Incrementally collect the body of the response.

This function may only be called once for a given response.

Parameters:
  • response (IResponse) – The HTTP response to collect the body from.
  • collector (single argument callable) – A callable to be called each time data is available from the response body.
Return type:

Deferred that fires with None when the entire body has been read.

treq.content(response)[source]

Read the contents of an HTTP response.

This function may be called multiple times for a response, it uses a WeakKeyDictionary to cache the contents of the response.

Parameters:response (IResponse) – The HTTP Response to get the contents of.
Return type:Deferred that fires with the content as a str.
treq.text_content(response, encoding='ISO-8859-1')[source]

Read the contents of an HTTP response and decode it with an appropriate charset, which may be guessed from the Content-Type header.

Parameters:
  • response (IResponse) – The HTTP Response to get the contents of.
  • encoding (str) – A charset, such as UTF-8 or ISO-8859-1, used if the response does not specify an encoding.
Return type:

Deferred that fires with a unicode string.

treq.json_content(response)[source]

Read the contents of an HTTP response and attempt to decode it as JSON.

This function relies on content() and so may be called more than once for a given response.

Parameters:response (IResponse) – The HTTP Response to get the contents of.
Return type:Deferred that fires with the decoded JSON.

HTTPClient Objects

The treq.client.HTTPClient class provides the same interface as the treq module itself.

class treq.client.HTTPClient(agent, cookiejar=None, data_to_body_producer=<InterfaceClass twisted.web.iweb.IBodyProducer>)[source]
delete(url, **kwargs)[source]
get(url, **kwargs)[source]
head(url, **kwargs)[source]
patch(url, data=None, **kwargs)[source]
post(url, data=None, **kwargs)[source]
put(url, data=None, **kwargs)[source]
request(method, url, **kwargs)[source]

Augmented Response Objects

treq.request(), treq.get(), etc. return an object which implements twisted.web.iweb.IResponse, plus a few additional convenience methods:

class treq.response._Response[source]
collect(collector)[source]

Incrementally collect the body of the response, per treq.collect().

Parameters:collector – A single argument callable that will be called with chunks of body data as it is received.
Returns:A Deferred that fires when the entire body has been received.
content()[source]

Read the entire body all at once, per treq.content().

Returns:A Deferred that fires with a bytes object when the entire body has been received.
json()[source]

Collect the response body as JSON per treq.json_content().

Return type:Deferred that fires with the decoded JSON when the entire body has been read.
text(encoding='ISO-8859-1')[source]

Read the entire body all at once as text, per treq.text_content().

Return type:A Deferred that fires with a unicode string when the entire body has been received.
history()[source]

Get a list of all responses that (such as intermediate redirects), that ultimately ended in the current response. The responses are ordered chronologically.

Returns:A list of _Response objects
cookies()[source]

Get a copy of this response’s cookies.

Return type:requests.cookies.RequestsCookieJar

Inherited from twisted.web.iweb.IResponse:

Variables:
  • version
  • code
  • phrase
  • headers
  • length
  • request
  • previousResponse
deliverBody(protocol)
setPreviousResponse(response)

Test Helpers

MultiPartProducer Objects

treq.multipart.MultiPartProducer is used internally when making requests which involve files.

class treq.multipart.MultiPartProducer(fields, boundary=None, cooperator=<module 'twisted.internet.task' from '/usr/lib/python2.7/site-packages/twisted/internet/task.pyc'>)[source]

MultiPartProducer takes parameters for a HTTP request and produces bytes in multipart/form-data format defined in RFC 2388 and RFC 2046.

The encoded request is produced incrementally and the bytes are written to a consumer.

Fields should have form: [(parameter name, value), ...]

Accepted values:

  • Unicode strings (in this case parameter will be encoded with utf-8)
  • Tuples with (file name, content-type, IBodyProducer objects)

Since MultiPartProducer can accept objects like IBodyProducer which cannot be read from in an event-driven manner it uses uses a Cooperator instance to schedule reads from the underlying producers. Reading is also paused and resumed based on notifications from the IConsumer provider being written to.

Variables:
  • _fields – Sorted parameters, where all strings are enforced to be unicode and file objects stacked on bottom (to produce a human readable form-data request)
  • _cooperate – A method like Cooperator.cooperate which is used to schedule all reads.
  • boundary – The generated boundary used in form-data encoding
pauseProducing()[source]

Temporarily suspend copying bytes from the input file to the consumer by pausing the CooperativeTask which drives that activity.

resumeProducing()[source]

Undo the effects of a previous pauseProducing and resume copying bytes to the consumer by resuming the CooperativeTask which drives the write activity.

startProducing(consumer)[source]

Start a cooperative task which will read bytes from the input file and write them to consumer. Return a Deferred which fires after all bytes have been written.

Parameters:consumer – Any IConsumer provider
stopProducing()[source]

Permanently stop writing bytes from the file to the consumer by stopping the underlying CooperativeTask.