去另一个观点 [英] Going to another view

查看:119
本文介绍了去另一个观点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说出我有以下观点:

  def show(request):
protect(request)

...这里有更多的代码...

返回render_to_response
...

保护是另一个我正在导入的应用程序视图:from watch.actions import protect



在保护中,我做了一些检查,如果满足条件,我想使用render_to_response从保护,并防止返回显示。如果条件不符合,我想通常返回显示并继续执行代码。



我该怎么做?



谢谢。

解决方案

如果它唯一的目的是你所描述的,你应该考虑写保护作为视图装饰器。 此答案提供了一个如何执行此操作的示例。



基于查看我写过的装饰器,您的保护装饰器可能看起来像:

  from functools import fraps 

from django.utils.decorators import available_attrs

def protect(func):
@wraps(func,assigned = available_attrs(func )
def inner(request,* args,** kwargs):
如果some_condition:
返回render_to_response('protected_template')
返回func(request,* args,* * kwargs)
返回内部

哪些可以让您使用它: p>

  @protect 
def show(request):
...
return render_to_response(.. 。)


Say I have the following view:

def show(request):
    protect(request)

    ... some more code here...

    return render_to_response
    ...

"protect" is another app view which I am importing like this: from watch.actions import protect

In protect, I make some checks and if a condition is met, I want to use render_to_response right from "protect" and prevent returning to show. If the condition is not met, I want to normally return to "show" and continue the code execution.

How may I do that?

Thanks.

解决方案

If its only purpose is what you've described, you should consider writing protect as a view decorator. This answer provides one example of how to do so.

Based on view decorators that I have written, your protect decorator could look something like:

from functools import wraps

from django.utils.decorators import available_attrs

def protect(func):
    @wraps(func, assigned=available_attrs(func))
    def inner(request, *args, **kwargs):
        if some_condition:
            return render_to_response('protected_template')
        return func(request, *args, **kwargs)
    return inner

Which would allow you to then use it like:

@protect
def show(request):
   ...
   return render_to_response(...)

这篇关于去另一个观点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