【问题标题】:AttributeError: 'tuple' object has no attribute 'status_code'AttributeError:“元组”对象没有属性“status_code”
【发布时间】:2019-12-25 04:09:27
【问题描述】:

我是 python 的初学者。我无法理解问题所在?

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'

【问题讨论】:

  • 请出示您的代码以供查看。

标签: python django python-2.7


【解决方案1】:

无论middleware_method 返回的是tuple,所以形式为('a', 1, []) 或其他形式。

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

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

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

一旦你声明了元组,进入它的名字就会丢失。您有多种选择可以解决问题。

直接访问

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

assert response[1] == 404

如果你不知道元组长什么样,就打印出来,然后计算索引。

命名元组

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

from collections import namedtuple

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

assert response.status_code == 404

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

必须查看代码才能获得更多帮助,但可能类似于:

response[2].status_code

【讨论】:

    【解决方案2】:

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

    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()
    

    这将返回错误

    AttributeError: 'tuple' object has no attribute 'a1'
    

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

    我可以通过使用以下修改后的 call_function 来摆脱它

    def call_function():
        strings = example_error()
        s1 = strings[0]
        s2 = strings[1]
        s3 = strings[2]
        print(s1, s2, s3)
    call_function()
    

    由于您没有显示您的代码,我假设您在第一种情况下已经做了类似的事情。

    【讨论】:

      猜你喜欢
      • 2018-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-21
      • 1970-01-01
      相关资源
      最近更新 更多