2012-10-10 51 views
0

我在Ubuntu 12.04上使用Python 2.7的Django 1.4。Django沒有調用異常函數

我有一個從窗體帖子獲取信息的視圖。它所做的第一件事就是嘗試根據表單中提供的信息來查找客戶信息。

雖然測試我在僞造信息,它似乎是確定的。我期待它拋出一個DoesNotExist異常,然後我打電話給原始視圖再次向用戶顯示錶單。我不能那樣做嗎?

這裏有兩種觀點:

def input_new_client(request): 
    """ 
    .. function:: input_new_client() 

     Add the client based on the addClientInfo form 

     :param request: Django Request object 
    """ 
    ## Create a logging object 
    path = os.path.join(os.path.dirname(__file__), 'logs/') 
    filename = '{0}inputNewClient.log'.format(path) 
    logfile = open(filename, 'w') 
    now = datetime.datetime.now() 
    logfile.write('\n --------------------- {0}\n'.format(now)) 

    if (request.method == "POST"): 
     tkz_ys_api_id = request.POST.get("tkz_ys_api_id") 
     tkz_ys_trans_key = request.POST.get("tkz_ys_trans_key") 

     ## Validate the YS authentication information 
     try: 
      clientInfo = ClientInfo.objects.get(tkz_api_id = tkz_ys_api_id, tkz_trans_key = tkz_ys_trans_key) 
     except ClientInfo.DoesNotExist or ClientInfo.MultipleObjectsReturned: 
      logfile.write('{0}\n\n'.format(tkz_ys_api_id)) 
      logfile.write('{0}\n\n'.format(tkz_ys_trans_key)) 
      logfile.write('{0}\n\n'.format(traceback.format_exc())) 
      logfile.close() 
      state = "Invalid YS Authentication! Please try again." 
      add_new_client(request, state) 
     else: 
      if (clientInfo.name != "Your Solutions"): 
       state = "Invalid YS Authentication! Please try again." 
       add_new_client(request, state) 

     ## Generate a Tokeniz API ID and Trans Key for the new client 
     (tkz_api_id, tkz_trans_key) = generate_credentials() 

     ## Create a new client 
     new_client = ClientInfo(name = request.POST.get("tkz_client_name"), 
           tkz_api_id = tkz_api_id, 
           tkz_trans_key = tkz_trans_key, 
           default_gateway_id = request.POST.get("tkz_gateway") 
           ) 
     new_client.save() 

     ## Validate the YS authentication information 
     try: 
      clientInfo = ClientInfo.objects.get(tkz_api_id = tkz_api_id, tkz_trans_key = tkz_trans_key) 
      foriegn_key = clientInfo.id 
     except ClientInfo.DoesNotExist or ClientInfo.MultipleObjectsReturned: 
      output = "Invalid YS Authentication! Please try again." 
      logfile.write('\n{0}\n'.format(output)) 
      logfile.write('{0}\n\n'.format(traceback.format_exc())) 
      logfile.close() 

     ## Setup the new clients gateway information 
     new_gateway_info = GatewayInfo(client = foriegn_key, 
             api_id = request.POST.get("tkz_gateway_api_id"), 
             trans_key = request.POST.get("tkz_gateway_trans_key"), 
             gateway_id = request.POST.get("tkz_gateway"), 
            ) 
     new_gateway_info.save() 

     data = {} 
     data.update(csrf(request)) 
     data.update({ 'tkz_api_id' : tkz_api_id }) 
     data.update({ 'tkz_trans_key' : tkz_trans_key }) 
     data.update({ 'client_name' : request.POST.get("tkz_client_name")}) 

    return render_to_response("updatedClientCredentials.html", data) 

和原來的觀點,即呈現形式:

