[Document] Requests

간단한 Requests 예시

r = requests.get('https://api.github.com/user', auth=('user', 'pass'))

print(r.status_code)
print(r.headers['content-type'])
print(r.encoding)
print(r.text)
print(r.json())
# 403
# application/json; charset=utf-8
# utf-8
# {"message":"Maximum number of login attempts exceeded. Please try again later.","documentation_url":"https://developer.github.com/v3"}
#  {'message': 'Maximum number of login attempts exceeded. Please try again later.', 'documentation_url': 'https://developer.github.com/v3'}

r.status_code.get 부분에 auth=에 자신의 깃허브 ID, Pass를 적으면 200이 출력된다.


소개

Requests를 사용하면 HTTP/1.1 요청을 매우 쉽게 보낼 수 있다. URL에 쿼리 문자열을 수동으로 추가하거나 POST 데이터를 양식 인코딩 할 필요가 없다. urllib3 덕분에 Keep-alive 및 HTTP connection pooling은 100% 자동이다.

철학

Requests는 몇가지 PEP20 관용구와 함께 개발이 되었다.

Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Readability counts.

  1. 못생긴 것보다 아름다운 것이 낫다.
  2. 암시적인 것보다 명시적인 것이 좋다.
  3. 복잡한 것보다 단순한 것이 낫다.
  4. 추상적인(복잡한) 것보다 복합적인 것이 낫다.
  5. 가독성이 중요하다.

설치

pipenv로 설치

$ pipenv install requests

pip로 설치

$ pip install requests

pipenv가 설치되지 않은 경우 pipene 웹 사이트로 이동하여 설치하면 된다.

HTTP 기본 지식

HTTP 응답 코드

응답 코드설명
100Continue (클라이언트로 부터 일부 요청을 받았으며 나머지 정보를 계속 요청함)
101Switching protocols
200OK(요청이 성공적으로 수행되었음)
201Created (PUT 메소드에 의해 원격지 서버에 파일 생성됨)
202Accepted(웹 서버가 명령 수신함)
203Non-authoritative information (서버가 클라이언트 요구 중 일부만 전송)
204No content, (사용자 요구 처리하였으나 전송할 데이터가 없음)
301Moved permanently (요구한 데이터를 변경된 타 URL에 요청함)
302Not temporarily
304Not modified (컴퓨터 로컬의 캐시 정보를 이용함, 대개 gif 등은 웹 서버에 요청하지 않음)
400Bad request (사용자의 잘못된 요청을 처리할 수 없음)
401Unauthorized (인증이 필요한 페이지를 요청한 경우)
402Payment required(예약됨)
403Forbidden (접근 금지, 디렉터리 리스팅 요청 및 관리자 페이지 접근 등을 차단)
404Not found, (요청한 페이지 없음)
405Method not allowed (혀용되지 않는 http method 사용함)
407Proxy authentication required (프락시 인증 요구됨)
408Request timeout (요청 시간 초과)
410Gone (영구적으로 사용 금지)
412Precondition failed (전체 조건 실패)
414Request-URI too long (요청 URL 길이가 긴 경우임)
500Internal server error (내부 서버 오류)
501Not implemented (웹 서버가 처리할 수 없음)
503Service unnailable (서비스 제공 불가)
504Gateway timeout (게이트웨이 시간 초과)
505HTTP version not supported (해당 http 버전 지원되지 않음)

HTTP 메소드 종류

