requests Library
requests 라이브러리
- HTTP를 호출하는데 관련된 기능들을 제공하는 라이브러리이다.
- requests 라이브러리는 Web에 대해 아래와 같은 기능들을 제공하고 있다:
- Keep-Alive & Connection Pooling
- International Domains and URLs
- Sessions with Cookie Persistence
- Browser-style SSL Verification
- Automatic Content Decoding
- Basic/Digest Authentication
- Elegant Key/Value Cookies
- Automatic Decompression
- Unicode Response Bodies
- HTTP(S) Proxy Support
- Multipart File Uploads
- Streaming Downloads
- Connection Timeouts
- Chunked Requests
- .netrc Support
Installation (설치)
Installation Command (설치 명령어) (URL)
# In terminal
$ python -m pip install requests
# Get the source code
$ git clone git://github.com/psf/requests.git
$ cd requests
$ python -m pip install .
Import (모듈 임포트)
import requests
requests Properties and Methods (requests 속성과 메소드)
basis
# Main Interface
import requests
# Requests Session
session = requests.Session()
requests Properties
Category | Property | Description |
Request Sessions |
session.auth |
Default Authentication tuple or object to attach to Request. |
session.cert | SSL client certificate default, if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair. | |
session.cookies | A CookieJar containing all currently outstanding cookies set on this session. By default it is a RequestsCookieJar, but may be any other cookielib.CookieJar compatible object. | |
session.headers | A case-insensitive dictionary of headers to be sent on each Request sent from this Session. | |
session.hooks | Event-handling hooks. | |
session.max_redirects | Maximum number of redirects allowed. If the request exceeds this limit, a TooManyRedirects exception is raised. This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is 30. | |
session.params | Dictionary of querystring data to attach to each Request. The dictionary values may be lists for representing multivalued query parameters. | |
session.proxies | Dictionary mapping protocol or protocol and host to the URL of the proxy (e.g. {‘http’: ‘foo.bar:3128’, ‘http://host.name’: ‘foo.bar:4012’}) to be used on each Request. | |
session.stream | Stream response content default. | |
session.trust_env | Trust environment settings for proxy configuration, default authentication and similar. | |
session.verify | SSL Verification default. Defaults to True, requiring requests to verify the TLS certificate at the remote end. If verify is set to False, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks. Only set this to False for testing. |
requests Methods (Summary)
Category | Method | Description |
Main Interface |
requests.request() | - Constructs and sends a Request. |
requests.head() | - Sends a HEAD request. | |
requests.get() | - Sends a GET request. | |
requests.post() | - Sends a POST request. | |
requests.put() | - Sends a PUT request. | |
requests.patch() | - Sends a PATCH request. | |
requests.delete() | - Sends a DELETE request. | |
Request Sessions |
session.close() | Closes all adapters and as such the session |
session.delete() | Sends a DELETE request. Returns Response object. |
|
session.get() | Sends a GET request. Returns Response object. |
|
session.get_adapter() | Returns the appropriate connection adapter for the given URL. |
|
session.get_redirect_target() | Receives a Response. Returns a redirect URI or None |
|
session.head() | Sends a HEAD request. Returns Response object. |
|
session.merge_environment_settings() | Check the environment and merge it with some settings. |
|
session.mount() | Registers a connection adapter to a prefix. Adapters are sorted in descending order by prefix length. |
|
session.options() | Sends a OPTIONS request. Returns Response object. |
|
session.patch() | Sends a PATCH request. Returns Response object. |
|
session.post() | Sends a POST request. Returns Response object. |
|
session.prepare_request() | Constructs a PreparedRequest for transmission and returns it. The PreparedRequest has settings merged from the Request instance and those of the Session. |
|
session.put() | Sends a PUT request. Returns Response object. |
|
session.rebuild_auth() | When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss. |
|
session.rebuild_method() | When being redirected we may want to change the method of the request based on certain specs or browser behavior. |
|
session.rebuild_proxies() | This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect). This method also replaces the Proxy-Authorization header where necessary. |
|
session.request() | Constructs a Request, prepares it and sends it. Returns Response object. |
|
session.resolve_redirects() | Receives a Response. Returns a generator of Responses or Requests. |
|
session.send() | Send a given PreparedRequest. |
|
session.should_strip_auth() | Decide whether Authorization header should be removed when redirecting |
requests Methods (Details, Signatures)
# Main Interface
requests.request(
method: str, # method for the new Request object: GET, OPTIONS, HEAD, POST, PUT, PATCH, or DELETE.
url: str, # URL for the new Request object.
params: dict, # (optional) Dictionary, list of tuples or bytes to send in the query string for the Request.
data: dict, # (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.
json, # (optional) A JSON serializable Python object to send in the body of the Request.
headers: dict, # (optional) Dictionary of HTTP Headers to send with the Request.
cookies: dict | CookieJar, # (optional) Dict or CookieJar object to send with the Request.
files: dict, # (optional) for multipart encoding upload.
# {'name': file-like-objects} or {'name': file-tuple}
# file-tuple can be a 2-tuple ('filename', fileobj), 3-tuple ('filename', fileobj, 'content_type') or a 4-tuple ('filename', fileobj, 'content_type', custom_headers),
# where 'content-type' is a string defining the content type of the given file and custom_headers a dict-like object containing additional headers to add for the file.
auth, # (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
timeout: float | tuple, # (optional) How many seconds to wait for the server to send data before giving up, as a float, or a (connect timeout, read timeout) tuple.
allow_redirects: bool, # (optional) Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to True.
proxies: dict, # (optional) Dictionary mapping protocol to the URL of the proxy.
verify, # (optional) Either a boolean, in which case it controls whether we verify the server’s TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to True.
stream, # (optional) if False, the response content will be immediately downloaded.
cert # (optional) if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair.
) -> requests.Response
requests.head(
url: str, # URL for the new Request object
**kwargs # (optional) If allow_redirects is not provided, it will be set to False (as opposed to the default request behavior)
) -> requests.Response
requests.get(
url, # URL for the new Request object
params: dict =None, # (optional) list of tuples or bytes to send in the query string for the Request
**kwargs # (optional) request takes
) -> requests.Response
requests.post(
url: str, # URL for the new Request object
data: dict =None, # (optional) list of tuples, bytes, or file-like object to send in the body of the Request
json =None, # (optional) json data to send in the body of the Request
**kwargs # (optional) request tasks
) -> requests.Response
requests.put(
url: str, # URL for the new Request object
data: dict =None, # (optional) list of tuples, bytes, or file-like object to send in the body of the Request
json =None, # (optional) json data to send in the body of the Request
**kwargs # (optional) request tasks
) -> requests.Response
requests.patch(
url: str, # URL for the new Request object
data: dict =None, # (optional) list of tuples, bytes, or file-like object to send in the body of the Request
json =None, # (optional) json data to send in the body of the Request
**kwargs # (optional) request tasks
) -> requests.Response
requests.delete(
url: str, # URL for the new Request object
**kwargs # (optional) request tasks
) -> requests.Response
# Request Sessions
requests Exceptions (requests 예외)
Exception | Description |
requests.RequestException(*args, **kwargs) | - There was an ambiguous exception that occurred while handling your request. |
requests.ConnectionError(*args, **kwargs) |
- A Connection error occurred. |
requests.HTTPError(*args, **kwargs) |
- An HTTP error occurred. |
requests.URLRequired(*args, **kwargs) |
- A valid URL is required to make a request. |
requests.TooManyRedirects(*args, **kwargs) |
- Too many redirects. |
requests.ConnectTimeout(*args, **kwargs) |
- The request timed out while trying to connect to remote server. - Requests that produced this error are safe to retry. |
requests.ReadTimeout(*args, **kwargs) |
- The server did not send any data in the allotted amount of time. |
requests.Timeout(*args, **kwargs) |
- The request timed out. - ConnectTimeout과 ReadTimeout을 포함한다. |
Reference: "Requests: HTTP for Humans", Read the Docs, 2022.08.31 검색, URL.