Python 在flask中渲染默认图像

Python 在flask中渲染默认图像,python,flask,jinja2,Python,Flask,Jinja2,我正在使用url\u生成我的图像url <img src="{{ url_for('static', filename='imgs/' + images[id]) }}" > 当服务器上不存在请求的图像时,如何为return/static/imgs/default.jpg创建url_?解决方案1:HTML/JavaScript 您可以使用onerror属性: <img src="{{ url_for('static', filename='imgs/' + images[id

我正在使用url\u生成我的图像url

<img src="{{ url_for('static', filename='imgs/' + images[id]) }}" >
当服务器上不存在请求的图像时,如何为return/static/imgs/default.jpg创建url_?

解决方案1:HTML/JavaScript 您可以使用onerror属性:

<img src="{{ url_for('static', filename='imgs/' + images[id]) }}" onerror="this.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)
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]) }}" >
location /static/imgs/ {
    try_files $uri /static/imgs/default.jpg;
}