-
반응형
-웹사이트를 CGI를 연동하여 구현한다.
-생활코딩의 파이썬 강의를 기반으로 학습하였다.
-파이썬은 3.9.2 ver를 사용한다.
단순한 웹사이트를 CGI를 이용하여 프로그래밍적으로 다룰 수 있는 웹애플리케이션을 구현해본다. htdocs디렉토리에 index.py 파일을 만들었다. 이 상태에서 그냥 127.0.0.1/index.py로 접근하면 파이썬 포맷팅 에러가 발생하니 최상단에 #!Python이라는 시작 주석을 넣어준다.(윈도우 기준이며 리눅스는 다름)
이후 다시 127.0.0.1/index.py로 접근하면 여전히 Internal Error가 발생하지만, 에러 로그의 내용이 바뀌어 있다.
에러 내용은 End of script output before headers라고 나온다. 참고로 에러 로그는 C:\Bitnami\wampstack-8.0.2-1\apache2\logs에서 error.log에서 볼 수 있다.
[Wed Mar 10 21:11:52.072438 2021] [cgi:error] [pid 8228:tid 1248] [client 127.0.0.1:64740] End of script output before headers: index.py
스크립트 앞에 Headers를 명시해줘야 한다. 이것을 통해 웹서버는 응답(response)하는 웹페이지가 어떤 데이터인지 알려준다.
다음과 같은 헤더 코드를 넣어준다.
#!Python print("Content-Type: text/html") print()
이후 URL로 접근하면 에러 없이 빈 화면을 확인할 수 있다. 이제 index.html이나 503.html의 내용을 복사해서 print문으로 출력해보자. 에러가 발생할 것이다. 줄바꿈이 안 되어 그런 것인데, docstring방식을 사용하면 귀찮은 줄바꿈 처리 없이 바로 html을 인식하도록 처리할 수 있다.
#!Python print("Content-Type: text/html") # HTML is following print() print('''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Your application is not available</title> <link href="/bitnami.css" media="all" rel="Stylesheet" type="text/css" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8"> <meta http-equiv="content-style-type" content="text/css"> <meta http-equiv="expires" content="0"> <meta http-equiv="refresh" content="15" /> </head> <body> <div class="container"> <div id="header"> <table class="tableHeader"> <tr> <td><img src="/img/bitnami.png" alt="Bitnami"></td> </tr> </table> </div> <div id="lowerContainer"> <table class="tableParagraph"> <tr> <td class="container"> <h1>Your application is not available</h1> <p>Your application may not be available for many reasons: <ul> <li>If you just launched the server, please wait a few minutes for the application to deploy. It is common behavior for Java applications.</li> <li>Your application may not be working properly. Please check the application log file.</li> </ul> This page will automatically refresh every 15 seconds until the application is available. </p> </td> </tr> </table> </div> </body> </html> ''')
보는 것처럼 print(''' HTML코드 ''')방식으로 코드를 삽입하였다.
이후 URL을 실행하면 다음과 같이 정상적으로 나옴을 확인할 수 있다.
반응형'BackEnd > Phython' 카테고리의 다른 글
[파이썬 기초]데이터타입-Boolean다루기 (0) 2021.03.14 [파이썬 기초]URL 쿼리스트링(Query String) 가져오기 (0) 2021.03.12 [파이썬 기초]데이터타입-숫자,문자열 다루기 (0) 2021.03.10 [파이썬 기초]웹서버 및 파이썬 설치, CGI 연동 (0) 2021.03.08 [개인적인 포스팅]파이썬을 시작 하는 이유 (0) 2021.03.07 댓글