본문 바로가기
카테고리 없음

Python’s Requests Library (Guide)​ HTTP 요청 및 응답

by EasyGPT 2023. 12. 24.
반응형

Python’s Requests Library (Guide)

by Alex Ronquillo

Table of Contents

requests library는 Python에서 HTTP 요청을 만드는 사실상의 표준.

아름답고 간단한 API를 통해 requests의 복잡성을 추상화하므로 애플리케이션에서 서비스와 상호작용하고 데이터를 소비하는 데 집중할 수 있습니다.

The requests library is the de facto standard for making HTTP requests in Python. It abstracts the complexities of making requests behind a beautiful, simple API so that you can focus on interacting with services and consuming data in your application.

이 글 전반에 걸쳐 requests이 제공해야 하는 가장 유용한 기능 중 일부.

발생할 수 있는 다양한 상황에 대해 이러한 기능을 사용자정의하고 최적화하는 방법.

효율적 방식으로 requests 사용하는 방법.

외부서비스에 대한 requests이 애플리케이션 속도 저하시키는 것을 방지하는 방법.

Throughout this article, you’ll see some of the most useful features that requests has to offer as well as how to customize and optimize those features for different situations you may come across. You’ll also learn how to use requests in an efficient way as well as how to prevent requests to external services from slowing down your application.

이 튜토리얼에서는 배우는 방법:

In this tutorial, you’ll learn how to:

  • 가장 일반적인 HTTP 방법을 사용, requests 만들기 Make requests using the most common HTTP methods
  • 쿼리 문자열과 메시지 본문을 사용, 요청 헤더와 데이터를 사용자맞춤하기 Customize your requests’ headers and data, using the query string and message body
  • 요청 및 응답에서 데이터 검사하기 Inspect data from your requests and responses
  • 인증된 requests 만들기 Make authenticated requests
  • 애플리케이션이 백업되거나 속도 느려지는 것을 방지하도록 requests 구성하기 Configure your requests to help prevent your application from backing up or slowing down

이 글에 포함된 기능과 예제를 이해하는 데 필요한 만큼의 정보를 포함하려고 노력했지만, HTTP에 대한 매우 basic general knowledge of HTTP 기본적 일반 지식이 있다고 가정합니다.

즉, 어쨌든 여전히 잘 따라갈 수 있을 수도 있습니다.

이제 문제가 해결되었으므로 애플리케이션에서 requests을 어떻게 사용할 수 있는지 살펴보겠습니다.

Though I’ve tried to include as much information as you need to understand the features and examples included in this article, I do assume a very basic general knowledge of HTTP. That said, you still may be able to follow along fine anyway.

Now that that is out of the way, let’s dive in and see how you can use requests in your application!

Getting Started With requests

requests library 설치 부터 시작해 보겠습니다.

Let’s begin by installing the requests library.

이렇게 하려면 다음 명령을 실행:

To do so, run the following command:

pip install requests

Python packages 관리 Pipenv를 사용하려는 경우, 다음을 실행할 수 있습니다:

If you prefer to use Pipenv for managing Python packages, you can run the following:

pipenv install requests

requests이 설치되면 애플리케이션에서 사용할 수 있습니다.

Importing requests 는 다음과 같습니다:

Once requests is installed, you can use it in your application. Importing requests looks like this:

Python

import requests

이제 모든 설정이 완료되었으므로 requests을 통한 여정을 시작할 차례입니다.

첫 번째 목표는 GET request을 만드는 방법을 배우는 것입니다.

Now that you’re all set up, it’s time to begin your journey through requests. Your first goal will be learning how to make a GET request.

The GET Request

GET 및 POST 같은 HTTP methodsHTTP 요청 시 수행하려는 작업을 결정.

GET 및 POST 외에도 이 튜토리얼 뒷부분에서 사용할 몇 가지 일반적 방법이 있습니다.

가장 일반적 HTTP 메소드 중 하나는 GET.

GET 메서드는 지정된 리소스에서 데이터를 가져오거나 검색하려고 함을 나타냅니다.

GET request 하려면 request.get()을 호출.

이를 테스트하려면, 다음 URL로 get()을 호출하여 GitHub의 Root REST APIGET request 할 수 있습니다:

