首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Karrigell 入門:輕量級 Python Web 框架快速上手指南

     編輯:PHP 綜合知識

Karrigell 是純 Python 實作的輕量級 Web 框架,內建 HTTP 伺服器,支援 CGI/WSGI,適合快速原型、教學、小型專案。本文涵蓋安裝、內建伺服器啟動、Apache 整合、基本路由與模板用法。

安裝與啟動

# 下載最新版(SourceForge 或 PyPI)
pip install Karrigell

# 或手動下載解壓後
python Karrigell.py          # 預設 port 80
python Karrigell.py -P 8080  # 指定 port

瀏覽 https://localhost:8080 即可看到歡迎頁。

目錄結構慣例

project/
├── Karrigell.py          # 入口/伺服器啟動
├── Karrigell.ini         # 設定檔
├── scripts/              # Python 腳本(*.py, *.ks, *.hip, *.pih)
├── static/               # 靜態資源
└── templates/            # 模板檔

撰寫第一個動態頁面

建立 scripts/index.py:

def index():
    return "Hello, Karrigell!"

瀏覽 https://localhost:8080/index.py 顯示文字。

模板引擎(Karrigell Template)

建立 scripts/index.ks(Karrigell Script):

<html>
<body>
<h1>Welcome, {{ name }}!</h1>
<ul>
{% for item in items %}
    <li>{{ item }}</li>
{% endfor %}
</ul>
</body>
</html>

對應 scripts/index.py:

def index():
    return HTTPResponse(Template('index.ks', name='User', items=['Apple', 'Banana', 'Cherry']))

Apache 整合(生產環境)

讓 Apache 處理靜態檔,動態請求代理至 Karrigell 內建伺服器(port 8080)。

# httpd.conf
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule rewrite_module modules/mod_rewrite.so

RewriteEngine On
# 靜態檔直接服務
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

# 動態腳本代理
RewriteRule ^/(.*).py(.*) https://localhost:8080/$1.py$2 [L,P]
RewriteRule ^/(.*).ks(.*) https://localhost:8080/$1.ks$2 [L,P]
RewriteRule ^/(.*).hip(.*) https://localhost:8080/$1.hip$2 [L,P]
RewriteRule ^/(.*).pih(.*) https://localhost:8080/$1.pih$2 [P]

並確保 Karrigell.ini 設定 port=8080。

核心特性速覽

特性說明
內建伺服器開發免額外安裝 Apache/Nginx
多種腳本格式.py (純 Python), .ks (模板), .hip (HTML+Python), .pih (Python in HTML)
Session 管理內建檔案/記憶體/資料庫後端
表單驗證Validators 模組
資料庫抽象支援 SQLite, MySQL, PostgreSQL 等
無強制結構適合腳本式快速開發

適用場景與限制

  • ✅ 教學、原型、內部工具、低流量服務
  • ❌ 高併發、大型團隊、需完整生態系(Admin, ORM, Migration, Testing)的專案
  • 現代替代方案:FastAPI(高效能、自動文檔)、Flask(微框架、擴充豐富)、Django(全功能)。

總結

Karrigell 以單一檔案、零配置、內建伺服器降低 Python Web 入門門檻。理解其運作原理有助於掌握 WSGI、路由、模板渲染等核心概念,為進階框架學習鋪路。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved