Flask python脚本在给定值之前运行



我有一个简单的Flask python脚本,我想通过一个表单添加2个图像路径,将这些路径发送到python do并发回一个字符串。我遇到的问题是,在填写表单并按下按钮之前,脚本就会运行。如何让脚本等待并只在按下提交按钮时运行?

参考代码

@app.route('/', methods=['GET', 'POST'])
@app.route('/index')
def index():
PATH_REFERENCE = request.form.get("referencePhoto")
PATH_TEST = request.form.get("testPhoto")
testImage = cv2.imread(PATH_TEST)
reference = setupReference(PATH_REFERENCE)
face_locations, face_encodings = getFaceEmbeddingsFromImage(testImage, convertToRGB=True)
for location, face_encoding in zip(face_locations, face_encodings):
distances = face_recognition.face_distance(reference[0], face_encoding)
if distances <= 0.6:
result = 'Match!'
else:
result = 'Not Match!'
return render_template('index.html', title='Home', result=result)

错误是脚本无法对NoneObject执行操作。如果表单没有发送所需的路径,这是有意义的。

只在Post上执行表单逻辑-在get上,只为表单服务。

@app.route('/', methods=['GET', 'POST'])
@app.route('/index')
def index():
result = ""
if request.method == "POST":
PATH_REFERENCE = request.form.get("referencePhoto")
PATH_TEST = request.form.get("testPhoto")
testImage = cv2.imread(PATH_TEST)
reference = setupReference(PATH_REFERENCE)
face_locations, face_encodings = getFaceEmbeddingsFromImage(testImage, convertToRGB=True)
for location, face_encoding in zip(face_locations, face_encodings):
distances = face_recognition.face_distance(reference[0], face_encoding)
if distances <= 0.6:
result = 'Match!'
else:
result = 'Not Match!'
return render_template('index.html', title='Home', result=result)