请教各位个问题,编写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
PHP中文网2017-04-18 10:29:17
Since it is a web application, you should abstract these verifications and write your own verification module or use someone else’s verification module
巴扎黑2017-04-18 10:29:17
Why not simply return a True or False? An exception generally means that there is an error in the program, but the registration information is illegal and there is an error in the table program, so it is enough to use conditional judgment to return a true or false value.
In addition, generally speaking, it is better to handle the legal judgment of the form on the front end.