DWQA QuestionsCategory: ProgramConsult Python coding style and exception handling
Flowers and names asked 1 month ago

Ask each question, write the web application registration module, such as the following code, the server needs to detect the parameters passed by the user. Which of the following is better? Is the exception handling method correct? Or do you have a better way

def check_args(account, passwd, birthday, name):
    #The first way to write
    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

    #The second way of writing
    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"]

    #Exceptions are placed in this layer, but how to check the success of the main function call user? Register
    #Whether the current exception continues to be thrown outwards or through the return value
    try:
        check_args(account, passwd, birthday, name)
        insertUserInfo(account, passwd, birthday, name)
    except ValueError:
        pass
    except MySQLError:
        pass
    except Exception:
        pass
2 Answers
sunhuachuang answered 1 month ago

Since it’s a web application, you should abstract these verifications, write your own verification module or use someone else’s verification module

Recall first answered 1 month ago

Why don’t you simply return a true or false value? An exception generally refers to an error in a program, but the registration information is illegal and the program with a table has an error, so it’s OK to use conditional judgment to return a true or false value.
In addition, generally speaking, the legal judgment of forms is better handled in the front end.

sunhuachuang replied 1 month ago

I think the back end must judge. I can’t believe any data from the front end~