Django:异常和返回,处理多种潜在情况的正确方法是什么? [英] Django: exceptions and returns, what is the correct way to handle multiple potential situations?
问题描述
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屋!