URLLIB Request with UTF-8 Encoded Data

I had a hard time making a Urllib API request with some non-ASCII data. Here’s what I had to do in order to make the request. The hard part was creating a secret token. I wasn’t sure whether to encode the token_text before generating the hashlib or not and that turned out to be the issue. The key is to encode all the data that is being sent via the urlencode parameter. The token itself would be ASCII but the hashlib.update method requires an ASCII parameter so the token text has to encoded using utf-8 before passing into the update function.

url_path = settings.API_URL
api_function = 'mail-send'
data = {}
data["function"] = api_function
data["csv_fileIds"] = "%d,%d" % (license_file_id, settings.LIC_UPLOAD_FILE_ID)
data["to"] = email_license_form.cleaned_data['email_to']
data["subject"] = email_license_form.cleaned_data['email_subject'].encode('utf8')
data["message"] = email_license_form.cleaned_data['email_body'].encode('utf8')
data["cc"] = email_license_form.cleaned_data['email_cc']
token_text = "function=%scsv_fileIds=%sto=%ssubject=%ssecret=%s" % (api_function,"%d,%d" % (license_file_id, settings.LIC_UPLOAD_FILE_ID), email_license_form.cleaned_data['email_to'], email_license_form.cleaned_data['email_subject'], settings.API_TOKEN )

h = hashlib.sha1()
token = h.hexdigest()
data["token"] = token
req = urllib2.Request(url_path, urllib.urlencode(data), headers={'Content-type': 'application/x-www-form-urlencoded'})
response = urllib2.urlopen(req)
result_raw = response.read()
result = simplejson.loads(result_raw)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s