首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >元组:“AttributeError”对象没有特性“”status_code“”

元组:“AttributeError”对象没有特性“”status_code“”
EN

Stack Overflow用户
提问于 2019-12-25 12:09:28
回答 2查看 2.3K关注 0票数 0

我是python的初学者。我不能理解问题出在哪里?

代码语言:javascript
复制
the runtime process for the instance running on port 43421 has unexpectedly quit

ERROR    2019-12-24 17:29:10,258 base.py:209] Internal Server Error: /input/
Traceback (most recent call last):
  File "/var/www/html/sym_math/google_appengine/lib/django-1.3/django/core/handlers/base.py", line 178, in get_response
    response = middleware_method(request, response)
  File "/var/www/html/sym_math/google_appengine/lib/django-1.3/django/middleware/common.py", line 94, in process_response
    if response.status_code == 404:
AttributeError: 'tuple' object has no attribute 'status_code'
EN

回答 2

Stack Overflow用户

发布于 2019-12-25 14:10:06

无论middleware_method返回什么,都是一个tuple,所以以('a', 1, [])或其他形式返回。

该错误告诉您不能按名称访问元组的成员,因为它们没有名称。

也许你创建了一个这样的元组:

代码语言:javascript
复制
status_code = 404
name = 'Not found'
response = (name, status_code)

一旦声明了元组,其中的名称就会丢失。你有几个选项可以把东西拿出来。

直接访问

您可以按索引获取对象,就像使用列表一样:

代码语言:javascript
复制
assert response[1] == 404

如果您不知道元组是什么样子,只需打印它,并计算索引。

命名元组

如果您决定使用名称,则可以创建一个namedtuple,前提是每次元组都采用相同的格式。

代码语言:javascript
复制
from collections import namedtuple

Response = namedtuple('Response', ('name', 'status_code')
response = Response('Not found', 404)

assert response.status_code == 404

或者,您的代码中可能存在错误,您无意中返回了一个元组,但其中一部分是requests.Response对象。在这种情况下,您可以像在“直接访问”中那样提取对象,然后像以前一样使用它。

代码语言:javascript
复制
response[2].status_code
票数 0
EN

Stack Overflow用户

发布于 2019-12-25 14:12:22

我将用一个简单的例子来解释这个错误是如何产生的。

代码语言:javascript
复制
def example_error():
    a1 = "I am here"
    b1 = "you are there"
    c1 = "This is error"
    return a1, b1, c1

def call_function():
    strings = example_error()
    s1 = strings.a1
    s2 = strings.b1
    s3 = strings.c1
    print(s1, s2, s3)

call_function()

这将返回错误

代码语言:javascript
复制
AttributeError: 'tuple' object has no attribute 'a1'

因为我在example_error函数中返回了三个变量a1,b1,c1,并试图通过使用单变量字符串来获取它们。

我可以通过使用以下修改后的call_function来摆脱这个问题

代码语言:javascript
复制
def call_function():
    strings = example_error()
    s1 = strings[0]
    s2 = strings[1]
    s3 = strings[2]
    print(s1, s2, s3)
call_function()

因为您没有展示您的代码,所以我假设您在第一个案例中已经做了类似于这里的事情。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59475157

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档