Customized middleware module in Django -- automatic search for stackoveflow answers

Classification of Django MIDDLEWARE middleware:

During request:

process_request(request)
process_view(request, view_func, view_args, view_kwargs)

Return period:

process_exception(request, exception) (only if the view raised an exception)
process_template_response(request, response) (only for template responses)
process_response(request, response)

If you need to customize it, just add the file with the corresponding path in 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',
    
    // Custom Middleware method
    'app_name.middleware.StackOverflowMiddleware',
)

Demand scenario

In normal django development and debugging, we will encounter such exception errors. We define a simple middleware, and django's customization steps are very simple, so we can implement the process UU exception method

According to the name and information of the exception, call the stackoveflow interface to automatically search for the relevant answers when the debug reports an error, save some time, and make the implementation very simple

Note: for the purpose of introducing ideas only, do not use online codes in this way

code implementation

File middleware.py in app directory

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

The effect is as follows:

Django version: 1.9.4
python version: 2.7.6
When debugging, settings.DEBUG is in on mode

Keywords: Python Django JSON

Added by dormouse1976 on Sat, 14 Dec 2019 22:10:28 +0200