HTTP Method전송 형태설명
GETGET [request-uri]?query_string
</brHTTP/1.1\r\n>HTTP/1.1\r\n
</brHost:[Hostname]>Host:[Hostname] 혹은 [IP] \r\n
GET 요청 방식은 URI(URL)가 가진 정보를 검색하기 위해 서버 측에 요청하는형태이다
POSTPOST [request-uri]?query_string
HTTP/1.1\r\n
HOST:[Hostname] 혹은 [IP] \r\n
Content-Lenght:[Lenght in Bytes] \r\n
\r\n
[query-string] 혹은 [데이터]
POST 요청 방식은 요청 URI(URL)에 폼 입력을 처리하기 위해 구성한 서버 측 스크립트(ASP, PHP, JSP 등) 혹은 CGI 프로그램으로 구성되고 Form Action과 함께 전송되는데, 이때 헤더 정보에 포함되지 않고 데이터 부분에 요청 정보가 들어가게 된다.
HEADHEAD [request-uri] HTTP/1.1\r\n
Host:[Hostname] 혹은 [IP] \r\n
HEAD 요청 방식은 GET과 유사한 방식이나 웹 서버에서 헤더 정보 이외에는 어떤 데이터도 보내지 않는다.
웹 서버의 다운 여부 점검(Health Check)이나 웹 서버 정보(버전 등)등을 얻기 위해 사용될 수 있다.
OPTIONSOPTIONS [request-ri]
HTTP/1.1\r\n
Host:[Hostname] 혹은 [IP] \r\n
해당 메소드를 통해 시스템에서 지원되는 메소드 종류를 확인할 수 있다.
PUTPUT [request-uri] HTTP/1.1\r\n
Host:[Hostname] 혹은 [IP] \r\n
Content-Lenght:[Length in Bytes] \r\n
Content-Type:[Content Type] \r\n
\r\n
[데이터]
POST와 유사한 전송 구조를 가지기 때문에 헤더 이외에 메시지(데이터)가 함께 전송된다.
원격지 서버에 지정한 콘텐츠를 저장하기 위해 사용되며 홈페이지 변조에 많이 악용되고 있다.
DELETEDELETE [request-uri] HTTP/1.1\r\n
Host:[Hostname] 혹은 [IP] \r\n
\r\n
원격지 웹 서버에 파일을 삭제하기 위해 사용되며 PUT과는 반대 개념의 메소드이다.
TRACETRACE [request-uri] HTTP/1.1\r\n
Host:[Hostname] 혹은 [IP] \r\n
\r\n
원격지 서버에 Loopback(루프백) 메시지를 호출하기 위해 사용된다.
CONNECTCONNECT [request-uri] HTTP/1.1\r\n
Host:[Hostname] 혹은 [IP] \r\n
\r\n
웹 서버에 프락시 기능을 요청할 때 사용된다.

취조선은 requests에서 지원을 안하는듯

Requests 사용하기

이제 Response라는 객체 r로 필요한 모든 정보를 얻을 수 있다. Requests의 간단한 API는 모든 형태의 HTTP 요청이 분명하다는 것을 의미한다.

###.get

r = requests.get("https://api.github.com/events")

print(r.status_code)
print(r.json())
print(r)
# 200
# [{'id': '11524845355', 'type': 'PullRequestEvent', 'actor': {'id': 39814207, 'login': 'pull[bot]', 'display_login': 'pull', 'gravatar_id': '', 'url': 'https://api.github.com/users/pull[bot]', 'avatar_url': 'https://avatars.githubusercontent.com/u/39814207?'}, ... 'org': {'id': 78455, 'login': 'moovweb', 'gravatar_id': '', 'url': 'https://api.github.com/orgs/moovweb', 'avatar_url': 'https://avatars.githubusercontent.com/u/78455?'}}]
# <Response [200]>

requests.get(url, params=None, **kwargs)[source]

Sends a GET request.

Parameters:
url – URL for the new Request object.
params – (optional) Dictionary, list of tuples or bytes to send in the query string for the Request.
**kwargs – Optional arguments that request takes.
Returns - Response object
Return type - requests.Response

###.post

r = requests.post('https://httpbin.org/post', data = {'key':'value'})

print(r.status_code)
print(r.json())
print(r)
# 200
# {'args': {}, 'data': '', 'files': {}, 'form': {'key': 'value'}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '9', 'Content-Type': 'application/x-www-form-urlencoded', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.22.0', 'X-Amzn-Trace-Id': 'Root=1-5e4767d1-8b2e1335e641a080800a47c2'}, 'json': None, 'origin': '27.179.9.117', 'url': 'https://httpbin.org/post'}
# <Response [200]>

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

Sends a POST request.

Parameters:
url – URL for the new Request object.
data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.
json – (optional) json data to send in the body of the Request.
**kwargs – Optional arguments that request takes.
Returns - Response object
Return type - requests.Response

other

.put
r = requests.put('https://httpbin.org/put', data = {'key':'value'})

