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

一、静态文件+脚本文件

1.首先开启cgiweb服务器

python2 -m CGIHTTPServer 8000

看到如下反应

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

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

friends.htm

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

friends.htm

friendsA.py

 #!/usr/bin/env python

 import cgi

 reshtml = '''Content-Type: text/html\n
<HTML><HEAD><TITLE>
Friends CGI Demo (dynamic screen)
</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>''' form = cgi.FieldStorage()
who = form['person'].value
howmany = form['howmany'].value
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\n\n' #需要先返回一个适当的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\n' 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\n\n'
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\n' 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应用程序完成了。

搭建简单的CGI应用程序的更多相关文章

  1. 简单说明CGI是什么

    html { font-family: sans-serif } body { margin: 0 } article,aside,details,figcaption,figure,footer,h ...

  2. 简单说明CGI和动态请求是什么

    1. CGI是什么 CGI是common gateway interface的缩写,大家都译作通用网关接口,但很不幸,我们无法见名知意. 我们知道,web服务器所处理的内容都是静态的,要想处理动态内容 ...

  3. 拿nodejs快速搭建简单Oauth认证和restful API server攻略

    拿nodejs快速搭建简单Oauth认证和restful API server攻略:http://blog.csdn.net/zhaoweitco/article/details/21708955 最 ...

  4. 转:windows下使用gvim搭建简单的IDE编译环境(支持C/C++/Python等)

    原文来自于:http://www.cnblogs.com/zhuyp1015/archive/2012/06/16/2552269.html 使用gvim在windows环境下搭建简单的IDE环境可以 ...

  5. mongoDB介绍、安装、搭建简单的mongoDB服务器(一)

    相关网站 1. http://www.mongodb.org/ 官网,可以下载安装程序,和doc,和驱动等. 2. http://www.mongoing.com/ 国内官方网站,博客,问题谈论等  ...

  6. JMS学习(四)-一个简单的聊天应用程序分析

    一,介绍 本文介绍一个简单的聊天应用程序:生产者将消息发送到Topic上,然后由ActiveMQ将该消息Push给订阅了该Topic的消费者.示例程序来自于<JAVA 消息服务--第二版 Mar ...

  7. 基于python2【重要】怎么自行搭建简单的web服务器

    基本流程:1.需要的支持     1)python本身有SimpleHTTPServer     2)ForkStaticServer.py支持,该文件放在python7目录下     3)将希望共享 ...

  8. 写了一个简单的CGI Server

    之前看过一些开源程序的源码,也略微知道些Apache的CGI处理程序架构,于是用了一周时间,用C写了一个简单的CGI Server,代码算上头文件,一共1200行左右,难度中等偏上,小伙伴可以仔细看看 ...

  9. 玩转Node.js(四)-搭建简单的聊天室

    玩转Node.js(四)-搭建简单的聊天室 Nodejs好久没有跟进了,最近想用它搞一个聊天室,然后便偶遇了socket.io这个东东,说是可以用它来简单的实现实时双向的基于事件的通讯机制.我便看了一 ...

随机推荐

  1. SpringMVC接收复杂集合对象(参数)代码示例

    原文: https://www.jb51.net/article/128233.htm SpringMVC接收复杂集合对象(参数)代码示例 更新时间:2017年11月15日 09:18:15   作者 ...

  2. bzoj 3834 [Poi2014]Solar Panels 数论分块

    3834: [Poi2014]Solar Panels Time Limit: 20 Sec  Memory Limit: 128 MBSubmit: 367  Solved: 285[Submit] ...

  3. Linux常用网络工具:fping主机扫描

    Linux下有很多强大网络扫描工具,网络扫描工具可以分为:主机扫描.主机服务扫描.路由扫描等. fping是一个主机扫描工具,相比于ping工具可以批量扫描主机. fping官方网站:http://f ...

  4. hdu 1846 Brave Gam

    Brave Game http://acm.hdu.edu.cn/showproblem.php?pid=1846 Time Limit: 1000/1000 MS (Java/Others)     ...

  5. 新Linux系统配置yum源

    新的Linux系统安装好以后,yum的源还是需要配置一下的,我使用的是redhat6.6版本,同时为了不注册而使用更多的yum源的资源,也需要做一下的修改. 1. 删除redhat原有的yum源 # ...

  6. unZip/Zip的安装

    1.apt-get安装: apt-get install zip 2.yum安装: yum install -y unzip zip

  7. CSS居中之美

    关于居中,你会想到什么? div{margin: auto;} 常见的居中方法 水平居中 .demo{ text-align: center; margin: auto; position: abso ...

  8. 三星c7换屏幕教程

    https://jingyan.baidu.com/article/20b68a88f49cb9796cec6282.html

  9. 【CodeForces】913 F. Strongly Connected Tournament 概率和期望DP

    [题目]F. Strongly Connected Tournament [题意]给定n个点(游戏者),每轮游戏进行下列操作: 1.每对游戏者i和j(i<j)进行一场游戏,有p的概率i赢j(反之 ...

  10. 【洛谷P2014】选课

    题目描述 在大学里每个学生,为了达到一定的学分,必须从很多课程里选择一些课程来学习,在课程里有些课程必须在某些课程之前学习,如高等数学总是在其它课程之前学习.现在有N门功课,每门课有个学分,每门课有一 ...