view raw
MMakela MMakela - 1 year ago 30
Python Question

Different return when using base64.encodestring with database and session variable

I'm trying to do API-request and I need API-key to different view. I'm trying to use session variable, but the key seems to be in some other format than trying to use variable from Sqlite database. API requests work with the key from database, but not with session variable

How I get API-key from database and from session:

key_session = request.session['key']
key_db = APIkey.objects.values_list('key', flat=True).get(pk=2)

Both of these return same values, when I print them. Key example:


I'm using base64.encodestring function when trying to do authentication to API-service with my key:

query = request.GET.get('query')
url = urllib2.Request('',
None, headers={'Content-Type':'application/json'})
base64string = base64.encodestring('%s' % (key_session)).replace('\n', '')

If I print base64string with session variable (key_session), I get:


If I print base64string with session variable (key_db), only difference is the two last characters == is now 'IC', and I think that's why the authentication to API service is failing:


What is making this difference in the base64 encoded string?


I can see difference when using print repr():

print repr(key_db)
print repr(key_session)


One of the strings probably contains some trailing characters that print isn't showing. If you use repr then you should be able to see what the difference is.


You can then strip any characters as necessary before encoding the string, for example:

key_session = key_session.rstrip('\x02')