我正在開發一個模擬社交媒體網站的應用程式。我目前有一個表格,用戶可以在其中輸入朋友的電子郵件,以便邀請他們加入該應用程式。
假設我們有一個用戶在電子郵件表單中輸入三個電子郵件地址,然后將其保存為字串串列:
emails_to_invite = ["[email protected]", "[email protected]", "[email protected]"]
在資料庫中,我們已經有一個已被邀請訪問該站點的用戶串列:
current_users = ["[email protected]", "[email protected]", "[email protected]", "[email protected]"]
所以我們有兩個用戶已經被邀請:[email protected] 和 [email protected]。
我正在嘗試撰寫一些回傳 ValidationError 的代碼,并可以在訊息中列出兩個匹配的用戶。這是我到目前為止所擁有的:
for email in emails_to_invite:
if email in current_users:
raise forms.ValidationError(f"{email} is already in the database.")
這是我希望顯示此錯誤的方式:
[email protected] is already in the database.
[email protected] is already in the database.
但是現在,錯誤僅顯示第一封電子郵件:
[email protected] is already in the database.
我也需要 [email protected] 來顯示。看起來 for 回圈一旦識別出一個匹配項就會停止,但我需要它繼續運行直到它識別出所有匹配項。誰能提供一些建議?
uj5u.com熱心網友回復:
如果您不希望Exception代碼塊中的 an 停止執行(并隱藏更多例外,正如您所發現的那樣),請將易受影響的代碼放入 aatry/except塊中以按照您認為合適的方式處理錯誤。
要稍后引發例外,請考慮使用類似的東西:
raised_exceptions = []
<loop that might raise exceptions>
try:
<loop that might raise exceptions>
except Exception as e:
raised_exceptions.append(e)
<do something with the exceptions you saved>
話雖如此,IMO 你不應該以這種方式使用例外 - 考慮回傳一系列串列,每個可能的結果一個,而不是:email sent和already invited(和/或joined user)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/536918.html
下一篇:HTML地址驗證模式
