You are not logged in Log in Join
You are here: Home » Members » andym » ZShellCLI » xmlrpclibBasicAuth.py » View File

Log in
Name

Password

 

xmlrpclibBasicAuth.py

File details
Size
1 K
File type
text/plain

File contents

# Thanks Amos and Chris at DC
# http://www.zope.org/Members/Amos/XML-RPC

# path to xmlrpclib, works fine in Zope but when running from the command line
# seems to fail. Annoying.
# import sys
# sys.path.insert(0, r'd:\XMLTest1\lib\python')

import string, xmlrpclib, httplib
from base64 import encodestring

def Server(url, username, password):
    t = BasicAuthTransport(username, password)
    return xmlrpclib.Server(url, t)

class BasicAuthTransport(xmlrpclib.Transport):
    def __init__(self, username=None, password=None):
        self.username = username
        self.password = password
        self.verbose = None

    def request(self, host, handler, request_body):
        # issue XML-RPC request
        h = httplib.HTTP(host)
        h.putrequest("POST", handler)

        # required by HTTP/1.1
        h.putheader("Host", host)

        # required by XML-RPC
        h.putheader("User-Agent", self.user_agent)
        h.putheader("Content-Type", "text/xml")
        h.putheader("Content-Length", str(len(request_body)))

        # basic auth
        if self.username is not None and self.password is not None:
            h.putheader("AUTHORIZATION", "Basic %s" % string.replace(
                    encodestring("%s:%s" % (self.username, self.password)),
                    "\012", ""))
        h.endheaders()

        if request_body: h.send(request_body)
        errcode, errmsg, headers = h.getreply()

        if errcode != 200:
            raise xmlrpclib.ProtocolError(host + handler, errcode, errmsg, headers)

        return self.parse_response(h.getfile()) 

if __name__=='__main__':
    pass