请教python编码风格和异常处理问题
天蓬老师
天蓬老师 2017-04-18 10:27:17
0
2
460

请教各位个问题,编写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 None

def 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
    
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回覆(2)
洪涛

既然是web應用,你應該把這些驗證抽像出來,自己寫驗證模組或用別人的驗證模組

巴扎黑

為什麼不樸素的回傳一個True or False呢,異常一般是指程式出現了錯誤,但註冊資訊不合法並不帶錶程式出了錯,所以用條件判斷回傳真假值就可以了。
另外一般來說表單的合法判斷在前端處理比較好。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!