gpt4 book ai didi

python - django View 中的重构/清理时间函数

转载 作者:太空宇宙 更新时间:2023-11-04 03:28:45 25 4
gpt4 key购买 nike

我的 Django 应用程序中有以下 View ,效果很好。我对 python/django 很陌生。我想重构它,以便我有一个处理时间编码的函数,我可以调用它,这样我的 View 就不会那么困惑。

@csrf_exempt
def emulate_create(request):
args = json.loads(request.body, object_hook=utils._datetime_decoder)
resourceId, count, hours = args['resourceId'], args['count'], args['hours']
now = timezone.now().replace(second=0, microsecond=0)
remainder = now.minute % 15
delta = (15 - remainder)
timeFrom = now + timedelta(minutes=delta)
timeTo = timeFrom + timedelta(hours=hours)

reservation = ReservationProspect(byUser=request.user, forUser=request.user, resource=get_object_or_404(Resource, uuid=resourceId), modality=get_object_or_404(Modality, name="online"), timeFrom=timeFrom, timeTo=timeTo, count=count)

return HttpResponse(json.dumps([reservation.toDict()], default=utils._datetime_encoder))

我该如何重构它?我认为这是应该提取到函数中的部分:

now = timezone.now().replace(second=0, microsecond=0)
remainder = now.minute % 15
delta = (15 - remainder)
timeFrom = now + timedelta(minutes=delta)
timeTo = timeFrom + timedelta(hours=hours)

你会怎么做?函数应该返回什么,你会如何调用它?谢谢!

最佳答案

def time_encode(hours):
now = timezone.now().replace(second=0, microsecond=0)
remainder = now.minute % 15
delta = (15 - remainder)
timeFrom = now + timedelta(minutes=delta)
timeTo = timeFrom + timedelta(hours=hours)
return (timeFrom, timeTo)

这将是一个很好的起点。该函数返回一个元组(两个结果),可以按以下方式使用。

@csrf_exempt
def emulate_create(request):
args = json.loads(
request.body,
object_hook=utils._datetime_decoder
)
resourceId, count, hours = args['resourceId'], args['count'], args['hours']

timeFrom, timeTo = time_encode(hours)

reservation = ReservationProspect(
byUser=request.user,
forUser=request.user,
resource=get_object_or_404(Resource, uuid=resourceId),
modality=get_object_or_404(Modality, name="online"),
timeFrom=timeFrom,
timeTo=timeTo,
count=count
)

return HttpResponse(
json.dumps(
[reservation.toDict()],
default=utils._datetime_encoder
)
)

关于python - django View 中的重构/清理时间函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31998873/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com