HTTP methods such as GET and POST, determine which action you’re trying to perform when making an HTTP request. Besides GET and POST, there are several other common methods that you’ll use later in this tutorial.

One of the most common HTTP methods is GET. The GET method indicates that you’re trying to get or retrieve data from a specified resource. To make a GET request, invoke requests.get().

To test this out, you can make a GET request to GitHub’s Root REST API by calling get() with the following URL:

Python

>>> requests.get('https://api.github.com')

<Response [200]>

축하해요!

첫 번째 request을 하셨습니다.

해당 요청의 response에 대해 좀 더 자세히 살펴보겠습니다.

Congratulations! You’ve made your first request. Let’s dive a little deeper into the response of that request.

https://smartstore.naver.com/dopza/products/4569179898

The Response

Response은 request 결과를 검사하는 강력한 객체.

동일한 request을 다시 만들어 보는데, 이번에는 return valuevariable에 저장하여 해당 attribute과 behaviors을 자세히 살펴볼 수 있습니다.

A Response is a powerful object for inspecting the results of the request. Let’s make that same request again, but this time store the return value in a variable so that you can get a closer look at its attributes and behaviors:

Python

>>> response = requests.get('https://api.github.com')

여기서는 response의 인스턴스인 get()의 반환 값을 캡처하여 response라는 변수에 저장했습니다.

이제 response을 사용, GET request 결과에 대한 많은 정보를 볼 수 있습니다.

In this example, you’ve captured the return value of get(), which is an instance of Response, and stored it in a variable called response. You can now use response to see a lot of information about the results of your GET request.

Status Codes

Response에서 수집할 수 있는 첫째 정보는 status code.

상태코드 status code는 요청 상태를 알려줍니다.

예를 들어,

200 OK 상태는 요청이 성공했음을 의미하고,

404 NOT FOUND 상태는 찾고 있던 리소스를 찾을 수 없음을 의미.

request에 대해 어떤 일이 발생했는지, 구체적 통찰력을 제공하는 다른 가능한 상태코드도 많이 있습니다 many other possible status codes.

.status_code에 접근하면 서버가 반환한 status code를 확인할 수 있슴:

The first bit of information that you can gather from Response is the status code. A status code informs you of the status of the request.

For example, a 200 OK status means that your request was successful, whereas a 404 NOT FOUND status means that the resource you were looking for was not found. There are many other possible status codes as well to give you specific insights into what happened with your request.

By accessing .status_code, you can see the status code that the server returned:

Python

>>> response.status_code

200

.status_code가 200을 반환했는데, 이는 당신의 request가 성공했고 서버가 당신이 요청한 데이터로 응답했음을 의미합니다.

때로는 이 정보를 사용하여 코드에서 결정을 내릴 수도 있습니다.

.status_code returned a 200, which means your request was successful and the server responded with the data you were requesting.

Sometimes, you might want to use this information to make decisions in your code:

Python

if response.status_code == 200:

print('Success!')

elif response.status_code == 404:

print('Not Found.')

이 논리를 사용하면, 서버가 상태코드 200를 반환하면 프로그램은 Success!를 인쇄.

결과가 404이면 프로그램은 찾을 수 없음 Not Found을 인쇄.

With this logic, if the server returns a 200 status code, your program will print Success!. If the result is a 404, your program will print Not Found.

requests는 이 프로세스를 한 단계 더 단순화할 수 있습니다.

조건식에서 Response 인스턴스를 사용하는 경우, 상태코드가 200에서 400 사이이면 True로 평가되고 그렇지 않으면 False로 평가.

따라서 if 문을 다시 작성하여 마지막 예를 단순화할 수 있습니다.

requests goes one step further in simplifying this process for you. If you use a Response instance in a conditional expression, it will evaluate to True if the status code was between 200 and 400, and False otherwise.

Therefore, you can simplify the last example by rewriting the if statement:

Python

if response:

print('Success!')

else:

print('An error has occurred.')

기술적 세부사항 Technical Detail

Truth Value Test __bool__()이 Response에 대한 overloaded method 이기 때문에 가능.

이는 객체의 진리값을 결정할 때, 상태코드를 고려하도록 Response의 기본 동작이 재정의되었음을 의미.

This Truth Value Test is made possible because __bool__() is an overloaded method on Response.

