Django视图中的无限循环

时间:2012-08-16 15:00:50

标签: python django

我正在python中编写time_slot的应用程序

请查看此代码

from datetime import datetime ,timedelta
appointments = [(datetime(2012, 5, 22, 10), datetime(2012, 5, 22, 10, 30)),

                    (datetime(2012, 5, 22, 12), datetime(2012, 5, 22, 13)),

                    (datetime(2012, 5, 22, 15, 30), datetime(2012, 5, 22, 17, 10))]

hours = (datetime(2012, 5, 22, 9), datetime(2012, 5, 24, 18))
duration = timedelta(minutes = 120)
def get_slots(hours, appointments,duration):

    slots = sorted([(hours[0], hours[0])] + appointments + [(hours[1], hours[1])])

    for start, end in ((slots[i][1], slots[i+1][0]) for i in range(len(slots)-1)):

        assert start <= end, "Cannot attend all appointments"

        while start + duration <= end:
            dt_obj = start
            date_str = dt_obj.strftime("%Y-%m-%d %H:%M:%S")


            today18 = start.replace(hour=17, minute=59, second=59, microsecond=0)

            if start <  today18:
               print "{:%d:%H:%M} - {:%d:%H:%M}".format(start, start + duration)

               start += duration
            else:
               start += timedelta(hours = 15)
if __name__ == "__main__":
    get_slots(hours, appointments,duration)

当我运行python time_slots.py

时,上面的代码对我来说很好

但是当我在djanog视图中使用上面的代码时,如

from datetime importdatetime ,timedelta 
    duration = timedelta(minutes = 60)
    appointments = [(datetime(2012, 5, 22, 10), datetime(2012, 5, 22, 10, 30)),

                (datetime(2012, 5, 22, 12), datetime(2012, 5, 22, 13)),

                (datetime(2012, 5, 22, 15, 30), datetime(2012, 5, 22, 17, 10))]


   # hours = (datetime.datetime(2012, 5, 24, 18), datetime.datetime(2012, 5, 22, 9))
    hours = (datetime(2012, 5, 22, 9), datetime(2012, 5, 24, 18))
    slots = sorted([(hours[0], hours[0])] + appointments + [(hours[1], hours[1])])
    for start, end in ((slots[i][1], slots[i+1][0]) for i in range(len(slots)-1)):

        assert start <= end, "Cannot attend all appointments"

        while start + duration <= end:

            today18 = start.replace(hour=17, minute=59, second=59, microsecond=0)

            if start <  today18:

               print "{:%H:%M} - {:%H:%M}".format(start, start + duration)

            else:
               start += timedelta(hours = 15)

当我调用此视图时,它在控制台中返回一个无限循环

请帮助我,我在这里做错了我想要的时间段,因为我在time_slots.py

1 个答案:

答案 0 :(得分:1)

在Django视图中,您忘记在if start < today18子句中添加持续时间。