我希望我的代碼顯示取決於遇到的錯誤類型的自定義錯誤消息。根據錯誤顯示自定義的異常消息
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.error
MySQLdb.Error
.The mysql
網站似乎只使用前者。關於後者似乎並沒有太多的官方文件,但幸好我發現this site.我更改了代碼,因此sign_in
視圖會從外部insert
功能接收到returned
信息,然後採取相應措施。
在[此頁的文檔的(https://dev.mysql.com /doc/connector-python/en/connector-python-api-errors-error.html),下面的第三個例子展示瞭如何對異常的錯誤號使用條件。在你的嘗試中,你永遠不會捕獲錯誤(或者它永遠不會被分配給任何東西),所以你無法與任何東西進行比較。 '''bool(Error(errno = 1062))'''可能計算爲''''True''',所以它總是*工作*。 – wwii
https://docs.python.org/3/tutorial/errors.html#handling-exceptions, – wwii
@wwii的評論是正確的。你可以編輯你的'try .. except'模塊並捕獲正確的異常,然後返回你想要的字符串/類型輸出。 –