從 Python 快速啓動 CGI 服務器

很多人知道 Python 3 可以快速啓動一個 HTTP 服務器:

$ python3 -m http.server 8000

今天我查閱 http.server 模塊發現它支持運行 CGI 腳本,只要加上 --cgi 選項。

入門 Web 後端的初學者一定是要學習 CGI 的(不管是學歷史還是學概念都有好處),而配置 Apache / NGINX 環境對他們來說可能比較困難。我發現用 Python 這種自帶的基礎服務器既方便又簡單。

例子

我們來寫一個 Hello World 的 Python CGI 程序 hello.py 放在 cgi-bin/ 裏:

#!/usr/bin/python3
print('Content-type: text/html')
print()
print('Hello world!')

再寫一個前端網頁 index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Hello Test</title>
</head>
<body>
    <form action="/cgi-bin/hello.py" method="post">
        <button type="submit">Hello</button>
    </form>
</body>
</html>

整個目錄結構爲:

cgi-bin/
    hello.py
index.html

然後將 CGI 腳本賦予運行權限:

$ chmod a+x cgi-bin/hello.py

運行測試

運行

$ python3 -m http.server --cgi 8000

瀏覽器訪問 http://127.0.0.1:8000/

圖片

點擊按鈕:

圖片

(本文完)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章