django自定义中间件–出错时自动搜索stackoveflow的答案

在平时django开发调试中,会遇到这样那样的exception报错,这里我们自定义一个中间件,根据exception的name和信息,调用stackoveflow的接口,搜索相关的答案,节省一些时间(后来发现,一来结果不算很准,二来需要网络请求,有时间网络慢,导致调试更卡。不过思路还是对的)

上代码:

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中间件的分类:

  • 请求期间:
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)

翻译自:simpleisbetterthancomplex

Written by

说点什么

欢迎讨论

avatar

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

  Subscribe  
提醒