python - Django model.DoesNotExist 异常以某种方式替换为 AttributeError

标签 python django django-models

我在 Django 1.5 网站上遇到了一个奇怪的异常:

 "TypeError: 'exceptions.AttributeError' object is not callable"

从本质上讲,它看起来像 model.DoesNotExist 异常已被 AttributeError 替换。

该错误是间歇性的,但一旦它发生,它似乎就会“卡住”,直到我重新启动该过程,这让我认为这可能是模型类在特定请求过程中设置不正确的情况,然后坚持不懈。

回溯底部:

File "/opt/mysite/django/apps/profiles/models.py", line 353, in profile_from_cache
    profile = self.get(user=user_id)

  File "/opt/mysite/.virtualenvs/django/lib/python2.7/site-packages/django/db/models/manager.py", line 143, in get
    return self.get_query_set().get(*args, **kwargs)

  File "/opt/mysite/.virtualenvs/django/lib/python2.7/site-packages/django/db/models/query.py", line 404, in get
    self.model._meta.object_name)

TypeError: 'exceptions.AttributeError' object is not callable

来自 django/db/models/query.py 的代码行:

if not num:
    raise self.model.DoesNotExist(
        "%s matching query does not exist." %
        self.model._meta.object_name)

所以它看起来好像是在尝试将消息传递给模型上的 DoesNotExist 异常,但它不知何故被 AttributeError 代替了。

问题似乎只发生在 http 请求中 - 如果我从命令行执行相同的操作,我只会收到 DoesNotExist 异常(这是应该发生的事情)。

我找不到任何明显的原因会发生这种情况。有什么想法吗?

(PS这好像是同一个问题,我觉得用户的回答是错误的:https://groups.google.com/forum/#!topic/django-users/k9JMyXlUt3Q)

可能相关的代码

这里是模型管理器的概要:

class CacheManager(models.Manager):
    def profile_from_cache(self, user_id=None):
        profile = cache.get("profile_%s" % user_id)
        if profile is None:
            try:
                profile = self.get(user=user_id)
            except Profile.DoesNotExist:
                return None
            cache.set("profile_%s" % user_id, profile, settings.CACHE_TIMEOUT)
        return profile

    ...

class Profile(models.Model):
    ...
    caches = CacheManager()

这是似乎导致错误的代码行。在这种情况下,它在一些中间件中,但有几个不同的地方,都导致了同样的事情。

Profile.caches.profile_from_cache(user_id=request.user.pk)

最佳答案

是因为项目中其他地方的语法不正确,导致捕获了多个这样的异常:

try:
   do_something()
except AttributeError, Profile.DoesNotExist:
   pass

应该是这样的:

try:
   do_something()
except (AttributeError, Profile.DoesNotExist):
   pass

发生这种情况时,AttributeError 被分配给内存中的 Profile.DoesNotExist,所以当它稍后引发时,它是错误的异常。

感谢this post帮助。

关于python - Django model.DoesNotExist 异常以某种方式替换为 AttributeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27174788/

相关文章:

python - 根据下拉列表和日期选择器为某个唯一值在破折号图中创建图表

python - 在字典键中组合子字符串的方法

python - sqlite 中的 Django hstore 字段

用于外键的 Django Tastypie apply_filter

python - Discord py 向 channel 发送消息

python - 将 for 循环中的字符串连接成一行

python - 在 Django 中填充 URLFields 的合法值的确切模式是什么?

python - Django:如何对多个数据库执行数据库自省(introspection)?

python - Django 中两个不直接相关的模型的内连接

python - 为什么 auth.User 不检查必填字段?