Python笔记 之 搭建简单web服务器及cgi脚本编写

本文将使用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)
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值