UnboundLocalError:分配前引用了本地变量'd'

时间:2019-11-24 19:12:53

标签: python flask

我正在使用烧瓶创建REST API,在其中我具有收据图像,并希望提取收据上的日期。这可以通过下面的代码中的date_extractor函数来完成,这些函数具有process_image_for_ocr函数,这是执行此任务的py代码。但是我得到了错误:

  

UnboundLocalError:赋值之前引用了本地变量'r'

return render_template("result.html",prediction=d)

  

代码:script.py

#importing libraries
import os
import numpy as np
import flask
import pickle
from flask import Flask, render_template, request,redirect
from preprocess import process_image_for_ocr
#from preprocess import process_image_for_ocr

def date_extractor(path):
    result = process_image_for_ocr(path)
    return result

#creating instance of the class
app=Flask(__name__)

APP_ROOT = os.path.dirname(os.path.abspath(__file__))


ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

#to tell flask what url shoud trigger the function index()
@app.route("/")
def index():
    return flask.render_template('index.html')



@app.route("/upload",methods=["POST"])
def upload():
    target = os.path.join(APP_ROOT, 'images/')
    print(target)

    if not os.path.isdir(target):
        os.mkdir(target)


    for file in request.files.getlist("file"):
        print(file)
        filename = file.filename
        destination = "/".join([target, filename])
        print(destination)
        file.save(destination)
    if request.method == 'POST':
        for root, dirs, files in os.walk(destination, topdown=False):
            for name in files:
                    path = os.path.join(root, name)
                    r = date_extractor(path)

                    if not r == "NULL":
                        d = r
                    else:
                        d = "NULL"

    return render_template("result.html",prediction=d)
if __name__ == "__main__":
    app.run(port=4555, debug=True)
  

result.html:

<!doctype html>
<html>
   <body>
       <h1> {{ prediction }}</h1>
   </body>
</html>

当我尝试传递.JPEG文件时,此代码中还有一个错误,它将无法成功上传。

1 个答案:

答案 0 :(得分:-2)

for循环内的变量d是局部变量。它仅存在于范围内,并且在完成循环后消失。因此,您尝试访问未分配的变量。 我认为您想使用global d(如果我没记错的话,请将其放在for循环之前)。然后,它创建全局d变量,该变量可从for循环内部访问。

if request.method == 'POST':
        global d
        for root, dirs, files in os.walk(destination, topdown=False):
            for name in files:
                    path = os.path.join(root, name)
                    r = date_extractor(path)

                    if not r == "NULL":
                        d = r
                    else:
                        d = "NULL"