django 中是否有像 Rails 中那样的 before_filter ?
django中有没有可用的功能,以便我们可以在django视图中对所有操作进行一些过滤,例如rails中可用的 before_filter: 。
Is there any feature available in django so that we can combine some filtering on all actions in the view of django, like before_filter: is available in rails.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我仍在学习 Rails,但从我迄今为止观察到的来看, python 装饰器 似乎也在 Django 中的使用方式与 Rails 中的 before_filter 非常相似。
以下是它在验证用户身份方面的用法的一个示例: https: //docs.djangoproject.com/en/1.2/topics/auth/#the-login-required-decorator
I'm still learning Rails but from what I've observed so far python decorators also seem to be used in Django in a very similar way to the before_filter in Rails.
Here's one example of it's usage in authenticating users: https://docs.djangoproject.com/en/1.2/topics/auth/#the-login-required-decorator
不。Django 中不存在 before_、around_ 和 after_ 过滤器概念,但编写自己的函数来完成相同的操作并不难。还有 信号 和 通用视图 可能会完成您需要做的事情。
No. before_, around_ and after_ filter concepts aren't present in Django, but it isn't hard to write your own functions to do the same thing. There are also signals and generic views that might accomplish what you're needing to do.
可以使用
装饰器
来实现此目的。你的装饰器可以是 before_filter 或 after_filter ,具体取决于它是首先还是最后调用装饰函数。这是一个例子
这里我们用
question_required
修饰了 show 函数,并希望它充当 before_filter。所以我们将像这样定义装饰器:正如您在上面看到的,装饰器首先检查数据库中是否存在问题。如果存在,它将调用实际的
show
函数,否则会引发异常。通过这种方式,它的作用就像轨道中的前置过滤器一样。
decorators
can be used for this. your decorator can be the before_filter or after_filter depending on how whether it calls the decorated function first or last.here is an example
Here we have decorated the show function with
question_required
and want it to act as a before_filter. so we will define the decorator like this:As you can see above the decorator is first checking for the question to exist in the db. If it exists it calls the actual
show
function or it raises an exception.In this way it acts like a before filter does in rails.