This means that the default behavior of Response has been redefined to take the status code into account when determining the truth value of the object.

이 메서드는 상태코드가 200인지 확인하는 것이 아니라는 점을 명심.

그 이유는 204 NO CONTENT 304 NOT MODIFIED 같은 200~400 범위 내의 다른 상태코드도, 실행가능한 응답을 제공한다고 생각에서, 성공으로 간주되기 때문입니다.

Keep in mind that this method is not verifying that the status code is equal to 200. The reason for this is that other status codes within the 200 to 400 range, such as 204 NO CONTENT and 304 NOT MODIFIED, are also considered successful in the sense that they provide some workable response.

예를 들어, 204는 응답이 성공했음을 알려주지만 메시지 본문에 반환할 콘텐츠가 없습니다.

따라서 request가 일반적으로 성공했는지 알고 싶은 경우에만 이 편리한 약칭을 사용하고, 필요한 경우 상태코드에 따라 응답을 적절하게 처리하십시오.

For example, the 204 tells you that the response was successful, but there’s no content to return in the message body.

So, make sure you use this convenient shorthand only if you want to know if the request was generally successful and then, if necessary, handle the response appropriately based on the status code.

if 문에서 응답의 상태코드를 확인하고 싶지 않다고 가정.

대신 요청이 실패한 경우, 예외 exception 를 발생시키려 합니다.

.raise_for_status()를 사용하여 이 작업을 수행할 수 있습니다.

Let’s say you don’t want to check the response’s status code in an if statement. Instead, you want to raise an exception if the request was unsuccessful. You can do this using .raise_for_status():

Python

import requests from requests.exceptions

import HTTPError

for url in ['https://api.github.com', 'https://api.github.com/invalid']:

try:

response = requests.get(url)

# If the response was successful, no Exception will be raised

response.raise_for_status()

except HTTPError as http_err:

print(f'HTTP error occurred: {http_err}') # Python 3.6

except Exception as err:

print(f'Other error occurred: {err}') # Python 3.6

else:

print('Success!')

.raise_for_status()를 호출하면 특정 상태코드에 대해 HTTPError 발생.

상태코드가 성공적 요청을 나타내면 해당 예외가 발생하지 않고 프로그램이 진행됩니다.

If you invoke .raise_for_status(), an HTTPError will be raised for certain status codes. If the status code indicates a successful request, the program will proceed without that exception being raised.

Further Reading: Python 3.6의 f-strings에 익숙하지 않다면, 이것은 형식화된 문자열을 단순화하는 좋은 방법이므로 이를 활용해 보시기 바랍니다 If you’re not familiar with Python 3.6’s f-strings, I encourage you to take advantage of them as they are a great way to simplify your formatted strings.
 

이제 서버에서 받은 응답의 상태코드를 처리하는 방법에 대해 많이 알게 되었습니다.

그러나 GET request 할 때 응답의 상태코드에만 관심을 두는 경우는 거의 없습니다.

일반적으로 더 많은 것을 보고 싶어합니다.

Now, you know a lot about how to deal with the status code of the response you got back from the server. However, when you make a GET request, you rarely only care about the status code of the response. Usually, you want to see more.

다음으로 서버가 응답본문 body of the response으로 다시 보낸 실제 데이터를 보는 방법을 살펴보겠습니다.

Next, you’ll see how to view the actual data that the server sent back in the body of the response.

Content

GET request의 응답에는 메시지 본문에 payload라는 몇 가지 중요한 정보가 포함되는 경우가 많습니다.

Response의 속성과 메서드를 사용, 다양한 형식으로 payload를 볼 수 있습니다.

응답 내용을 bytes 단위로 보려면 .content를 사용:

The response of a GET request often has some valuable information, known as a payload, in the message body. Using the attributes and methods of Response, you can view the payload in a variety of different formats.

To see the response’s content in bytes, you use .content:

Python

>>> response = requests.get('https://api.github.com')

