Python CGI编程和CGIHTTPServer


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.

  

 

转载于:https://www.cnblogs.com/roronoa-sqd/p/4929773.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值