spi*_*itz 5 python static-files flask
我有一个大型网站,在各个 html 页面中包含数百个 href=".html、href="css/、href="img/ 和 src="js/ 引用。我已将所有 css、js、img、声音等文件夹放在“static”文件夹中,并将所有 html 文件放在“模板文件夹”中。
我不想浏览所有 html 文件并使用 Flask 的“url_for”函数手动编辑每个 href。
有没有一种方法可以让我保留现有的 html 文件并告诉 Flask 使用这些 html 文件中定义的 css/、js/ 和图像路径?
现在以下代码会导致一堆 404 错误
import os
from flask import Flask, render_template
PROJECT_PATH = os.path.dirname(os.path.realpath(__file__))
app = Flask(__name__,
template_folder=os.path.join(PROJECT_PATH, 'templates'),
static_folder=os.path.join(PROJECT_PATH, 'static')
)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=True)
Run Code Online (Sandbox Code Playgroud)
好的,根据 Martijn 的脚本,我使用以下代码运行了我的网站。但是,为了捕获 index.html 文件中的许多 href=someHTMLfile.html 链接,我添加了 @app.route('/')。我想知道是否有更好的方法来做到这一点?
from flask import Flask, render_template, safe_join, send_from_directory
app = Flask(__name__)
@app.route('/<any(css, js, img, fonts, sound):folder>/<path:filename>')
def toplevel_static(folder, filename):
filename = safe_join(folder, filename)
cache_timeout = app.get_send_file_max_age(filename)
return send_from_directory(app.static_folder, filename, cache_timeout=cache_timeout)
@app.route('/<path:filename>')
def public(filename):
return render_template(filename)
# @app.route('/')
# def index():
# return render_template('index.html')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=True)
Run Code Online (Sandbox Code Playgroud)
您可以注册其他路由来提供静态文件夹中的文件:
from flask import app, safe_join, send_from_directory
@app.route('/<any(css, img, js, sound):folder>/<path:filename>')
def toplevel_static(folder, filename):
filename = safe_join(folder, filename)
cache_timeout = app.get_send_file_max_age(filename)
return send_from_directory(app.static_folder, filename,
cache_timeout=cache_timeout)
@app.route('/<path:htmlfile>.html')
def toplevel_static(htmlfile):
filename = htmlfile + '.html'
cache_timeout = app.get_send_file_max_age(filename)
return send_from_directory(app.template_folder, filename,
cache_timeout=cache_timeout)
Run Code Online (Sandbox Code Playgroud)
这复制了视图的static功能,但适用于以 、 或 开头/css/的/img/路由。HTML 文件是从模板文件夹加载的。/js//sound/
| 归档时间: |
|
| 查看次数: |
2519 次 |
| 最近记录: |