我正在使用django-rest框架,我能够使用以下元信息获取并设置自定义标题,
class log_middleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self,request):
# set thread local values
# This will execute before every request
correlation_id = request.META['HTTP_X_REQUEST_ID'] if 'HTTP_X_REQUEST_ID' in request.META else str(uuid.uuid4())
request.META['HTTP_X_REQUEST_ID'] = correlation_id
#logger.debug("Entered service")
response = self.get_response(request)
response['HTTP_X_REQUEST_ID'] = correlation_id
#logger.debug("Processed response")
return response
现在在我的视图中。并且它可以在响应标头
中使用但是,当我尝试使用以下配置记录UWSGI中的HTTP标头值时,它具有' - '空值字段。因为UWSGI在%var.xxx变量中仅具有实际请求标头,并且响应标头转到%标题,并且仅显示计数和实际值。问题:https://github.com/unbit/uwsgi/issues/1407
因此,django中有任何方法可以在实际请求标头中附加数据,而不是响应标头?
[uwsgi]
master = 1
memory-report = true
module = my_service.wsgi
http = 0.0.0.0:8080
max-requests = 50
processes = 16
log-format = { "ctime": "%(ctime)", "addr": "%(addr)", "method": "%(method)", "uri": "%(uri)", "correlation_id": "%(var.HTTP_X_REQUEST_ID)" }
,如果我在从剩下的客户端utils发送请求本身时设置了http_x_request的标题http_x_request,则同样的事情也有效。
如果您需要中间件,则可以使用此信息:
middlewares.py:
def add_header_middleware(get_response):
def middleware(request):
request.META['hello'] = 'world'
response = get_response(request)
response['world'] = 'hello'
return response
return middleware
views.py:
@api_view(['GET'])
def sample_view(request):
return Response(request.META['hello'])
settings.py:
MIDDLEWARE = [
# ...
'your_app.middlewares.add_header_middleware'
]