配置方法
1.找到apache配置文件httpd.conf ,去掉下面代码前面的#号
1 |
LoadModule cgi_module modules/mod_cgi.so |
2.找到
1 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. |
下面的类似这样的一段代码
1 2 3 4 5 |
<Directory "d:/wamp/bin/apache/apache2.4.9/cgi-bin"> AllowOverride None Options None Require all granted </Directory> |
改为:
1 2 3 4 5 6 |
<Directory "E:/test/python/cgi/"> AllowOverride None Options Indexes FollowSymLinks ExecCGI Require all granted Require host ip </Directory> |
1 2 |
E:/test/python/cgi/ 这个是你的.py文件存放目录 设置CGI的访问权限和路径 |
3.找到:
类似:
1 |
ScriptAlias /cgi-bin/ "d:/wamp/bin/apache/apache2.4.9/cgi-bin/" |
改为:
1 |
ScriptAlias /cgi-bin/ "E:/test/python/cgi/" |
1 |
E:/test/python/cgi/ 这个是你的.py文件存放目录 |
4.找到
1 |
#AddHandler cgi-script .cgi |
替换为:
1 |
AddHandler cgi-script .cgi .py |
这样就可以支持python的.py文件,如果你需要解释shell的脚本文件,可以添加.pl
到此为止基本配置成功了web服务器了。
py文件里面需要注意以下几点:
1 2 3 4 5 6 7 8 9 10 11 12 |
#!C:\Users\Administrator\AppData\Local\Programs\Python\Python36\python.exe # -*- coding: utf-8 -*- print "Content-type:text/html\n\n"# 这里的两个\n是换行符,作用是告诉服务器结束头部 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>' |
如果遇到500错误就是语法错了,注意python2和python3写法是不一样的。比如Python的print就是要带括号的,如 print(‘<html>’)
前面4行非常必要,否则可能报错
1 |
#!D:\Program Files\python27\python.exe 这个是指名python解释器(windows下的,linux下的类似 #!/usr/bin/env python ) |
1 2 3 |
# -*- coding: utf-8 -*- 指定页面编码 print "Content-type:text/html" 指定文件类型 |
1 |
print # 空行,告诉服务器结束头部 |
另外,如果遇到网页中文乱码的情况,就在上面添加两行代码:
1 2 |
import codecs, sys sys.stdout = codecs.getwriter('utf8')(sys.stdout.buffer) |
转载请注明出处:看飞碟 » Python3+Apache搭建WebCGI
评论前必须登录!
登陆 注册