Django:结合两个类似的util函数

时间:2019-01-31 18:24:04

标签: python django

我的views.py中具有以下get函数。我的两个直到函数的外观几乎相同,而且我似乎并不遵循DRY原理。但是,我目前不知道如何写得更好。你能建议一个更好的方法吗?

def get(self, request, *args, **kwargs):
    # Delete discount code cookie if ?delete_discout is set in get parameter
    delete_discount_code = request.GET.get('delete_discount')
    if delete_discount_code:
        self.discount_code = delete_discount_session(request, self.discount_code_session)

    # Delete discount code cookie if ?delete_social_ticketing is set in get parameter
    delete_social_ticketing = request.GET.get('delete_social_ticketing')
    if delete_social_ticketing:
        self.social_ticketing_code = delete_social_ticketing_session(request, self.social_ticketing_session)

我的utils.py的结构如下:

def discount_cookie_name(event):
    """Unique discount cookie name per event"""
    return f'discount_code_{str(event.pk)}'

def social_ticketing_cookie_name(event):
    """Unique social ticketing cookie name per event"""
    return f'social_ticketing_{str(event.pk)}'

def delete_social_ticketing_session(request, social_ticketing_code_session):
            if social_ticketing_code_session:
                del request.session[social_ticketing_cookie_name(request.event)]
                return None

def delete_discount_session(request, discount_code_session):
    if discount_code_session:
        del request.session[discount_cookie_name(request.event)]
        return None

1 个答案:

答案 0 :(得分:0)

首先有两个问题:

像这样的行

self.discount_code = delete_discount_session(request, self.discount_code_session)

可以写为:

delete_discount_session(request, self.discount_code_session)

因为delete_discount_sessiondelete_social_ticketing_session将始终返回None

另一方面,delete_discount_session将始终删除一个dicount Coockie,与delete_social_ticketing_session相同,它将始终删除一个social_tiketing cookie,因此,您可以在那里进行名称解析:

def delete_social_ticketing_session(request, social_ticketing_code_session):
    if social_ticketing_code_session:
        del request.session[f'social_ticketing_{str(request.event.pk)}']

def delete_discount_session(request, discount_code_session):
    if discount_code_session:
        del request.session[f'discount_code_{str(request.event.pk)}']

然后您唯一的区别是条件变量的名称和cookie的名称,因此:

def delete_cookie(request, cookie_prefix, condition):
    if condition:
        del request.session[f'{cookie_prefix}_{str(request.event.pk)}']

所有这些都可以编写:

def get(self, request, *args, **kwargs):
    # Delete discount code cookie if ?delete_discout is set in get parameter
    if request.GET.get('delete_discount'):
        self.delete_cookie(request, 'discount_code', self.discount_code_session)

    # Delete discount code cookie if ?delete_social_ticketing is set in get parameter
    if request.GET.get('delete_social_ticketing'):
        self.delete_cookie(request, 'social_ticketing', self.social_ticketing_session)