Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

python - jinja2.exceptions.UndefinedError: 'message' is undefined

I have made the machine learning model which removes the background of image.I am trying to pass the message variable in index.html file but it throws an error. When I am printing the file name of the variable it is giving the name of it but when I render it to the index.html file, it throws an error.

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)

In HTML file ,I get that message variable using below

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You don't pass message in your render comand (you don't even declare it in your route):

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

You must declare it inside your route and pass it in render, like below:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...