原文来源于《核心编程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. linux小命令集合

    du -sh *  查看当前目录下的当前子目录的内存大小 df -h  查看内存占用情况 tar -xvf src.tgz ;    rsync -avzL   src/  desc/     lin ...

  2. centos7安装ZABBIX 3.0+ 邮件报警【OK】

    设置主机名: vi /etc/hosts 10.0.0.252 zabbix-server hostnamectl set-hostname   关闭防火墙: systemctl stop firew ...

  3. windows下MySQL 5.7+ 解压缩版安装配置方法--转载

    方法来自伟大的互联网. 1.去官网下载https://dev.mysql.com/downloads/mysql/.zip格式的MySQL Server的压缩包,根据需要选择x86或x64版.注意:下 ...

  4. Order By 问题集合

    问题(一):Order By 多个参数排序 在做多字段的排序的时候我们经常会会用到该语句. 所以多参数排序是从左到右的局部排序,修改的范围只有前面参数(几个参数)相同的情况下在排序. select * ...

  5. 分块+二分,统计对数 CDOJ

    http://acm.uestc.edu.cn/#/problem/show/1157 数列(seq) Time Limit: 3000/1000MS (Java/Others)     Memory ...

  6. 2017 ACM-ICPC 西安网络赛 F.Trig Function Chebyshev多项式

    自己太菜,数学基础太差,这场比赛做的很糟糕.本来想吐槽出题人怎么都出很数学的题,现在回过头来想还是因为自己太垃圾,竞赛就是要多了解点东西. 找$f(cos(x))=cos(nx)$中$x^m$的系数模 ...

  7. Python学习笔记(四十三)virtualenv (创建一套“隔离”的Python运行环境)

    摘抄自:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001432712108 ...

  8. Image Scaling using Deep Convolutional Neural Networks

    Image Scaling using Deep Convolutional Neural Networks This past summer I interned at Flipboard in P ...

  9. 重构改善既有代码设计--重构手法19:Replace Data Value with Object (以对象取代数据值)

    你有一笔数据项(data item),需要额外的数据和行为. 将这笔数据项变成一个对象. class Order... private string customer; ==> class Or ...

  10. Spark 基本架构及原理

    转载自: http://blog.csdn.net/swing2008/article/details/60869183 转自:http://www.cnblogs.com/tgzhu/p/58183 ...