You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行Flask图片识别函数时遇UnboundLocalError求助

Fixing the UnboundLocalError in Your Flask Vision Function

Hey there, let's break down why you're hitting that UnboundLocalError: local variable 'labels' referenced before assignment error and fix it step by step.

What's Causing the Issue?

There are two key problems in your code:

  • Incorrect Vision API syntax: You're trying to call response.label_annotations() as a method, but it's actually a property (a pre-populated list of label objects) — those parentheses are invalid. This line will throw an error before labels gets assigned, leading to the UnboundLocalError when you try to use it in render_template.
  • Undefined variable in non-POST paths: If the request is a GET (the default when someone first loads the page) or the POST request doesn't include a 'photo' file, your function never defines the labels variable. Even though you only pass it in the POST branch, leaving it uninitialized for other paths risks this exact error.

Corrected Code

Here's the fixed version of your function with clear improvements:

@app.route('/', methods=['GET', 'POST']) 
def upload_file(): 
    # Initialize labels upfront to cover all request scenarios
    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) 
        # Fix: label_annotations is a property, not a method — remove the parentheses
        labels = response.label_annotations 
    
    # Always render the template, passing labels (empty or populated)
    return render_template('index.html', thelabels=labels)

Key Changes Explained

  • Pre-initialize labels: Setting labels = [] at the start ensures the variable exists no matter what type of request comes in, eliminating the UnboundLocalError entirely.
  • Fix label_annotations access: Removing the () after response.label_annotations correctly accesses the list of labels returned by the Google Cloud Vision API.
  • Centralize template rendering: Moving render_template outside the POST block ensures your page always loads, whether it's a fresh GET request (showing an empty label list) or a POST request with detected labels. This makes your function flow more consistent and avoids hidden Flask errors from missing return values.

Bonus Robustness Tip

To handle edge cases like invalid images or API failures, add a try-except block around the Vision API call:

try:
    response = vision_client.label_detection(image=image) 
    labels = response.label_annotations 
except Exception as e:
    # Log the error for debugging, then fall back to an empty list
    print(f"Vision API error: {str(e)}")
    labels = []

内容的提问来源于stack exchange,提问作者dev python

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:10:49