中间件与类视图的简单理解

------类视图
1、类视图引入
def register(request):
"""处理注册"""

  # 获取请求方法,判断是GET/POST请求
  if request.method == 'GET':
  # 处理GET请求,返回注册页面
    return render(request, 'register.html')
  else:
  # 处理POST请求,实现注册逻辑
    return HttpResponse('这里实现注册逻辑')

 

from django.views.generic import View

class RegisterView(View):
"""类视图:处理注册"""

  def get(self, request):
  """处理GET请求,返回注册页面"""
    return render(request, 'register.html')

  def post(self, request):
  """处理POST请求,实现注册逻辑"""
    return HttpResponse('这里实现注册逻辑')

类视图的好处:
* 代码可读性好
* 类视图相对于函数视图有更高的复用性, 如果其他地方需要用到某个类视图的某个特定逻辑,直接继承该类视图即可

2、类视图使用
from django.views.generic import View

urlpatterns = [
  # 视图函数:注册
  # url(r'^register/$', views.register, name='register'),
  # 类视图:注册
  url(r'^register/$', views.RegisterView.as_view(), name='register'),
  ]


3、类视图原理
@classonlymethod
def as_view(cls, **initkwargs):
"""
Main entry point for a request-response process.
"""
...省略代码...

  def view(request, *args, **kwargs):
    self = cls(**initkwargs)
    if hasattr(self, 'get') and not hasattr(self, 'head'):
      self.head = self.get
      self.request = request
      self.args = args
      self.kwargs = kwargs
      # 调用dispatch方法,按照不同请求方式调用不同请求方法
      return self.dispatch(request, *args, **kwargs)

    ...省略代码...

   # 返回真正的函数视图

   return view


  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)

4、类视图使用装饰器

def my_decorator(func):
  def wrapper(request, *args, **kwargs):
  print('自定义装饰器被调用了')
  print('请求路径%s' % request.path)
    return func(request, *args, **kwargs)
  return wrapper

class DemoView(View):
  def get(self, request):
    print('get方法')
  return HttpResponse('ok')

  def post(self, request):
    print('post方法')
  return HttpResponse('ok')

4-1、在URL配置中装饰
urlpatterns = [
  url(r'^demo/$', my_decorate(DemoView.as_view()))
]

4-2、 在类视图中装饰
from django.utils.decorators import method_decorator

# 为全部请求方法添加装饰器class DemoView(View):

@method_decorator(my_decorator)
  def dispatch(self, *args, **kwargs):
    return super().dispatch(*args, **kwargs)

  def get(self, request):
    print('get方法')
    return HttpResponse('ok')

  def post(self, request):
    print('post方法')
    return HttpResponse('ok')


# 为特定请求方法添加装饰器class DemoView(View):

@method_decorator(my_decorator)
def get(self, request):
  print('get方法')
  return HttpResponse('ok')

def post(self, request):
  print('post方法')
  return HttpResponse('ok')


4-3 构造Mixin扩展类
class MyDecoratorMixin(object): @classmethod
def as_view(cls, *args, **kwargs):
  view = super().as_view(*args, **kwargs)
  view = my_decorator(view)
  return view

class DemoView(MyDecoratorMixin, View):
  def get(self, request):
    print('get方法')
    return HttpResponse('ok')

  def post(self, request):
    print('post方法')
    return HttpResponse('ok')


-----中间件
Django中的中间件是一个轻量级、底层的插件系统,可以介入Django的请求和响应处理过程,修改Django的输入或输出。中间件的设计为开发者提供了一种无侵入式的开发方式,增强了Django框架的健壮性。
我们可以使用中间件,在Django处理视图的不同阶段对输入或输出进行干预。

1、中间件的定义方法
def simple_middleware(get_response):
# 此处编写的代码仅在Django第一次配置和初始化的时候执行一次。

  def middleware(request):
# 此处编写的代码会在每个请求处理视图前被调用。

    response = get_response(request)

# 此处编写的代码会在每个请求处理视图之后被调用。

    return response

  return middleware

def my_middleware(get_response):
  print('init 被调用')
  def middleware(request):
    print('before request 被调用')
    response = get_response(request)
    print('after response 被调用')
    return response
  return middleware


# 定义好中间件后,需要在settings.py文档中添加注册中间件
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'users.middleware.my_middleware', # 添加中间件
]


2、多个中间件的执行顺序
* 在请求视图被处理前,中间件由上至下依次执行
* 在请求视图被处理后,中间件由下至上依次执行

 

关键词:request self 视图 return def get view django 请求 middleware

相关推荐:

Django - 中间件