Thursday, January 28, 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']
    try:
        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 teyen.liu@gmail.com:123456 -d '{"extra_property":"version1=aaa|version2=bbb"}'  http://10.0.2.10:8000/api/test/

[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.


Reference:
http://stackoverflow.com/questions/28345842/getting-custom-header-on-post-request-with-django-rest-framework
curl --header "X-MyHeader: 123" --data "test=test" http://127.0.0.1:8000/api/update_log/
The name of the meta data attribute of request is in upper case:
print request.META
Your header will be available as:
request.META['HTTP_X_MYHEADER']
Or:
request.META.get('HTTP_X_MYHEADER') # return `None` if no such header

No comments: