requests.post() 함수는 HTTP POST 요청을 보내는 데 사용됩니다. 이 함수를 사용하여 서버에 데이터를 전송하고, 응답을 받을 수 있습니다. 아래는 requests.post() 함수를 사용하는 방법에 대한 예시입니다.
1. 기본적인 방법
import requests
url = "https://example.com/api"
data = {"name": "John", "age": 30}
response = requests.post(url, data=data)
print(response.text)
위 코드는 https://example.com/api URL로 데이터를 전송하는 POST 요청을 보냅니다. data 매개변수에 전송할 데이터를 딕셔너리 형태로 지정합니다. 응답은 response 변수에 저장되며, response.text 속성을 사용하여 응답 본문을 출력합니다.
2. 헤더를 지정하는 방법
import requests
url = "https://example.com/api"
data = {"name": "John", "age": 30}
headers = {"Authorization": "token"}
response = requests.post(url, data=data, headers=headers)
print(response.text)
위 코드는 https://example.com/api URL로 데이터를 전송하는 POST 요청을 보냅니다. headers 매개변수에 전송할 헤더를 딕셔너리 형태로 지정합니다. 응답은 response 변수에 저장되며, response.text 속성을 사용하여 응답 본문을 출력합니다.
3. JSON 데이터를 전송하는 POST 요청
import requests
import json
url = "https://example.com/api"
data = {"name": "John", "age": 30}
headers = {"Content-Type": "application/json"}
json_data = json.dumps(data)
response = requests.post(url, data=json_data, headers=headers)
#response = requests.post(url, data=json.dumps(data), headers=headers)
print(response.text)
위 코드는 https://example.com/api URL로 JSON 데이터를 전송하는 POST 요청을 보냅니다. headers 매개변수에 Content-Type을 application/json으로 지정하여 JSON 데이터를 전송합니다. data 매개변수에는 JSON 데이터를 문자열로 직렬화한 값을 전달합니다. 응답은 response 변수에 저장되며, response.text 속성을 사용하여 응답 본문을 출력합니다.
4. 파일을 전송하는 POST 요청
import requests
url = "https://example.com/api"
files = {"file": open("example.txt", "rb")}
response = requests.post(url, files=files)
print(response.text)
위 코드는 https://example.com/api URL로 파일을 전송하는 POST 요청을 보냅니다. files 매개변수에 전송할 파일을 딕셔너리 형태로 지정합니다. 파일은 open() 함수를 사용하여 바이너리 모드로 열어서 전달합니다. 응답은 response 변수에 저장되며, response.text 속성을 사용하여 응답 본문을 출력합니다.
위 예시들은 requests.post() 함수를 사용하는 방법에 대한 다양한 예시입니다. 이를 참고하여 필요한 방식으로 requests.post() 함수를 사용하시면 됩니다.
'성장일기 > 파이썬' 카테고리의 다른 글
[python] 문자열 리스트를 문자열로 변환하는 방법 ("".join()) (0) | 2023.06.26 |
---|---|
[python] 중복되지 않는 램던 추출 하는 방법 random.sample() (0) | 2023.06.26 |
파이썬 데이터 ->문자열 ,파이썬 데이터 -> JSON 데이터로 변환 (josn.dumps()와 json.loads()) (0) | 2023.06.26 |
[python] json 데이터 파싱하는 방법 정리 (0) | 2023.06.26 |
[python] json.dumps()로 json 데이터 출력 이쁘게 출력하기 (0) | 2023.06.25 |