使用 Python 条件和 Django 返回进行 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'))
这里发生的唯一事情是根据状态设置消息。必须有一种方法只调用一次返回,甚至可能收紧条件。
有想法吗?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可能是以下行中的内容:
lib module
难道不是为了“p.result”条件,字典会更好:
view module
Could it be something in the line of:
lib module
Wouldn't it be for the 'p.result' condition, a dictionary would have been much better:
view module
我注意到你的最后一个返回是有条件的,并且根据我自己的类似代码猜测,如果两个检查都没有触发,你想继续并返回其他内容,甚至可能不是重定向......
这就是我想我会做的it:
请注意,函数 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:
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.