>>> response.content b'{"current_user_url":"https://api.github.com/user","current_user_authorizations_html_url":"https://github.com/settings/connections/applications{/client_id}","authorizations_url":"https://api.github.com/authorizations","code_search_url":"https://api.github.com/search/code?q={query}{&page,per_page,sort,order}","commit_search_url":"https://api.github.com/search/commits?q={query}{&page,per_page,sort,order}","emails_url":"https://api.github.com/user/emails","emojis_url":"https://api.github.com/emojis","events_url":"https://api.github.com/events","feeds_url":"https://api.github.com/feeds","followers_url":"https://api.github.com/user/followers","following_url":"https://api.github.com/user/following{/target}","gists_url":"https://api.github.com/gists{/gist_id}","hub_url":"https://api.github.com/hub","issue_search_url":"https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}","issues_url":"https://api.github.com/issues","keys_url":"https://api.github.com/user/keys","notifications_url":"https://api.github.com/notifications","organization_repositories_url":"https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}","organization_url":"https://api.github.com/orgs/{org}","public_gists_url":"https://api.github.com/gists/public","rate_limit_url":"https://api.github.com/rate_limit","repository_url":"https://api.github.com/repos/{owner}/{repo}","repository_search_url":"https://api.github.com/search/repositories?q={query}{&page,per_page,sort,order}","current_user_repositories_url":"https://api.github.com/user/repos{?type,page,per_page,sort}","starred_url":"https://api.github.com/user/starred{/owner}{/repo}","starred_gists_url":"https://api.github.com/gists/starred","team_url":"https://api.github.com/teams","user_url":"https://api.github.com/users/{user}","user_organizations_url":"https://api.github.com/user/orgs","user_repositories_url":"https://api.github.com/users/{user}/repos{?type,page,per_page,sort}","user_search_url":"https://api.github.com/search/users?q={query}{&page,per_page,sort,order}"}'

.content를 사용하면 응답 payload원시 bytes에 액세스할 수 있지만, UTF-8 같은 문자 인코딩을 사용하여 이를 string로 변환하려는 경우도 많습니다.

.text에 액세스하면, response이 자동으로 해당 작업을 수행합니다:

While .content gives you access to the raw bytes of the response payload, you will often want to convert them into a string using a character encoding such as UTF-8. response will do that for you when you access .text:

Python

>>> response.text '{"current_user_url":"https://api.github.com/user","current_user_authorizations_html_url":"https://github.com/settings/connections/applications{/client_id}","authorizations_url":"https://api.github.com/authorizations","code_search_url":"https://api.github.com/search/code?q={query}{&page,per_page,sort,order}","commit_search_url":"https://api.github.com/search/commits?q={query}{&page,per_page,sort,order}","emails_url":"https://api.github.com/user/emails","emojis_url":"https://api.github.com/emojis","events_url":"https://api.github.com/events","feeds_url":"https://api.github.com/feeds","followers_url":"https://api.github.com/user/followers","following_url":"https://api.github.com/user/following{/target}","gists_url":"https://api.github.com/gists{/gist_id}","hub_url":"https://api.github.com/hub","issue_search_url":"https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}","issues_url":"https://api.github.com/issues","keys_url":"https://api.github.com/user/keys","notifications_url":"https://api.github.com/notifications","organization_repositories_url":"https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}","organization_url":"https://api.github.com/orgs/{org}","public_gists_url":"https://api.github.com/gists/public","rate_limit_url":"https://api.github.com/rate_limit","repository_url":"https://api.github.com/repos/{owner}/{repo}","repository_search_url":"https://api.github.com/search/repositories?q={query}{&page,per_page,sort,order}","current_user_repositories_url":"https://api.github.com/user/repos{?type,page,per_page,sort}","starred_url":"https://api.github.com/user/starred{/owner}{/repo}","starred_gists_url":"https://api.github.com/gists/starred","team_url":"https://api.github.com/teams","user_url":"https://api.github.com/users/{user}","user_organizations_url":"https://api.github.com/user/orgs","user_repositories_url":"https://api.github.com/users/{user}/repos{?type,page,per_page,sort}","user_search_url":"https://api.github.com/search/users?q={query}{&page,per_page,sort,order}"}'

bytes를 str로 디코딩하려면 인코딩체계가 필요하기 때문에, requests은 인코딩체계를 지정하지 않으면 응답 headers를 기반으로 encoding을 추측하려고 시도합니다.

.text에 액세스하기 전 .encoding을 설정하여 명시적 인코딩을 제공할 수 있습니다.

