python实现基于CGI的Web应用

本文用一个“网上书店”的web应用示例,简要介绍如何用Python实现基于CGI标准的Web应用,介绍python的cgi模块、cigtb模块对编写CGI脚本提供的支持。
 
CGI简介
CGI  Common Gateway Interface (通用网关接口),是一个Internet标准,允许Web服务器运行一个服务器端程序,称为CGI脚本。一般的,CGI脚本都放在一个名为cgi-bin的特殊文件夹内,这样web服务器就知道到哪里查找cgi脚本。
 
CGI Architecture Diagram
When a request arrives, HTTP server execute  a program, and whatever that program outputs is sent back for your browser to display. This function is called the Common Gateway Interface or CGI, and the programs are called CGI scripts. These CGI programs can be a Python Script, PERL Script, Shell Script, C or C++ program etc.
 
 
“网上书店”Web应用目录结构
(操作系统:win7;python版本:3.3)
BookWebApp|
        |cgi-bin
       ------|book_detail_view.py
       ------|book_list_view.py
       ------|template
          ----|yate.py
       ------|mode
          ----|Book.by
       ------|service
          ----|book_service.py
      |resource
      ------- |books.png
      |book.txt
      |index.html
      |run_server.py
 
1、Web服务器
所有的Web应用都要在Web服务器上运行,实际上所有的web服务器都支持CGI,无论是Apache、IIS、nginx、Lighttpd还是其他服务器,它们都支持用python编写的cgi脚本。这些web服务器都比较强大,这里我们使用python自带的简单的web服务器,这个web服务器包含在http.server库模块中。
 
run_server.py:
运行此程序,即启动此web应用。
from http.server import HTTPServer, CGIHTTPRequestHandler

port = 8081

httpd = HTTPServer(('', port), CGIHTTPRequestHandler)
print("Starting simple_httpd on port: " + str(httpd.server_port))
httpd.serve_forever()

2、index.html

首页;URL: “http://localhost:8081/cgi-bin/book_list_view.py” 将调用 cgi-bin文件夹下的book_list_view.py

<html>
<head>
<title>BookStore</title>
</head>
<body>
<h1>Welcome to My Book Store.</h1>
<img src="resource/books.png">
<h3>
please choose your favorite book, click <a href="cgi-bin/book_list_view.py">here</a>.
</h3>
<p>
<strong> Enjoy!</strong>
</p>
</body>
</html>

3、book_list_view.py

图书清单页面。用户选择要查看的图书,提交表单,然后调动图书详细界面。

#Python标准库中定义的CGI跟踪模块:cgibt
import cgitb
cgitb.enable()
#启用这个模块时,会在web浏览器上显示详细的错误信息。enable()函数打开CGI跟踪
#CGI脚本产生一个异常时,Python会将消息显示在stderr(标准输出)上。CGI机制会忽略这个输出,因为它想要的只是CGI的标准输出(stdout) import template.yate as yate
import service.book_service as book_service #CGI标准指出,服务器端程序(CGI脚本)生成的任何输出都将会由Web服务器捕获,并发送到等待的web浏览器。具体来说,会捕获发送到Stdout(标准输出)的所有内容

#一个CGI脚本由2部分组成, 第一部分输出 Response Headers, 第二部分输出常规的html.
print("Content-type:text/html\n")#Response Headers
#网页内容:有html标签组成的文本
print('<html>')
print('<head>')
print('<title>Book List</title>')
print('</head>')
print('<body>')
print('<h2>Book List:</h2>')
print(yate.start_form('book_detail_view.py'))
book_dict=book_service.get_book_dict()
for book_name in book_dict:
print(yate.radio_button('bookname',book_dict[book_name].name))
print(yate.end_form('detail'))
print(yate.link("/index.html",'Home'))
print('</body>')
print('</html>')

4、yate.py

自定义的简单模板,用于快捷生成html

