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

先大概介紹一下:Python CGI編程html

什麼是CGI

CGI 目前由NCSA維護,NCSA定義CGI以下:python

CGI(Common Gateway Interface),通用網關接口,它是一段程序,運行在服務器上如:HTTP服務器,提供同客戶端HTML頁面的接口。linux

網頁瀏覽

爲了更好的瞭解CGI是如何工做的,咱們能夠從在網頁上點擊一個連接或URL的流程:web

  • 一、使用你的瀏覽器訪問URL並鏈接到HTTP web 服務器。
  • 二、Web服務器接收到請求信息後會解析URL,並查找訪問的文件在服務器上是否存在,若是存在返回文件的內容,不然返回錯誤信息。
  • 三、瀏覽器從服務器上接收信息,並顯示接收的文件或者錯誤信息。

CGI程序能夠是Python腳本,PERL腳本,SHELL腳本,C或者C++程序等。shell

CGI架構圖

 cgiarch

下面說重點:apache

Web服務器配置

下面配置以wampserver版的apache爲例,其餘版本應該大同小異的。編程

1.找到apache配置文件httpd.conf ,去掉下面代碼前面的#號windows

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          # 空行,告訴服務器結束頭部
相關文章
相關標籤/搜索