print(r.status_code)
print(r.json())
print(r)
# 200
# {'args': {}, 'data': '', 'files': {}, 'form': {'key': 'value'}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '9', 'Content-Type': 'application/x-www-form-urlencoded', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.22.0', 'X-Amzn-Trace-Id': 'Root=1-5e47687b-3e252ba025bd68e0bf043810'}, 'json': None, 'origin': '27.179.9.117', 'url': 'https://httpbin.org/put'}
# <Response [200]>

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

Sends a PUT request.

Parameters:
url – URL for the new Request object.
data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.
json – (optional) json data to send in the body of the Request.
**kwargs – Optional arguments that request takes.
Returns - Response object
Return type - requests.Response

.delete
r = requests.delete('https://httpbin.org/delete')

print(r.status_code)
print(r.json())
print(r)
# 200
# {'args': {}, 'data': '', 'files': {}, 'form': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '0', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.22.0', 'X-Amzn-Trace-Id': 'Root=1-5e4768f0-decd6710f49d2320ba414150'}, 'json': None, 'origin': '27.179.9.117', 'url': 'https://httpbin.org/delete'}
# <Response [200]>

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

Sends a DELETE request.

Parameters:
url – URL for the new Request object.
**kwargs – Optional arguments that request takes.
Returns - Response object
Return type - requests.Response

r = requests.head('https://httpbin.org/get')

print(r.status_code)
print(r.headers)
print(r)
# 200
# {'Date': 'Sat, 15 Feb 2020 03:45:55 GMT', 'Content-Type': 'application/json', 'Content-Length': '306', 'Connection': 'keep-alive', 'Server': 'gunicorn/19.9.0', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true'}
# <Response [200]>

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

Sends a HEAD request.

Parameters:
url – URL for the new Request object.
**kwargs – Optional arguments that request takes. If allow_redirects is not provided, it will be set to False (as opposed to the default request behavior).
Returns - Response object
Return type - requests.Response

.options
r = requests.options('https://httpbin.org/get')

print(r.status_code)
print(r.headers)
print(r)
# 200
# {'Date': 'Sat, 15 Feb 2020 03:51:55 GMT', 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': '0', 'Connection': 'keep-alive', 'Server': 'gunicorn/19.9.0', 'Allow': 'HEAD, GET, OPTIONS', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS', 'Access-Control-Max-Age': '3600'}
# <Response [200]>

URL로 매개변수 전달

URL 쿼리 문자열에 데이터를 보내려고 한다. URL을 직접 작성하는 경우 데이터는 물음표 뒤에 키 / 값 쌍으로 제공된다. https://httpbin.org/get?key=val 요청을 사용하면 params 키워드 인수를 사용하여 이러한 인수를 문자열 사전으로 제공 할 수 있다.
값이 None인 경우 URL's 쿼리 문자열에 추가되지 않는다.
list 형식으로도 값을 전달 할 수 있다.

payload = {"key1": 'value1', 'key2':'value2'}
payload2 = {'key3' : None}
payload3 = {'key4' : ['value3','value4']}

r = requests.get('https://httpbin.org/get', params=payload)
print(r.url)

r = requests.get('https://httpbin.org/get', params=payload2)
print(r.url)

r = requests.get('https://httpbin.org/get', params=payload3)
print(r.url)
# https://httpbin.org/get?key1=value1&key2=value2
# https://httpbin.org/get
# https://httpbin.org/get?key4=value3&key4=value4

Response Content

r = requests.get('https://api.github.com/events')
print(r.text)
# [{"id":"11528229236","type":"IssuesEvent","actor":{"id":10379601,"login" ... ]

requests는 서버에서 컨턴츠를 자동으로 디코딩한다. 대부분의 유니코드 문자셋은 완벽하게 디코딩된다.

