WEB2 - Python

활용 - 수정 구현

수업소개

여기서는 Python 웹애플리케이션에서 어떻게 수정 기능을 구현하는가를 살펴봅니다. 


 

강의

 

 

소스코드

변경사항 

update.py

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

files = os.listdir('data')
listStr = ''
for item in files:
    listStr = listStr + '<li><a href="index.py?id={name}">{name}</a></li>'.format(name=item)

form = cgi.FieldStorage()
if 'id' in form:
    pageId = form["id"].value
    description = open('data/'+pageId, 'r').read()
else:
    pageId = 'Welcome'
    description = 'Hello, web'
print('''<!doctype html>
<html>
<head>
  <title>WEB1 - Welcome</title>
  <meta charset="utf-8">
</head>
<body>
  <h1><a href="index.py">WEB</a></h1>
  <ol>
    {listStr}
  </ol>
  <a href="create.py">create</a>
  <form action="process_update.py" method="post">
      <input type="hidden" name="pageId" value="{form_default_title}">
      <p><input type="text" name="title" placeholder="title" value="{form_default_title}"></p>
      <p><textarea rows="4" name="description" placeholder="description">{form_default_description}</textarea></p>
      <p><input type="submit"></p>
  </form>
</body>
</html>
'''.format(title=pageId, desc=description, listStr=listStr, form_default_title=pageId, form_default_description=description))

 

process_update.py

#!/usr/local/bin/python3

import cgi, os
form = cgi.FieldStorage()
pageId = form["pageId"].value
title = form["title"].value
description = form['description'].value

opened_file = open('data/'+pageId, 'w')
opened_file.write(description)
opened_file.close()

os.rename('data/'+pageId, 'data/'+title)

#Redirection
print("Location: index.py?id="+title)
print()

 

index.py

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

files = os.listdir('data')
listStr = ''
for item in files:
    listStr = listStr + '<li><a href="index.py?id={name}">{name}</a></li>'.format(name=item)

form = cgi.FieldStorage()
if 'id' in form:
    pageId = form["id"].value
    description = open('data/'+pageId, 'r').read()
    update_link = '<a href="update.py?id={}">update</a>'.format(pageId)
else:
    pageId = 'Welcome'
    description = 'Hello, web'
    update_link = ''
print('''<!doctype html>
<html>
<head>
  <title>WEB1 - Welcome</title>
  <meta charset="utf-8">
</head>
<body>
  <h1><a href="index.py">WEB</a></h1>
  <ol>
    {listStr}
  </ol>
  <a href="create.py">create</a>
  {update_link}
  <h2>{title}</h2>
  <p>{desc}</p>
</body>
</html>
'''.format(title=pageId, desc=description, listStr=listStr, update_link=update_link))

 

댓글

