当我尝试运行此功能时,它会给我这个错误“ UnboundLocalError:赋值之前引用的局部变量'labels'”可以帮助我
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST' and 'photo' in request.files:
filename = photos.save(request.files['photo'])
file_url = photos.url(filename)
with io.open(filename, 'rb') as image_file:
content = image_file.read()
image = types.Image(content=content)
response = vision_client.label_detection(image=image)
labels = response.label_annotations()
return render_template('index.html', thelabels=labels)
答案 0 :(得分:1)
仅当labels
语句返回if
时才实例化函数中的True
变量,否则将永远不会创建该变量。
如果初始检查未返回else
(或在True
之前为labels
提供默认值,则需要设置if
语句来创建变量声明,如艾哈迈德的建议):
@app.route('/', methods=['GET', 'POST'])
def upload_file():
# Option 1: give `labels` a default value here - Doesn't have to be `None`
labels = None
if request.method == 'POST' and 'photo' in request.files:
filename = photos.save(request.files['photo'])
file_url = photos.url(filename)
with io.open(filename, 'rb') as image_file:
content = image_file.read()
image = types.Image(content=content)
response = vision_client.label_detection(image=image)
labels = response.label_annotations()
else: # Option 2: set `labels` to `None` in an `else` statement in case the `if` statement check returns False
labels = None
return render_template('index.html', thelabels=labels)
答案 1 :(得分:-1)
由于在labels
语句中定义了变量if
,导致了本地错误。在函数中定义
@app.route('/', methods=['GET', 'POST'])
def upload_file():
labels = ''
if request.method == 'POST' and 'photo' in request.files:
filename = photos.save(request.files['photo'])
file_url = photos.url(filename)
with io.open(filename, 'rb') as image_file:
content = image_file.read()
image = types.Image(content=content)
response = vision_client.label_detection(image=image)
labels = response.label_annotations()
return render_template('index.html', thelabels=labels)
渲染模板时,请检查模板中
thelabels
是否为''
希望有帮助