WEB2 - Python

활용 - 홈페이지를 CGI로 구현

수업소개

이 수업에서는 CGI로 홈페이지를 출력하는 가장 간단한 방법을 살펴봅니다. 

 

 

강의

 

 

소스코드

index.py

#!/usr/local/bin/python3
print("Content-Type: text/html")
print()
print('''<!doctype html>
<html>
<head>
  <title>WEB1 - Welcome</title>
  <meta charset="utf-8">
</head>
<body>
  <h1><a href="index.html">WEB</a></h1>
  <ol>
    <li><a href="1.html">HTML</a></li>
    <li><a href="2.html">CSS</a></li>
    <li><a href="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>
''')

 

댓글

댓글 본문
  1. 코딩척척석사
    2023.03.15
  2. scientist
    덕분에 한글 안깨지고 나오네요 감사합니다!
    대화보기
    • scientist
      220729
    • 윤재승
      0318 잘 듣구있습니다
    • labis98
      2022.02.18 좋은 강의 한번 더 들어요~~~!
    • pmxsg
      2022.02.04
    • LisKis
      22.01.19. 완료
      감사합니다. 좋은 강의 잘 들었습니다.
    • dolphin1234
      안녕하세요 이고잉님^^ 강의 정말 잘 보고 있습니다. 질문이 있어서 댓글을 적었습니다. ''' '''을 쓰면 그 안에 있는 것들은 다 주석 처리가 돼서 웹사이트가 실행이 안 되어야 하는 거 아닌가요? 어떨 때에는 주석이 되고 또 어떨 때는 독스트링이 돼서 실행이 되는 건가요?
    • labis98
      20220104 좋은 강의 감사합니다.
    • 다시마
      윈도우 으악 에러 자꾸나
      에러가 자꾸 나면
      AH02101 : failed 어쩌구 -> 아래 @Scia 님 댓글
      couldn't spawn child 어쩌구 -> atom 파일 첫 부분에 #!파일경로 붙이기. 이떄 경로는 파이썬 프로그램 의 경로. 이거 되면 같이 뜨던 비슷한 문구의 에러도 사라짐.
      End of script 어쩌구 -> 아래 @Scia 님 댓글

      허허.. 한글로 하니까 글씨 완전 이상해졌음
    • 권홍석
      2021.9.21 완료
    • 2021.09.10 완료
    • 단희
      21.05.19 re
    • 초딩 개발자
      2021/05/09
    • jeisyoon
      2021.04.08 홈페이지를 CGI로 구현 - OK
    • Scia
      windows는 권한을 가리지 않는다. 다른 운영체제처럼 execute할 필요가 없다.
      윈도우 환경은 여기부터 보면 됨. https://youtu.be......182

      ' AH02101: Failed to read cgi file ' 오류 : shebang 즉, #!python 넣으면 됨.
      ' End of script output before headers ' 오류 : 강의처럼 header 추가

      윈도우 환경은 어디부터 해야하는지 조마조마하면서 했네요 ㅋㅋ
    • Americano
      파일 위치를 못찾는것 같은데 htdocs 폴더에 해당 파일이 있는지 확인해보면 될것 같습니다.
      이름이 변경되거나 위치가 잘못되었을때 그게 뜨는것 같아요
      대화보기
      • Americano
        21.02.27
      • ㅎㅎㅎㅎ
        윈도우입니다. web1부터 계속 봐왔는데 [cgi:error] [pid 3900:tid 1172] [client ::1:7600] AH02811: script not found or unable to stat: C:/Bitnami/wampstack-8.0.1-0/apache2/htdocs/index.py 몇번을 시도해도 이러한 오류만 뜹니다, 해결방법이 있을까요?
      • 박민지
        2021.01.11
      • hksap
        210101
      • Sgoing
        맨 앞줄에 #!python 말고 #!파이썬 경로 하면 되던데요?
        대화보기
        • KINGJ
          #!python 으로 하셔야해요
          대화보기
          • cocoha11
            [Wed Nov 04 15:46:05.007755 2020] [win32:error] [pid 23988:tid 1320] (70014)End of file found: [client 127.0.0.1:60567] AH02101: Failed to read cgi file C:/Bitnami/wampstack-7.4.11-0/apache2/htdocs/index.py for testing
            [Wed Nov 04 15:46:05.007755 2020] [cgi:error] [pid 23988:tid 1320] (70014)End of file found: [client 127.0.0.1:60567] AH01222: don't know how to spawn child process: C:/Bitnami/wampstack-7.4.11-0/apache2/htdocs/index.py

            window에서 계속 에러떠요 저같은분은 안 계신 것 같은데, 혹시 아시는 분 계시면 도와주세요
          • park
            2020.10.12
          • dagel0102
            20.10.09
          • cgoing
            cgoing / 2020.10.01
          • jiyeong
            2020.08.31.
          • OneJae EE
            20.04.29 수 / 37세 비전공자 / 완료
          • 악어
            20200308 완료
          • 스티븐잡숴
            완료
          • new_3
            완료 - codeanywhere에서는 리눅스 환경이라
            맨위의 shebang을 #!/usr/bin/python3로 바꿔야되네요
            주소도 localhost가 아닌
            https://web2-python-.....codeanyapp.com/index.py
            여기로요
          • 윤희철
            UnicodeEncodeError: 'cp949' codec can't encode character '\\u2013' in position 456: illegal multibyte sequence\r:
            에러는 이렇게 뜹니다ㅠ
            대화보기
            • 윤희철
              localhost/index.py 해서 오류은뜨고 파이썬이랑 아파치랑 연동되는것 까지는 왔습니다(print(1+2)문 적고 새로고침하면 3니다.) 근데 index.html에 있는 html자료 복붙해서 print문에 복사(''' '''따옴표 3개까지했어요)하고 localhost/index.py에서 새로고침하면 백지화면이 뜹니다 ㅠㅠ egoing님이 한것과 차이가 없는것 같은데 뭐가 문제인지 모르겠네요.. 도와주세요 ㅠ
            • asdf
              에러자체가 안되고 html 파일로만 반환되요
            • apldeap
              12/22
            • 보는이
              처음엔 몰랐는데 코드치는게 계산된게 아니고 친것 그대로 나오면 설치및 연동 강의에 있는 동영상 단계 여러개중 어딘가를 빠뜨렸거나 잘못해서 그러는 거더라고요
            • xuanxi
              20191125
            • 쑤우
              수강완료. 감사합니다~
            • 굼벵이
              완료
            • 20191003 Ted 완료!
            • 솜브라온라인
              어째서인지는 모르겠지만 저는 왼쪽에 웹 페이지 띄웠을 때 localhost로는 안되어서 127.0.0.1/syntax/index.py 로 하니 되더라구요
              강의 감사합니다
            • yssss
              감사합니다!
            • Inyeong Gim
              파이썬 정복 고고!
            • 이제 알았어요
              말씀 주신 대로 print('') 안의 출력 내용에 한글이 있을때 아래를 넣어 줘야 했습니다.

              import sys
              import codecs
              sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
            • 감사합니다
              위 방법대로 했더니 윈도우에서도 한글이 잘 작동합니다
              대화보기
              • 하하
                (""" 이하에 한글이 있는 경우, 한글 출력이 되지 않을 때 - 리눅스 기준으로
                https://blog.ayukawa.kr......342 링크 글에 '한글 출력이 되지 않을 때' 항목을 참고하시면 됩니다.
                저는 윗줄에
                #!/usr/bin/python3
                #-*- coding: utf-8 -*-
                import sys
                import codecs
                import cgi

                import cgitb
                cgitb.enable()

                sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())

                print("content-type:text/html; charset=utf-8\r\n")

                그리고 프린트 블라블라 하니까 되더라구요
              • 항상 강의 잘 듣고 있습니다 에고잉님
                그리고 댓글에 있는 대로 한글 깨질때 가장 상위의 charset을 euc-kr 로 바꾸니까 되네요 근데 밑의 meta charset은 안바꿔도 되네요...왤까용??? 암튼 감사합니당ㅠㅠㅠ
              • shadow0116@naver.com
                index.py가 윈도우에서 실행하고 있는데 안 되서 찾아보니...
                이렇게 하면 되네요...
                #!C:\Program Files (x86)\Python37-32\python.exe
                print("content-type: text/html; charset=utf-8\n")
                print()
                print('''<!doctype html>
                <html>
                <head>
                <title>WEB1 - Welcome</title>
                <meta charset="euc-kr">
                </head>
                <body>
                <h1><a href="index.html">WEB</a></h1>
                <ol>
                <li><a href="1.html">HTML</a></li>
                <li><a href="2.html">CSS</a></li>
                <li><a href="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>
                ''')
              • Seankim
                아하, 웹에서 실행하기
              graphittie 자세히 보기