請教python編碼風格和異常處理問題
問題描述
請教各位個問題,編寫web應用注冊模塊,如下面這段代碼,服務端需要檢測用戶的傳遞的參數。下面幾種寫法哪個更好,異常處理方式是否正確,或者各位是否有更好的方式呢
def check_args(account, passwd, birthday, name): # 第一種寫法 if account == ’’ or not isinstance(account, str):raise ValueError if passwd == ’’ or not isinstance(passwd, str):raise ValueError if birthday == ’’ or not isinstance(birthday, str):raise ValueError if name == ’’ or not isinstance(name, str):raise ValueError # 第二種寫法 if (account == ’’ or not isinstance(account, str)) or (passwd == ’’ or not isinstance(passwd, str)) or (birthday == ’’ or not isinstance(birthday, str)) or (name == ’’ or not isinstance(name, str)):raise ValueError return Nonedef user_register(form): account = form['account'] passwd = form['passwd'] birthday = form['birthday'] name = form['name'] # 異常放在這一層,但在main函數調用 user_register 如何檢測是否成功呢 # 是當前異常繼續向外拋,還是通過返回值 try:check_args(account, passwd, birthday, name)insertUserInfo(account, passwd, birthday, name) except ValueError:pass except MySQLError:pass except Exception:pass
問題解答
回答1:既然是web應用,你應該把這些驗證抽象出來,自己寫驗證模塊或者用別人的驗證模塊
回答2:為什么不樸素的返回一個True or False呢,異常一般是指程序出現了錯誤,但注冊信息不合法并不帶表程序出了錯,所以用條件判斷返回真假值就可以了。另外一般來說表單的合法判斷在前端處理比較好。
相關文章:
1. [python2]local variable referenced before assignment問題2. 求救一下,用新版的phpstudy,數據庫過段時間會消失是什么情況?3. mysql - 如何在有自增id的情況下,讓其他某些字段能不重復插入4. python小白,關于函數問題5. django - Python error: [Errno 99] Cannot assign requested address6. angular.js - 百度支持_escaped_fragment_嗎?7. java - 線上應用,如果數據庫操作失敗的話應該如何處理?8. node.js - win 下 npm install 遇到了如下錯誤 會導致 無法 run dev么?9. python小白 關于類里面的方法獲取變量失敗的問題10. Python2中code.co_kwonlyargcount的等效寫法
