Esta parte da documentação cobre todas as interfaces do Requests. Para partes onde Requests depende de bibliotecas externas, nós documentamos o mais imoprtante aqui e fornecemos links para a documentação oficial.
Todas as funcionalidades de Requests podem ser acessadas por estes 7 métodos. Todos retornam uma instância de Response.
Constructs and sends a Request. Returns Response object.
Parâmetros: |
|
---|
Usage:
>>> import requests
>>> req = requests.request('GET', 'http://httpbin.org/get')
<Response [200]>
Sends a HEAD request. Returns Response object.
Parâmetros: |
|
---|
Sends a GET request. Returns Response object.
Parâmetros: |
|
---|
Sends a PATCH request. Returns Response object.
Parâmetros: |
---|
Sends a DELETE request. Returns Response object.
Parâmetros: |
|
---|
A user-created Request object.
Used to prepare a PreparedRequest, which is sent to the server.
Parâmetros: |
|
---|
Usage:
>>> import requests
>>> req = requests.Request('GET', 'http://httpbin.org/get')
>>> req.prepare()
<PreparedRequest [GET]>
Deregister a previously registered hook. Returns True if the hook existed, False if not.
Constructs a PreparedRequest for transmission and returns it.
Properly register a hook.
The Response object, which contains a server’s response to an HTTP request.
The apparent encoding, provided by the lovely Charade library (Thanks, Ian!).
Content of the response, in bytes.
A CookieJar of Cookies the server sent back.
The amount of time elapsed between sending the request and the arrival of the response (as a timedelta)
Encoding to decode with when accessing r.text.
Case-insensitive Dictionary of Response Headers. For example, headers['content-encoding'] will return the value of a 'Content-Encoding' response header.
A list of Response objects from the history of the Request. Any redirect responses will end up here. The list is sorted from the oldest to the most recent request.
Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place.
Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses.
Returns the json-encoded content of a response, if any.
Parâmetros: | **kwargs – Optional arguments that json.loads takes. |
---|
Returns the parsed header links of the response, if any.
File-like object representation of response (for advanced usage). Requires that ``stream=True` on the request.
Integer Code of responded HTTP Status.
Content of the response, in unicode.
if Response.encoding is None and chardet module is available, encoding will be guessed.
Final URL location of Response.
A Requests session.
Provides cookie persistience, connection-pooling, and configuration.
Basic Usage:
>>> import requests
>>> s = requests.Session()
>>> s.get('http://httpbin.org/get')
200
SSL certificate default.
Closes all adapters and as such the session
Sends a DELETE request. Returns Response object.
Parâmetros: |
|
---|
Sends a GET request. Returns Response object.
Parâmetros: |
|
---|
Returns the appropriate connnection adapter for the given URL.
Sends a HEAD request. Returns Response object.
Parâmetros: |
|
---|
A case-insensitive dictionary of headers to be sent on each Request sent from this Session.
Event-handling hooks.
Maximum number of redirects to follow.
Registers a connection adapter to a prefix.
Sends a OPTIONS request. Returns Response object.
Parâmetros: |
|
---|
Dictionary of querystring data to attach to each Request. The dictionary values may be lists for representing multivalued query parameters.
Dictionary mapping protocol to the URL of the proxy (e.g. {‘http’: ‘foo.bar:3128’}) to be used on each Request.
Constructs a Request, prepares it and sends it. Returns Response object.
Parâmetros: |
|
---|
Receives a Response. Returns a generator of Responses.
Send a given PreparedRequest.
Stream response content default.
Should we trust the environment?
SSL Verification default.
The built-in HTTP Adapter for urllib3.
Provides a general-case interface for Requests sessions to contact HTTP and HTTPS urls by implementing the Transport Adapter interface. This class will usually be created by the Session class under the covers.
Parâmetros: |
|
---|
Usage:
>>> import requests
>>> s = requests.Session()
>>> a = requests.adapters.HTTPAdapter()
>>> s.mount('http://', a)
Add any headers needed by the connection. Currently this adds a Proxy-Authorization header.
This should not be called from user code, and is only exposed for use when subclassing the HTTPAdapter.
Parâmetros: |
|
---|
Builds a Response object from a urllib3 response. This should not be called from user code, and is only exposed for use when subclassing the HTTPAdapter
Parâmetros: |
|
---|
Verify a SSL certificate. This method should not be called from user code, and is only exposed for use when subclassing the HTTPAdapter.
Parâmetros: |
|
---|
Disposes of any internal state.
Currently, this just closes the PoolManager, which closes pooled connections.
Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the HTTPAdapter.
Parâmetros: |
|
---|
Initializes a urllib3 PoolManager. This method should not be called from user code, and is only exposed for use when subclassing the HTTPAdapter.
Parâmetros: |
|
---|
Obtain the url to use when making the final request.
If the message is being sent through a proxy, the full URL has to be used. Otherwise, we should only use the path portion of the URL.
This shoudl not be called from user code, and is only exposed for use when subclassing the HTTPAdapter.
Parâmetros: |
|
---|
Sends PreparedRequest object. Returns Response object.
Parâmetros: |
|
---|
There was an ambiguous exception that occurred while handling your request.
A Connection error occurred.
An HTTP error occurred.
A valid URL is required to make a request.
Too many redirects.
Dictionary lookup object.
>>> requests.codes['temporary_redirect']
307
>>> requests.codes.teapot
418
>>> requests.codes['\o/']
200
The Response object, which contains a server’s response to an HTTP request.
The apparent encoding, provided by the lovely Charade library (Thanks, Ian!).
Content of the response, in bytes.
A CookieJar of Cookies the server sent back.
The amount of time elapsed between sending the request and the arrival of the response (as a timedelta)
Encoding to decode with when accessing r.text.
Case-insensitive Dictionary of Response Headers. For example, headers['content-encoding'] will return the value of a 'Content-Encoding' response header.
A list of Response objects from the history of the Request. Any redirect responses will end up here. The list is sorted from the oldest to the most recent request.
Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place.
Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses.
Returns the json-encoded content of a response, if any.
Parâmetros: | **kwargs – Optional arguments that json.loads takes. |
---|
Returns the parsed header links of the response, if any.
Raises stored HTTPError, if one occurred.
File-like object representation of response (for advanced usage). Requires that ``stream=True` on the request.
Integer Code of responded HTTP Status.
Content of the response, in unicode.
if Response.encoding is None and chardet module is available, encoding will be guessed.
Final URL location of Response.
A user-created Request object.
Used to prepare a PreparedRequest, which is sent to the server.
Parâmetros: |
|
---|
Usage:
>>> import requests
>>> req = requests.Request('GET', 'http://httpbin.org/get')
>>> req.prepare()
<PreparedRequest [GET]>
Deregister a previously registered hook. Returns True if the hook existed, False if not.
Constructs a PreparedRequest for transmission and returns it.
Properly register a hook.
The fully mutable PreparedRequest object, containing the exact bytes that will be sent to the server.
Generated from either a Request object or manually.
Usage:
>>> import requests
>>> req = requests.Request('GET', 'http://httpbin.org/get')
>>> r = req.prepare()
<PreparedRequest [GET]>
>>> s = requests.Session()
>>> s.send(r)
<Response [200]>
request body to send to the server.
Deregister a previously registered hook. Returns True if the hook existed, False if not.
dictionary of HTTP headers.
dictionary of callback hooks, for internal usage.
HTTP verb to send to the server.
Build the path URL to use.
Prepares the given HTTP auth data.
Prepares the given HTTP body data.
Prepares the given HTTP cookie data.
Prepares the given HTTP headers.
Prepares the given hooks.
Prepares the given HTTP method.
Prepares the given HTTP URL.
Properly register a hook.
HTTP URL to send the request to.
A Requests session.
Provides cookie persistience, connection-pooling, and configuration.
Basic Usage:
>>> import requests
>>> s = requests.Session()
>>> s.get('http://httpbin.org/get')
200
Default Authentication tuple or object to attach to Request.
SSL certificate default.
Closes all adapters and as such the session
Sends a DELETE request. Returns Response object.
Parâmetros: |
|
---|
Sends a GET request. Returns Response object.
Parâmetros: |
|
---|
Returns the appropriate connnection adapter for the given URL.
Sends a HEAD request. Returns Response object.
Parâmetros: |
|
---|
A case-insensitive dictionary of headers to be sent on each Request sent from this Session.
Event-handling hooks.
Maximum number of redirects to follow.
Registers a connection adapter to a prefix.
Sends a OPTIONS request. Returns Response object.
Parâmetros: |
|
---|
Dictionary of querystring data to attach to each Request. The dictionary values may be lists for representing multivalued query parameters.
Sends a PATCH request. Returns Response object.
Parâmetros: |
---|
Sends a POST request. Returns Response object.
Parâmetros: |
---|
Dictionary mapping protocol to the URL of the proxy (e.g. {‘http’: ‘foo.bar:3128’}) to be used on each Request.
Sends a PUT request. Returns Response object.
Parâmetros: |
---|
Constructs a Request, prepares it and sends it. Returns Response object.
Parâmetros: |
|
---|
Receives a Response. Returns a generator of Responses.
Send a given PreparedRequest.
Stream response content default.
Should we trust the environment?
SSL Verification default.
The built-in HTTP Adapter for urllib3.
Provides a general-case interface for Requests sessions to contact HTTP and HTTPS urls by implementing the Transport Adapter interface. This class will usually be created by the Session class under the covers.
Parâmetros: |
|
---|
Usage:
>>> import requests
>>> s = requests.Session()
>>> a = requests.adapters.HTTPAdapter()
>>> s.mount('http://', a)
Add any headers needed by the connection. Currently this adds a Proxy-Authorization header.
This should not be called from user code, and is only exposed for use when subclassing the HTTPAdapter.
Parâmetros: |
|
---|
Builds a Response object from a urllib3 response. This should not be called from user code, and is only exposed for use when subclassing the HTTPAdapter
Parâmetros: |
|
---|
Verify a SSL certificate. This method should not be called from user code, and is only exposed for use when subclassing the HTTPAdapter.
Parâmetros: |
|
---|
Disposes of any internal state.
Currently, this just closes the PoolManager, which closes pooled connections.
Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the HTTPAdapter.
Parâmetros: |
|
---|
Initializes a urllib3 PoolManager. This method should not be called from user code, and is only exposed for use when subclassing the HTTPAdapter.
Parâmetros: |
|
---|
Obtain the url to use when making the final request.
If the message is being sent through a proxy, the full URL has to be used. Otherwise, we should only use the path portion of the URL.
This shoudl not be called from user code, and is only exposed for use when subclassing the HTTPAdapter.
Parâmetros: |
|
---|
Sends PreparedRequest object. Returns Response object.
Parâmetros: |
|
---|
Essa seção detalha as principais diferenças entre 0.x e 1.x e é feita para facilitar a dor da atualização.
Response.json agora é chamável e não uma propriedade de Response.
import requests
r = requests.get('https://github.com/timeline.json')
r.json() # Essa *chamada* levanta uma exceção quando a decodificação do JSON falha
A API de Session mudou. Objetos Session não aceitam mais parâmetros. Session agora é capitalizado, mas ainda pode ser instanciado com o session minúsculo para retrocompatibilidade.
s = requests.Session() # originalmente, session recebia parâmetros
s.auth = auth
s.headers.update(headers)
r = s.get('http://httpbin.org/headers')
Todos os hooks de requisição foram removidos com exceção de ‘response’.
Helpers de autenticação foram quebrados em módulos separados. Veja requests-oauthlib and requests-kerberos.
O parâmetro para requisições de streaming oram mudados de prefetch para stream e a lógica foi invertida. Além disso, stream agora é exigido para leitura de resposta crua.
# na 0.x, passando prefetch=False iria realizar a mesma coisa
r = requests.get('https://github.com/timeline.json', stream=True)
r.raw.read(10)
O parâmetro config dos métodos de requisição foi removido. Algumas das opções agora são configuradas em um objeto Session como keep-alive e o número máximo de redirecionamentos. A opção de verbosidade deve ser manipulada pela configuração de logging.
import requests
import logging
# essas duas linhas habilitam debugging no nível do httplib (requests->urllib3->httplib)
# você verá o REQUEST, incluindo HEADERS e DATA, e RESPONSE com HEADERS mas sem DATA.
# a única coisa faltando será o response.body que não será registrado.
import httplib
httplib.HTTPConnection.debuglevel = 1
logging.basicConfig() # você precisa inicializar o logging, se não você não verá nada
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
requests.get('http://httpbin.org/headers')