AttributeError at /index
'TestMiddleware' object has no attribute 'get_response'
from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponse
class TestMiddleware(object):
'''中间件类'''
def __init__(self,request):
'''服务器重启之后,接收第一个请求时调用'''
print('----init----')
def process_request(self, request):
'''产生request对象之后,url匹配之前调用'''
print('----process_request----')
# return HttpResponse('process_request')
def process_view(self, request, view_func, *view_args, **view_kwargs):
'''url匹配之后,视图函数调用之前调用'''
print('----process_view----')
return HttpResponse('process_view')
def process_response(self, request, response):
'''视图函数调用之后,内容返回浏览器之前'''
print('----process_response----')
return response
发生错误:
Internal Server Error: /index
Traceback (most recent call last):
File "C:day06\test5\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
TypeError: 'TestMiddleware' object is not callable
修改后的代码:
from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponse
class TestMiddleware(MiddlewareMixin): # 继承MiddlewareMixin
'''中间件类'''
# def __init__(self,request):
# '''服务器重启之后,接收第一个请求时调用'''
# print('----init----')
def process_request(self, request):
'''产生request对象之后,url匹配之前调用'''
print('----process_request----')
# return HttpResponse('process_request')
def process_view(self, request, view_func, *view_args, **view_kwargs):
'''url匹配之后,视图函数调用之前调用'''
print('----process_view----')
return HttpResponse('process_view')
def process_response(self, request, response):
'''视图函数调用之后,内容返回浏览器之前'''
print('----process_response----')
return response
问题分析:1,再继承object的时候由于django版本支持的问题,不能使用,使用兼容方面,继承MiddlewareMixin。继承之后又发生错误
Django version 3.0.6, using settings 'test5.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
----init----
服务器重启之后,浏览器访问服务器主页/index
2、注释__init()方法问题解决:
个人分析再写了__init__(self):方法后,覆盖了元素的初始化方法,导致初始化失败,正确原因,具体原因还未验证,望大佬们评论指出,谢谢。