Three parts of codes for this project:
1. Index.html:
<html>
<head>
<title>File Editor</title>
</head>
<body>
<form action='edit.cgi' method='POST'>
<b>File name:</b><br />
<input type='text' name='filename' />
<input type='submit' value='Open' />
</body>
</html>
Providing a form to enter the file name for editing.
2. edit.cgi:
#!D:\Program Files\Python\python.exe
print ('Content-type: text/html\n')
from os.path import join, abspath
import cgi, sys
BASE_DIR = abspath('data')
form = cgi.FieldStorage()
filename = form.getvalue('filename')
if not filename:
print('Please enter a file name')
sys.exit()
text = open(join(BASE_DIR, filename)).read()
print("""
<html>
<head>
<title>Editing...</title>
</head>
<body>
<form action='save.cgi' method='POST'>
<b>File:</b>%s<br />
<input type='hidden' value='%s' name='filename' />
<b>Password:</b><br />
<input name='password' type='password' /><br />
<b>Text:</b><br />
<textarea name='text' cols='40' rows='20'>%s</textarea><br />
<input type='submit' value='Save' />
</form>
</body>
</html>
""" %(filename, filename, text)
)
Using the abapath to get the abstract path of the 'data' folder(I created). Getting the value of filename from FieldStorage. And open the save.cgi after click the 'save' button.
3. save.cgi
#!D:\Program Files\Python\python.exe
print('Content-type: text/html\n')
from os.path import join, abspath
import cgi, sys
BASE_DIR = abspath('data')
form = cgi.FieldStorage()
text = form.getvalue('text')
filename = form.getvalue('filename')
password = form.getvalue('password')
if not (filename and text and password):
print('Invalid parameters.')
sys.exit()
if password != '123456':
print('Invalid password')
sys.exit()
f = open(join(BASE_DIR, filename),'w')
f.write(text)
f.close()
print('The file has been saved.')
Validating the password and saving the input text into the file.