大多数pythonic方式处理对话框?

时间:2011-12-19 14:37:14

标签: python exception wxpython

我在我的wxpython应用程序中创建了一个弹出密码框的函数。 dialogs.py中的代码如下所示:

def password_dialog(self, password):
    # Only ask for password if it actually exist
    if password == 'False':
        return True

    question = 'Put in password:'
    dialog = wx.PasswordEntryDialog(self, question, 'Password...')
    if dialog.ShowModal() == wx.ID_OK:
        if dialog.GetValue() == password:
            dialog.Destroy()
            return True
        else:
            dialog.Destroy()
            __wrong_pass()
            raise WrongPassword
    else:
        dialog.Destroy()
        raise CancelDialog

例外情况在同一个文件中:

class WrongPassword(Exception):
    pass

class CancelDialog(Exception):
    pass   

在我的主程序中,我有一些看起来像这样的方法:

def on_sort_songs(self, event): 
    """Renumbering the database and sort in artist and title order"""
    # Check for password first
    try:
        dialogs.password_dialog(self, opts.generic['password'])
    except dialogs.CancelDialog:
        return
    except dialogs.WrongPassword:
        return

    # Sort database and repopulate GUI
    self.jbox.sort_songs()
    self.populate_songlist()

工作正常。但它似乎不是处理密码对话框的一种非常好的和pythonic方式。或者是吗?

1 个答案:

答案 0 :(得分:1)

我不认为你的对话功能应该在这种情况下引发异常。根据验证是否通过,只需返回True或False。那么你需要做的就是:

validated = dialogs.password_dialog(self, opts.generic['password'])
if validated:
    print "Yay"
else:
    print "Boo"

仅在您要区分的其他随机故障情况下才需要例外,例如“身份验证服务器已关闭”

我认为在这种情况下返回True或False的另一个原因是因为您可以使用可以换出的模块化身份验证方法。例如django如何使用返回布尔值的单个is_authenticated()方法。最终用途只需要担心其是否经过身份验证。不是它特别引发的各种异常,例如关闭对话框。有些情况甚至可能不使用对话框......可能是命令行,也可能是Web界面等。

相关问题