Flask HTML JS CSS 图片链接404错误

5 投票
1 回答
2520 浏览
提问于 2025-04-18 06:41

我有一个很大的网站,里面有很多页面,每个页面都有很多链接,比如href=".html"、href="css/"、href="img/"和src="js/"。我把所有的css、js、图片、声音等文件夹都放在一个叫“static”的文件夹里,把所有的html文件放在一个叫“template”的文件夹里。

我不想一个一个去修改我的html文件,手动用Flask的“url_for”函数来更新每个链接。

有没有办法让我不动现有的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)

根据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)

1 个回答

1

你可以注册额外的路径来从你的静态文件夹中提供文件:

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)

这和static视图的功能是一样的,不过是针对以/css//img//js//sound/开头的路径。而HTML文件则是从你的模板文件夹中加载的。

撰写回答