댓글 본문
  1. scientist
    220818 너무 재미있어요
  2. 윤재승
    재밌는데요 뭔가????
  3. labis98
    2022.02.26 좋은 강의 한번 더 들어요~~~!
  4. deskim
    value를 넣어서 해봤는데 이게 id가 form에 없다고 인식하고 else로 빠져서 pageId가 welcome이나오고
    description이 hello web으로 나오는데 혹시 해결방법 아시는 분 있으시면 도와주세요!!
    윈도우를 씁니다
  5. pmxsg
    2022.02.06
  6. labis98
    20220118 good 좋은 강의 항상 감사합니다.
  7. 최호
    파일 정보 수정후 Submit 클릭시 에러
    error_log
    [Tue Nov 09 01:14:16.968057 2021] [cgid:error] [pid 7357:tid 140360604972800] AH01241: error spawning CGI child: exec of '/var/www/html/process_update.py' failed (No such file or directory): /var/www/html/process_update.py, referer: http://*/update.py?id=HTML
    [Tue Nov 09 01:14:16.969379 2021] [cgid:error] [pid 7357:tid 140360604972800] End of script output before headers: process_update.py, referer: http://*/update.py?id=HTML

    해당 문제 해결하신분 있나요
  8. 최호
    data 폴더에 대한 권한을 주면 해결 됩니다.
    #chmod 755 data/
    대화보기
    • babtist
      open('data/'+title, 'w')가 permission denied가 뜨네요 혹시 어떻게 처리 해야 할지 아시는 분 계세요?
    • 2021.09.11 완료
    • 전준표
      감사합니다 3시간 동안 고민했네요..
      대화보기
      • 이택진
        210520
      • 초딩 개발자
        2021/05/10
      • jeisyoon
        2021.04.09 수정 구현 - OK
      • 카디프
        에러는 안나는데, 수정이 안되고 계속 생성이 되네요;;; ㅠ
        우선 먼저 delete로 넘어갑니다~~ ㅎ;
      • 박민지
        2021.01.16
      • cgoing
        cgoing / 2020.10.04
      • urban
        제일 아래 댓글 ddojai님이 윈도우 환경에서 'close()' 호출 없이 작성 시 에러가 난다고 말씀하셨는데, 이걸 못보고 에러로그에 퍼미션 에러라고 뜨길래 폴더 공유설정도 바꿔보고 이런저런 짓을 해봤습니다..ㅋㅋㅋ근데 여전히 왜 close()를 안하면 에러가 나는지 이해는 못하고 있지만요..!
      • 개발개발개발
        pageid pageId 대문자 소문자 때문 아닌가용?ㅠ
        대화보기
        • hyuunny
          윈도우 사용자인데 process_update.py 부분에서 왜 500internal server error 가 나는 거죠?
          이고잉님도 헤더부에는 프린트 명령 띄우지 말라셔서 안했는데 계속 나오네요
          End of script output before headers: process_update.py, referer: http://127.0.0.1......hon

          AH01215: Traceback (most recent call last):\r: C:/Bitnami/wampstack-7.4.6-1/apache2/htdocs/process_update.py, referer: http://127.0.0.1......hon

          AH01215: File "C:/Bitnami/wampstack-7.4.6-1/apache2/htdocs/process_update.py", line 6, in <module>\r: C:/Bitnami/wampstack-7.4.6-1/apache2/htdocs/process_update.py, referer: http://127.0.0.1......hon

          [cgi:error] [pid 8632:tid 1244] [client 127.0.0.1:12394] AH01215: pageid = form['pageid'].value\r: C:/Bitnami/wampstack-7.4.6-1/apache2/htdocs/process_update.py, referer: http://127.0.0.1......hon

          AH01215: File "C:\\Python38\\lib\\cgi.py", line 517, in __getitem__\r: C:/Bitnami/wampstack-7.4.6-1/apache2/htdocs/process_update.py, referer: http://127.0.0.1......hon

          AH01215: raise KeyError(key)\r: C:/Bitnami/wampstack-7.4.6-1/apache2/htdocs/process_update.py, referer: http://127.0.0.1......hon

          AH01215: KeyError: 'pageid'\r: C:/Bitnami/wampstack-7.4.6-1/apache2/htdocs/process_update.py, referer: http://127.0.0.1......hon
        • process_update.py 에서

          os.rename 이나 .close() 를 쓰고나면

          [http:error] [pid 7256:tid 1256] [client 127.0.0.1:54439] AH02429: Response header name '<!--' contains invalid characters, aborting request, referer:

          이런 오류가 나옵니다... 구글링을 해도 이유를 못찾아서 고수님들 도움을 구합니다...
        • rsong
          기존에 포멧에서 사용한 'title'을 안쓰고 새로 'form_deafault_title'을 새롭게 지정하는 이유가 있을까요?
          둘 다 같은 'pageId' 값으로 치환되는데
          이렇게 되면 한 포멧 안에서 'pageId'라는 하나의 값이 두 개의 이름을 가지게 되니
          중복이 발생하게 되는거 아닌가요?
          게다가 'form_default_title'을 만들지 않고 'title'로 해도 동작하는데 말이죠..

          제 나름의 해석으로는 의미론적인 이유 때문이라고 생각되는데
          혹시 기능적인 이유도 있을까요??
        • 악어
          2020-03-15 완료
        • 스티븐잡숴
          완료
        • new_3
          대충 감을 잡은거 같습니다. https://itholic.github.io......od/ https://unix.stackexchange.com/a/140944
          두 곳을 많이 참고했습니다.
          SSH TERMINAL에 들어가서 data 디렉토리에서 ls -al이라고 입력하면, 이렇게 나옵니다.
          -rw-r--r-- 1 cabox www-data 37 Feb 28 07:48 Console
          -rw-r--r-- 1 www-data www-data 30 Feb 28 08:32 Console2

          console은 codeanywhere에서 직접 작성한 파일이고,
          console2는 웹 폼에서 작성한 파일입니다.
          console의 소유자는 cabox이고,
          console2의 소유자는 www-data입니다.

          이 설명을 보니
          두 파일은 모두 소유자만 쓰기 권한이 있고, 그룹/기타사용자는 읽기권한만 있네요.

          "www-data is the user that web servers on Ubuntu (Apache, nginx, for example) use by default for normal operation." www-data는 웹 서버가 사용하는 유저 이름이라고 합니다.
          그래서 웹 상에서 파일을 수정하고자 할 경우
          console2는 (유저:www-data = 소유자: www-data)이므로 수정이 되는데,
          console은 유저:www-data != 소유자: cabox이므로 퍼미션 에러가 뜨고,

          그룹 사용자에게도 쓰기 권한을 주면 문제가 해결될 것 같습니다. 소유자가 cabox인 파일도 그룹소유자는 www-data로 동일해서요.
          그래서 모든 파일에 대해 sudo chmod 664 [파일명]을 하고 나니 이제 어디서 파일을 작성했는지와 관계없이 update.py를 통해 수정이 가능하게 되었습니다.
          대화보기
          • new_3
            codeanywhere 환경에서 실습 중인데
            codeanywhere의 에디터에서 직접 파일을 만들어서 내용을 입력한 파일들은 수정시 permission error가 뜨고,
            웹페이지에서 이전강좌에서 만든 form을 이용해 만든 파일들은 에러 없이 수정이 됩니다.
            왜 이런 차이가 나는지 알려주실 분 계신가요?

            PermissionError: [Errno 13] Permission denied: 'data/Console'
            [Fri Feb 28 07:49:39.280636 2020] [cgid:error] [pid 1120:tid 139933549311744] [client 38.128.66.69:60202] End of script output before headers: process_update.py, referer: https://web2-python-....codeanyapp.com......ole
          • dj bak
            1/25
          • 방목
            1/19
          • apldeap
            12/28
          • 쑤우
            수강완료. 감사합니다.~
          • 굼벵이
            완료
          • 20191004 Ted 완료!
          • 민턴쟁이
            print("Content-Type: text/html")
            print()

            이것을 말씀하시는 거라면
            빈 프린트문은 반드시 있어야 합니다. 첫번째 프린트문은 헤더정보를 담고 있는데
            헤더정보 다음에 반드시 줄바꿈이 있어야 하기 때문입니다.

            고로 한줄로 줄이고 싶다면 첫 번째 프린트문 뒤에 \n을 붙이시면 됩니다.
            print("content-type: text/html \n")
            대화보기
            • popsapple
              선생님 왜 빈 print문이 없으면 header error가 뜨나요???
              의미없는 print문을 없앨 방법은 없나요??
            • Avatar
              띄어쓰기는 인식을 못하나요?
              title이나 pageid에 띄어쓰기가 들어가면 제대로 인식을 못하는것 같아요
            • 와 감사합니다!!!ㅠㅠㅠ
            • JuicyFresh
              감사합니다.
            • Lethesriver
              와 감사합니다!! 해결됐어요
              대화보기
              • 오춘식
                mark position
              • 물속의달
                저도 같은 에러가 나서 당황했는데 도움주셔서 감사합니다.
                대화보기
                • ddojai
                  윈도우 환경에서는 opened_file.close()를 호출 안하고 os.rename을 시도하면 에러가 발생하는듯 합니다.

                  [Sun Apr 08 15:23:07.678729 2018] [cgi:error] [pid 5476:tid 1272] [client 127.0.0.1:54030] End of script output before headers: process_update.py, referer: http://127.0.0.1......TML
                  [Sun Apr 08 15:23:07.679731 2018] [cgi:error] [pid 5476:tid 1272] [client 127.0.0.1:54030] AH01215: Traceback (most recent call last):\r: C:/Bitnami/wampstack-7.1.15-0/apache2/htdocs/process_update.py, referer: http://127.0.0.1......TML
                  [Sun Apr 08 15:23:07.679731 2018] [cgi:error] [pid 5476:tid 1272] [client 127.0.0.1:54030] AH01215: File "C:/Bitnami/wampstack-7.1.15-0/apache2/htdocs/process_update.py", line 13, in <module>\r: C:/Bitnami/wampstack-7.1.15-0/apache2/htdocs/process_update.py, referer: http://127.0.0.1......TML
                  [Sun Apr 08 15:23:07.679731 2018] [cgi:error] [pid 5476:tid 1272] [client 127.0.0.1:54030] AH01215: os.rename('data/'+pageId, 'data/'+title)\r: C:/Bitnami/wampstack-7.1.15-0/apache2/htdocs/process_update.py, referer: http://127.0.0.1......TML
                  [Sun Apr 08 15:23:07.679731 2018] [cgi:error] [pid 5476:tid 1272] [client 127.0.0.1:54030] AH01215: PermissionError: [WinError 32] \xb4\xd9\xb8\xa5 \xc7\xc1\xb7\xce\xbc\xbc\xbd\xba\xb0\xa1 \xc6\xc4\xc0\xcf\xc0\xbb \xbb\xe7\xbf\xeb \xc1\xdf\xc0\xcc\xb1\xe2 \xb6\xa7\xb9\xae\xbf\xa1 \xc7\xc1\xb7\xce\xbc\xbc\xbd\xba\xb0\xa1 \xbe\xd7\xbc\xbc\xbd\xba \xc7\xd2 \xbc\xf6 \xbe\xf8\xbd\xc0\xb4\xcf\xb4\xd9: 'data/HTML' -> 'data/HTML5'\r: C:/Bitnami/wampstack-7.1.15-0/apache2/htdocs/process_update.py, referer: http://127.0.0.1......TML
                버전 관리
                egoing
                현재 버전
                선택 버전
                graphittie 자세히 보기