I write some code as below,but it raise an exception
here is request_id_middleware.py
import uuid
from django.middleware.common import CommonMiddleware
from taiji.logger import logger
class RequestIDMiddleware(CommonMiddleware):
# pass
def process_request(self, request):
request.META['request_id'] = str(uuid.uuid4())
logger.info(f"start request id: {request.META['request_id']}")
return request
def process_response(self, request, response):
if request.META.get('request_id') is None:
response.headers['X-REQUEST-ID'] = request.META['request_id']
logger.info(f"finish request id: {response.headers['X-REQUEST-ID']}")
return response
logger.py
import logging
def set_logger(name):
logger=logging.getLogger(name)
handler=logging.StreamHandler()
handler.setLevel(logging.DEBUG)
fmt=logging.Formatter(fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(fmt)
logger.addHandler(handler)
return logger
logger=set_logger('gg')
views
def index(request: HttpRequest):
logger.info("hello world")
return JsonResponse("hello world")
but it tell me
Traceback (most recent call last):
File "E:\miniconda\envs\py312\Lib\wsgiref\handlers.py", line 137, in run
self.result = application(self.environ, self.start_response)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\miniconda\envs\py312\Lib\site-packages\django\contrib\staticfiles\handlers.py", line 80, in __call__
return self.application(environ, start_response)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\miniconda\envs\py312\Lib\site-packages\django\core\handlers\wsgi.py", line 124, in __call__
response = self.get_response(request)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\miniconda\envs\py312\Lib\site-packages\django\core\handlers\base.py", line 141, in get_response
response._resource_closers.append(request.close)
^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'WSGIRequest' object has no attribute '_resource_closers'
[20/Apr/2024 22:32:59] "GET /index/ HTTP/1.1" 500 59
is it right way to implement a middleware? why it call a WSGIRequest error? it should be a respone-like object error Any help will be appreciate
After reading Django middleware docs and this repo, I wrote a simple code like this.
from Application import local
import uuid
class UserAuthMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
local.request_id = uuid.uuid1()
response = self.get_response(request)
return response
in Application.__init__.py
try:
from asgiref.local import Local
except ImportError:
from threading import local as Local
local = Local()
in request_filter.py
import logging
from Application import local
class RequestIDFilter(logging.Filter):
def filter(self, record) -> bool:
record.request_id = getattr(local, "request_id", None)
return True
besides, you just need config your django log config, add request_id and filter field to your config like that repo I mention in the begin, it work well for me