# -*- coding: utf-8 -*- # !/usr/bin/env python from apps.web.constant import REQUEST_ID_HEADER from utils import local, generate_request_id def get_request_id(request): if hasattr(request, 'request_id'): return request.request_id else: return request.META.get(REQUEST_ID_HEADER, generate_request_id()) class RequestIdMiddleware(object): # Code for Django >= 1.10 def __init__(self, get_response = None): self.get_response = get_response def __call__(self, request): request_id = get_request_id(request) request.request_id = request_id local.request_id = request_id response = self.get_response(request) del local.request_id return response # Compatibility methods for Django <1.10 def process_request(self, request): request_id = get_request_id(request) request.request_id = request_id local.request_id = request_id def process_response(self, request, response): del local.request_id return response