動態Web頁面的實現需要模板和後端服務器程序的配合,其中Python CGI可以實現Web頁面和後台Python代碼的交互,因此成為一種常見的實現方法。
一、CGI概述
CGI(Common Gateway Interface)是一種標準,用於定義Web服務器如何與其他應用程序或腳本進行交互。CGI程序是一種可以接收HTTP請求並返回Web頁面或其他數據的應用程序。Python標準庫中就有CGI模塊,可以直接使用。
使用CGI需要在Web服務器上設置相應的權限,在Apache服務器中,需要在 httpd.conf 配置文件中添加以下語句:
ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
<Directory "/var/www/cgi-bin">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
</Directory>
這樣就可以將 /var/www/cgi-bin/ 目錄下的所有腳本識別為CGI程序。
二、Python CGI腳本編寫
Python CGI腳本需要滿足以下要求:
- 腳本必須以“#! /usr/bin/python” 或 “#! /usr/bin/env python”開始
- 腳本必須被標記為可執行
- 在HTML標記中,CGI腳本可以在<form>標籤的action屬性中指定,以實現表單提交等交互操作
三、Python CGI示例程序
以下是一個簡單的Python CGI示例:
#! /usr/bin/python
print("Content-type:text/html\r\n\r\n")
print("<html>")
print("<head><title>Python CGI示例程序</title></head>")
print("<body>")
print("<h2>歡迎來到Python CGI示例程序</h2>")
print("<p>以下是您的提交信息:</p>")
import cgi
form = cgi.FieldStorage()
for field in form.keys():
print("<p>{}:{}</p>".format(field, form[field].value))
print("</body>")
print("</html>")
該程序通過CGI處理表單提交信息,將信息打印在Web頁面上。
四、總結
通過Python CGI可以實現Web頁面和後台Python代碼的交互,可以應用於表單提交、動態頁面生成等Web應用場景。
完整Python CGI示例代碼:
#! /usr/bin/python
print("Content-type:text/html\r\n\r\n")
print("<html>")
print("<head><title>Python CGI示例程序</title></head>")
print("<body>")
print("<h2>歡迎來到Python CGI示例程序</h2>")
print("<p>以下是您的提交信息:</p>")
import cgi
form = cgi.FieldStorage()
for field in form.keys():
print("<p>{}:{}</p>".format(field, form[field].value))
print("</body>")
print("</html>")
原創文章,作者:ZRFE,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/148674.html