views:

1997

answers:

5

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

+1  A: 

You can do it with the base64 library, legacy interface.

johnstok
+3  A: 
Pat Notz
A: 

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.

Sam Corder
+1  A: 

NOTE: this is a community-wiki owned copy of Pat Notz's answer. This answer can be selected as the chosen answer. Edit freely to improve.

Pat Notz says:

Actually, after some more digging, it looks like the xmlrpclib module may have the piece I need with its 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()))
ΤΖΩΤΖΙΟΥ
Nice, thank you ΤΖΩΤΖΙΟΥ. Improvements welcome.
Pat Notz
Um. Somebody downvoted this answer. I don't mind rep-wise, it's a community-owned answer; and EXACTLY because it's a community-owned answer, either edit it directly to improve it, or if you don't have enough rep, comment what's wrong so sb else corrects it. Sheesh.
ΤΖΩΤΖΙΟΥ
+2  A: 

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