Notice
Recent Posts
Recent Comments
Link
SeouliteLab
파이썬으로 HTTP/2 통신하기: h2 모듈 활용법 본문
HTTP/2는 성능을 향상시키기 위해 설계된 최신의 HTTP 프로토콜 중 하나입니다. 파이썬에서는 h2 모듈을 사용하여 HTTP/2 통신을 간편하게 처리할 수 있습니다. 이 모듈을 사용하면 단일 연결을 통해 여러 요청을 동시에 처리하고, 헤더 압축 및 스트림 병렬화 등의 기능을 활용할 수 있습니다. 이제 몇 가지 예제를 통해 h2 모듈의 활용법을 살펴보겠습니다.
예제 1: HTTP/2 클라이언트 생성 및 요청 보내기
import h2.connection
import h2.events
import h2.config
import h2.settings
# HTTP/2 연결 설정
config = h2.config.H2Configuration(client_side=True)
conn = h2.connection.H2Connection(config=config)
# 연결 초기화
conn.initiate_connection()
print(conn.data_to_send())
# 요청 보내기
conn.send_headers(1, headers=[(':method', 'GET'), (':path', '/'), (':authority', 'example.com')])
conn.send_data(1, b'', end_stream=True)
print(conn.data_to_send())
이 예제에서는 h2 모듈을 사용하여 HTTP/2 클라이언트를 만들고, 서버에 GET 요청을 보냅니다. 연결을 초기화하고, 요청에 필요한 헤더 및 데이터를 보냅니다.
예제 2: HTTP/2 서버 생성 및 응답 보내기
import h2.connection
import h2.events
import h2.config
import h2.settings
# HTTP/2 연결 설정
config = h2.config.H2Configuration(client_side=False)
conn = h2.connection.H2Connection(config=config)
# 연결 초기화
conn.initiate_connection()
print(conn.data_to_send())
# 응답 보내기
response_headers = [
(':status', '200'),
('content-type', 'text/plain'),
]
conn.send_headers(1, headers=response_headers)
conn.send_data(1, b'Hello, HTTP/2!', end_stream=True)
print(conn.data_to_send())
이 예제에서는 h2 모듈을 사용하여 HTTP/2 서버를 만들고, 클라이언트에 응답을 보냅니다. 연결을 초기화하고, 응답에 필요한 헤더 및 데이터를 보냅니다.
예제 3: 스트림 처리하기
def process_events(conn, events):
for event in events:
if isinstance(event, h2.events.RequestReceived):
print("Received request:", event.headers)
elif isinstance(event, h2.events.DataReceived):
print("Received data:", event.data)
elif isinstance(event, h2.events.StreamEnded):
print("Stream ended")
conn.reset_stream(event.stream_id)
print("Reset stream")
# HTTP/2 이벤트 처리
conn.receive_data(b'') # 클라이언트로부터 수신한 데이터
events = conn.receive_data(b'')
process_events(conn, events)
이 예제에서는 h2 모듈을 사용하여 HTTP/2 이벤트를 처리하는 방법을 보여줍니다. 요청 및 데이터 수신 이벤트를 처리하고, 스트림이 종료되면 해당 스트림을 재설정합니다.