下面是一个完整的 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/
你将看到一个简单的网页页面,带有样式。