s=str(binary)

gert gert.cuykens at gmail.com
Tue Jan 20 13:31:19 EST 2009


On Jan 20, 5:23 am, John Machin <sjmac... at lexicon.net> wrote:
> On Jan 20, 12:54 pm, gert <gert.cuyk... at gmail.com> wrote:
>
> > How do you convert s back to binary data in python 3 so I can put in a
> > sqlite blob ?
> > Is there a build in function or do I need to use binascii ?
> > byte(s) or bin(s) would make more sense but can not figure it out ?
>
> Can't imagine why you would do str(binary_data) especially if you want
> it back again ... however:

def application(environ, response):
    s = str(environ['wsgi.input'].read())
    b = compile('boundary=(.*)').search(environ['CONTENT_TYPE']).group
(1)
    p = compile(r'.*Content-Type: application/octet-stream\\r\\n\\r\\n
(.*)\\r\\n--'+b+'.*'+b+'--', DOTALL).match(s).group(1)
    db.execute('UPDATE users SET picture=? WHERE uid=?',
(p,session.UID))

> According to the fabulous manual:
>
> str([object[, encoding[, errors]]])
> Return a string version of an object, using one of the following
> modes:
> [snip]
> When only object is given, this returns its nicely printable
> representation. For strings, this is the string itself. The difference
> with repr(object) is that str(object) does not always attempt to
> return a string that is acceptable to eval(); its goal is to return a
> printable string.
>
> Hmm looks like (1) we need to do the dreaded eval() and (2) there's no
> guarantee it will work.
>
> >>> for i in range(256):
>
> ...    blob = bytes([i])
> ...    if eval(str(blob)) != blob:
> ...       print(i, blob, str(blob), eval(str(blob)))
> ...
>
> >>> # no complaints!
>
> Looks like it's going to work, but you better be rather sure that you
> trust the source.

Any other suggestions ?




More information about the Python-list mailing list