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

AttributeError求助:'function'对象无'response'属性,API模块返回值问题

Fixing the AttributeError and API Error Handling Issues

Let's walk through what's causing your errors and how to fix them properly.

Key Problems in Your Code

1. Function Return Logic is Broken

In my_module.py, you have two back-to-back return statements:

return response
return data

Once the first return runs, the function exits immediately—so the second return will never execute. You can't return two values like this; instead, return a tuple containing both values.

2. Incorrectly Accessing Function "Attributes"

In my_script.py, you're trying to access errorHandler.response—but errorHandler is a function, not an object with attributes. You need to call the function and capture its returned values instead.

3. Unhandled Undefined Variables in Exceptions

If an exception (like a Timeout or ConnectionError) occurs, the response and data variables are never created. Trying to return them in this case will throw a NameError.

4. Outdated Print Syntax (Python 2 vs 3)

Your print "..." syntax is Python 2-specific. For compatibility with modern Python, use print("...") instead.


Corrected my_module.py

import requests
import json

def errorHandler(url):
    response = None
    data = None
    try:
        response = requests.get(url, timeout=5)
        status = response.status_code
        data = response.json()
    except requests.exceptions.Timeout:
        print("Timeout error.\n")
    except requests.exceptions.ConnectionError:
        print("Connection error.\n")
    except ValueError:
        print("ValueError: No JSON object could be decoded.\n")
    else:
        if response.status_code == 200:
            print("Status: 200 OK \n")
        elif response.status_code == 400:
            print(f"Status: {status} error. Bad request.")
            print(f"Correlation ID: {data['correlationId']}\n")
        else:
            print(f"Status: {status} error.\n")
    # Return both values as a tuple
    return response, data

Changes Made:

  • Initialized response and data to None at the start, so they exist even if an exception is thrown.
  • Combined the return into a single return response, data (this returns a tuple).
  • Updated print statements to use Python 3 syntax, plus f-strings for cleaner string formatting.

Corrected my_script.py

from my_module import errorHandler

# Call the function and capture both returned values
response, data = errorHandler("https://api.weather.gov/alerts/active")

# Check if response exists before accessing its attributes
if response is not None:
    print(f"Content type is {response.headers['content-type']}.\n")

# Check if data exists before accessing nested keys
if data is not None and 'features' in data and len(data['features']) > 0:
    nwsId = data['features'][0]['properties']['id']
    print(f"Retrieved NWS ID: {nwsId}")
else:
    print("No valid data returned from the API.")

Changes Made:

  • Imported errorHandler from my_module (you were missing this import in your original script).
  • Captured the returned tuple into response and data variables.
  • Added checks for None and valid data structure before accessing attributes/keys—this prevents crashes if the API call fails.

Why This Fixes Your Error

The original AttributeError: 'function' object has no attribute 'response' happened because you were treating the errorHandler function like an object with a response attribute. By calling the function and capturing its returned values, you're properly accessing the data the function generates.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:55:31