Django框架的使用教程--类视图-中间间-模板[六]

时间:2023-03-09 22:15:04
Django框架的使用教程--类视图-中间间-模板[六]

类视图

类视图的使用

视图函数

class class_view(View):
"""类视图""" def get(self, request):
return render(request, 'index.html') def post(self, request):
return render(request, 'show.html')

路由

url(r'^class_view/$', views.class_view.as_view()),

结果

Django框架的使用教程--类视图-中间间-模板[六]

类视图的源码

    @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("You tried to pass in the %s method name as a "
"keyword argument to %s(). Don't do that."
% (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):
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
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
    # 根据不同的请求函数返回不同的值
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) # http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

类视图使用装饰器

方法一:使用装饰器定义类视图(不推荐使用,只能整个类添加装饰器,不能单独方法添加)

代码

def my_decorator(func):
def without(request, *args, **kwargs):
print('装饰器被调用')
print('路径%s' % request.path)
return func(request, *args, **kwargs) return without class decorator_view(View):
def get(self, request):
print('这是get方法')
return HttpResponse('ok') def post(self, request):
print('这是post方法')
return HttpResponse('ok')

路由

# 直接在URL中使用装饰器
from .views import decorator_view
url(r'^decorator_view/$', views.my_decorator(decorator_view.as_view())),

结果

Django框架的使用教程--类视图-中间间-模板[六]

方法二:使用装饰器定义类视图(可以指定的请求方式)

代码(以下的视图函数名字可以自己定义过)

# 可以指定装饰器的特定请求,如name='get'
@method_decorator(my_decorator, name='dispatch')
class decorator_view(View):
def get(self, request):
print('这是get方法')
return HttpResponse('ok') def post(self, request):
print('这是post方法')
return HttpResponse('ok')

路由

# 直接在URL中使用装饰器
from .views import decorator_view
url(r'^decorator_view/$', views.my_decorator(decorator_view.as_view())),

运行结果

Django框架的使用教程--类视图-中间间-模板[六]

方法三:使用装饰器定义类视图(定义方法的类装饰器)

代码

class decorator_view(View):
# 给get添加装饰器
@method_decorator(my_decorator)
def get(self, request):
print('这是get方法')
return HttpResponse('ok') # 给post添加装饰器
@method_decorator(my_decorator)
def post(self, request):
print('这是post方法')
return HttpResponse('ok')

路由

# 直接在URL中使用装饰器
from .views import decorator_view
url(r'^decorator_view/$', views.my_decorator(decorator_view.as_view())),

运行(postman测试)

Django框架的使用教程--类视图-中间间-模板[六]

中间件

在子应用工程目录中新建一个middleware.py文件

middleware.py(在调试模式下,中间件被调用两次)

def my_middleware(get_response):
print('__init__初始化') def in_middleware(request):
print('请求之前被调用')
response = get_response(request)
print('请求之后被调用')
return response return in_middleware

视图函数

def index_view(request):
print('view视图被调用')
return HttpResponse('ok')

运行

Django框架的使用教程--类视图-中间间-模板[六]

注册中间件

Django框架的使用教程--类视图-中间间-模板[六]

多个中间件的使用

1)在视图函数执行之前,中间件由上至下执行

2)在视图函数请求至后,中间间由下到上

注册中间间

Django框架的使用教程--类视图-中间间-模板[六]

定义两个中间件

def my_middleware(get_response):
print('__init__初始化') def in_middleware(request):
print('请求之前被调用')
response = get_response(request)
print('请求之后被调用')
return response return in_middleware def my_middleware1(get_response):
print('__init2__初始化') def in_middleware(request):
print('请求2之间被调用')
response = get_response(request)
print('请求2之后被调用')
return response
return in_middleware

运行结果

Django框架的使用教程--类视图-中间间-模板[六]

模板的使用

根目录创建一个静态文件static_files

修改静态文件的参数

Django框架的使用教程--类视图-中间间-模板[六]

访问

Django框架的使用教程--类视图-中间间-模板[六]

模板的配置

Django框架的使用教程--类视图-中间间-模板[六]

模板的继承

{% extends "父模板路径"%}

代码块

{% block 名称 %}

预留区域,可以编写默认内容,也可以没有默认内容

{% endblock 名称 %}

注释

{#...#}

多行注释

{% comment %}

...

{% endcomment %}