检查多个字段:如果try / except条件成功,则继续IF循环

时间:2016-02-25 20:05:32

标签: python

仍然是一名编程学习者,我在理解中发现了一个漏洞,所以我很感激任何反馈。我有一个基于Django的HTML表单,允许您为车辆路径问题定义其他驱动程序。至关重要的是,在存储之前捕获并拒绝每个输入字段格式中的任何错误。我的方法是一系列ifelif子句,用于预期错误的原型列表,其中一部分工作得很好。但是,我测试了是否可以使用try / except块将字段解析为日期时间对象,并且我的if / elif链终止成功try(因为elif已满足)。问题是,我仍然需要在成功时运行剩余的测试,使用continue对我能找到的任何缩进都不起作用。

我无法想到while循环或for循环来实现相同的效果。我尝试将它放在一个函数中,如下所示,但那是抓着稻草。

我有两个问题1)我对如何检查数据输入非常不敏感;我喜欢这个方向吗? 2)我是否必须将其分解为多个单独的测试以返回driverinfomessage的错误?

准系统在下面。在starttime测试成功后,循环结束并且永远不会检查endtime(编辑:虽然我知道continue语句会抛出错误;它们会出现预期的行为)

def is_timestamp(stamp_string):
    is_time = False
    try:
        stamp_string.datetime.datetime.strptime(stamp_string, "%H:%M")
        is_time = True
    except:
        is_time = False
    return is_time

if drivername == '':
    driverinfomessage = "No driver name"

elif starttime != '':
    test = is_timestamp(starttime)
    if test:
        continue
    else:
        driverinfomessage = "Invalid start time"

elif endtime != '':
    test = is_timestamp(endtime)
    if test:
        continue
    else:
        driverinfomessage = "invalid end time"

如果需要,我可以发布更多功能。提前致谢。

2 个答案:

答案 0 :(得分:1)

从主代码中删除异常,在外面处理它们。

在Python中,你经常编写主要的快乐场景,好像一切都好 并且在出现问题时抛出异常。

check_and_process此类"快乐代码的例子"。

调用函数(此处为test_it)正在使用try - except对(可以使用 甚至更多except部分),每个都期待已知的例外。

这样你的代码保持干净,仍然可以处理异常 情况。

class FieldException(Exception):
    pass


def get_timestamp(fieldname, stamp_string):
    try:
        return stamp_string.datetime.date.strptime(stamp_string, "%H:%M")
    except:
        msg = "Field {fieldname} expects time in HH:MM format."
        raise FieldException(msg.format(fieldname=fieldname))


def check_and_process(driver_name, start_time_str, end_time_str):
    if not driver_name:
        raise FieldException("Driver name is required")
    start_time = get_timestamp("start time", start_time_str)
    end_time = get_timestamp("end time", end_time_str)

    print("processing {}, {} and {}".format(driver_name, start_time, end_time))


def test_it():
    try:
        check_and_process("Johny", "12:34", "23:55")
        # check_and_process("Johny", "12:34", "25:62")
        # check_and_process("", "12:34", "25:62")
    except FieldException as e:
        print(e.msg)

请注意,捕获和处理所有预期的异常非常重要 遵循以下规则:

  • 从不使用pass作为except块中的唯一内容,因为它隐藏了您将发现的问题(以及稍后解决)
  • 了解,可以抛出预期的异常类型,并根据需要捕获这些异常并进行处理。
  • 让其他(意外)异常来提升和破坏您的程序。这将是纠正它的最快方法。

答案 1 :(得分:0)

您可能会瞄准以下内容:

if drivername == '':
    driverinfomessage = "No driver name"
elif not is_timestamp(starttime):
    driverinfomessage = "Invalid start time"
elif not is_timestamp(endtime):
    driverinfomessage = "invalid end time"