我有一个基于类的视图叫做PalletContentProductionView
@method_decorator(PermissionManager.production_worker_required, name='dispatch')
class PalletContentProductionView(APIView):
"""
Update a Pallet Content count and/or product
"""
def put(self, request, pk):
pallet_content = QuickFind.get_pallet_content_or_404(pallet_content_id=pk)
def validate_pending_and_created_by_user(pallet_content, user=request.user):
if not pallet_content.pending():
raise PermissionDenied("Non-Pending pallet content cannot be updated by production worker")
EntryFormHelper.throw_403_when_not_created_by_user(pallet_content=pallet_content, user=user)
return update_pallet_content(request, pallet_content, validate_pending_and_created_by_user)
"""
Delete pallet only if pallet content is pending and creater by user
"""
def delete(self, request, pk):
pallet_content = QuickFind.get_pallet_content_or_404(pallet_content_id=pk)
def validate_pending_and_created_by_user(pallet_content, user=request.user):
if pallet_content.pending() is False:
raise PermissionDenied("Non-Pending pallet content cannot be updated by production worker")
EntryFormHelper.throw_403_when_not_created_by_user(pallet_content=pallet_content, user=user)
return delete_pallet_content(request, pallet_content, validate_pending_and_created_by_user)
我想知道如何重构以避免四行重复?你知道吗
这四条线是:
def validate_pending_and_created_by_user(pallet_content, user=request.user):
if not pallet_content.pending():
raise PermissionDenied("Non-Pending pallet content cannot be updated by production worker")
EntryFormHelper.throw_403_when_not_created_by_user(pallet_content=pallet_content, user=user)
我试着把它拉出来,放在PalletContentProductionView
内,并与put和delete方法相邻,但这是错误的。你知道吗
只需创建一个生成相应函数的方法:
注意,这里我们还使用
get_pallet_content
来避免QuickFind.get_pallet_content_or_404(pallet_content_id=pk)
的重复。你知道吗另外,请注意您应该使用
if not something:
而不是if something is False:
。你知道吗相关问题 更多 >
编程相关推荐