如题所述
ããé ç½®Apache webæå¡å¨ï¼è®©å ¶è½è¿è¡CGIèæ¬
ããå¨è¿ä¸ªæç¨éï¼æ们å设Apache webæå¡å¨å·²ç»å®è£ 好ï¼å¹¶å·²è¿è¡ãè¿ç¯æç¨ä½¿ç¨çApache webæå¡å¨(çæ¬2.2.15ï¼ç¨äºCentOSåè¡ç6.5)è¿è¡å¨æ¬å°ä¸»æº(127.0.0.1)ï¼å¹¶ä¸çå¬80端å£ï¼å¦ä¸é¢çApacheæ令æå®ä¸æ ·ï¼
ããServerName 127.0.0.1:80Listen 80
ããä¸é¢ä¸¾ä¾ä¸çHTMLæ件åæ¾å¨webæå¡å¨ä¸ç/var/www/htmlç®å½ä¸ï¼å¹¶éè¿DocumentRootæ令æå®(æå®ç½é¡µæ件æå¨ç®å½)ï¼
ããDocumentRoot "/var/www/html"
ããç°å¨å°è¯è¯·æ±URLï¼http://localhost/page1.html
ããè¿å°è¿åwebæå¡å¨ä¸ä¸é¢æ件çå 容ï¼
ãã/var/www/html/page1.html
ãã为äºå¯ç¨CGIèæ¬ï¼æä»¬å¿ é¡»æå®CGIèæ¬å¨webæå¡å¨ä¸çä½ç½®ï¼éè¦ç¨å°ScriptAliasæ令ï¼
ããScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
ãã以ä¸æ令表æCGIèæ¬ä¿åå¨webæå¡å¨ç/var/www/cgi-binç®å½ï¼è¯·æ±URLéå å«/cgi-bin/çå°ä¼æç´¢è¿ä¸ªç®å½ä¸çCGIèæ¬ã
ããæä»¬å¿ é¡»è¿è¦æç¡®CGIèæ¬å¨/var/www/cgi-binç®å½ä¸ææ§è¡æéï¼è¿è¦æå®CGIèæ¬çæ件æ©å±åã使ç¨ä¸é¢çæ令ï¼
ãã<Directory "/var/www/cgi-bin"> Options +ExecCGI AddHandler cgi-script .py</Directory>
ããä¸é¢è®¿é®URLï¼http://localhost/cgi-bin/myscript-1.py
ããè¿å°ä¼è°ç¨webæå¡å¨ä¸ä¸é¢æ示èæ¬ï¼
ãã/var/www/cgi-bin/myscript-1.py
ããå建ä¸ä¸ªCGIèæ¬
ããå¨å建ä¸ä¸ªPython CGIèæ¬ä¹åï¼ä½ éè¦ç¡®è®¤ä½ å·²ç»å®è£ äºPython(è¿é常æ¯é»è®¤å®è£ çï¼ä½æ¯å®è£ çæ¬å¯è½ä¼ææä¸å)ãæ¬ç¯æç¨ä½¿ç¨çèæ¬æ¯ä½¿ç¨Pythonçæ¬2.6.6ç¼åçãä½ å¯ä»¥éè¿ä¸é¢ä»»æä¸å½ä»¤(-Vå--versionåæ°å°æ¾ç¤ºæå®è£ Pythonççæ¬å·)æ£æ¥Pythonççæ¬ã
ãã$ python -V$ python --version
ããå¦æä½ çPython CGIèæ¬è¦ç¨æ¥å¤çç¨æ·è¾å ¥çæ°æ®(ä»ä¸ä¸ªwebè¾å ¥è¡¨å)ï¼é£ä¹ä½ å°éè¦å¯¼å ¥Python cgi模åãè¿ä¸ªæ¨¡åå¯ä»¥å¤çç¨æ·éè¿webè¾å ¥è¡¨åè¾å ¥çæ°æ®ãä½ å¯ä»¥å¨ä½ çèæ¬ä¸éè¿ä¸é¢çè¯å¥å¯¼å ¥è¯¥èæ¬ï¼
ããimport cgi
ããä½ ä¹å¿ 须修æ¹Python CGIèæ¬çæ§è¡æéï¼ä»¥é²æ¢webæå¡å¨ä¸è½è°ç¨ãå¯ä»¥éè¿ä¸é¢çå½ä»¤å¢å æ§è¡æéï¼
ãã# chmod o+x myscript-1.py
ããPython CGIä¾å
ããæ¶åå°Python CGIèæ¬ç两个æ¹æ¡å°ä¼å¨ä¸é¢è®²è¿°ï¼
ãã使ç¨Pythonèæ¬å建ä¸ä¸ªç½é¡µ
ãã读å并æ¾ç¤ºç¨æ·è¾å ¥çæ°æ®ï¼å¹¶ä¸å¨ç½é¡µä¸æ¾ç¤ºç»æ
ãã注æï¼Python cgi模åå¨æ¹æ¡2ä¸æ¯å¿ éçï¼å 为è¿æ¶åå°ç¨æ·ä»web表åè¾å ¥æ°æ®ã
ããä¾å1 ï¼ä½¿ç¨Pythonèæ¬å建ä¸ä¸ªç½é¡µ
ãã对äºè¿ä¸ªæ¹æ¡ï¼æ们å°éè¿å建å å«ä¸ä¸ªåä¸æ交æé®çç½é¡µ/var/www/html/page1.htmlå¼å§ã
ãã<html><h1>Test Page 1</h1><form name="input" action="/cgi-bin/myscript-1.py" method="get"><input type="submit" value="Submit"></form></html>
ããå½"æ交"æé®è¢«ç¹å»ï¼/var/www/cgi-bin/myscript-1.pyèæ¬å°è¢«è°ç¨(éè¿actionåæ°æå®)ãéè¿è®¾ç½®æ¹æ³åæ°ä¸º"get"æ¥æå®ä¸ä¸ª"GET"请æ±ï¼æå¡å¨å°ä¼è¿åæå®çç½é¡µã/var/www/html/page1.htmlå¨æµè§å¨ä¸çæ¾ç¤ºæ åµå¦ä¸ï¼
ãã/var/www/cgi-bin/myscript-1.pyçå 容å¦ä¸ï¼
ãã#!/usr/bin/pythonprint "Content-Type: text/html"print ""print "<html>"print "<h2>CGI Script Output</h2>"print "<p>This page was generated by a Python CGI script.</p>"print "</html>"
ãã第ä¸è¡å£°æ表示è¿æ¯ä½¿ç¨ /usr/bin/pythonå½ä»¤è¿è¡çPythonèæ¬ã"Content-Type: text/html"æå°è¯å¥æ¯å¿ éçï¼è¿æ¯ä¸ºäºè®©webæå¡å¨ç¥éæ¥åèªCGIèæ¬çè¾åºç±»åãå ¶ä½çè¯å¥ç¨æ¥è¾åºHTMLæ ¼å¼çå ¶ä½ç½é¡µå 容ã
ããå½"Submit"æé®ç¹å»ï¼ä¸é¢çç½é¡µå°è¿åï¼
ããè¿ä¸ªä¾åçè¦ç¹æ¯ä½ å¯ä»¥å³å®åªäºä¿¡æ¯å¯ä»¥è¢«CGIèæ¬è¿åãè¿å¯è½å æ¬æ¥å¿æ件çå 容ï¼å½åç»éç¨æ·çå表ï¼æè ä»å¤©çæ¥æãå¨ä½ å¤çæ¶æ¥æææpythonåºçå¯è½æ§æ¯æ ç©·æ å°½çã