How should I base64 encode a PDF file for transport over XML-RPC in Python?
            Asked
            
        
        
            Active
            
        
            Viewed 3.2k times
        
    10
            
            
        - 
                    this is really a non-question, as xmlrpclib does this for you – Oct 16 '08 at 15:21
- 
                    2Actually, that fact turned out to be the answer. I just didn't know about it when I asked the question. – Pat Notz Oct 16 '08 at 15:27
4 Answers
26
            
            
        If you don't want to use the xmlrpclib's Binary class, you can just use the .encode() method of strings:
a = open("pdf_reference.pdf", "rb").read().encode("base64")
 
    
    
        Tony Meyer
        
- 10,079
- 6
- 41
- 47
- 
                    Doesn't this read the entire file by calling `read()` before encoding it? Is that how it's supposed to work? I can't imagine encoding a multi-MB file or larger with this. – Ehtesh Choudhury Aug 07 '11 at 18:50
- 
                    5@Shurane it's a one-line example of using the encode method of strings. Optimising performance will be application specific and is left as an exercise. – Tony Meyer Aug 08 '11 at 00:28
- 
                    2this no longer works in Python 3, try this: `base64.b64encode(open('path/to/your.pdf', 'rb').read())` credit: https://stackoverflow.com/a/43084065/5125264 – Matt Oct 19 '21 at 17:22
5
            
            
        Actually, after some more digging, it looks like the xmlrpclib module may have the piece I need with it's Binary helper class:
binary_obj = xmlrpclib.Binary( open('foo.pdf').read() )
Here's an example from the 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())) 
 
    
    
        Pat Notz
        
- 208,672
- 30
- 90
- 92
2
            
            
        You can do it with the base64 library, legacy interface.
 
    
    
        Maximilian Fischer
        
- 9
- 1
- 4
 
    
    
        johnstok
        
- 96,212
- 12
- 54
- 76
0
            
            
        Looks like you might be able to use the binascii module
binascii.b2a_base64(data)
Convert binary data to a line of ASCII characters in base64 coding. The return value is the converted line, including a newline char. The length of data should be at most 57 to adhere to the base64 standard.
 
    
    
        Community
        
- 1
- 1
 
    
    
        Sam Corder
        
- 5,374
- 3
- 25
- 30
