0

我有这个功能。我想执行以下两行:

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/')
4

1 回答 1

0

听起来您想使用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

于 2013-07-25T13:01:05.243 回答