使用 Python 条件和 Django 返回进行 DRY

发布于 2024-11-28 15:25:16 字数 723 浏览 0 评论 0原文

我要分享的是我的项目中的常见模式。有些案例比其他案例更长,但模式或多或少是相同的,我想知道如何才能更干燥。

if status == 'ACTIVE' and p.result != "0":

    messages.add_message(request, messages.ERROR, 
        _('Active Message... bla bla bla'))

    return HttpResponseRedirect(reverse('billing_update'))

if status == 'TOO MANY FAILURES':

    messages.add_message(request, messages.ERROR, 
        _('Failed. Foooobarrrrr'))

    return HttpResponseRedirect(reverse('billing_update'))

if status == 'DEACTIVATED BY MERCHANT':

    messages.add_message(request, messages.ERROR, 
        _('Deactivated derpa derp'))

    return HttpResponseRedirect(reverse('billing_update'))

这里发生的唯一事情是根据状态设置消息。必须有一种方法只调用一次返回,甚至可能收紧条件。

有想法吗?

What I'm about to share is a common pattern in my projects. Some cases are longer than others but the pattern is more or less the same and I'm wondering how I can be more DRY.

if status == 'ACTIVE' and p.result != "0":

    messages.add_message(request, messages.ERROR, 
        _('Active Message... bla bla bla'))

    return HttpResponseRedirect(reverse('billing_update'))

if status == 'TOO MANY FAILURES':

    messages.add_message(request, messages.ERROR, 
        _('Failed. Foooobarrrrr'))

    return HttpResponseRedirect(reverse('billing_update'))

if status == 'DEACTIVATED BY MERCHANT':

    messages.add_message(request, messages.ERROR, 
        _('Deactivated derpa derp'))

    return HttpResponseRedirect(reverse('billing_update'))

The only thing that is happening here is setting a message based on status. Theres got to be a way to called the return only once and maybe even tighten up the conditional.

Ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眼泪淡了忧伤 2024-12-05 15:25:16

可能是以下行中的内容:

lib module

def add_error_message(request, status, result=0):
    if status == 'ACTIVE' and not result:
        msg = 'Active Message... bla bla bla'
    elif status == 'TOO MANY FAILURES':
        msg = 'Failed. Foooobarrrrr'
    elif status == 'DEACTIVATED BY MERCHANT':
        msg = 'Deactivated derpa derp'
    messages.add_message(request, messages.ERROR, _(msg))

难道不是为了“p.result”条件,字典会更好:

MESSAGES = {
    'ACTIVE': 'Active Message... bla bla bla',
    'TOO MANY FAILURES': 'Failed. Foooobarrrrr',
    'DEACTIVATED BY MERCHANT': 'Deactivated derpa derp',
}
def add_error_message(request, status):
    try:
        messages.add_message(request, messages.ERROR, _(MESSAGES[status]))
    except KeyError:
        pass

view module

from lib import add_error_message

def your_view(request, *args, **kwargs):
    # ...
    add_error_message(request, status, p.result if p else 0)
    return HttpResponseRedirect(reverse('billing_update'))

Could it be something in the line of:

lib module

def add_error_message(request, status, result=0):
    if status == 'ACTIVE' and not result:
        msg = 'Active Message... bla bla bla'
    elif status == 'TOO MANY FAILURES':
        msg = 'Failed. Foooobarrrrr'
    elif status == 'DEACTIVATED BY MERCHANT':
        msg = 'Deactivated derpa derp'
    messages.add_message(request, messages.ERROR, _(msg))

Wouldn't it be for the 'p.result' condition, a dictionary would have been much better:

MESSAGES = {
    'ACTIVE': 'Active Message... bla bla bla',
    'TOO MANY FAILURES': 'Failed. Foooobarrrrr',
    'DEACTIVATED BY MERCHANT': 'Deactivated derpa derp',
}
def add_error_message(request, status):
    try:
        messages.add_message(request, messages.ERROR, _(MESSAGES[status]))
    except KeyError:
        pass

view module

from lib import add_error_message

def your_view(request, *args, **kwargs):
    # ...
    add_error_message(request, status, p.result if p else 0)
    return HttpResponseRedirect(reverse('billing_update'))
高冷爸爸 2024-12-05 15:25:16

我注意到你的最后一个返回是有条件的,并且根据我自己的类似代码猜测,如果两个检查都没有触发,你想继续并返回其他内容,甚至可能不是重定向......

这就是我想我会做的it:

def checkForMessage():
    if status == 'ACTIVE' and p.result != "0":
        return 'Active Message... bla bla bla'
    if status == 'TOO MANY FAILURES':
        return 'Failed. Foooobarrrrr'
    if status == 'DEACTIVATED BY MERCHANT':
        return 'Deactivated derpa derp'
    return None

msg = checkForMessage()
if msg:
    messages.add_message(request, messages.ERROR, _(msg))

    return HttpResponseRedirect(reverse('billing_update'))

// ... go on and do some other stuff ...
return direct_to_template('some/template.html', {some: stuff})

请注意,函数 checkForMessage 是在视图函数内部定义的,因此我们不必将测试中涉及的所有内容作为参数传递给它(如果 tets 数量众多且多种多样,如果它们只需要状态和一些信息) “p”变量,它也可以是在视图函数外部声明并获取这些参数)。

要点是,我们根本不想添加任何消息的“失败”替代方案可以通过在 check 方法中返回 None 并检查 view 方法中是否存在消息来处理。

I notice that your last return is conditional, and guess based on my own similar code that if neither of the checks triggers, you want to go on and return something else, maybe not even a redirect ...

Here's how I think I would do it:

def checkForMessage():
    if status == 'ACTIVE' and p.result != "0":
        return 'Active Message... bla bla bla'
    if status == 'TOO MANY FAILURES':
        return 'Failed. Foooobarrrrr'
    if status == 'DEACTIVATED BY MERCHANT':
        return 'Deactivated derpa derp'
    return None

msg = checkForMessage()
if msg:
    messages.add_message(request, messages.ERROR, _(msg))

    return HttpResponseRedirect(reverse('billing_update'))

// ... go on and do some other stuff ...
return direct_to_template('some/template.html', {some: stuff})

Note that the function checkForMessage is defined inside the view function, so we don't have to pass everything involved in a test as a parameter to it (in case the tets are many and varied, if they just require a status and some "p" variable, it can just as well be declared outside the view function and take those parameters).

The main point is that the "fall through" alternative where we don't want to add any message at all can be handled by returning None in the check method and checking for the existence of a message in the view method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文