Flask 使用静态文件
示例
Web应用程序通常需要静态文件,例如CSS或JavaScript文件。要在Flask应用程序中使用静态文件,请static在您的程序包中或模块旁边创建一个名为的文件夹,该文件夹将/static在应用程序上提供。
使用模板的示例项目结构如下:
MyApplication/
/static/
/style.css
/script.js
/templates/
/index.html
/app.pyapp.py是带有模板渲染功能的Flask的基本示例。
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')要在模板index.html中使用静态CSS和JavaScript文件,我们需要使用特殊的“静态”端点名称:
{{url_for('static', filename = 'style.css')}}因此,index.html可能包含:
<html>
<head>
<title>Static File</title>
<link href="{{url_for('static', filename = 'style.css')}}" rel="stylesheet">
<script src="{{url_for('static', filename = 'script.js')}}"></script>
</head>
<body>
<h3>Hello World!</h3>
</body>
</html>运行后,app.py我们将在http://localhost:5000/中看到该网页。