在Debian上進行Python Web開發,你可以選擇多種流行的Web框架,如Flask、Django或FastAPI。以下是使用Flask框架進行Web開發的詳細步驟:
sudo apt update
sudo apt install python3 python3-pip -y
python3 -m venv venv
source venv/bin/activate
新建一個文件 app.py,并寫入以下代碼:
from flask import Flask, render_template, request
app = Flask(__name__)
# 存儲留言
messages = []
@app.route("/")
def index():
return render_template("index.html", messages=messages)
@app.route("/submit", methods=["POST"])
def submit():
name = request.form.get("name")
message = request.form.get("message")
if name and message:
messages.append({"name": name, "message": message})
return index()
if __name__ == "__main__":
app.run(debug=True)
在 app.py 同級目錄下,新建 templates 文件夾,然后創建 index.html:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>留言板</title>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
form { margin-bottom: 20px; }
input, textarea { display: block; margin: 10px 0; width: 100%; max-width: 500px; }
</style>
</head>
<body>
<h1>留言板</h1>
<form action="/submit" method="post">
<input type="text" name="name" placeholder="名字" required>
<textarea name="message" placeholder="留言" required></textarea>
<button type="submit">提交留言</button>
</form>
<h2>留言列表:</h2>
<ul>
{% for msg in messages %}
<li><strong>{{ msg.name }}</strong>: {{ msg.message }}</li>
{% endfor %}
</ul>
</body>
</html>
在終端運行以下命令啟動Flask服務器:
python app.py
然后打開瀏覽器,訪問 http://127.0.0.1:5000/,你將看到留言板的頁面。
選擇合適的框架取決于你的項目需求。無論是快速原型開發還是構建大型應用,Python都有豐富的框架生態系統來支持。