我有这个函数。我想执行以下两行:
list = utils.get_connection().get_list_by_id(MAILCHIMP_LIST_ID)
list.subscribe(email_address, {'EMAIL': email_address, 'FNAME': fname, 'LNAME': lname})
如果它们失败了,我想将它们重定向到'/mailing_list_failure'
以下是完整的功能:
def add_email_to_mailing_list(request):
if request.POST['email'] and len(request.POST['email']) > 4:
email_address = request.POST['email']
fname = request.POST['fname']
lname = request.POST['lname']
#If two next lines are failure return to '/mailing_list_failure/'
list = utils.get_connection().get_list_by_id(MAILCHIMP_LIST_ID)
list.subscribe(email_address, {'EMAIL': email_address, 'FNAME': fname, 'LNAME': lname})
return HttpResponseRedirect('/mailing_list_success/')
else:
return HttpResponseRedirect('/mailing_list_failure/')
听起来您想要使用try
/except
块。我不是python专家,所以让我知道这是否可以改进,我会更新它。
def add_email_to_mailing_list(request):
if request.POST['email'] and len(request.POST['email']) > 4:
email_address = request.POST['email']
fname = request.POST['fname']
lname = request.POST['lname']
#If two next lines are failure return to '/mailing_list_failure/'
try:
list = utils.get_connection().get_list_by_id(MAILCHIMP_LIST_ID)
list.subscribe(email_address, {'EMAIL': email_address, 'FNAME': fname, 'LNAME': lname})
return HttpResponseRedirect('/mailing_list_success/')
except:
return HttpResponseRedirect('/mailing_list_failure/')
查看此链接:
http://docs.python.org/2/tutorial/errors.html