KR_HTTP - somaz94/python-study GitHub Wiki
HTTPλ ν΄λΌμ΄μΈνΈμ μλ² κ°μ ν΅μ μ μν νλ‘ν μ½μ΄λ€.
import requests
import json
# κΈ°λ³Έ GET μμ²
response = requests.get('https://api.example.com/data')
print(f"μν μ½λ: {response.status_code}") # μν μ½λ
print(f"μλ΅ ν€λ: {response.headers}") # μλ΅ ν€λ
print(f"μλ΅ λ΄μ©: {response.text}") # μλ΅ λ΄μ©
print(f"JSON μλ΅: {response.json()}") # JSON μλ΅ νμ±
# μλ΅ μν νμΈ
if response.status_code == 200:
print("μμ² μ±κ³΅!")
elif response.status_code == 404:
print("리μμ€λ₯Ό μ°Ύμ μ μμ΅λλ€")
else:
print(f"μ€λ₯ λ°μ: {response.status_code}")
# κΈ°λ³Έ POST μμ²
data = {'username': 'user1', 'email': '[email protected]'}
response = requests.post('https://api.example.com/users', json=data)
# multipart/form-data μμ² (νμΌ μ
λ‘λ)
files = {'file': open('document.pdf', 'rb')}
form_data = {'description': 'μ€μ λ¬Έμ'}
response = requests.post(
'https://api.example.com/upload',
files=files,
data=form_data
)
# PUT μμ² (리μμ€ μμ )
update_data = {'username': 'updated_user', 'email': '[email protected]'}
response = requests.put('https://api.example.com/users/123', json=update_data)
# DELETE μμ² (리μμ€ μμ )
response = requests.delete('https://api.example.com/users/123')
# νμμμ μ€μ
try:
response = requests.get('https://api.example.com/data', timeout=5) # 5μ΄ νμμμ
except requests.exceptions.Timeout:
print("μμ² μκ°μ΄ μ΄κ³Όλμμ΅λλ€")
β
νΉμ§:
- κ°λ¨ν μμ²/μλ΅
- JSON μ²λ¦¬
- μν μ½λ νμΈ
- λ€μν HTTP λ©μλ μ§μ
- νμμμ μ€μ
- νμΌ μ λ‘λ
- μν μ½λ μ²λ¦¬
HTTP ν΅μ μμ μ¬μ©λλ μ£Όμ λ©μλμ μ©λμ΄λ€.
λ©μλ | λͺ©μ | νΉμ§ | Python μμ |
---|---|---|---|
GET | λ°μ΄ν° μ‘°ν | λ°μ΄ν°λ₯Ό URLμ ν¬ν¨, μΊμ± κ°λ₯ | requests.get(url) |
POST | λ°μ΄ν° μμ± | λ°μ΄ν°λ₯Ό λ³Έλ¬Έμ ν¬ν¨, μΊμ± λΆκ° | requests.post(url, json=data) |
PUT | λ°μ΄ν° μμ | 리μμ€ μ 체 λ체, λ©±λ±μ± | requests.put(url, json=data) |
PATCH | λ°μ΄ν° λΆλΆ μμ | 리μμ€ μΌλΆ μμ | requests.patch(url, json=data) |
DELETE | λ°μ΄ν° μμ | 리μμ€ μ κ±° | requests.delete(url) |
HEAD | ν€λλ§ μ‘°ν | λ³Έλ¬Έ μμ΄ ν€λλ§ λ°ν | requests.head(url) |
OPTIONS | μ§μ μ΅μ νμΈ | μλ² μ§μ μ΅μ νμΈ | requests.options(url) |
HTTP μμ²μ ν€λμ λ§€κ°λ³μλ₯Ό μΆκ°νμ¬ μλ²μμ ν΅μ μ 컀μ€ν°λ§μ΄μ§νλ λ°©λ²μ΄λ€.
import requests
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
# ν€λ μΆκ°
headers = {
'User-Agent': 'Python/3.9 Requests/2.26.0',
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-Request-ID': '123e4567-e89b-12d3-a456-426614174000',
'Cache-Control': 'no-cache'
}
# URL λ§€κ°λ³μ (쿼리 νλΌλ―Έν°)
params = {
'page': 1,
'limit': 10,
'sort': 'created_at',
'order': 'desc',
'filter': 'active'
}
# κΈ°λ³Έ μμ²
response = requests.get(
'https://api.example.com/users',
headers=headers,
params=params
)
print(f"μ΅μ’
URL: {response.url}") # 쿼리 νλΌλ―Έν°κ° ν¬ν¨λ URL μΆλ ₯
# κΈ°λ³Έ μΈμ¦ (Basic Authentication)
response = requests.get(
'https://api.example.com/protected',
auth=HTTPBasicAuth('username', 'password')
)
# λ€μ΄μ μ€νΈ μΈμ¦ (Digest Authentication)
response = requests.get(
'https://api.example.com/protected',
auth=HTTPDigestAuth('username', 'password')
)
# API ν€ μΈμ¦
api_key = '1234567890abcdef'
# 쿼리 νλΌλ―Έν°λ‘ API ν€ μ λ¬
response = requests.get(
'https://api.example.com/data',
params={'api_key': api_key}
)
# ν€λλ‘ API ν€ μ λ¬
response = requests.get(
'https://api.example.com/data',
headers={'X-API-Key': api_key}
)
# OAuth 2.0 μΈμ¦
token = 'access_token_here'
response = requests.get(
'https://api.example.com/me',
headers={'Authorization': f'Bearer {token}'}
)
# μΏ ν€ μ€μ
cookies = {'session_id': '12345', 'user_id': '42'}
response = requests.get(
'https://api.example.com/dashboard',
cookies=cookies
)
# μλ΅ μΏ ν€ νμΈ
print(response.cookies)
for cookie in response.cookies:
print(f"{cookie.name}: {cookie.value}")
β
νΉμ§:
- ν€λ 컀μ€ν°λ§μ΄μ§
- λ§€κ°λ³μ μ λ¬
- μΈμ¦ μ²λ¦¬
- μΏ ν€ κ΄λ¦¬
- API ν€ μΈμ¦
- OAuth μ§μ
- 컀μ€ν ν€λ
HTTP ν΅μ μμ μμ£Ό μ¬μ©λλ μμ² λ° μλ΅ ν€λμ΄λ€.
ν€λ | μ©λ | μμ |
---|---|---|
Content-Type | λ°μ΄ν° νμ μ§μ |
application/json , multipart/form-data
|
Authorization | μΈμ¦ μ 보 μ λ¬ |
Bearer token123 , Basic base64encoded
|
User-Agent | ν΄λΌμ΄μΈνΈ μλ³ | Python/3.9 Requests/2.26.0 |
Accept | μλ΅ νμ μμ² |
application/json , text/html
|
Cache-Control | μΊμ± λμ μ μ΄ |
no-cache , max-age=3600
|
Cookie | μΏ ν€ μ μ‘ | session_id=abc123 |
X-Request-ID | μμ² μΆμ | 123e4567-e89b-12d3-a456-426614174000 |
μΈμ
μ μ¬μ©νμ¬ μ¬λ¬ μμ² κ°μ μνλ₯Ό μ μ§νκ³ ν¨μ¨μ μΌλ‘ HTTP ν΅μ μ κ΄λ¦¬νλ λ°©λ²μ΄λ€.
import requests
import time
# μΈμ
μμ±
session = requests.Session()
# μΈμ
μ κΈ°λ³Έ ν€λ μ€μ
session.headers.update({
'User-Agent': 'Python/3.9 SessionClient/1.0',
'Authorization': 'Bearer token123',
'Accept': 'application/json'
})
# μΈμ
μ κΈ°λ³Έ μΏ ν€ μ€μ
session.cookies.update({'user_preference': 'dark_mode'})
# μΈμ
μ ν΅ν μμ² - λͺ¨λ μμ²μ ν€λμ μΏ ν€κ° μλμΌλ‘ ν¬ν¨λ¨
response = session.get('https://api.example.com/profile')
print(f"νλ‘ν μλ΅: {response.status_code}")
# μΈμ
μ μΆκ° λ§€κ°λ³μ μ€μ
response = session.get(
'https://api.example.com/articles',
params={'category': 'technology', 'page': 1}
)
print(f"κΈ°μ¬ μλ΅: {response.status_code}")
# μΈμ
μ ν΅ν POST μμ²
response = session.post(
'https://api.example.com/comments',
json={'article_id': 42, 'text': 'μ’μ κΈ°μ¬μ
λλ€!'}
)
print(f"λκΈ μλ΅: {response.status_code}")
# μΈμ
μ μΈμ¦ μ€μ (λͺ¨λ μμ²μ μ μ©)
session.auth = ('username', 'password')
response = session.get('https://api.example.com/secure')
# μΈμ
μ μμ² ν
μΆκ°
def logging_hook(response, *args, **kwargs):
print(f"μμ² URL: {response.url}")
print(f"μν μ½λ: {response.status_code}")
print(f"μλ΅ μκ°: {response.elapsed.total_seconds()}μ΄")
return response
session.hooks['response'] = [logging_hook]
# μΈμ
μ νμμμ μ€μ
session.request('GET', 'https://api.example.com/data', timeout=(3.05, 27)) # (μ°κ²° νμμμ, μ½κΈ° νμμμ)
# 컨ν
μ€νΈ λ§€λμ λ‘ μΈμ
μ¬μ© (μλμΌλ‘ 리μμ€ μ 리)
with requests.Session() as session:
session.headers.update({'Authorization': 'Bearer session_token'})
response = session.get('https://api.example.com/data')
print(f"μλ΅: {response.json()}")
# μΈμ
λ΄μμ μ¬λ¬ μμ² μν
for page in range(1, 4):
response = session.get(
'https://api.example.com/articles',
params={'page': page}
)
articles = response.json().get('articles', [])
print(f"νμ΄μ§ {page}: {len(articles)} κΈ°μ¬")
# μΈμ
μν νμΈ λ° λ¦¬μμ€ μ 리
print(f"μΈμ
μΏ ν€: {session.cookies}")
print(f"μΈμ
ν€λ: {session.headers}")
session.close() # μΈμ
리μμ€ λͺ
μμ μ 리
β
νΉμ§:
- μΈμ μ¬μ¬μ©
- ν€λ μ μ§
- μΏ ν€ κ΄λ¦¬
- μΈμ¦ μ 보 보쑴
- 리μμ€ ν¨μ¨μ±
- λ€νΈμν¬ μ΅μ ν
- μμ² ν μ§μ
μΈμ
μ μ¬μ©νμ¬ HTTP μμ²μ κ΄λ¦¬ν λμ μ₯μ μ΄λ€.
- μ°κ²° μ¬μ¬μ©: TCP μ°κ²°μ μ¬μ¬μ©νμ¬ λ€νΈμν¬ ν¨μ¨μ± ν₯μ
- μΏ ν€ μλ κ΄λ¦¬: μλ²κ° μ€μ ν μΏ ν€λ₯Ό μλμΌλ‘ μ μ₯νκ³ νμ μμ²μ ν¬ν¨
- μΌκ΄λ ν€λ: λͺ¨λ μμ²μ λμΌν κΈ°λ³Έ ν€λ μ μ© κ°λ₯
- μΈμ¦ μν μ μ§: λ‘κ·ΈμΈ ν μΈμ¦ μνλ₯Ό μ μ§νλ©° μμ² κ°λ₯
- TCP μ°κ²° νλ§: HTTP Keep-Aliveλ₯Ό ν΅ν μ°κ²° νλ§μΌλ‘ μ±λ₯ ν₯μ
- μμ κ΄λ¦¬ κ°μν: 컨ν μ€νΈ λ§€λμ λ₯Ό ν΅ν μλ 리μμ€ μ 리 κ°λ₯
import time
from requests.exceptions import RequestException
def make_request_with_retry(url, max_retries=3, delay=1):
for attempt in range(max_retries):
try:
response = requests.get(url)
response.raise_for_status()
return response
except RequestException as e:
if attempt == max_retries - 1:
raise e
time.sleep(delay * (attempt + 1))
return None
β νΉμ§:
- μμΈ μ²λ¦¬
- μ¬μλ λ‘μ§
- μ§μ° μκ° μ€μ
import aiohttp
import asyncio
async def fetch_url(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
urls = [
'https://api.example.com/1',
'https://api.example.com/2',
'https://api.example.com/3'
]
async with aiohttp.ClientSession() as session:
tasks = [fetch_url(session, url) for url in urls]
results = await asyncio.gather(*tasks)
return results
β νΉμ§:
- λΉλκΈ° μ²λ¦¬
- λμ μμ²
- μ±λ₯ μ΅μ ν
class APIClient:
def __init__(self, base_url, api_key=None):
self.base_url = base_url.rstrip('/')
self.session = requests.Session()
if api_key:
self.session.headers.update({
'Authorization': f'Bearer {api_key}'
})
def _make_request(self, method, endpoint, **kwargs):
url = f"{self.base_url}/{endpoint.lstrip('/')}"
response = self.session.request(method, url, **kwargs)
response.raise_for_status()
return response.json()
def get(self, endpoint, params=None):
return self._make_request('GET', endpoint, params=params)
β νΉμ§:
- ν΄λμ€ κΈ°λ° κ΅¬ν
- λ©μλ μΆμν
- μ¬μ¬μ©μ±
β λͺ¨λ² μ¬λ‘:
- νμμμ μ€μ
- μ μ ν μλ¬ μ²λ¦¬
- μΈμ μ¬μ¬μ©
- λΉλκΈ° μμ² νμ©
- ν€λ κ΄λ¦¬
- μΈμ¦ μ²λ¦¬
- μ¬μλ λ‘μ§ κ΅¬ν
- νλ‘μ μ¬μ© κ³ λ €