前言

有個工作案子要求架設一個後端為 Pyhton 的客語翻譯網站。

需要實現的功能有:後端執行 Pyhton 程式、前端後端相互傳遞資料。

為了在沿用前輩留下來的伺服器軟體 XAMPP 上實現目前工作的需求,稍微做了點研究。


關於 CGI

CGI 全名為 Common Gateway Interface,功能是扮演瀏覽器和程式的橋樑。

當使用者在瀏覽器上發出一個請求時,會傳送特定的訊息給網頁伺服器。

而 CGI 程式的功能就是接收這些訊息後,再加以處理並回應,或儲存至資料庫中。


軟體需求

XAMPP:免費且易於安裝的 Apache 發行版本,其中包含 MariaDB、PHP 和 Perl。

Python:是一種廣泛使用的直譯式、進階程式、通用型程式語言。


實作過程

安裝 XAMPP、Python

以 Windows 系統為例,建議將 XAMPP、Python 皆安裝於C:/下,以便於後續操作。

範例:C:/xamppC:/Python37


允許 Apache 執行 .py 檔

  • 方法一:

    於 Apache 的配置檔案C:/xampp/conf/httpd.conf中搜尋.cgi直到找到:

    AddHandler cgi-script .cgi .asp
    

    於行尾添加.py,允許 Apache 執行副檔名為.py的檔案:

    AddHandler cgi-script .cgi .asp .py
    
  • 方法二:

    於存放.py檔的目錄下,新增名為.htaccess的純文字檔,內容為:

    AddHandler cgi-script .cgi .asp .py
    

不修改也可以,只是 Python 程式檔的副檔名要改成.cgi才能被執行。


前端 HTML

需要用到 AJAX 功能,所以先導入 jQuery。

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>

建立兩個textarea與一個button

<body>
  <p>input_txt:</p>
  <textarea id="input_txt"></textarea>
  <button id="btn">button</button>
  <p>output_txt:</p>
  <textarea id="output_txt"></textarea>
</body>

前端 JS

btn被按下後,使用 POST 方法,將值input_txt傳回後端add_hello.py,格式為 JSON。

如果成功接收來自後端的回應,則將回應中值with_hello顯示於output_txt

<script>
  $("#btn").on("click",function(){
    $.ajax({
      url: "./add_hello.py",
      type: "post",
      datatype: "json",
      data: {'input_txt': $("#input_txt").val()},
      success: function(response){ $("#output_txt").val(response.with_hello); }
    });
  });
</script>

後端 Python

首先,先指定 Python 路徑及導入必要的函式庫。

#!C:/Python37/python
import json, cgi

透過 CGI 接收前端資料。

fs = cgi.FieldStorage()
input_txt = fs.getvalue("input_txt")

將回覆內容放進字典轉成 JSON,並直接print給前端即可。

response = {}
response["with_hello"] = input_txt + "+hello"

print("Content-Type: application/json\n\n")
print(json.dumps(response))