macOS自带Apache,简单配置httpd.conf文件后即可支持Python CGI编程:
1. 用电脑终端打开httpd.conf
sudo vim /etc/apache2/httpd.conf
2.搜索并激活CGI模块包(约在164行,去掉前面的#号)
LoadModule cgi_module libexec/apache2/mod_cgi.so
3.放开权限,并修改CGI程序默认位置
DocumentRoot用于修改默认程序位置
增加ExecCGI,使得在当前目录下可以执行CGI script,没有增加的话会出现403 forbidden错误
Order allow,deny
Allow from all 放开当前文件夹权限
#DocumentRoot "/Library/WebServer/Documents" #<Directory "/Library/WebServer/Documents"> DocumentRoot "/Users/shen/websites" <Directory "/Users/shen/websites"> # # Possible values for the Options directive are "None", "All", # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that "MultiViews" must be named *explicitly* --- "Options All" # doesn't give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.4/mod/core.html#options # for more information. # Options FollowSymLinks ExecCGI Multiviews MultiviewsMatch Any # # AllowOverride controls what directives may be placed in .htaccess files. # It can be "All", "None", or any combination of the keywords: # AllowOverride FileInfo AuthConfig Limit # AllowOverride None # # Controls who can get stuff from this server. # Require all granted Order allow,deny Allow from all </Directory>
4.在AddHandler上.py,使得Apache可以识别Python文件
AddHandler cgi-script .cgi .pl .py .rb
5.保存httpd.conf文件
6.重启Apache
sudo apachectl restart
7.将hello.py放在/Users/shen/websites中,并赋予755权限,并在浏览器中输入 http://localhost/hello.py
代码1
#!/usr/bin/python # -*- coding: UTF-8 -*- print("Content-type:text/html") print('') # 空行,告诉服务器结束头部 print('<html>') print('<head>') print('<meta charset="utf-8">') print('<title>Hello World! 我是来自菜鸟教程的第一CGI程序</title>') print('</head>') print('<body>') print('<h2>Hello World! 新的CGI脚本路径设置</h2>') print('</body>') print('</html>')
代码2
#!/usr/bin/python # -*- coding: UTF-8 -*- print("Content-type:text/html ") # ,告诉服务器结束头部 #print('') print('<html>') print('<head>') print('<meta charset="utf-8">') print('<title>Hello World! 我是来自菜鸟教程的第一CGI程序</title>') print('</head>') print('<body>') print('<h2>Hello World! 新的CGI脚本路径设置</h2>') print('</body>') print('</html>')
一定要告诉服务器结束头部,否则出现“500 Internal Server Error”错误