How base64 encodes a PDF file in Python

How should I base64 encode a PDF file for transport via XML-RPC in Python?

+6
python encoding base64 xml-rpc
source share
5 answers

NOTE: this is a copy of Pat noz owned by the wiki community. This answer can be selected as the selected answer. Change freely to improve.

Pat Knotz says:

Actually, after some additional digging, it looks like the xmlrpclib module may have the part I need, with its Binary helper class:

 binary_obj = xmlrpclib.Binary( open('foo.pdf').read() ) 

Here is an example from Trac XML-RPC Documentation

 import xmlrpclib server = xmlrpclib.ServerProxy("http://athomas: password@localhost :8080/trunk/login/xmlrpc") server.wiki.putAttachment('WikiStart/t.py', xmlrpclib.Binary(open('t.py').read())) 
+1
source share

If you do not want to use the xmlrpclib binary class, you can simply use the .encode () method for strings:

 a = open("pdf_reference.pdf", "rb").read().encode("base64") 
+23
source share

Actually, after some additional digging, it looks like the xmlrpclib module may have the piece I need, with it the Binary helper class:

  binary_obj = xmlrpclib.Binary (open ('foo.pdf'). read ())

Here is an example from Trac XML-RPC Documentation

 import xmlrpclib server = xmlrpclib.ServerProxy("http://athomas: password@localhost :8080/trunk/login/xmlrpc") server.wiki.putAttachment('WikiStart/t.py', xmlrpclib.Binary(open('t.py').read())) 
+4
source share

You can do this with the base64 library , an obsolete interface.

+1
source share

It looks like you could use the binascii module

binascii.b2a_base64 (data)

Convert binary data to base64 encoded ASCII character string. The return value is a converted string, including a new char string. The data length should be no more than 57 to comply with the base64 standard.

0
source share

All Articles