- 项目目录结构
要保证项目目录结构如下:
your_project/
├── app.py
├── templates/
│ └── index.html
└── static/
├── css/
│ └── style.css
├── js/
│ └── script.js
└── images/
└── tupian.png
- 修改 index.html 文件
运用 Flask 的 url_for() 函数来生成静态文件的 URL,示例如下:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
<script src="{{ url_for('static', filename='js/script.js') }}"></script>
<img src="{{ url_for('static', filename='images/tupian.png') }}">
</body>
</html>
- Flask 应用配置
确保 Flask 应用正确设置了静态文件目录(默认就是 static):
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)