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.conf1 开启加载模块
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.
相关文章推荐
- PHP模拟发送POST请求之一、HTTP协议头部解析
- Netscape HTTP Cookie File php程序中用curl保存的cookie文件格式
- win7如何添加网络打印机和共享网络打印机
- HTTP所承载的货物(图像、文本、软件等)要满足的条件
- java网络编程——Socket和ServerSocket,套接字编程——简单聊天室
- 一个简单的网络验证程序的分析
- 从网络下载的图片加缓存功能
- httpclient
- Http Response Code[整理]
- Http 四种请求访问代码 HttpGet HttpPost HttpPut HttpDelete
- 网络字节序与主机字节序
- 保护HTTP的安全
- 创建安全的基于HTTP的api应用接口
- TCP/IP
- [Servlet]HttpServletResponse的二进制输出(获取应用程序中的资源再输出)、重定向、错误发送
- HTTP深入浅出 http请求(转)
- 10月第4周网络安全报告:放马站点.COM占75.8%
- HTTPS的使用学习
- 认识HTTP
- OKHttpClient