birk 发表于 2017-12-24 07:56:26

python配置apache的web服务器方法(python的CGI配置)

  先大概介绍一下:Python CGI编程

什么是CGI
  CGI 目前由NCSA维护,NCSA定义CGI如下:
  CGI(Common Gateway Interface),通用网关接口,它是一段程序,运行在服务器上如:HTTP服务器,提供同客户端HTML页面的接口。

网页浏览
  为了更好的了解CGI是如何工作的,我们可以从在网页上点击一个链接或URL的流程:


[*]1、使用你的浏览器访问URL并连接到HTTP web 服务器。
[*]2、Web服务器接收到请求信息后会解析URL,并查找访问的文件在服务器上是否存在,如果存在返回文件的内容,否则返回错误信息。
[*]3、浏览器从服务器上接收信息,并显示接收的文件或者错误信息。
  CGI程序可以是Python脚本,PERL脚本,SHELL脚本,C或者C++程序等。

CGI架构图

  下面说重点:

Web服务器配置
  下面配置以wampserver版的apache为例,其他版本应该大同小异的。
  1.找到apache配置文件httpd.conf ,去掉下面代码前面的#号
  

LoadModule cgi_module modules/mod_cgi.so  

  2.找到
  

#  
# "d:/wamp/bin/apache/apache2.4.9/cgi-bin" should be changed to whatever your ScriptAliased
  
# CGI directory exists, if you have that configured.
  
#
  

  下面的类似这样的一段代码
  

<Directory "d:/wamp/bin/apache/apache2.4.9/cgi-bin">  
AllowOverride None
  
Options None
  
Require all granted
  

</Directory>  

  改为:
  

<Directory "E:/test/python/cgi/">  
AllowOverride None
  
Options Indexes FollowSymLinks ExecCGI
  
Require all granted
  
Require host ip
  

</Directory>  

  

E:/test/python/cgi/ 这个是你的.py文件存放目录  设置CGI的访问权限和路径
  

  3.找到:
  类似:
  

ScriptAlias /cgi-bin/ "d:/wamp/bin/apache/apache2.4.9/cgi-bin/"  

  改为:
  

ScriptAlias /cgi-bin/ "E:/test/python/cgi/"  

  

E:/test/python/cgi/ 这个是你的.py文件存放目录  

  4.找到
  

#AddHandler cgi-script .cgi  

  替换为:
  

AddHandler cgi-script .cgi .py  

  这样就可以支持python的.py文件,如果你需要解释shell的脚本文件,可以添加.pl
  到此为止基本配置成功了web服务器了。
  py文件里面需要注意以下几点:
  

#!D:\Program Files\python27\python.exe  
# -*- coding: utf-8 -*-
  
print "Content-type:text/html"
  
print                               # 空行,告诉服务器结束头部
  
print '
<html>'  
print '
<head>'  
print '
<meta charset="utf-8">'  
print '
<title>Hello Word - 我的第一个 CGI 程序!</title>'  
print '
</head>'  
print '
<body>'  
print '
<h2>Hello Word! 我是CGI程序</h2>'  
print '
</body>'  
print '
</html>'  

  前面4行非常必要,否则可能报错
  

#!D:\Program Files\python27\python.exe 这个是指名python解释器(windows下的,linux下的类似 #!/usr/bin/env python )  

# -*- coding: utf-8 -*- 指定页面编码  print "Content-type:text/html" 指定文件类型
  

print          # 空行,告诉服务器结束头部  

  

  

  

  

  
页: [1]
查看完整版本: python配置apache的web服务器方法(python的CGI配置)