一个完整的 Flask 项目示例

半兽人 发表于: 2025-05-09   最后更新时间: 2025-05-09 17:06:39  
{{totalSubscript}} 订阅, 16 游览

下面是一个完整的 Flask 项目示例,包含基本的目录结构、主页和静态资源(CSS)。

一、项目结构如下:

myapp/
├── app.py
├── templates/
│   └── index.html
├── static/
│   └── style.css

二、代码文件内容:

1. app.py — 主程序

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)

2. templates/index.html — HTML 页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Flask 示例</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <h1>欢迎来到 Flask 网站!</h1>
    <p>这是主页内容。</p>
</body>
</html>

3. static/style.css — 样式文件

body {
    font-family: Arial, sans-serif;
    background-color: #f5f5f5;
    padding: 30px;
}

h1 {
    color: #007acc;
}

三、运行方式:

在终端中进入 myapp 目录,然后运行:

python app.py

打开浏览器访问:http://127.0.0.1:5000/
你将看到一个简单的网页页面,带有样式。

更新于 2025-05-09

查看python更多相关的文章或提一个关于python的问题,也可以与我们一起分享文章