本文将使用Python语言的http模块和cgi模块编写简单的web服务,html页面及cgi脚本。
web服务默认监视本机的80端口,如果已使用请修改端口号。
web服务默认监视当前目录下的html文件,请将要打开的html文件放在脚本同一目录,cgi文件请放在当前目录下的子目录 cgi-bin。
更加详细的html语法请参考W3school.com.cn。
更多的练习脚本请点击下载。
web服务脚本
#配置 config.py
defaultwebdir = '.'
defaultport = 80
#web服务 webserver.py
import os,sys
import http.server
import config
def showParameter():
webdir = input('Please enter your webserver path: =>').strip()
port = input('Please enter your webserver port: =>').strip()
if not webdir:
webdir = config.defaultwebdir
if not port:
port = config.defaultport
else:
try:
port = int(port)
except:
print('Wrong number .')
print('The webserver path is "%s" and port is %d .'%(webdir,port))
return webdir,port
def startserver(webdir,port):
os.chdir(webdir)
svraddr = ('',port)
server = http.server.HTTPServer(svraddr,http.server.CGIHTTPRequestHandler)
server.serve_forever()
if __name__ == '__main__':
webdir,port = showParameter()
startserver(webdir,port)
html脚本
#tutor5b.html
<html>
<title>CGI 101</title>
<body>
<h1>Common input devices: alternative layout</h1>
<p>
Use the same tutor5.py server side script ,but change the
layout of the form itself . Notice the separation of user
interface and processing logic here ; the CGI script is independent of
the HTML used to interact with the user/client .
</p>
<hr>
<form method="post" action="cgi-bin/tutor5.py">
<h3>Please complete the following form and click Send</h3>
<p>
<table border="1" cellpadding="3">
<tr>
<th align="right">Name:</th>
<td><input type=text name=name></td>
</tr>
<tr>
<th align="right">ShoeSize:</th>
<td>
<table>
<td><input type="radio" name="shoesize" value="small">Small</td>
<td><input type="radio" name="shoesize" value="medium">Medium</td>
<td><input type="radio" name="shoesize" value="large">Large</td>
</table>
</td>
</tr>
<tr>
<th align="right">Occupation</th>
<td>
<select name="job">
<option>Developer</option>
<option>Manager</option>
<option>Student</option>
<option>Evangelist</option>
<option>Other</option>
</select>
</td>
</tr>
<tr>
<th align="right">PoliticalAffiliations</th>
<td>
<table>
<td><input type="checkbox" name="language" value="Python">Pythonsta</td>
<td><input type="checkbox" name="language" value="Perl">Perlmonger</td>
<td><input type="checkbox" name="language" value="Tcl">Tcler</td>
</table>
</td>
</tr>
<tr>
<th align="right">Comments:</th>
<td><textarea name="comment" clos="30" rows="2">Enter text here</textarea></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type=submit value="Submit" >
<input type="reset" value="Reset">
</td>
</tr>
</table>
</p>
</form>
<hr>
</body>
</html>
cgi脚本
#写log writer.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import datetime
def writeLog(_text,_filename=None,_encoding='utf-8'):
# 默认根据时间选择文件名
if not _filename:
_filename = datetime.datetime.today().strftime('%Y-%m')+'.log'
fullname = os.path.join('F:\Pythonfiles\PythonProgram\Caption15_webserver\cgi-bin\logs',_filename)
print(fullname)
header = datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')
with open(fullname,'a',encoding=_encoding) as file:
file.write('*'*30+header+'*'*30)
file.write('\n')
file.writelines(_text)
file.write('\n')
if __name__ == '__main__':
text = '''
Line1
Line2
Line3'''
writeLog(_text=text)
#cgi响应脚本 tutor5.py
#!/usr/bin/python3
import cgi,sys
import writer
sys.stderr = sys.stdout
form = cgi.FieldStorage()
print("Content-Type:text/html;charset=utf-8\n")
html = '''
<title>tutor5.py</title>
<h1>
Greetings
</h1>
<hr>
<body>
<h4>Your name is %(name)s .<h4>
<h4>You wear rather %(shoesize)s shoes .<h4>
<h4>You current job : %(job)s .<h4>
<h4>You program in %(language)s .</h4>
<h4>You also said:</h3>
<p>%(comment)s</p>
<hr>
</body>
</html>'''
data = {}
for field in ('name','shoesize','job','language','comment'):
if not field in form:
data[field] = 'unknown'
else:
if not isinstance(form[field],list):
data[field] = form[field].value
else:
values = [x.value for x in form[field]]
data[field] = ' and '.join(values)
text = ''
for (key,value) in data.items():
text += '%s : %s \n'%(key,value)
writer.writeLog(text)
print(html%data)