python) 웹 페이지를 CGI로 구현

jun_legend·2021년 5월 10일
0

Python-Web Application

목록 보기
1/11
post-thumbnail

[Mac 기준]

"파이썬으로 웹 페이지를 CGI로 구현하기"


"CGI (Common Gateway Interface)"

웹 서버 상에서 사용자 프로그램을 동작시키기 위한 조합

웹 서버가 사용자의 요청을 받았을 때,
그 요청과 관련해서 웹 애플리케이션이 (웹 페이지가) 어떤 처리를 할 수 있도록
약속된 이름의 데이터를 환경변수 라는 형태로 전달해줌


[웹 서버 세팅하기]


1) Bitnami MAMP 설치 (apache 웹 서버가 포함되어 있음) 다운로드 페이지


2) Applications-mampstack-apache2-htdocs 디렉토리 내에 웹 페이지_파일(예. index.html) 준비


3) htdocs 디렉토리 내 확장자가 py인 (예. index.py) 파이썬 파일 생성


4) 파이썬 파일의 코드를 읽고 실행까지 할 수 있도록 apache 웹 서버의 세팅을 변경


4-1) 에디터에서
Applications/mampstack/apache2/conf 디렉토리 내 httpd.conf 열기
( httpd.conf 는 apache가 동작하는 방법을 변경할 수 있는 설정 파일 )


4-2) httpd.conf 에 입력된 코드 중 mod_cgi 로 검색해서
LoadModule cgid_module modules/mod_cgid.so 앞에 있는 #(주석) 제거


4-3) httpd.conf 에 입력된 코드 중
documentroot 로 검색해서 Directory 태그 안에 코드 추가

	<Directory "/Applications/mampstack-8.0.5-0/apache2/htdocs">
      #
      # Possible values for the Options directive are "None", "All",
      # or any combination of:
      #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI 			MultiViews
      #
      # Note that "MultiViews" must be named *explicitly* --- "Options All"
      # doesn't give it to you.
      #
      # The Options directive is both complicated and important.  Please see
      # http://httpd.apache.org/docs/2.4/mod/core.html#options
      # for more information.
      #
      Options Indexes FollowSymLinks

      #
      # AllowOverride controls what directives may be placed in .htaccess files.
      # It can be "All", "None", or any combination of the keywords:
      #   AllowOverride FileInfo AuthConfig Limit
      #
      AllowOverride None

      #
      # Controls who can get stuff from this server.
      #
      Require all granted

      <Files *.py>
          Options ExecCGI
          AddHandler cgi-script .py
      </Files>
      
	</Directory>
<Files *.py>
    Options ExecCGI
    AddHandler cgi-script .py
</Files>

htdocs 디렉토리 내 확장자가 py인 모든 파일은
CGI기능을 활성시키고 CGI로 실행하라는 의미


5) manager-osx (spotlight로 검색 가능) 에서 Apache Web Server 재시동(Restart)



[웹 페이지 (파이썬) 파일 세팅]


1) 터미널에서 index.py 파일에 권한 부여

(index.py 가 있는 htdocs 디렉토리에서)
sudo chmod a+x index.py 실행


2) 에디터에서 index.py 파일을 열고 아래와 같이 코드 입력

  #!/usr/local/bin/python3  
  print("Content-Type: text/html")
  print()

파이썬을 찾아 실행시키고 이 웹페이지가 어떤 데이터인지를 알려주는 코드


3) index.html 의 코드 넣기

#!/usr/local/bin/python3
print("Content-Type: text/html")
print()
print('''<!doctype html>  # ---> 줄바꿈을 위해 docsting (''' ''') 사용
<html>
<head>
  <title>WEB1 - Welcome</title>
  <meta charset="utf-8">
</head>
<body>
  <h1><a href="index.html">WEB</a></h1>
  <ol>
    <li><a href="qs-1.html">HTML</a></li>
    <li><a href="qs-2.html">CSS</a></li>
    <li><a href="qs-3.html">JavaScript</a></li>
  </ol>
  <h2>WEB</h2>
  <p>The World Wide Web (abbreviated WWW or the Web) is an information space where documents and other web resources are identified by Uniform Resource Locators (URLs), interlinked by hypertext links, and can be accessed via the Internet.[1] English scientist Tim Berners-Lee invented the World Wide Web in 1989. He wrote the first web browser computer program in 1990 while employed at CERN in Switzerland.[2][3] The Web browser was released outside of CERN in 1991, first to other research institutions starting in January 1991 and to the general public on the Internet in August 1991.
  </p>
</body>
</html>
''')

index.py가 실행되었을 때 index.html 의 코드가 출력되게 해주는 코드


4) 웹 브라우저 주소창에 localhost:8080/index.py 입력하고 접속


5) index.html 파일의 내용이 잘 출력된다면 구현 성공

→ Internal Server Error 가 확인된다면
에디터에서 apache2/logs 디렉토리 내 error_log 파일에 있는 에러 코드 확인 및 구글링




[출처] 생활코딩 WEB2 - Python
https://opentutorials.org/module/3357

0개의 댓글