HTML 폼 페이지 작성
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CGI Form Example</title>
</head>
<body>
<form action="/cgi-bin/welcome.py" method="post">
<label for="name">Enter your name:</label>
<input type="text" id="name" name="name">
<input type="submit" value="Submit">
</form>
</body>
</html>
Python으로 CGI 스크립트 작성 후 welcome.py로 저장
#!/usr/bin/env python3
import cgi
import cgitb
cgitb.enable() # 디버깅을 위해 CGI 트레이스백 활성화
print("Content-Type: text/html") # HTML로 응답을 보냄
print() # 빈 줄로 헤더와 본문을 구분
# 폼 데이터 파싱
form = cgi.FieldStorage()
name = form.getvalue('name')
print("<html><head>")
print("<title>CGI Form Response</title>")
print("</head><body>")
print("<h1>Welcome, {}</h1>".format(name if name else "Guest"))
print("</body></html>")
CGI 스크립트에 실행 권한 부여
chmod 755 welcome.py
Apache 웹 서버 설정 파일에 다음과 같이 설정하여 CGI 스크립트를 사용할 수 있게 설정
<Directory "/path/to/cgi-bin">
AllowOverride None
Options +ExecCGI
Require all granted
AddHandler cgi-script .py
</Directory>
웹 브라우저에서 http://example/form.html
에 접근하여 폼에 이름을 입력하고 제출하면, CGI 스크립트 welcome.py가 실행되어 입력된 이름을 포함한 환영 메시지가 출력
정리가 너무 깔끔해요!! 잘 배우고 갑니다