• 搭建简单的CGI应用程序


    原文来源于《核心编程3》第10章web编程

    一、静态文件+脚本文件

    1.首先开启cgiweb服务器

    python2 -m CGIHTTPServer 8000

    看到如下反应

    2.服务器目录新建cgi-bin目录,html文件放入服务器目录,python cgi脚本放入刚刚建好的cgi-bin目录

    3.看下html代码和python cgi脚本代码都是些什么内容

    friends.htm

     1 <HTML><HEAD><TITLE>
     2 Friends CGI Demo (static screen)
     3 </TITLE></HEAD>
     4 <BODY><H3>Friends list for: <I>NEW USER</I></H3>
     5 <FORM ACTION="/cgi-bin/friendsA.py">
     6 <B>Enter your Name:</B>
     7 <INPUT TYPE=text NAME=person VALUE="NEW USER" SIZE=15>
     8 <P><B>How many friends do you have?</B>
     9 <INPUT TYPE=radio NAME=howmany VALUE="0" CHECKED> 0
    10 <INPUT TYPE=radio NAME=howmany VALUE="10"> 10
    11 <INPUT TYPE=radio NAME=howmany VALUE="25"> 25
    12 <INPUT TYPE=radio NAME=howmany VALUE="50"> 50
    13 <INPUT TYPE=radio NAME=howmany VALUE="100"> 100
    14 <P><INPUT TYPE=submit></FORM></BODY></HTML>
    friends.htm

    friendsA.py

     1 #!/usr/bin/env python
     2 
     3 import cgi
     4 
     5 reshtml = '''Content-Type: text/html
    
     6 <HTML><HEAD><TITLE>
     7 Friends CGI Demo (dynamic screen)
     8 </TITLE></HEAD>
     9 <BODY><H3>Friends list for: <I>%s</I></H3>
    10 Your name is: <B>%s</B><P>
    11 You have <B>%s</B> friends.
    12 </BODY></HTML>'''
    13 
    14 form = cgi.FieldStorage()
    15 who = form['person'].value
    16 howmany = form['howmany'].value
    17 print reshtml % (who, who, howmany)
    friendsA.py

    4.运行起来看看,浏览器输入

    http://localhost:8000/friends.htm

    结果可以看到

    我们随意添加一个,点提交

    可以看到正文部分变化了,同时地址内容也变化了,

     

    再看下终端,也在有相应的显示。

    二、单个脚本文件

      1.服务器照常开启,脚本文件friendsB.py放在cgi-bin目录下

      2.代码内容

    #coding=utf-8
    import cgi
    
    header = 'Content-Type: text/html
    
    '  #需要先返回一个适当的http头文件,再返回结果页面
    
    formhtml = '''<HTML><HEAD><TITLE>
    Friends CGI Demo</TITLE></HEAD>
    <BODY><H3>Friends list for: <I>NEW USER</I></H3>
    <FORM ACTION="/cgi-bin/friendsB.py">
    <B>Enter your Name:</B>
    <INPUT TYPE=hidden NAME=action VALUE=edit>
    <INPUT TYPE=text NAME=person VALUE="NEW USER" SIZE=15>
    <P><B>How many friends do you have?</B>
    %s
    <P><INPUT TYPE=submit></FORM></BODY></HTML>'''
    
    fradio = '<INPUT TYPE=radio NAME=howmany VALUE="%s" %s> %s
    '
    
    def showForm():
        friends = []
        for i in (0, 10, 25, 50, 100):
            checked = ''
            if i == 0:
                checked = 'CHECKED'
            friends.append(fradio % (str(i), checked, str(i)))  #灵活输出,避免太多重复
    
        print '%s%s' % (header, formhtml % ''.join(friends))    #表单页面http头文件和内容都加进去了
    
    reshtml = '''<HTML><HEAD><TITLE>
    Friends CGI Demo</TITLE></HEAD>
    <BODY><H3>Friends list for: <I>%s</I></H3>
    Your name is: <B>%s</B><P>
    You have <B>%s</B> friends.
    </BODY></HTML>'''
    
    def doResults(who, howmany):
        print header + reshtml % (who, who, howmany)    #结果页面也都加进去了
    
    def process():
        form = cgi.FieldStorage()
        if 'person' in form:
            who = form['person'].value
        else:
            who = 'NEW USER'
    
        if 'howmany' in form:
            howmany = form['howmany'].value
        else:
            howmany = 0
    
        if 'action' in form:            #action变量用来判断选择哪个页面,表单页面、结果页面
            doResults(who, howmany)
        else:
            showForm()
    
    if __name__ == '__main__':
        process()
    friendsB.py

      3.浏览器输入

    http://localhost:8000/cgi-bin/friendsB.py

    会看到一样的界面,提交后也是一样的

    三、单个脚本文件,带有用户交互和错误处理

      1.代码

    #coding=utf-8
    #!/usr/bin/env python
    import cgi
    from urllib import quote_plus
    
    header = 'Content-Type: text/html
    
    '
    url = '/cgi-bin/friendsC.py'
    
    errhtml = '''<HTML><HEAD><TITLE>
    Friends CGI Demo</TITLE></HEAD>
    <BODY><H3>ERROR</H3>
    <B>%s</B><P>
    <FORM><INPUT TYPE=button VALUE=Back
    ONCLICK="window.history.back()"></FORM>
    </BODY></HTML>'''   #后退按钮
    
    def showError(error_str):   #错误处理部分
        print header + errhtml % error_str
    
    formhtml = '''<HTML><HEAD><TITLE>
    Friends CGI Demo</TITLE></HEAD>
    <BODY><H3>Friends list for: <I>%s</I></H3>
    <FORM ACTION="%s">
    <B>Enter your Name:</B>
    <INPUT TYPE=hidden NAME=action VALUE=edit>
    <INPUT TYPE=text NAME=person VALUE="%s" SIZE=15>
    <P><B>How many friends do you have?</B>
    %s
    <P><INPUT TYPE=submit></FORM></BODY></HTML>'''
    
    fradio = '<INPUT TYPE=radio NAME=howmany VALUE="%s" %s> %s
    '
    
    def showForm(who, howmany):
        friends = []
        for i in (0, 10, 25, 50, 100):
            checked = ''
            if str(i) == howmany:   #多传一个参数,用来记录'历史数据'
                checked = 'CHECKED'
            friends.append(fradio % (str(i), checked, str(i)))
        print '%s%s' % (header, formhtml % (
            who, url, who, ''.join(friends)))
    
    reshtml = '''<HTML><HEAD><TITLE>
    Friends CGI Demo</TITLE></HEAD>
    <BODY><H3>Friends list for: <I>%s</I></H3>
    Your name is: <B>%s</B><P>
    You have <B>%s</B> friends.
    <P>Click <A HREF="%s">here</A> to edit your data again.
    </BODY></HTML>'''
    
    def doResults(who, howmany):
        newurl = url + '?action=reedit&person=%s&howmany=%s' % (
            quote_plus(who), howmany)               #表单记录包含
    
        print header + reshtml % (who, who, howmany, newurl)    #再次编辑回到表单界面
    
    def process():
        error = ''
        form = cgi.FieldStorage()
    
        if 'person' in form:
            who = form['person'].value.title()
        else:
            who = 'NEW USER'
    
        if 'howmany' in form:   #根据howmany字段判定有没有选择人数,没有就算有错误,返回错误页面
            howmany = form['howmany'].value
        else:
            if 'action' in form and 
                    form['action'].value == 'edit':
                error = 'Please select number of friends.'
            else:
                howmany = 0
    
        if not error:
            if 'action' in form and 
                    form['action'].value != 'reedit':
                doResults(who, howmany)
            else:
                showForm(who, howmany)
        else:
            showError(error)
    
    if __name__ == '__main__':
        process()
    friendsC

      2.用法和B一样,代码结构也差不多,看下使用效果

    浏览器输入地址后

    提交用户名,但是不提交数量

    点back返回,选数量

    点击here,里面是个引用

    会回到提交表单的地方,保存了"历史记录"

     至此一个简单的cgi应用程序完成了。

  • 相关阅读:
    node.js 基础篇
    node.js 开发环境搭建
    Velocity VelocityEngine 支持多种loader 乱码问题
    tomcat集群及session共享
    上海支付宝终面后等了两周,没能收到offer却来了杭州淘宝的电话面试
    支付宝hr终面,忐忑的等待结果
    mysql 数据范围总结
    rsync同步文件(多台机器同步代码...)
    linux基础命令
    路飞学城项目之前后端交互,跨域问题
  • 原文地址:https://www.cnblogs.com/dahu-daqing/p/6573488.html
Copyright © 2020-2023  润新知