AttributeError:'function'对象没有属性'response'

时间:2018-05-31 20:08:54

标签: python python-2.6

我有一个错误处理模块,我在主脚本中使用它来向API发出请求。我想返回在主脚本中使用的“响应”和“数据”。它一直工作,直到尝试打印“响应”。对于不一致的道歉,我显然还在学习。如果不先犯下一些错误,我就不会学习。我赞赏建设性的批评。

my_module

import requests
import json

def errorHandler(url):
    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 "Status: " + str(status) + " error. Bad request."
            print "Correlation ID: " + str(data['correlationId']) + "\n"
        else:
            print "Status: " + str(status) + " error.\n"

    return response
    return data

my_script

errorHandler("https://api.weather.gov/alerts/active")

print "Content type is " + response.headers['content-type'] +".\n" #expect geo+json

# I need the data from the module to do this, but not for each get request
nwsId = data['features'][0]['properties']['id']

错误

Traceback (most recent call last):
  File "my_script.py", line 20, in <module>
    print errorHandler.response
AttributeError: 'function' object has no attribute 'response'

1 个答案:

答案 0 :(得分:3)

如果要返回多个值,可以在单个语句中将它们作为元组返回:

return response, data

然后在调用者中,将它们分配给具有元组赋值的变量:

response, data = errorHandler("https://api.weather.gov/alerts/active")
print "Content type is " + response.headers['content-type'] +".\n"
nwsId = data['features'][0]['properties']['id']

但是,如果发生任何异常,您的功能将无法正常工作。如果有异常,则不会设置变量responsedata,因此当它尝试返回变量时会出现错误。