본문 바로가기
WEB/Python

[Python] 삭제하기(form, remove)

by Ellen571 2020. 8. 23.

[생활코딩] 활용 - 삭제 구현

 

 

삭제버튼 만들기

 

index.py

#!/usr/local/bin/python3
print("content-type:text/html; charset=UTF-8\n")
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).read()
    update_link = '<a href="update.py?id={pageId}">update</a>'.format(pageId=pageId)
    delete_action = '''
        <form action="process_delete.py" method="post">
            <input type="hidden" name="pageId" value="{}">
            <input type="submit" value="delete">
        </form>
    '''.format(pageId)
else:
    pageId = 'Welcome'
    description = 'Hello Python'
    update_link = ''
    delete_action = ''

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}
  {delete_action}
  <h2>{title}</h2>
  <p>{desc}</p>
</body>
</html>
'''.format(title=pageId, desc=description, listStr=liststr, update_link=update_link, delete_action=delete_action))

- 삭제는 링크 이동이 아닌 바로 처리해야하기에 form으로 만들어야 함

 

 

파일 삭제하기

 

process_delete.py

#!/usr/local/bin/python3

import cgi, os

form = cgi.FieldStorage()

pageId = form["pageId"].value

os.remove('data/'+pageId)

# Redirection
print("Location: index.py")
print()

- os모듈의 remove로 파일 삭제함

반응형