------------------------------------------------------------------------------------- """ Con-way XML Interface Sample Code for Python - Image Retrieval Requires: ElementTree 1.X - http://effbot.org/downloads expat (get PyXML from http://pyxml.sourceforge.net) ----------------- TODO: * replace the USERNAME and PASSWORD String values in the ConwayXml class with your Con-way username and password * replace FILEPATH and URLPATH String values in the ConwayXml class with your desired filesystem and URL locations * If you are not passing in the PRO Number, type and format, enter the string values ----------------- Send questions to Con-way XML Support at web.support@Con-way.com """ import string, httplib, urllib, base64, sys, pprint from elementtree.ElementTree import ElementTree from time import localtime, strftime class HTTPRequest: """Helper class that abstracts HTTP request process""" def __init__(self,host,path,username,password): self.host = host self.path = path self.username = username self.password = password def getBasicAuth(self): """Return basic authentication userid password""" s = self.username +':' + self.password z = base64.encodestring(s)[:-1] # strip trailing \12 return 'Basic '+z def encodeParams(self,d={}): """Given a dict of key values, return encoded params""" return urllib.urlencode(d) def getPostBody(self): """return the body of the post, implement in subclass""" raise NotImplementedError def Process(self): """Submit the HTTP POST XML request""" body = self.getPostBody() h = httplib.HTTP(self.host) h.putrequest('POST',self.path) h.putheader("Content-type","application/x-www-form-urlencoded") h.putheader('Content-length',"%d" % len(body)) h.putheader('Authorization',self.getBasicAuth()) h.putheader('Accept','*/*') h.putheader('Host',self.host) h.endheaders() h.send(body) reply, msg, hdrs = h.getreply() if reply != 200: raise RuntimeError('HTTP request error',(reply,msg,hdrs)) return self.decodeResponseFile(h.getfile()) def DecodeResponse(self,f): """Decode response data from file object f""" raise NotImplementedError class ConwayXml(HTTPRequest): """Submit the XML request and return its detailed information""" # TODO replace the USERNAME and PASSWORD String values # with your Con-way username and password: USERNAME='USERNAME' PASSWORD='PASSWORD' # TODO replace the FILEPATH and URLPATH String values # with your desired filepath and URL locations: # FILEPATH='/Library/WebServer/Documents/conwayImages/' # On Mac FILEPATH='C:/Program Files/Apache Group/Apache2/htdocs/conwayImages/' # On Windows URLPATH='http://localhost/conwayImages/' HOST='www.Con-way.com' PATH='/webapp/imaging_app/XmlImageRetrieverServlet' def __init__(self,pro,type,format): # initialize base class HTTPRequest.__init__(self,self.HOST,self.PATH,self.USERNAME,self.PASSWORD) self.mypro = pro self.mytype = type self.myformat = format timestamp = strftime('%Y%m%d-%H%M%S', localtime()) self.imgFile = self.FILEPATH + type + '-' + pro + '-' + timestamp self.imgUrl = self.URLPATH + type + '-' + pro + '-' + timestamp self.imgUrls = [] def getIt(self): """Process the request""" return self.Process() def getPostBody(self): # return the body of the post # construct the request XML, send URL-Form-encoded instead of plain XML req = [] # Build the XML input stream here req.append('<ImageRequest><ImageKey>') req.append('<PRONumber>%s</PRONumber>' % self.mypro) req.append('<ImageType>%s</ImageType>' % self.mytype) req.append('<ImageFormat>%s</ImageFormat>' % self.myformat) req.append('</ImageKey></ImageRequest>') return self.encodeParams({'ImageRequest':"\n".join(req)}) def decodeResponseFile(self,f): """Decode response data from file object f""" tree = ElementTree(file=f) # decode xml return in file object 'f' root = tree.getroot() error = root.find('Error') if error is not None: raise RuntimeError((error.text,error.get('returncode'),error.get('responsecode'))) # get all the images in the response XML for image in root.findall('Image'): images = image.findall('ImageData') for i in range (0, len(images)): decodedImage = base64.decodestring(images[i].text) pageString = '' if len(images) > 1: pageString = '_%s' % (i+1) fileName = self.imgFile + pageString + '.' + format thisUrl = self.imgUrl + pageString + '.' + format self.imgUrls.append(thisUrl) outfile = open(fileName, 'wb') # open file in binary write mode outfile.write(decodedImage) return self.imgUrls if __name__ == "__main__": # You can hardcode your input String arguments here # Replace PRONUMBER with your own 9 digit PRO number pro = 'PRONUMBER' type = 'DR' ## Type may be BL, DR, LOA, WI format = 'jpeg' ## Format may be pdf, jpeg, png, tiff # or pass them in as arguments: if len(sys.argv) == 3: pro = sys.argv[1] type = sys.argv[2] format = sys.argv[3] myXml = ConwayXml(pro, type, format) # process: get the image, and print the URL urls = myXml.getIt() for url in urls: print url -------------------------------------------------------------------------------------