Because the decoding of bytes to a str requires an encoding scheme, requests will try to guess the encoding based on the response’s headers if you do not specify one. You can provide an explicit encoding by setting .encoding before accessing .text:

Python

>>> response.encoding = 'utf-8' # Optional: requests infers this internally

>>> response.text '{"current_user_url":"https://api.github.com/user","current_user_authorizations_html_url":"https://github.com/settings/connections/applications{/client_id}","authorizations_url":"https://api.github.com/authorizations","code_search_url":"https://api.github.com/search/code?q={query}{&page,per_page,sort,order}","commit_search_url":"https://api.github.com/search/commits?q={query}{&page,per_page,sort,order}","emails_url":"https://api.github.com/user/emails","emojis_url":"https://api.github.com/emojis","events_url":"https://api.github.com/events","feeds_url":"https://api.github.com/feeds","followers_url":"https://api.github.com/user/followers","following_url":"https://api.github.com/user/following{/target}","gists_url":"https://api.github.com/gists{/gist_id}","hub_url":"https://api.github.com/hub","issue_search_url":"https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}","issues_url":"https://api.github.com/issues","keys_url":"https://api.github.com/user/keys","notifications_url":"https://api.github.com/notifications","organization_repositories_url":"https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}","organization_url":"https://api.github.com/orgs/{org}","public_gists_url":"https://api.github.com/gists/public","rate_limit_url":"https://api.github.com/rate_limit","repository_url":"https://api.github.com/repos/{owner}/{repo}","repository_search_url":"https://api.github.com/search/repositories?q={query}{&page,per_page,sort,order}","current_user_repositories_url":"https://api.github.com/user/repos{?type,page,per_page,sort}","starred_url":"https://api.github.com/user/starred{/owner}{/repo}","starred_gists_url":"https://api.github.com/gists/starred","team_url":"https://api.github.com/teams","user_url":"https://api.github.com/users/{user}","user_organizations_url":"https://api.github.com/user/orgs","user_repositories_url":"https://api.github.com/users/{user}/repos{?type,page,per_page,sort}","user_search_url":"https://api.github.com/search/users?q={query}{&page,per_page,sort,order}"}'

응답을 살펴보면 실제로 직렬화된 JSON 콘텐츠임을 알 수 있습니다.

사전을 얻으려면 .text에서 검색한 문자열을 가져와 json.loads()를 사용하여 역직렬화할 수 있습니다.

그러나 이 작업을 수행하는 더 간단한 방법은 .json()을 사용하는 것입니다.

If you take a look at the response, you’ll see that it is actually serialized JSON content. To get a dictionary, you could take the str you retrieved from .text and deserialize it using json.loads(). However, a simpler way to accomplish this task is to use .json():

Python

>>> response.json()

{'current_user_url': 'https://api.github.com/user', 'current_user_authorizations_html_url': 'https://github.com/settings/connections/applications{/client_id}', 'authorizations_url': 'https://api.github.com/authorizations', 'code_search_url': 'https://api.github.com/search/code?q={query}{&page,per_page,sort,order}', 'commit_search_url': 'https://api.github.com/search/commits?q={query}{&page,per_page,sort,order}', 'emails_url': 'https://api.github.com/user/emails', 'emojis_url': 'https://api.github.com/emojis', 'events_url': 'https://api.github.com/events', 'feeds_url': 'https://api.github.com/feeds', 'followers_url': 'https://api.github.com/user/followers', 'following_url': 'https://api.github.com/user/following{/target}', 'gists_url': 'https://api.github.com/gists{/gist_id}', 'hub_url': 'https://api.github.com/hub', 'issue_search_url': 'https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}', 'issues_url': 'https://api.github.com/issues', 'keys_url': 'https://api.github.com/user/keys', 'notifications_url': 'https://api.github.com/notifications', 'organization_repositories_url': 'https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}', 'organization_url': 'https://api.github.com/orgs/{org}', 'public_gists_url': 'https://api.github.com/gists/public', 'rate_limit_url': 'https://api.github.com/rate_limit', 'repository_url': 'https://api.github.com/repos/{owner}/{repo}', 'repository_search_url': 'https://api.github.com/search/repositories?q={query}{&page,per_page,sort,order}', 'current_user_repositories_url': 'https://api.github.com/user/repos{?type,page,per_page,sort}', 'starred_url': 'https://api.github.com/user/starred{/owner}{/repo}', 'starred_gists_url': 'https://api.github.com/gists/starred', 'team_url': 'https://api.github.com/teams', 'user_url': 'https://api.github.com/users/{user}', 'user_organizations_url': 'https://api.github.com/user/orgs', 'user_repositories_url': 'https://api.github.com/users/{user}/repos{?type,page,per_page,sort}', 'user_search_url': 'https://api.github.com/search/users?q={query}{&page,per_page,sort,order}'}

