您的位置:首页 > 理论基础 > 计算机网络

Python CGI编程和CGIHTTPServer

2015-11-02 12:00 447 查看

Python2.7 的CGIHTTPServer

可以作为一个简单的HTTP服务器,能够调用cgi脚本

1 在任意目录下创建一个特殊的目录 cgi-bin ,用于存放自己写的脚本(.py或.cgi)

2 在 cgi-bin 所在目录 执行 python -m CGIHTTPServer ,启动服务器

3 在浏览器输入 IP:8000/cgi-bin/xxx.py 即可调用cgi-bin目录下的xxx.py脚本了(Linux可能要更改权限755)

示例1

hello.py

#!/usr/bin/python          #for Linux   Windows: #!C:/Python34/python.exe
# -*- coding: utf-8 -*-

print "Content-type:text/html\r\n\r\n"      #HTTP的header 必不可少  \r\n\r\n表示头部结束,后面的内容都为body
print '''
<html>
<head>
<title>Hello from Python CGI</title>
</head>
<body>
<h1>Hello! This is my first CGI program!!!</h1>
</body>
</html>
'''



Headers

描述
Content-type:请求的与实体对应的MIME信息。例如: Content-type:text/html
Expires: Date响应过期的日期和时间
Location: URL用来重定向接收方到非请求URL的位置来完成请求或标识新的资源
Last-modified: Date请求资源的最后修改时间
Content-length: N请求的内容长度
Set-Cookie: String设置Http Cookie

Apache 执行cgi脚本

  修改配置文件 /path/to/conf/httpd.conf

  1 开启加载模块

    LoadModule cgid_module /usr/lib/apache2/modules/mod_cgid.so

  2 配置脚本目录别名

    ScriptAlias /cgi-bin/ /home/zoro/cgi-bin/ #注意最后一个斜杠前后要保持一致 别名和目录名都可以随意起

  3 设置脚本目录访问权限

    <Directory "/home/zoro/cgi-bin">

      Options ExecCGI //

      Require all granted

    </Directory>

  

  另一个例子:  

  /home/sqd/cgi-bin/hello.sh  

#/bin/sh

echo "Content-Type: text/html; charset=utf-8"   #header

echo                 #表示header结束 不能少

echo "<h1>Hello from sh CGI.</h1>"


  chmod 755 hello.sh

  缺少header会报错: Internal Server Error

  查看错误日志(/usr/local/apache2/logs/error_log)可见:malformed header from script 'hello.sh': Bad header: Hello from sh CGI.

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: