Django:异常和返回,处理多种潜在情况的正确方法是什么? [英] Django: exceptions and returns, what is the correct way to handle multiple potential situations?

查看:811
本文介绍了Django:异常和返回,处理多种潜在情况的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在管理器中有一个功能,通过一个键激活用户帐户。当提供密钥时,需要执行几个检查:密钥是否存在?密钥已过期?然后如果没有,则管理员激活该帐户。

  def activate(key):
try:
profile = self.get(key = key)
除了self.model.DoesNotExist:
返回无

如果没有profile.key_expired():
##激活用户
返回用户

返回无

问题是当然,对于密钥不存在和给定的密钥已过期,这将返回False。对于两者都是假的,并不能说明我的上游观点,目前的问题是什么。我不会做404错误,因为这是不透明的用户,并没有帮助的事情。



什么是最好/正确的django / pythonic处理方式给上游更有用的信息?自定义错误的前进方向?我应该返回上游分析值(似乎是一个难看的解决方案)吗?有另外一种方法吗?

解决方案

我会在激活中引发一个异常,并将其捕获到外面。

  def activate(key):
try:
profile = self.get_query_set()。get(key = key)
除self.model.DoesNotExist:
raise

如果profile.key_expired():
raise YourCustomException()
#或简单地返回False

##激活用户
返回用户

另外我建议使用 self.get_query_set()。get(key = key)而不是 self.get(key = key)


I have a function in a Manager which activates a user account via a key. When a key is provided, several checks need to be performed: does the key exist? has the key expired? and then if not, the manager activates the account.

def activate(key):
    try:
        profile = self.get(key=key)
    except self.model.DoesNotExist:
        return None

    if not profile.key_expired():
        ## Activate user
        return user

    return None

The issue is of course, that this returns False for both 'the key doesn't exist', and 'the key given is expired'. Giving False for both doesn't tell my upstream view what was the issue at hand. I don't do a 404 error as that is opaque to the user and doesn't help matters.

What is the best/correct django/pythonic way of handling this to give more useful information upstream? Are custom errors the way forward? Should I return values for analysis upstream (seems an ugly solution)? Is there another way?

解决方案

I'd raise an exception inside activate and catch it outside.

def activate(key):
    try:
        profile = self.get_query_set().get(key=key)
    except self.model.DoesNotExist:
        raise

    if profile.key_expired():
       raise YourCustomException()
       # or simply return False

    ## Activate user
    return user

Also I'd suggest to use self.get_query_set().get(key=key) instead of self.get(key=key)

这篇关于Django:异常和返回,处理多种潜在情况的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