Try/except database query in django
I am checking a user's submitted email address against two lists from the database -- a list of authorized domains and a list of authorized email addresses. Currently, if neither are found, it is rainsing a DoesNotExist
exception. How would I handle this if neither are found?
Here is the code I currently have in views.py --
def register(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
try:
email_list = EmailList.objects.get(domain=(cd['email'].split('@')[1]))
except:
email_list = EmailList.objects.get(email=cd['email'])
# I also need another except if neither works for the validator.
network= Network.objects.get(network=email_list.network)
User.objects.create(name=cd['name'], email=cd['email'], network=network)
return HttpResponseRedirect ('/user/view/')
el开发者_如何学Cse:
form = UserForm()
return render_to_response('register.html',{'form':form}, context_instance = RequestContext(request))
Nested try
/except
blocks. And don't use a bare except
; catch only the exceptions you can handle.
You can nest try
/except
:
try:
email_list = EmailList.objects.get(domain=(cd['email'].split('@')[1]))
except:
try:
email_list = EmailList.objects.get(email=cd['email'])
except:
...do something else
If you are just using these try/except to do a simple test, it's worthwhile to wrap the try/except:
def get_or_none(model, **kwargs):
try:
return model.objects.get(**kwargs)
except model.DoesNotExist:
return None
Which gives you slightly more readable code:
if get_or_none(EmailList, domain='domain.com'):
...do something
elif get_or_none(EmailList, domain='domain.com'):
...do something
else:
...do something
As Ignacio mentioned in his answer you should always be explicit and catch only the exceptions you intend.
精彩评论