def start_form(the_url, form_type="POST"):
return('<form action="' + the_url + '" method="' + form_type + '">') def end_form(submit_msg="Submit"):
return('<input type=submit value="' + submit_msg + '"></form>') def radio_button(rb_name, rb_value):
return('<input type="radio" name="' + rb_name +
'" value="' + rb_value + '"> ' + rb_value + '<br />') def u_list(items):
u_string = '<ul>'
for item in items:
u_string += '<li>' + item + '</li>'
u_string += '</ul>'
return(u_string) def header(header_text, header_level=2):
return('<h' + str(header_level) + '>' + header_text +
'</h' + str(header_level) + '>')
def para(para_text):
return('<p>' + para_text + '</p>') def link(the_link,value):
link_string = '<a href="' + the_link + '">' + value + '</a>'
return(link_string)

5、book_detail_view.py

图书详细页面

import cgitb
cgitb.enable() import cgi
import template.yate as yate
import service.book_service as book_service
import template.yate as yate #使用cig.FieldStorage() 访问web请求发送给web服务器的数据,这些数据为一个Python字典
form_data = cgi.FieldStorage()
print("Content-type:text/html\n")
print('<html>')
print('<head>')
print('<title>Book List</title>')
print('</head>')
print('<body>')
print(yate.header('Book Detail:'))
try:
book_name = form_data['bookname'].value
book_dict=book_service.get_book_dict()
book=book_dict[book_name]
print(book.get_html)
except KeyError as kerr:
print(yate.para('please choose a book...'))
print(yate.link("/index.html",'Home'))
print(yate.link("/cgi-bin/book_list_view.py",'Book List'))
print('</body>')
print('</html>')

6、Book.py

图书类

from template import yate

class Book:
def __init__(self,name,author,price):
self.name=name
self.author=author
self.price=price @property
def get_html(self):
html_str=''
html_str+=yate.header('BookName:',4)+yate.para(self.name)
html_str+=yate.header('Author:',4)+yate.para(self.author)
html_str+=yate.header('Price:',4)+yate.para(self.price)
return(html_str)

7、book_service.py

图书业务逻辑类

from model.Book import Book

def get_book_dict():
book_dict={}
try:
with open('book.txt','r') as book_file:
for each_line in book_file:
book=parse(each_line)
book_dict[book.name]=book
except IOError as ioerr:
print("IOErr:",ioerr)
return(book_dict) def parse(book_info):
(name,author,price)=book_info.split(';')
book=Book(name,author,price)
return(book)

8、book.txt

待显示的图书信息(书名;作者;价格)

The Linux Programming Interface: A Linux and UNIX System Prog;Michael Kerrisk;$123.01
HTML5 and CSS3, Illustrated Complete (Illustrated Series);Jonathan Meersman Sasha Vodnik;$32.23
Understanding the Linux Kernel;Daniel P. Bovet Marco Cesati;$45.88
Getting Real;Jason Fried, Heinemeier David Hansson, Matthew Linderman;$87.99

 
测试结果
运行run_server.py,浏览器访问:http://localhost:8081/
控制台会监控请求的信息:
 
点击“here”,查看图书清单,即书名列表
 
选择书名,点击“detail”提交表单,返回该书的详细信息:书名、作者、价格
 
 
 (转载请注明出处 ^.^)
 
 
 
分类: Python
标签: cgiWeb应用