requests를 할 때 requests는 HTTP 헤더를 기반으로 response의 인코딩에 대해 교육된 추측을 한다. r.text에 액세스 할 때 requests에서 추측한 텍스트 인코딩이 사용됩니다. ㄱ.encoding속성을 사용하여 requests가 사용중인 인코딩을 찾아서 변경할 수 있습니다.
인코딩을 변경하면 r.text를 호출할 때마다 requests에서 새로운 r.encoding값을 사용합니다. 콘텐츠의 인코딩이 무엇인지 알아 내기 위해 특수로직을 적용할 수 있는 모든 상황에서 이 작업을 수행할 수 있습니다.
예를 들어 HTML과 XML은 본문에서 인코딩을 지정할 수 있습니다. 이와 같은 상황에서는 r.content를 사용하여 인코딩을 찾은 다음 r.encoding을 설정해야합니다. 올바른 인코딩으로 r.text를 사용할 수 있습니다.

print(r.encoding)
r.encoding = 'ISO-8859-1'
print(r.encoding)
# utf-8
# ISO-8859-1

JSON 응답 내용

JSON 디코딩에 실패하면 r.json ()에서 예외가 발생합니다. 예를 들어 응답에 204 (콘텐츠 없음)가 표시되거나 응답에 유효하지 않은 JSON이 포함되어 있으면 r.json ()을 시도하면 ValueError가 발생합니다. JSON 객체를 디코딩 할 수 없습니다.
r.json () 호출 성공은 응답 성공을 나타내지 않습니다. 일부 서버는 실패한 응답 (예 : HTTP 500의 오류 세부 사항)으로 JSON 오브젝트를 리턴 할 수 있습니다. 이러한 JSON은 디코딩되어 반환됩니다. 요청이 성공했는지 확인하려면 r.raise_for_status ()를 사용하거나 r.status_code가 예상 한 것인지 확인하십시오.

print(r.json())
# [{'id': '11528273836', 'type': 'IssueCommentEvent', 'actor': {'id': 24736507 ... ]

사용자 정의 헤더

requests에 HTTP 헤더를 추가하려면 간단히 헤더 매개 변수에 dict를 전달하십시오.
예를 들어 이전 예에서 사용자 에이전트를 지정하지 않았습니다.

url = 'https://api.github.com/'
headers = {'user-agent': 'my-app/0.0.1'}

r = requests.get(url, headers=headers)

참고 : 사용자 지정 헤더는보다 구체적인 정보 소스보다 우선 순위가 낮습니다.
예를 들어 :

  • 자격 증명이 .netrc에 지정된 경우 headers =로 설정된 권한 부여 헤더가 재정의되고 auth = 매개 변수로 재정의됩니다.
  • 호스트 외부로 리디렉션되면 승인 헤더가 제거됩니다.
  • 프록시 인증 헤더는 URL에 제공된 프록시 자격 증명으로 재정의됩니다.
  • 콘텐츠 길이를 결정할 수 있으면 콘텐츠 길이 헤더가 재정의됩니다.
    또한 요청은 지정된 사용자 정의 헤더에 따라 동작을 전혀 변경하지 않습니다. 헤더는 단순히 최종 요청에 전달됩니다.

참고 : 모든 헤더 값은 문자열, 바이트 열 또는 유니 코드 여야합니다. 허용되는 동안 유니 코드 헤더 값을 전달하지 않는 것이 좋습니다.

더 복잡한 POST 요청

일반적으로 HTML 형식과 매우 유사한 형식으로 인코딩 된 데이터를 보내려고합니다. 이렇게하려면 단순히 데이터 인수에 사전을 전달하십시오. 요청하면 데이터 사전이 자동으로 양식 인코딩됩니다

payload = {'key1': 'value1', 'key2': 'value2'}

r = requests.post("https://httpbin.org/post", data=payload)
print(r.text)
# ...
#   "form": {
#     "key1": "value1", 
#     "key2": "value2"
#   }, 
# ...

data 인수는 각 키에 대해 여러 값을 가질 수도 있습니다. 데이터를 튜플 리스트 또는 리스트을 값으로 사용하는 사전을 만들어서 수행 할 수 있습니다. 양식에 동일한 키를 사용하는 여러 요소가있는 경우 특히 유용합니다.

payload_tuples = [('key1', 'value1'), ('key1', 'value2')]
r1 = requests.post('https://httpbin.org/post', data=payload_tuples)
payload_dict = {'key1': ['value1', 'value2']}
r2 = requests.post('https://httpbin.org/post', data=payload_dict)

r1_text = r1.text

