Search code examples
python-2.7raspberry-piurllib2basic-authentication

Basic authentication error with urllib2 since python 2.7 update


This piece of python code worked fine an hour ago, before I ran an apt-get upgrade on my raspberry pi.

This is now my python version: Python 2.7.9 (default, Sep 17 2016, 20:26:04)

import urllib, urllib2
from PIL import Image

URL="http://server.local/picture.jpg"
headers = {'Authorization': 'Basic ' + base64.encodestring('Guess:Thepassword')}
req = urllib2.Request(URL, None, headers)
img=Image.open(urllib2.urlopen(req,timeout=1))

But now I get this error:

File "/usr/lib/python2.7/httplib.py", line 1017, in putheader
raise ValueError('Invalid header value %r' % (one_value,))
ValueError: Invalid header value 'Basic TGlvbjpSdW5SYWJiaXRSdW4=\n'

I assume something has changed, but can't figure out what..


Solution

  • You can't have a new line character \n at the end of your header. Instead of using base64.encodestring, use base64.b64encode.

    I don't think this has anything to do with an update to Python, since this behaviour has been there since the base64 module was included back in Python 2.4 (see the bolded text):

    Encode the string s, which can contain arbitrary binary data, and return a string containing one or more lines of base64-encoded data. encodestring() returns a string containing one or more lines of base64-encoded data always including an extra trailing newline ('\n').