from django.contrib import admin from django.urls import path from app01 import views urlpatterns = [ path(‘admin/‘, admin.site.urls), path(‘login/‘, views.LoginView.as_view()), path(‘books/‘, views.BookView.as_view()), ]
from django.shortcuts import render,HttpResponse # Create your views here. import json #第一步导包 from django.views import View #自定义一个类接口,必须继承View class LoginView(View): def dispatch(self, request, *args, **kwargs): print("接受请求...") ret=super().dispatch(request, *args, **kwargs) return ret def get(self,request): return render(request,"login.html") def post(self,request): print(request.POST.get("user")) print(request.POST.get("pwd")) return HttpResponse("OK") def delete(self,request): return HttpResponse("delete...") class BookView(View): def get(self,request): book_list=["python","linux","go"] return HttpResponse(json.dumps(book_list))
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post"> {% csrf_token %} 用户名:<input type="text" name="user"> 密码:<input type="password" name="pwd"> <input type="submit"> </form> </body> </html>
执行urls.py中的 path(‘login/‘, views.LoginView.as_view())
先在自己定义LoginViews类中查找as_iew(),找不到再到父类中查找
def as_view(cls, **initkwargs): """Main entry point for a request-response process.""" #...看不懂的省略。 def view(request, *args, **kwargs): #...看不懂的省略。 return self.dispatch(request, *args, **kwargs) view.view_class = cls view.view_initkwargs = initkwargs #...看不懂的省略。 return view #这就是我们要找的,返回一个函数
这一步的结果: path(‘login/‘, views.LoginView.as_view())---》path(‘login/‘, View.view),
#执行view代码 def view(request): #看不懂代码省略 return self.dispatch(request, *args, **kwargs) #返回一个分发函数的结果
def dispatch(request, *args, **kwargs): 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) #返回执行结果
此步骤:根据请求方式分发给不同的执行函数
5 步骤五
执行请求方式对应的函数,先从自己的类(LoginView)中寻找。
没找到就执行父类的方法
注意:self代表的是LoginView类
原文:https://www.cnblogs.com/angle6-liu/p/10474045.html