print(r1.text)
print(r2.text)
# {
# ...
#   "form": {
#     "key1": [
#       "value1", 
#       "value2"
#     ]
#  ...
# }
# 
# {
# ...
#     "key1": [
#       "value1", 
#       "value2"
#     ]
# ...
# }

양식 인코딩되지 않은 데이터를 보내려는 경우가 있습니다. dict 대신 문자열을 전달하면 해당 데이터가 직접 게시됩니다.

예를 들어, GitHub API v3은 JSON 인코딩 POST / PATCH 데이터를 허용합니다.
dict을 직접 인코딩하는 대신 json 매개 변수 (버전 2.4.2에 추가)를 사용하여 직접 전달할 수 있으며 자동으로 인코딩됩니다.

데이터 또는 파일이 전달되면 json 매개 변수는 무시됩니다.

요청에서 json 매개 변수를 사용하면 헤더의 Content-Type이 application / json으로 변경됩니다.

url = "https://api.github.com/"
payload = {'some':'data'}

r1 = requests.post(url, data=json.dumps(payload))
r2 = requests.post(url, json=payload)

print(r1.headers['Content-Type'])
print(r2.headers['Content-Type'])
# application/json; charset=utf-8
# application/json; charset=utf-8

POST a Multipart-Encoded File

requests으로 멀티 파트 인코딩 파일을 간단하게 업로드 할 수 있습니다.
파일 이름, content_type 및 헤더를 명시적으로 설정할 수 있습니다.
원하는 경우 문자열을 파일로 수신하도록 보낼 수 있습니다.

url = 'https://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}


r = requests.post(url, files=files)

Response Status Codes

응답 상태 코드를 확인 할 수 있습니다.
requests에는 또한 쉽게 참조 할 수 있도록 내장 된 상태 코드 조회 객체가 제공됩니다.

r = requests.get('https://httpbin.org/get')

print(r.status_code)
print(requests.codes.ok)
# 200
# 200

잘못된 요청을 만든 경우 Response.raise_for_status ()를 사용하여 요청할 수 있습니다.

bad_r = requests.get('https://httpbin.org/status/404')
print(bad_r.status_code)

print(bad_r.raise_for_status())
# 404
# Traceback (most recent call last):
#   File "D:/source/test/requests_test.py", line 8, in <module>
#     print(bad_r.raise_for_status())
#   File "D:\python\venv\lib\site-packages\requests\models.py", line 940, in raise_for_status
#     raise HTTPError(http_error_msg, response=self)
# requests.exceptions.HTTPError: 404 Client Error: NOT FOUND for url: https://httpbin.org/status/404

그러나 r에 대한 status_code는 200이므로, raise_for_status ()를 호출하면 다음과 같은 결과를 얻습니다.

r.raise_for_status()
# None

Response Headers

Python 사전을 사용하여 서버의 응답 헤더를 볼 수 있습니다.
그러나 사전은 특별합니다. HTTP 헤더 전용입니다. RFC 7230에 따르면 HTTP 헤더 이름은 대소 문자를 구분하지 않습니다.
따라서 원하는 대문자를 사용하여 헤더에 액세스 할 수 있습니다.

r = requests.get('https://httpbin.org/get')

print(r.headers)
print(r.headers['Content-Type'])
print(r.headers.get('content-type'))
# {'Date': 'Sun, 16 Feb 2020 06:18:37 GMT', 'Content-Type': 'application/json', 'Content-Length': '309', 'Connection': 'keep-alive', 'Server': 'gunicorn/19.9.0', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true'}
# application/json
# application/json

또한 서버가 다른 값으로 동일한 헤더를 여러 번 전송할 수 있다는 점에서 특별하지만 RFC 7230에 따라 요청이 단일 매핑 내 사전에 표시 될 수 있도록 요청을 결합합니다.

수신자는 메시지의 의미를 변경하지 않고 동일한 필드 이름을 가진 여러 헤더 필드를 하나의 "field-name : field-value"쌍으로 결합 할 수 있습니다. 각 후속 필드 값을 결합 된 필드 값에 순서대로 추가하여 반점.

쿠키

응답에 일부 쿠키가 포함된 경우 쿠키에 빠르게 접근할 수 있습니다.

url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url)

r.cookies['example_cookie_name']

