2016-12-06 146 views
0

我希望我的代碼顯示取決於遇到的錯誤類型的自定義錯誤消息。根據錯誤顯示自定義的異常消息

from .forms import NameForm, IdForm 
from django.shortcuts import render 
from django.http import HttpResponse, HttpResponseRedirect 
from django.contrib import messages 
from client_storage import insert 
import mysql.connector.errors 
from mysql.connector.errors import Error 
import MySQLdb 


def sign_in(request): 
     #we need to handle all the data that was just typed, we'll add a condition for that 
     if request.method == "POST": 
      #here will construct the form with the POST data 
      form = NameForm(request.POST) 
      #the next part is to check that the information submitted is valid 
      if form.is_valid(): 
       post = form.save() 
       post.save() 
       return HttpResponse(post.question_text) 
      else: 
       return HttpResponse("Form is invalid") 
     else: 
      form = NameForm() 
     return render(request, 'checkin/base.html', {'form': form}) 

    #this view will be the sign-up view, where new clients will be given new ID numbers for training 

def sign_up(request): 

    if request.method == "POST": 
     form = IdForm(request.POST) 
     if form.is_valid(): 
      post = form.save() 
      post.save() 
      ID = post.id_text 
      #we'll call an external function that checks membership of the users input in the database 
      # query is the first element of the tuple that is returned from insert() 
      query = insert(post.id_text) 
      if query == 1062: 
       messages.add_message(request, messages.INFO, 'Already taken ') 
       return HttpResponseRedirect('sign_up') 
      if query == 1054: 
       messages.add_message(request, messages.INFO, 'Invalid input') 
       return HttpResponseRedirect('sign_up') 
      else: 
       messages.add_message(request, messages.INFO, 'Thank you for signing up!') 
       return HttpResponseRedirect('sign_up') 

      # if the user enters a number that is already in use raise an 'duplicate' error 
      # Capture the exception here 
     else: 
      return HttpResponse('That text is invalid') 
    else: 
     form = IdForm() 
    return render(request, 'checkin/base.html', {'form': form}) 

For the `except` block I'm trying to figure out how to display either "Already taken" or "Invalid input" depending on the error code. However only "Already taken" ever appears. I feel like the problem is that the exception is being thrown before it even gets to the `if` clauses? 

我使用了INSERT過程另一個文件:

import MySQLdb 
import mysql.connector 
from mysql.connector import errorcode 
from django.contrib import messages 

#Use a function to insert new information into the database 

def insert(info): 
    #open a connection 
    db = MySQLdb.connect('localhost','root','password', 'CLIENTS') 
    #prepare a cursor 
    cursor = db.cursor() 
    #prepare SQL query 
    sql = "INSERT INTO clients(ID) VALUES (%s)" % info 

    try: 
     #execute the command 
     cursor.execute(sql) 
     #commit changes to the database 
     print 'success' 
     db.commit() 
    except MySQLdb.Error as e: 
     #return the first element in the tuple that contains the error message, which will be the errorcode 
     if e[0] == 1062: 
      return e[0] 
     if e[0] == 1054: 
      return e[0] 

    #disconnect from server 
    db.close() 

編輯這個問題似乎已經是我用的,而不是mysql.connector.errorMySQLdb.Error .The mysql網站似乎只使用前者。關於後者似乎並沒有太多的官方文件,但幸好我發現this site.我更改了代碼,因此sign_in視圖會從外部insert功能接收到returned信息,然後採取相應措施。

+2

在[此頁的文檔的(https://dev.mysql.com /doc/connector-python/en/connector-python-api-errors-error.html),下面的第三個例子展示瞭如何對異常的錯誤號使用條件。在你的嘗試中,你永遠不會捕獲錯誤(或者它永遠不會被分配給任何東西),所以你無法與任何東西進行比較。 '''bool(Error(errno = 1062))'''可能計算爲''''True''',所以它總是*工作*。 – wwii

+2

https://docs.python.org/3/tutorial/errors.html#handling-exceptions, – wwii

+1

@wwii的評論是正確的。你可以編輯你的'try .. except'模塊並捕獲正確的異常,然後返回你想要的字符串/類型輸出。 –

回答

1

就像@wwii在評論中所說的那樣,您需要編輯try ... except區塊才能發現異常。見documentations的這一頁。

此外,在您的實際代碼中Error(errno=1062)總是返回一個非零字符串,用於驗證您的if語句。這就是爲什麼你總是得到Already Taken消息。

爲了處理這個問題,你應該修改你的代碼是這樣的例子:

# What you need to import 
import mysql.connector 
from mysql.connector import errorcode 

try: 
    insert(post.id_text) 
    messages.add_message(request, messages.INFO, 'Thank you for signing up ') 
    return HttpResponseRedirect('sign_in') 

# Catch the error exception 
except mysql.connector.Error as err: 
    # Error code 1062: https://dev.mysql.com/doc/refman/5.6/en/error-messages-server.html#error_er_dup_entry 
    if err.errno == errorcode.ER_DUP_ENTRY: 
     messages.add_message(request, messages.INFO, "Already taken") 
     return HttpResponseRedirect('sign_up') 

    # Error code 1054: https://dev.mysql.com/doc/refman/5.6/en/error-messages-server.html#error_er_bad_field_error 
    if err.errno == errorcode.ER_BAD_FIELD_ERROR: 
     messages.add_message(request, messages.INFO, "Invalid input") 
     return HttpResponseRedirect('sign_up') 

編輯:

你編輯答案既Python2Python3內正確的。

否則,如果你使用Python2你可以做這樣的事情。

try: 
    #execute the command 
    cursor.execute(sql) 
    #commit changes to the database 
    print 'success' 
    db.commit() 
except MySQLdb.Error, e: 
    if e.args[0] == 1062 or e.args[0] == 1054: 
     # e.args[0] is the error code in int format 
     # e.args[1] is the complete error message in str format 
     return e.args[1] 
    else: 
     # I didn't test all the cases, but this message 
     # can save you more time during the debug later 
     # if your code catch another error code rather than 1062 or 1054 
     return "Something odd happened" 

你也可以做這樣的事情(這個例子,如果有效期爲兩個Python2Python3):

try: 
    #execute the command 
    cursor.execute(sql) 
    #commit changes to the database 
    print 'success' 
    db.commit() 
except MySQLdb.Error as e: 
    if e[0] == 1062 or e[0] == 1054: 
     # e[0] is the error code in int format 
     # e[1] is the complete error message in str format 
     return e[1] 
    else: 
     # Good for the debug 
     return "Something odd happened" 
+0

我似乎仍然有輸出自定義文本的問題,我得到正確的錯誤代碼,但它不在我喜歡的網站內。它只是顯示Django錯誤頁面 – Amon

+1

你的意思是在第二個文件中,你使用'除了mysql.connector.Error作爲e:... return e'? –

+0

不是第一個,我應該編輯第二個嗎? – Amon