Wednesday, January 27, 2016

[Python] How to get key and value from a custom header or from a form data with django rest framework

The following python code is part of handling a post method of my Restful API. I only excerpt it because I want to only hightlight my experiment of dealing with key and value from a custom HTTP header or from a form data.

""" Deal with the header property """
header_property_kwargs = {}
for field in request.META:
    logger.debug("...[Testing]...field,value==> %s,%s" % (field, request.META[field]))
    if 'HTTP_X_EXTRA_PROPERTY_' in field:        
     new_field = field.replace('HTTP_X_EXTRA_PROPERTY_','').lower()
        header_property_kwargs[new_field] = request.META[field]
logger.debug("...[Testing]...header_properties==> %s" % header_property_kwargs)

""" Deal with the extra_property  """
extra_property_kwargs = {}
if 'extra_property' in request.DATA.keys():
    extra_property = request.DATA['extra_property']
        property_list = extra_property.split("|")
        for property_item in property_list:
            key_value = property_item.split("=")
            extra_property_kwargs[key_value[0]] = key_value[1]
    except Exception as e:
        logger.error("Cannot parse extra_property" % e)
        return Response(status=status.HTTP_400_BAD_REQUEST)
logger.debug("...[Testing]...extra_properties==> %s" % extra_property_kwargs)

If I use the curl command to try my code, I will get the result:

curl -v -X POST -H 'Content-Type: application/json; indent=4' -H 'x-extra-property-version1: ccccc' -H 'x-extra-property-version2: ddddd' -u -d '{"extra_property":"version1=aaa|version2=bbb"}'

[Testing]...header_properties==> {'version1': 'ccccc', 'version2': 'ddddd'}
[Testing]...extra_properties==> {u'version1': u'aaa', u'version2': u'bbb'}

It proves that both approaches are able to do the same job. 
P.S: From HTTP Header it seams to use "X-" prefix string otherwise the parameter won't appear in request's header.

curl --header "X-MyHeader: 123" --data "test=test"
The name of the meta data attribute of request is in upper case:
print request.META
Your header will be available as:
request.META.get('HTTP_X_MYHEADER') # return `None` if no such header

No comments: