我正在使用django-rest框架,并且能够使用以下META信息获取并设置自定义标头,
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
现在在我的views.py中,我能够以request.META ['HTTP_X_REQUEST_ID']的形式获取此标头。它可以在响应头中找到
但是当我尝试使用以下配置在uwsgi中记录http标头值时,它具有“-”空值字段。因为uwsgi在%var.XXX变量中只有实际的请求标头,而响应标头转到%headers,因此它仅显示计数和实际值。 问题: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标头,则同样的事情也可以工作。
答案 0 :(得分:2)
如果您需要中间件,则可以使用此:
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'
]