Python 属性错误:';功能';对象没有属性';答复';

Python 属性错误:';功能';对象没有属性';答复';,python,python-2.6,Python,Python 2.6,我在主脚本中使用了一个错误处理模块来请求API。我想返回“response”和“data”以在主脚本中使用。它一直工作到试图打印“响应”。为前后矛盾道歉,我显然还在学习。如果不先犯一些错误,我就不会学习。我欣赏建设性的批评 my_模块 import requests import json def errorHandler(url): try: response = requests.get(url, timeout=5) status = respon

我在主脚本中使用了一个错误处理模块来请求API。我想返回“response”和“data”以在主脚本中使用。它一直工作到试图打印“响应”。为前后矛盾道歉,我显然还在学习。如果不先犯一些错误,我就不会学习。我欣赏建设性的批评

my_模块

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
我的脚本

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'
回溯(最近一次呼叫最后一次):
文件“my_script.py”,第20行,在
打印errorHandler.response
AttributeError:“函数”对象没有属性“响应”

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

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']

但是,如果出现任何异常,您的函数将无法正常工作。如果出现异常,它不会设置变量
response
data
,因此当它尝试返回它们时,会出现错误。

您的意思是
打印错误处理程序()
?(您的函数只返回
response
).2返回,只返回第一个,尝试
返回response,data
并相应地使用该函数,它现在将返回一个元组。为什么设置
status
变量但从不使用它?也许你想要
返回状态,数据
?@Barmar它被使用。这是缩短代码的缩写版本。我将对其进行编辑,向您展示我需要返回多个对象的确切方式和原因。修复编辑代码中的缩进。第一个
后面的所有内容:
需要缩进。实际上,响应返回的
内容类型是application/problem+json
。对于数据,我仍然有一条错误消息要处理。我想我可以在一个try语句中包含我的数据方程,除了一个keyrerror…谢谢,这让我有了更多的思考。我不确定你为什么会得到那种内容类型,它不是API返回的内容。