.json()의 반환 값 type은 사전이므로 키를 통해 객체의 값에 액세스할 수 있습니다.

상태 코드와 메시지 본문을 사용하여 많은 작업을 수행할 수 있습니다.

그러나 응답 자체에 대한 메타데이터와 같은 추가 정보가 필요한 경우 응답 헤더를 살펴봐야 합니다.

The type of the return value of .json() is a dictionary, so you can access values in the object by key.

You can do a lot with status codes and message bodies. But, if you need more information, like metadata about the response itself, you’ll need to look at the response’s headers.

https://amzn.to/41x75fO

Headers

response headers는 응답 페이로드의 콘텐츠 type 및 응답을 캐시하는 기간에 대한 time limit 같은 유용한 정보를 제공할 수 있습니다.

이러한 헤더를 보려면 .headers에 액세스:

The response headers can give you useful information, such as the content type of the response payload and a time limit on how long to cache the response. To view these headers, access .headers:

Python

>>> response.headers

{'Server': 'GitHub.com', 'Date': 'Mon, 10 Dec 2018 17:49:54 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Transfer-Encoding': 'chunked', 'Status': '200 OK', 'X-RateLimit-Limit': '60', 'X-RateLimit-Remaining': '59', 'X-RateLimit-Reset': '1544467794', 'Cache-Control': 'public, max-age=60, s-maxage=60', 'Vary': 'Accept', 'ETag': 'W/"7dc470913f1fe9bb6c7355b50a0737bc"', 'X-GitHub-Media-Type': 'github.v3; format=json', 'Access-Control-Expose-Headers': 'ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type', 'Access-Control-Allow-Origin': '*', 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains; preload', 'X-Frame-Options': 'deny', 'X-Content-Type-Options': 'nosniff', 'X-XSS-Protection': '1; mode=block', 'Referrer-Policy': 'origin-when-cross-origin, strict-origin-when-cross-origin', 'Content-Security-Policy': "default-src 'none'", 'Content-Encoding': 'gzip', 'X-GitHub-Request-Id': 'E439:4581:CF2351:1CA3E06:5C0EA741'}

.headers는 사전과 유사한 객체를 반환하므로 키로 헤더 값에 액세스할 수 있습니다.

예를 들어 응답 페이로드의 콘텐츠 type을 보려면 Content-Type에 액세스하면 됩니다.

.headers returns a dictionary-like object, allowing you to access header values by key. For example, to see the content type of the response payload, you can access Content-Type:

Python

>>> response.headers['Content-Type']

'application/json; charset=utf-8'

하지만 사전과 유사한 이 headers object에는 뭔가 특별한 것이 있습니다.

HTTP spec에서는 헤더가 대소문자를 구분하지 않도록 정의합니다.

, 대문자 사용에 대해 걱정하지 않고 이러한 헤더에 액세스할 수 있습니다.

There is something special about this dictionary-like headers object, though. The HTTP spec defines headers to be case-insensitive, which means we are able to access these headers without worrying about their capitalization:

Python

>>> response.headers['content-type']

'application/json; charset=utf-8'

'content-type' 키를 사용하든 'Content-Type' 키를 사용하든 동일 값을 얻게 됩니다.

이제 Response에 대한 기본 사항을 배웠습니다.

가장 유용한 속성과 메소드가 실제로 작동하는 것을 확인했습니다.

한 걸음 물러서서 GET 요청을 맞춤설정할 때 응답이 어떻게 변하는지 살펴보겠습니다.

Whether you use the key 'content-type' or 'Content-Type', you’ll get the same value.

Now, you’ve learned the basics about Response. You’ve seen its most useful attributes and methods in action. Let’s take a step back and see how your responses change when you customize your GET requests.

https://amzn.to/3ttKILQ

반응형

댓글