python实现基于CGI的Web应用的更多相关文章

  1. Python flask 基于 Flask 提供 RESTful Web 服务

    转载自 http://python.jobbole.com/87118/ 什么是 REST REST 全称是 Representational State Transfer,翻译成中文是『表现层状态转 ...

  2. python web编程-CGI帮助web服务器处理客户端编程

    这几篇博客均来自python核心编程 如果你有任何疑问,欢迎联系我或者仔细查看这本书的地20章 另外推荐下这本书,希望对学习python的同学有所帮助 概念预热 eb客户端通过url请求web服务器里 ...

  3. [ Python ] Flask 基于 Web开发 大型程序的结构实例解析

    作为一个编程入门新手,Flask是我接触到的第一个Web框架.想要深入学习,就从<FlaskWeb开发:基于Python的Web应用开发实战>这本书入手,本书由于是翻译过来的中文版,理解起 ...

  4. 什么是 WSGI -- Python 中的 “CGI” 接口简介

    今天在 git.oschina 的首页上看到他们推出演示平台,其中,Python 的演示平台支持 WSGI 接口的应用.虽然,这个演示平台连它自己提供的示例都跑不起来,但是,它还是成功的勾起了我对 W ...

  5. Python全栈开发:web框架们

    Python的WEB框架 Bottle Bottle是一个快速.简洁.轻量级的基于WSIG的微型Web框架,此框架只由一个 .py 文件,除了Python的标准库外,其不依赖任何其他模块. 1 2 3 ...

  6. 【python之路42】web框架们的具体用法

    Python的WEB框架 (一).Bottle Bottle是一个快速.简洁.轻量级的基于WSIG的微型Web框架,此框架只由一个 .py 文件,除了Python的标准库外,其不依赖任何其他模块. p ...

  7. Python(九)Tornado web 框架

    一.简介 Tornado 是 FriendFeed 使用的可扩展的非阻塞式 web 服务器及其相关工具的开源版本.这个 Web 框架看起来有些像web.py 或者 Google 的 webapp,不过 ...

  8. 用Python写一个简单的Web框架

    一.概述 二.从demo_app开始 三.WSGI中的application 四.区分URL 五.重构 1.正则匹配URL 2.DRY 3.抽象出框架 六.参考 一.概述 在Python中,WSGI( ...

  9. Flask —— 使用Python和OpenShift进行即时Web开发

    最近Packtpub找到了我,让我给他们新出版的关于Flask的书写书评.Flask是一个很流行的Python框架.那本书是Ron DuPlain写的<Flask 即时Web开发>.我决定 ...

随机推荐

  1. 剖析Jetty实现原理

    之前写一个简单易用Jetty文章.Jetty对于做JAVA Web发展的方面来说并不陌生,他是一个servlet集装箱,只有相对Tomcat这是比较简单的设计,并且也相对简单,使用灵活,我是学习和使用 ...

  2. vistual studio 2012 安装失败,提示Microsoft Vistual Studio 2012 Devenv找不到元素,等错误信息

    在安装vistual studio 2012过程中,出现安装失败,提示Microsoft Vistual Studio 2012 Devenv找不到元素,等错误信息 解决方法是更新相应的server补 ...

  3. cmd 跟踪路由

    cmd   命令   tracert  ip 地址 用 来 跟踪路由

  4. [WPF]程序全屏

    原文:[WPF]程序全屏 代码: 使用:

  5. VisualStudio2012轻松把JSON数据转换到POCO的代码

    原文:VisualStudio2012轻松把JSON数据转换到POCO的代码       在Visual Studio 2012中轻松把JSON数据转换到POCO的代码,首先你需要安装Web Esse ...

  6. Swift 简简单单实现手机九宫格手势密码解锁

    原文:Swift 简简单单实现手机九宫格手势密码解锁 大家可以看到我之前的文章[HTML5 Canvas简简单单实现手机九宫格手势密码解锁] 本文是使用苹果语言对其进行了移植 颜色配色是拾取的支付宝的 ...

  7. 关于springmvc 方法注解拦截器的解决方案,多用于方法的鉴权

    最近在用SpringMvc写项目的时候,遇到一个问题,就是方法的鉴权问题,这个问题弄了一天了终于解决了,下面看下解决方法 项目需求:需要鉴权的地方,我只需要打个标签即可,比如只有用户登录才可以进行的操 ...

  8. Linux C 多线程

    原文:Linux C 多线程 linux下C语言多线程编程 #include <pthread.h> #include <stdio.h> #include <sys/t ...

  9. Visual Studio 2010 单元测试--运行测试并查看代码覆盖率

    原文:Visual Studio 2010 单元测试--运行测试并查看代码覆盖率 运行测试并查看代码覆盖率对程序集中的代码运行测试时,可以通过收集代码覆盖率数据来查看正在测试的项目代码部分. 运行测试 ...

  10. 在OpenWrt上编写自己的硬件操作程序

    上一篇文章中有写到如何使用OPENWRT的SDK,这里继续,写怎么在上面开发自己的应用程序. 我欲在OpenWrt上编写一个软件,它能够去读取某个AD芯片的多通道采样值. 在看这篇文章之前请看这官方的 ...