debian

Python在Debian上如何进行Web开发

小樊
46
2025-04-16 04:36:32
栏目: 编程语言

在Debian上进行Python Web开发,你可以选择多种流行的Web框架,如Flask、Django或FastAPI。以下是使用Flask框架进行Web开发的详细步骤:

环境准备

  1. 安装Python和pip
sudo apt update
sudo apt install python3 python3-pip -y
  1. 创建虚拟环境(推荐):
python3 -m venv venv
source venv/bin/activate

编写Flask应用

  1. 创建Flask应用

新建一个文件 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)
  1. 创建前端页面

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都有丰富的框架生态系统来支持。

0
看了该问题的人还看了