- Timestamp:
- 06/06/06 00:03:30 (18 years ago)
- Location:
- pkipplib/trunk
- Files:
-
- 2 modified
Legend:
- Unmodified
- Added
- Removed
-
pkipplib/trunk/pkipplib/pkipplib.py
r24 r25 24 24 25 25 import sys 26 import os 26 27 import urllib2 27 28 import socket … … 283 284 operation_id=None, \ 284 285 request_id=None, \ 285 url = "http://localhost:631", \286 username = None, \287 password = None, \288 286 debug=False) : 289 287 """Initializes an IPP Message object. … … 294 292 debug : a boolean value to output debug info on stderr. 295 293 """ 296 if url.endswith("/") :297 url = url[:-1]298 self.url = url.replace("ipp://", "http://")299 self.username = username300 self.password = password301 294 self.debug = debug 302 295 self._data = data 303 296 self.parsed = False 304 self.error = None305 297 306 298 # Initializes message … … 422 414 self.request_id = reqid 423 415 424 def nextRequestId(self) :425 """Increments the current request id and returns the new value."""426 try :427 self.request_id += 1428 except TypeError :429 self.request_id = 1430 return self.request_id431 432 416 def dump(self) : 433 417 """Generates an IPP Message. … … 437 421 mybuffer = [] 438 422 if None not in (self.version, self.operation_id) : 439 if self.request_id is None :440 self.nextRequestId()441 423 mybuffer.append(chr(self.version[0]) + chr(self.version[1])) 442 424 mybuffer.append(pack(">H", self.operation_id)) 443 mybuffer.append(pack(">I", self.request_id ))425 mybuffer.append(pack(">I", self.request_id or 1)) 444 426 for attrtype in self.attributes_types : 445 427 for attribute in getattr(self, "_%s_attributes" % attrtype) : … … 566 548 return self.parseTag() 567 549 568 def doRequest(self, url=None, username=None, password=None, samerequestid=False) :569 """Sends the current request to the URL.570 NB : only ipp:// URLs are currently unsupported so use571 either http://host:631/ or https://host:443 instead...572 573 returns a new IPPRequest object, containing the parsed answer.574 """575 if not samerequestid :576 self.nextRequestId()577 578 url = url or self.url or "http://localhost:631"579 cx = urllib2.Request(url=url, \580 data=self.dump())581 cx.add_header("Content-Type", "application/ipp")582 583 username = username or self.username584 password = password or self.password585 if username :586 password = password or ""587 pwmanager = urllib2.HTTPPasswordMgrWithDefaultRealm()588 pwmanager.add_password(None, \589 "%s%s" % (cx.get_host(), cx.get_selector()), \590 username, \591 password)592 authhandler = urllib2.HTTPBasicAuthHandler(pwmanager)593 opener = urllib2.build_opener(authhandler)594 urllib2.install_opener(opener)595 596 try :597 response = urllib2.urlopen(cx)598 except (urllib2.URLError, urllib2.HTTPError, socket.error), error :599 self.error = error600 return None601 else :602 self.error = None603 datas = response.read()604 ippresponse = IPPRequest(datas)605 ippresponse.parse()606 return ippresponse607 608 550 609 551 class CUPS : 610 552 """A class for a CUPS instance.""" 611 def __init__(self, url= "http://localhost:631", username=None, password=None, charset="utf-8", language="en-us") :553 def __init__(self, url=None, username=None, password=None, charset="utf-8", language="en-us", debug=False) : 612 554 """Initializes the CUPS instance.""" 613 self.url = url 555 if url is not None : 556 self.url = url.replace("ipp://", "http://") 557 if self.url.endswith("/") : 558 self.url = self.url[:-1] 559 else : 560 self.url = self.getDefaultURL() 614 561 self.username = username 615 562 self.password = password 616 563 self.charset = charset 617 564 self.language = language 565 self.debug = debug 618 566 self.lastError = None 619 567 self.lastErrorMessage = None 620 568 self.requestId = None 569 570 def getDefaultURL(self) : 571 """Builds a default URL.""" 572 # TODO : encryption methods. 573 server = os.environ.get("CUPS_SERVER") or "localhost" 574 port = os.environ.get("IPP_PORT") or 631 575 if server.startswith("/") : 576 # it seems it's a unix domain socket. 577 # we can't handle this right now, so we use the default instead. 578 return "http://localhost:%s" % port 579 else : 580 return "http://%s:%s" % (server, port) 581 621 582 def identifierToURI(self, service, ident) : 622 583 """Transforms an identifier into a particular URI depending on requested service.""" … … 625 586 ident) 626 587 588 def nextRequestId(self) : 589 """Increments the current request id and returns the new value.""" 590 try : 591 self.requestId += 1 592 except TypeError : 593 self.requestId = 1 594 return self.requestId 595 627 596 def newRequest(self, operationid=None) : 628 597 """Generates a new empty request.""" 629 598 if operationid is not None : 630 599 req = IPPRequest(operation_id=operationid, \ 631 url=self.url, \ 632 username=self.username, \ 633 password=self.password) 600 request_id=self.nextRequestId(), \ 601 debug=self.debug) 634 602 req.operation["attributes-charset"] = ("charset", self.charset) 635 603 req.operation["attributes-natural-language"] = ("naturalLanguage", self.language) … … 637 605 638 606 def doRequest(self, req) : 639 """Does a request and saves its error status in the lastErrorMessage attribute.""" 640 result = req.doRequest() 641 self.lastError = req.error 642 if self.lastError is not None : 643 self.lastErrorMessage = str(self.lastError) 607 """Sends a request to the CUPS server. 608 returns a new IPPRequest object, containing the parsed answer. 609 """ 610 connexion = urllib2.Request(url=self.url, \ 611 data=req.dump()) 612 connexion.add_header("Content-Type", "application/ipp") 613 if self.username : 614 pwmanager = urllib2.HTTPPasswordMgrWithDefaultRealm() 615 pwmanager.add_password(None, \ 616 "%s%s" % (connexion.get_host(), connexion.get_selector()), \ 617 self.username, \ 618 self.password or "") 619 authhandler = urllib2.HTTPBasicAuthHandler(pwmanager) 620 opener = urllib2.build_opener(authhandler) 621 urllib2.install_opener(opener) 622 self.lastError = None 623 self.lastErrorMessage = None 624 try : 625 response = urllib2.urlopen(connexion) 626 except (urllib2.URLError, urllib2.HTTPError, socket.error), error : 627 self.lastError = error 628 self.lastErrorMessage = str(error) 629 return None 644 630 else : 645 self.lastErrorMessage = None 646 return result 647 631 datas = response.read() 632 ippresponse = IPPRequest(datas) 633 ippresponse.parse() 634 return ippresponse 635 648 636 def getDefault(self) : 649 637 """Retrieves CUPS' default printer.""" … … 670 658 else : 671 659 infile = open(sys.argv[1], "rb") 672 data = infile.read()660 filedata = infile.read() 673 661 infile.close() 674 662 675 m essage = IPPRequest(data, debug=(sys.argv[-1]=="--debug"))676 m essage.parse()677 m essage2 = IPPRequest(message.dump())678 m essage2.parse()679 data2 = message2.dump()680 681 if data ==data2 :663 msg = IPPRequest(filedata, debug=(sys.argv[-1]=="--debug")) 664 msg.parse() 665 msg2 = IPPRequest(msg.dump()) 666 msg2.parse() 667 filedata2 = msg2.dump() 668 669 if filedata == filedata2 : 682 670 print "Test OK : parsing original and parsing the output of the dump produce the same dump !" 683 print str(m essage)671 print str(msg) 684 672 else : 685 673 print "Test Failed !" 686 print str(m essage)674 print str(msg) 687 675 print 688 print str(m essage2)689 676 print str(msg2) 677 -
pkipplib/trunk/README
r21 r25 130 130 131 131 # Sends this request to the CUPS server 132 answer = request.doRequest()132 answer = cups.doRequest(request) 133 133 134 134 # Print the answer as a string of text