Fun with 'str' and 'bytes'

Frank Millman frank at chagford.com
Fri Mar 4 07:32:14 EST 2011


Hi all

I want to create a cookie containing a session id. In python 2.6 I had the 
following -

from __future__ import unicode_literals
session_id = b64encode(urandom(20))
response_headers.append(
    (b'Set-Cookie', b'sid="{0}"'.format(session_id)))

After upgrading to 3.2, the above lines generate this traceback -
    AttributeError: 'bytes' object has no attribute 'format'

The best workaround I can come up with is the following -

session_id = b64encode(urandom(20))
response_headers.append(
    (b'Set-Cookie', b'sid="' + session_id + b'"'))

It works, but it is not pretty. Is there a more elegant solution?

Thanks

Frank Millman






More information about the Python-list mailing list