在flask中渲染默认图像

问题描述 投票:0回答:1

我正在使用url_for生成我的图片网址。

<img src="{{ url_for('static', filename='imgs/' + images[id]) }}" >

当服务器上不存在请求的图像时,如何使url_for返回/static/imgs/default.jpg

python flask jinja2
1个回答
1
投票

解决方案1:HTML / JavaScript

你可以使用onerror属性:

<img src="{{ url_for('static', filename='imgs/' + images[id]) }}" onerror="this.src='/static/imgs/default.jpg'">

或者使用JavaScript(jQuery)为error元素听img事件:

$('img').on("error", function() {
  $(this).attr('src', '/static/imgs/default.jpg');
});

解决方案2:烧瓶

如果你只想用Flask制作它,你需要创建一个自定义视图函数来处理你的图像,例如(还没测试):

import os
from flask import send_from_directory

# ...

@app.route('/img/<path:filename>')
def get_image(filename):
    static_path = os.path.join(app.root_path, 'static')
    img_path = os.path.join(static_path, filename)

    if not os.path.exists(img_path):
        return send_from_directory(os.path.join(static_path, '/imgs/default.jpg'))
    return send_from_directory(img_path)

模板代码:

<img src="{{ url_for('get_image', filename='/static/imgs/' + images[id]) }}" >

解决方案3:Nginx

在制作中,您可以使用像Nginx这样的Web服务器来提供图像,在这种情况下,您可以在Nginx中使用[try_files](http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files)指令:

location /static/imgs/ {
    try_files $uri /static/imgs/default.jpg;
}
© www.soinside.com 2019 - 2024. All rights reserved.