You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django视图中获取请求头中的xyzId和abcData?

How to Get Custom Request Headers in Django API

Hey there! The issue you're facing comes down to how Django processes HTTP request headers under the hood. Let me break it down and show you the correct way to access those custom headers.

Why request.META['abcData'] Throws a KeyError

Django automatically transforms incoming request headers to a standardized format:

  • All characters are converted to uppercase
  • Prefixes the header name with HTTP_
  • Replaces any camelCase capitalization or hyphens (-) with underscores (_)

So your custom headers get renamed like this:

  • xyzId → HTTP_XYZID
  • abcData → HTTP_ABCDATA

Correct Way to Access the Headers

Use these transformed keys with request.META. For safer access (to avoid KeyError if the header is missing), use the get() method instead of direct key lookup:

In a Function-Based View:

from django.http import JsonResponse

def your_api_view(request):
    if request.method == 'POST':
        # Get custom headers (returns None if header doesn't exist)
        xyz_id = request.META.get('HTTP_XYZID')
        abc_data = request.META.get('HTTP_ABCDATA')
        
        # If you're certain the headers will always be present, you can use direct lookup:
        # xyz_id = request.META['HTTP_XYZID']
        # abc_data = request.META['HTTP_ABCDATA']
        
        # Process your data here
        return JsonResponse({
            'xyzId': xyz_id,
            'abcData': abc_data
        })

In a Class-Based View (e.g., DRF APIView):

from rest_framework.views import APIView
from rest_framework.response import Response

class YourAPIView(APIView):
    def post(self, request):
        xyz_id = request.META.get('HTTP_XYZID')
        abc_data = request.META.get('HTTP_ABCDATA')
        
        return Response({
            'xyzId': xyz_id,
            'abcData': abc_data
        })

Pro Tip

Using get() is recommended because it gracefully handles cases where the header might be missing (returns None instead of crashing with a KeyError). You can even set a default value if needed:

abc_data = request.META.get('HTTP_ABCDATA', 'default_value')

内容的提问来源于stack exchange,提问作者Mr Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:55:03