서버에 자체 쿠키를 보내려면 다음 cookies 매개변수를 사용할 수 있습니다.

url = 'https://httpbin.org/cookies'
cookies = dict(cookies_are='working')
print(cookies)

r = requests.get(url, cookies=cookies)
print(r.text)
# {'cookies_are': 'working'}
#
# {
#   "cookies": {
#     "cookies_are": "working"
#   }
# }

쿠키는 dicts처럼 작동하지만 여러 도메인이나 경로에서 사용하기에 더 완벽한 인터페이스를 제공하는 RequestsCookieJar에 반환됩니다. 쿠키 jar는 requests에 전달할 수도 있습니다.

jar = requests.cookies.RequestsCookieJar()
jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
url = 'https://httpbin.org/cookies'
r = requests.get(url, cookies=jar)

print(r.text)
# {
#   "cookies": {
#     "tasty_cookie": "yum"
#   }
# }

Redirection and History

기본적으로 요청은 HEAD를 제외한 모든 동사에 대해 위치 재 지정을 수행합니다.

Response 객체의 history 속성을 사용하여 리디렉션을 추적 할 수 있습니다.

Response.history 목록에는 요청을 완료하기 위해 작성된 Response 오브젝트가 있습니다. 목록은 가장 오래된 것부터 가장 최근의 것까지 정렬됩니다.

예를 들어 blex는 모든 HTTP 요청을 HTTPS로 리디렉션합니다.

r = requests.get("http://blex.me/")

print(r.url)
print(r.status_code)
print(r.history)
# https://blex.me/trendy
# 200
# [<Response [301]>, <Response [302]>]

GET, OPTIONS, POST, PUT, PATCH 또는 DELETE를 사용하는 경우 allow_redirects 매개 변수를 사용하여 리디렉션 처리를 비활성화 할 수 있습니다.

r = requests.get('https://blex.me/', allow_redirects=False)

print(r.url)
print(r.status_code)
print(r.history)
# https://blex.me/
# 302
# []

HEAD를 사용하는 경우 리디렉션을 활성화 할 수도 있습니다.

r = requests.head('https://blex.me/', allow_redirects=True)

print(r.url)
print(r.status_code)
print(r.history)
# https://blex.me/trendy
# 200
# [<Response [302]>]

Timeouts

timeout 매개 변수를 사용하여 지정된 시간 (초) 후에 응답 대기를 중지하도록 요청에 지시 할 수 있습니다. 거의 모든 프로덕션 코드는 거의 모든 요청에서 이 매개 변수를 사용해야합니다. 그렇지 않으면 프로그램이 무기한 중단 될 수 있습니다.

requests.get('https://github.com/', timeout=0.001)

예외

exception requests.RequestException(*args, **kwargs)[source]

요청을 처리하는 동안 발생한 모호한 예외가있었습니다.

exception requests.ConnectionError(*args, **kwargs)[source]

연결 오류가 발생했습니다.

exception requests.HTTPError(*args, **kwargs)[source]

HTTP 오류가 발생했습니다.

exception requests.URLRequired(*args, **kwargs)[source]

요청하려면 유효한 URL이 필요합니다.

exception requests.TooManyRedirects(*args, **kwargs)[source]

리디렉션이 너무 많습니다.

exception requests.ConnectTimeout(*args, **kwargs)[source]

원격 서버에 연결하는 동안 요청 시간이 초과되었습니다.

이 오류가 발생한 요청은 다시 시도해도 안전합니다.

exception requests.ReadTimeout(*args, **kwargs)[source]

서버가 할당 된 시간 내에 데이터를 보내지 않았습니다.

exception requests.Timeout(*args, **kwargs)[source]

요청 시간이 초과되었습니다.

이 오류를 잡으면 ConnectTimeout 및 ReadTimeout 오류가 모두 발생합니다.

세션

몰라

참고문헌

Requests: HTTP for Humans™. "https://requests.readthedocs.io/en/master/"

HTTP 응답 코드 종류 && HTTP 메소드 종류, "http://bitly.kr/SAXCblyO"

이 글이 도움이 되었나요?

신고하기
0분 전
작성된 댓글이 없습니다. 첫 댓글을 달아보세요!
    댓글을 작성하려면 로그인이 필요합니다.