1. 程式人生 > >一個簡單的cgi程式設計例子

一個簡單的cgi程式設計例子

工作環境

  • 作業系統:Ubuntu 12.04
  • Web伺服器:Apache
  • 開發語言:Python

準備工作

安裝Apache

sudo apt-get install apache2

配置Apache

修改Apache配置檔案(/etc/apache2/httpd.conf),新增以下內容

<Directory "/var/www/bin-cgi/">  
   AllowOverride None  
   Options ExecCGI  
   Order allow,deny  
   Allow from all  
</Directory>  
AddHandler cgi-script .py

重啟Apache

sudo /etc/init.d/apache2 restart
訪問http://localhost/ ,看看Apache是否成功開啟

Hello World

新建路徑

按照之前Apache的配置,在/var/www/下新建bin-cgi資料夾

cgi程式碼

在建好的資料夾下新建檔案helloworld.py,裡面內容如下

#!/usr/bin/python   
print "Content-type:text/html\r\n\r\n"  
print '<html>'  
print '<head>'  
print '<title>Hello World - First CGI Program</title>'
print '</head>' print '<body>' print '<h2>Hello World! This is my first CGI program</h2>' print '</body>' print '</html>'

修改檔案許可權

sudo chmod 647 helloworld.py

測試

文/揹著龜殼的豬(簡書作者)
原文連結:http://www.jianshu.com/p/8b0036f194e7
著作權歸作者所有,轉載請聯絡作者獲得授權,並標註“簡書作者”。