Hom's Blog


Python:CGI编程

CGI (Common Gateway Interface)

ScriptAlias /cgi-bin/ /var/www/cgi-bin/

<Directory "/var/www/cgi-bin">
   AllowOverride None
   Options +ExecCGI
   Order allow,deny
   Allow from all
</Directory>

AddHandler cgi-script .cgi .pl .py
#!/usr/bin/python
# -*- coding: UTF-8 -*-

print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<head>'
print '<title>Hello Word - First CGI Program</title>'
print '</head>'
print '<body>'
print '<h2>Hello Word! This is first CGI program</h2>'
print '</body>'
print '</html>'

脚本第一行的输出内容Content-type:text/html\r\n\r\n发送到浏览器并告知浏览器显示的内容类型为”text/html”。相应类型要作变更, 缺少这行头信息会出错!

一般cgi编程会需要用到两个模块: cgicgitb, 前者是一些基础接口用于处理交互(例如GET,POST), 后者是处理trackback.

处理GET/POST是最常用的了. 对于python的cgi, 并没有太大区别去获取GET/POST数据, 不像PHP那样区分那么细:

import cgi,cgitb
form = cgi.FieldStorage() 
name=form.getvalue('name')

以上代码就能获取GET和POST



◆ 本文地址: http://platinhom.github.io/2016/02/24/py-cgi/, 转载请注明 ◆

前一篇: Python:super函数
后一篇: Python:StringIO模块模拟文件对象


Contact: Hom / 已阅读()
Source 类别: Coding  标签: Python  Internet