This page lists all of the interfaces exposed by the treq package.
request(method, url, **kwargs)¶
Make an HTTP request.
- method (str) – HTTP method. Example:
- 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.
- reactor – Optional twisted reactor.
- persistent (bool) – Use persistent HTTP connections. Default:
- allow_redirects (bool) – Follow HTTP redirects. Default:
- auth (tuple of
('username', 'password').) – HTTP Basic Authentication information.
- cookies (
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
- browser_like_redirects (bool) – Use browser like redirects
(i.e. Ignore RFC2616 section 10.3 and follow redirects from
POST requests). Default:
- unbuffered (bool) – Pass
Trueto to disable response buffering. By default treq buffers the entire response body in memory.
Deferred that fires with an IResponse provider.
- method (str) – HTTP method. Example:
Incrementally collect the body of the response.
This function may only be called once for a given response.
- 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.
Deferred that fires with None when the entire body has been read.
Read the contents of an HTTP response.
This function may be called multiple times for a response, it uses a
WeakKeyDictionaryto 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.
Read the contents of an HTTP response and decode it with an appropriate charset, which may be guessed from the
- response (IResponse) – The HTTP Response to get the contents of.
- encoding (str) – An valid charset, such as
Deferred that fires with a unicode.
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(agent, cookiejar=None, data_to_body_producer=<InterfaceClass twisted.web.iweb.IBodyProducer>)¶
patch(url, data=None, **kwargs)¶
post(url, data=None, **kwargs)¶
put(url, data=None, **kwargs)¶
request(method, url, **kwargs)¶
Augmented Response Objects¶
Incrementally collect the body of the response, per
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.
Read the entire body all at once, per
Returns: A Deferred that fires with a bytes object when the entire body has been received.
Collect the response body as JSON per
Return type: Deferred that fires with the decoded JSON when the entire body has been read.
Read the entire body all at once as text, per
Return type: A Deferred that fires with a unicode string when the entire body has been received.
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
Get a copy of this response’s cookies.
In-memory version of treq for testing.
Since Twisted adds headers to a request, such as the host and the content length, it’s necessary to test whether request headers CONTAIN the expected headers (the ones that are not automatically added by Twisted).
This wraps a set of headers, and can be used in an equality test against a superset if the provided headers. The headers keys are lowercased, and keys and values are compared in their bytes-encoded forms.
Headers should be provided as a mapping from strings or bytes to a list of strings or bytes.
For an example usage, see
Takes a sequence of:
[((method, url, params, headers, data), (code, headers, body)), ...]
Expects the requests to arrive in sequence order. If there are no more responses, or the request’s paramters do not match the next item’s expected request paramters, raises
For the expected request arguments:
methodshould be bytes normalized to lowercase.
urlshould be normalized as per the transformations in https://en.wikipedia.org/wiki/URL_normalization that (usually) preserve semantics. A url to http://something-that-looks-like-a-directory would be normalized to http://something-that-looks-like-a-directory/ and a url to http://something-that-looks-like-a-page/page.html remains unchanged.
paramsis a dictionary mapping bytes to lists of bytes
headersis a dictionary mapping bytes to lists of bytes - note that
twisted.web.client.Agentmay add its own headers though, which are not guaranteed (for instance, user-agent or content-length), so it’s better to use some kind of matcher like
datais a bytes
For the response:
codeis an integer representing the HTTP status code to return
headersis a dictionary mapping bytes to bytes or lists of bytes
bodyis a bytes
- sequence (list) – The sequence of expected request arguments mapped to stubbed responses
- async_failure_reporter – A callable that takes a single message
reporting failures - it’s asynchronous because it cannot just raise
an exception - if it does,
Resource.renderwill just convert that into a 500 response, and there will be no other failure reporting mechanism.
sequence_stubs = RequestSequence([...]) stub_treq = StubTreq(StringStubbingResource(sequence_stubs)) with sequence_stubs.consume(self.fail): # self = unittest.TestCase stub_treq.get('http://fakeurl.com') stub_treq.get('http://another-fake-url.com')
If there are still remaining expected requests to be made in the sequence, fails the provided test case.
Parameters: sync_failure_reporter – A callable that takes a single message reporting failures. This can just raise an exception - it does not need to be asynchronous, since the exception would not get raised within a Resource. Returns: a context manager that can be used to ensure all expected requests have been made.
Returns: bool representing whether the entire sequence has been consumed. This is useful in tests to assert that the expected requests have all been made.
IAgentimplementation that issues an in-memory request rather than going out to a real network socket.
Flush all data between pending client/server pairs.
This is only necessary if a
Resourceunder test returns
rendermethod, making a response asynchronous. In that case, after each write from the server,
pump()must be called so the client can see it.
request(method, uri, headers=None, bodyProducer=None)¶
A resource that takes a callable with 5 parameters
(method, url, params, headers, data)and returns
(code, headers, body).
The resource uses the callable to return a real response as a result of a request.
The parameters for the callable are:
method, the HTTP method as bytes.
url, the the full URL of the request as bytes.
params, a dictionary of query parameters mapping query keys lists of values (sorted alphabetically).
headers, a dictionary of headers mapping header keys to a list of header values (sorted alphabetically).
data, the request body as bytes.
The callable must return a
tupleof (code, headers, body) where the code is the HTTP status code, the headers is a dictionary of bytes (unlike the headers parameter, which is a dictionary of lists), and body is a string that will be returned as the response body.
If there is a stubbing error, the return value is undefined (if an exception is raised,
Resourcewill just eat it and return 500 in its place). The callable, or whomever creates the callable, should have a way to handle error reporting.
Produce a response according to the stubs provided.
treq.multipart.MultiPartProducer is used internally when making requests which involve files.
MultiPartProducer(fields, boundary=None, cooperator=<module 'twisted.internet.task' from '/home/docs/checkouts/readthedocs.org/user_builds/treq/envs/latest/local/lib/python2.7/site-packages/twisted/internet/task.pyc'>)¶
The encoded request is produced incrementally and the bytes are written to a consumer.
Fields should have form:
[(parameter name, value), ...]
- Unicode strings (in this case parameter will be encoded with utf-8)
- Tuples with (file name, content-type,
MultiPartProducercan accept objects like
IBodyProducerwhich cannot be read from in an event-driven manner it uses uses a
Cooperatorinstance to schedule reads from the underlying producers. Reading is also paused and resumed based on notifications from the
IConsumerprovider being written to.
- _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
Temporarily suspend copying bytes from the input file to the consumer by pausing the CooperativeTask which drives that activity.
Undo the effects of a previous pauseProducing and resume copying bytes to the consumer by resuming the CooperativeTask which drives the write activity.
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
Permanently stop writing bytes from the file to the consumer by stopping the underlying CooperativeTask.