def add_new_client(request, state = None): 
    """ 
    .. function:: add_new_client() 

     Provide a form for entering new client information 

     :param request: Django Request object 
     :param state: A message representing the state of the addition of a client 
    """ 
    ## Create a logging object 
    path = os.path.join(os.path.dirname(__file__), 'logs/') 
    filename = '{0}addNewClient.log'.format(path) 
    logfile = open(filename, 'a') 
    now = datetime.datetime.now() 
    logfile.write('\n --------------------- {0}\n'.format(now)) 

    if (state is None): 
     state = "Enter information for adding a new client to Tokeniz." 

    try: 
     form = AddClientInfo() 
    except: 
     output = "Handle Error: Cannot create a valid form" 
     logfile.write('{0}\n'.format(output)) 
     logfile.write('{0}\n\n'.format(traceback.format_exc())) 
     logfile.close() 
     return HttpResponse(output) 

    try: 
     data = {} 
     data.update(csrf(request)) 
     data.update({ 'form' : form }) 
     data.update({ 'state' : state }) 
    except: 
     output = "Handle Error: Cannot generate CSRF token" 
     logfile.write('{0}\n'.format(output)) 
     logfile.write('{0}\n\n'.format(traceback.format_exc())) 
     logfile.close() 
     return HttpResponse(output) 

    logfile.close() 
    return render_to_response("addNewClientInfo.html", data) 

我預計,在input_new_clientclientInfo = ClientInfo.objects.get(tkz_api_id = tkz_ys_api_id, tkz_trans_key = tkz_ys_trans_key)請求將拋出一個DoesNotExist異常(如我把在假數據,以確保這種情況)。

所以,我只打算從異常中調用add_new_client視圖。

問題是,input_new_client一路下降到new_client.save()行,由於顯而易見的原因失敗。

有什麼想法?

EDIT1:

我已經修改了input_new_client觀點有以下異常聲明:

if (request.method == "POST"): 
    tkz_ys_api_id = request.POST.get("tkz_ys_api_id") 
    tkz_ys_trans_key = request.POST.get("tkz_ys_trans_key") 
    tkz_gateway_id = int(request.POST.get("tkz_gateway")) 

    ## Validate the YS authentication information 
    try: 
     clientInfo = ClientInfo.objects.get(tkz_api_id = tkz_ys_api_id, tkz_trans_key = tkz_ys_trans_key) 
    except (ClientInfo.DoesNotExist, ClientInfo.MultipleObjectsReturned): 
     logfile.write('tkz_ys_api_id = {0}\n\n'.format(tkz_ys_api_id)) 
     logfile.write('tkz_ys_trans_key = {0}\n\n'.format(tkz_ys_trans_key)) 
     logfile.write('tkz_gateway_id = {0}\n\n'.format(tkz_gateway_id)) 
     logfile.write('{0}\n\n'.format(traceback.format_exc())) 
     logfile.close() 
     state = "Invalid YS Authentication! Please try again." 
     add_new_client(request, state) 
    else: 
     if (clientInfo.name != "Your Solutions"): 
      state = "Invalid YS Authentication! Please try again." 
      add_new_client(request, state) 

我知道它進入例外 - 我可以用日誌信息,並回溯驗證。但是,它不會繼續到add_new_client。它會沿着前方跳過,並嘗試在數據不正確的ClientInfo模型中插入新條目。

爲什麼它跳過add_new_client的電話?

回答

4

這條線:

except ClientInfo.DoesNotExist or ClientInfo.MultipleObjectsReturned: 

沒有做什麼,你認爲它。首先對or進行評估,所以實際上(我認爲)這只是試圖捕獲類型爲True的例外,當然這是從未提出的。你真正想要的是:

except (ClientInfo.DoesNotExist, ClientInfo.MultipleObjectsReturned): 

(注意圓括號)。

另外請注意,在你的第二個片段裸except子句是一個非常糟糕的主意:它會趕上所有異常,因此如果出現錯誤,你沒有想到,你永遠不會知道。確保你只抓住你的除外子句知道如何處理的處理錯誤。

編輯

啊,我看你現在在做什麼 - 你試圖從異常中返回給用戶的響應。好吧,除此之外沒有什麼問題,除非你實際上沒有把它發回給用戶:你只需撥打add_new_client(),並且不要對發回的HTTP響應做任何事情。您需要從此處將其返回給用戶:

except (ClientInfo.DoesNotExist, ClientInfo.MultipleObjectsReturned): 
    ... logging stuff ... 
    state = "Invalid YS Authentication! Please try again." 
    return add_new_client(request, state) 
+0

感謝您的幫助。我會試試這個。關於除......之外的裸機,這就是爲什麼我記錄了回溯。我想知道哪些地方出了問題。 – Rico

+0

我認爲這是解決方案,但事實並非如此。我仍然無法讓我的函數在異常中調用。我會編輯我的原始帖子,以顯示我所做的。 – Rico

+0

是的,那是我的問題。謝謝 - 我應該看到了。 – Rico