Django的中间件MIDDLEWARE的分类:
请求期间:
process_request(request)
process_view(request, view_func, view_args, view_kwargs)
返回期间:
process_exception(request, exception) (only if the view raised an exception)
process_template_response(request, response) (only for template responses)
process_response(request, response)
如果需要自定义,在MIDDLEWARE_CLASSES中添加对应路径的文件即可
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
// 自定义Middleware方法
'app_name.middleware.StackOverflowMiddleware',
)
需求场景
在平时django开发调试中,会遇到这样那样的exception报错,我们自定义一个简单的中间件,django的自定义步骤很简单,实现process_exception方法即可
根据exception的name和信息,调用stackoveflow的接口,当debug报错时自动搜索相关的答案,节省一些时间,实现起来很简单
备注:仅为介绍思路,线上代码不要这么使用
代码实现
app目录下 middleware.py文件
import requests
from django.conf import settings
class StackOverflowMiddleware(object):
def process_exception(self, request, exception):
if settings.DEBUG:
intitle = u'{}: {}'.format(exception.__class__.__name__, exception.message)
url = 'https://api.stackexchange.com/2.2/search'
params = {
'order': 'desc',
'sort': 'votes',
'site': 'stackoverflow',
'pagesize': 3,
'tagged': 'python;django',
'intitle': intitle
}
r = requests.get(url, params=params)
questions = r.json()
if len(questions['items']) > 0:
print '\nThe stackoverflow answer top 3 is :\n'
for question in questions['items'][:3]:
print '\n'
print question['title']
print question['link'] + '\n'
else :
print '\nstackoverflow answer not found\n'
return None
效果如下:
Django版本:1.9.4
python版本:2.7.6
调试时,settings.DEBUG处于开启模式