函数视图:
在view文件中以函数形式定义视图,视图函数与url一一对应。
URL文件中:
urlpatterns = [
url(r'^nodes/$', views.nodes),
]
urlpatterns += router.urls
view文件中:
def nodes(request):
'''
123
'''
name = request.GET.get('name', None)
return JsonResponse(ReturnMsg(data=result, totalCount=totalcount).listdict())
当遇到一个路径需要接收多中请求方法时,函数视图中需要增加对请求方法(get,post,delete,put)的判断逻辑部分
此时引入类视图会使代码更加清晰,结构更加好
类视图:
类名与url一一对应
view文件中定义视图类,继承django的View类,在类中定义get,post,delete,put方法,来接收同url的不同请求方法
url文件
urlpatterns = [
url(r'^workloads/$', views.Workloads.as_view()),
]
urlpatterns += router.urls
view文件:
class Workloads(View):
def get(self, request):
'''
'''
search = request.GET.get('search', None) # 按命名空间搜索
search_result = []
return JsonResponse(ReturnMsg(data=data_list, totalCount=totalcount).listdict())
def post(self, request):
data = request.data
return JsonResponse(ReturnMsg(data=re).dict())
def put(self, request):
data = request.data
return JsonResponse(ReturnMsg(data=re).dict())
def delete(self, request):
data = request.data
return JsonResponse(ReturnMsg(data=data).dict())
原理:
每个类视图都有一个as_view()方法,用于在urlconf中使用。
as_view()方法会创建一个类视图的实例,并调用它的dispatch()方法。
dispatch()方法会在类中查找类似GET\POST之类的类方法,然后与请求request中的HTTP方法匹配。匹配上了就调用对应的代码,匹配不上就弹出异常
dispatch代码:
def dispatch(self, request, *args, **kwargs):
# Try to dispatch to the right method; if a method doesn't exist,
# defer to the error handler. Also defer to the error handler if the
# request method isn't on the approved list.
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs)
类视图使用装饰器
摘抄自:https://blog.csdn.net/qq_42684307/article/details/81042845
定义一个为函数视图准备的装饰器,和一个要被装饰的类视图
def my_decorator(view_func):
"""
定义装饰器,装饰类视图
:param view_func: 被装饰的视图函数
:return: wrapper,装饰的结果
"""
def wrapper(request, *args, **kwargs):
print('装饰器被调用了')
print(request.method, request.path)
# 调用给装饰的视图函数
return view_func(request, *args, **kwargs)
return wrapper
class DefineClassview(View):
"""演示类视图的定义和使用"""
def get(self, request):
"""处理GET请求业务逻辑"""
return HttpResponse('GET请求业务逻辑')
def post(self, request):
"""处理POST请求业务逻辑"""
return HttpResponse('POST请求业务逻辑')
def put(self, request):
pass
url(r'^define_classview/$',my_decorator(views.DefineClassview.as_view())), #这种方法可以给类视图的所有方法添加装饰器功能
@method_decorator(my_decorator, name='dispatch') # 直接在类视图上面添加装饰器 同样可以实现给类视图的所有方法添加装饰器功能
url(r'^define_classview/$', views.DefineClassview.as_view()),
method_decorator装饰器使用name参数指明被装饰的方法
为特定的请求方法添加装饰器:
如果需要为类视图的多个方法添加装饰器,但又不是所有的方法(为所有方法添加装饰器参考上面例子),可以直接在需要添加装饰器的方法上使用method_decorator,如下所示
# 在不同的视图函数上添加装饰器,有的不需要
class DefailView(View):
@method_decorator(my_decorator,name='get')
def get(self,request):
print('get方法')
return HttpResponse('get请求方法')
@method_decorator(my_decorator,name='post')
def post(self,request):
print('post方法')
return HttpResponse('post方法')
def put(self,request):
pass