These days I’m working on django application which will be processing binary data, encoded in %xx (quoted hex), via GET url request.
Lets look at a sample url:
http://mosms.senthadev.com/submit/?udh=%02q%00&ud=%00%0B%0A%B0%00%01%00%00%00%00%12%00%01
To retrieve the url GET params, I used following method:
ud = request.GET.get(‘ud’)
udh = request.GET.get(‘udh’)
And I have convert the ud and udh to hex string (e.g. 027100). But, these variables currently holding the values as ascii.
print('%r' % ud) => u'\x02q\x00'
print('%r' % udh) => u'\x00\x0b\n\ufffd\x00\x01\x00\x00\x00\x00\x12\x00\x01'
But, I faced an error when I tried to convert it using : binascii.b2a_hex(ud)
Because, Django threw the following error:
UnicodeEncodeError: ‘charmap’ codec can’t encode character u’\ufffd’ in position 3: character maps to
Interesting problem. But, I was running out of time. So, I got down little lower and found another alternative solution.
This is the solution I used:
import urllib, binascii
from django.http import HttpResponse
def submit():
#collecting the get params into dict
data = dict(item.rsplit('=') for item in request.META['QUERY_STRING'].rsplit('&'))
udh = str(binascii.b2a_hex(urllib.unquote(data['udh'])))
ud = str(binascii.b2a_hex(urllib.unquote(data['ud'])))
#now I have the ud, udh as proper hex string to be stored in db.
#udh : 027100
#ud : 000b0ab0000100000000120001
Thank you stackoverflow for 1 line code to parse the url params into dict()
