jinja2.exceptions.undefinedError: 'message' is undefined



我制作了去除图像背景的机器学习模型。我试图在index.html文件中传递消息变量,但它抛出了一个错误。当我打印变量的文件名时,它给出了它的名称,但当我将其呈现到index.html文件时,它会抛出一个错误。

import argparse
import os
import tqdm
import logging
from libs.strings import *
from libs.networks import model_detect
import libs.preprocessing as preprocessing
import libs.postprocessing as postprocessing
# Flask utils
from flask import Flask, redirect, url_for, request, render_template
from werkzeug.utils import secure_filename
from gevent.pywsgi import WSGIServer
import torch
# Define a flask app
app = Flask(__name__)

def __save_image_file__(img, file_name, output_path, wmode):
"""
Saves the PIL image to a file
:param img: PIL image
:param file_name: File name
:param output_path: Output path
:param wmode: Work mode
"""
# create output directory if it doesn't exist
folder = os.path.dirname(output_path)
if folder != '':
os.makedirs(folder, exist_ok=True)
if wmode == "file":
file_name_out = os.path.basename(output_path)
if file_name_out == '':
# Change file extension to png
file_name = os.path.splitext(file_name)[0] + '.png'
# Save image
img.save(os.path.join(output_path, file_name))
print("file name 1",file_name)
# return render_template('index.html',message=file_name)
else:
try:
# Save image
img.save(output_path)
print("file name 2",file_name)
return render_template("index.html",message=file_name)
except OSError as e:
if str(e) == "cannot write mode RGBA as JPEG":
raise OSError("Error! "
"Please indicate the correct extension of the final file, for example: .png")
else:
raise e
else:
# Change file extension to png
file_name = os.path.splitext(file_name)[0] + '.png'
# Save image
img.save(os.path.join(output_path, file_name))
# return render_template("index.html",message=file_name)


def cli(inp,oup):
"""CLI"""

parser = argparse.ArgumentParser(description=DESCRIPTION, usage=ARGS_HELP)
parser.add_argument('-i',help="Path to input file or dir.", action="store",dest="input_path", default=inp)
parser.add_argument('-o',help="Path to output file or dir.", action="store",dest="output_path", default=oup)
parser.add_argument('-m', required=False,
help="Model name. Can be {} . U2NET is better to use.".format(MODELS_NAMES),
action="store", dest="model_name", default="u2net")
parser.add_argument('-prep', required=False,
help="Preprocessing method. Can be {} . `bbd-fastrcnn` is better to use."
.format(PREPROCESS_METHODS),
action="store", dest="preprocessing_method_name", default="bbd-fastrcnn")
parser.add_argument('-postp', required=False,
help="Postprocessing method. Can be {} ."
" `rtb-bnb` is better to use.".format(POSTPROCESS_METHODS),
action="store", dest="postprocessing_method_name", default="rtb-bnb")
args = parser.parse_args()
# Parse arguments
input_path = args.input_path
output_path = args.output_path
model_name = args.model_name
preprocessing_method_name = args.preprocessing_method_name
postprocessing_method_name = args.postprocessing_method_name
if model_name == "test":
print(input_path, output_path, model_name, preprocessing_method_name, postprocessing_method_name)
else:
process(input_path, output_path, model_name, preprocessing_method_name, postprocessing_method_name)

if __name__ == "__main__":


@app.route('/', methods=['GET'])
def index():
return render_template('index.html')

@app.route('/input', methods=['GET','POST'])
def result():
if request.method == 'POST':
file = request.files['file']
basepath = os.path.dirname(__file__)
print(file.filename)
input_p = file.save(os.path.join(basepath,'uploadsinput',secure_filename(file.filename)))
#output_p = file.save(os.path.join(basepath,'uploadsoutput',secure_filename(file.filename)))
cli((os.path.join(basepath,'uploadsinput',secure_filename(file.filename))),
(os.path.join(basepath,'staticimages',secure_filename(file.filename))) )
userImage=os.path.join(basepath,'staticimages',secure_filename(file.filename))
print(userImage)
return 'ok'
app.run(debug=True)

在HTML文件中,我使用下面的获得消息变量

<img src="{{ url_for('static', filename= '/images/'+ message ) }}" />   

您不会在渲染命令中传递消息(甚至不会在路由中声明(:

@app.route('/', methods=['GET'])
def index():
return render_template('index.html')

你必须在你的路线内声明它,并在渲染中传递它,如下所示:

@app.route('/', methods=['GET'])
def index():
message='some code'
return render_template('index.html', message=message)

关于如何处理jinga文件中丢失的变量的几个例子。

https://www.shellhacks.com/jinja2-check-if-variable-empty-exists-defined-true/

{% if variable is defined %}
variable is defined
{% else %}
variable is not defined
{% endif %}

相关内容

最新更新