as_view()(用于基于类的视图)可以在装饰器中实现吗?
Django 基于类的视图的 as_view() 语法一直困扰着我。基本上,我厌倦了必须为每个我想使用的基于类的视图执行 my_view = MyView.as_view() (或者将 as_view() 放在我使用基于 c 的视图的每个 url conf 的每一行中)。我认为类装饰器将是实现此目的的一种更简洁的方法,并且我正在尝试找出如何实现这一点,对于我自己的代码并在 django 片段上共享,以防其他人感兴趣。所以我的问题是:是否有一种合理的方法来实现“as_view”装饰器,以便以下代码可以正常工作?
@as_view(my_view)
class MyView(View):
pass
这基本上相当于:
class MyView(View):
pass
my_view = MyView.as_view()
谢谢,这也帮助我学习Python的高级功能(即装饰器)。
本
Django's as_view() syntax for Class-based views has been bugging me. Basically, I am tired of having to do a my_view = MyView.as_view() for every class-based view that I want to use (or putting as_view() in every line of every url conf I use c-based views in). I think a class decorator would be a cleaner way to implement this, and I am trying to figure out how to acheive that, for my own code and to share on django snippets, in case others are interested. So my question is: Is there a reasonable way to implement an "as_view" decorator so that the following code would be functional?
@as_view(my_view)
class MyView(View):
pass
which would basically be equivalent to:
class MyView(View):
pass
my_view = MyView.as_view()
Thanks, this is also helping me learn the advanced features (i.e. decorators) of python.
Ben
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想到的一种方法是让类装饰器只是
setattr
某个对象,该对象将包含您想要定义的所有as_views
。然后你可以在你的 urls.py 中使用它,然后在你的views.py中你可以像这样使用它:
..并且
MyView.as_view
将存储在views
上对象为views.my_view
。您还可以在views.py中执行类似的操作:
这会将
my_view
设置为views
模块上的属性。然后,您可以在urls.py
中:我认为
my_view = MyView.as_view
非常简单且可读,所以坦率地说,我自己更喜欢这样做。One approach that comes to mind is to have the class decorator just
setattr
some object which will contain all theas_views
you want defined. You could then use that in your urls.pyAnd then in your views.py you would use it like this:
..and
MyView.as_view
would be stored on theviews
object asviews.my_view
.You could also do something like this in your views.py:
Which would set
my_view
as an attribute on yourviews
module. You could then in yoururls.py
:I think doing
my_view = MyView.as_view
is pretty simple and readable, so I'd frankly prefer that myself.