django处理请求的两种方式
1、FBV(function base views) 就是在视图里使用函数处理请求。
代码实例:
#view中这样写一个函数
from django.http import HttpResponse
def index(request):
if request.method == 'GET':
return HttpResponse('index')
url.py中这几引入views。指向index就可以了
from API import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.index),
]
2、CBV(class base views) 就是在视图里使用类处理请求。
代码实例
views.py代码
from django.views import View
class authView(View):
def get(self,*args,**kwargs):
return HttpResponse('CBV之get请求')
url.py中这几引入views。class-based view提供了一个as_view()
静态方法(也就是类方法),调用这个方法,会创建一个类的实例,然后通过实例调用dispatch()
方法,dispatch()
方法会根据request的method的不同调用相应的方法来处理request(如get()
, post()
等)。
from API import views
urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/auth/',views.authView.as_view()),
]
我们自定义的类继承自Django自身的View,其中有个as_view()方法,URL中直接调用这个方法:
class View:
"""
Intentionally simple parent class for all views. Only implements
dispatch-by-method and simple sanity checking.
"""
http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
def __init__(self, **kwargs):
"""
Constructor. Called in the URLconf; can contain helpful extra
keyword arguments, and other things.
"""
# Go through keyword arguments, and either save their values to our
# instance, or raise an error.
for key, value in kwargs.items():
setattr(self, key, value)
@classonlymethod
def as_view(cls, **initkwargs):
"""Main entry point for a request-response process."""
for key in initkwargs:
if key in cls.http_method_names:
raise TypeError(
'The method name %s is not accepted as a keyword argument '
'to %s().' % (key, cls.__name__)
)
if not hasattr(cls, key):
raise TypeError("%s() received an invalid keyword %r. as_view "
"only accepts arguments that are already "
"attributes of the class." % (cls.__name__, key))
def view(request, *args, **kwargs):
#相当于AuthView().实例化当前类cls特殊方法
self = cls(**initkwargs)
self.setup(request, *args, **kwargs)
if not hasattr(self, 'request'):
raise AttributeError(
"%s instance has no 'request' attribute. Did you override "
"setup() and forget to call super()?" % cls.__name__
)
return self.dispatch(request, *args, **kwargs)
view.view_class = cls
view.view_initkwargs = initkwargs
# take name and docstring from class
update_wrapper(view, cls, updated=())
# and possible attributes set by decorators
# like csrf_exempt from dispatch
update_wrapper(view, cls.dispatch, assigned=())
return view
上面代码先不看具体执行了什么,可以看出最终return了一个view,而这个view是一个函数,return了一个self。dispatch。也就是说其实是执行了self.dispatch(request)
接着进入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)
注意:getattr方法,平时不怎么用,这个方法是python内置的一个方法,其作用是 用于返回一个对象属性值。
测试:
class test():
def a(self):
return '我是A调用返回值'
def b(self):
return '我是B调用返回值'
textgetattr = getattr(test,'a')
print(textgetattr(test))
也就是自动调用指定参数类的内的函数返回‘我是A调用返回值’
总结:
as_view()方法默认调dispatch方法,此方法内部,又根据method也就是请求类型的不同调用指定的视图类中的方法。