00001 import xlate 00002 from types import * 00003 00004 """The io module handles the actual connection to the Bio-SPHERE 00005 daemon and the necessary wrapping of data structures. 00006 """ 00007 00008 class BiosphereConnector: 00009 """This class can set up a connection with a Bio-SPHERE daemon. 00010 It can query the daemon for its services and can forward requests 00011 to it. It also performs type and error checking. 00012 """ 00013 00014 def __init__(self, address = 'localhost', port = 2915): 00015 """Initialize the BiosphereConnector class. 00016 00017 Args: 00018 address -- The hostname or IP address of the daemon. 00019 port -- The TCP/IP port on which it is listening. 00020 """ 00021 self.addressaddress = address 00022 self.portport = port 00023 self.errorerror = None 00024 self.parserparser = xlate.XMLParser() 00025 00026 def SetAddress(self, address): 00027 """Set the address of the connector. 00028 00029 Args: 00030 address -- a string with the address (if there's no port 00031 given, 2915 will be assumed. 00032 """ 00033 a = address.split(':') 00034 self.addressaddress = a[0] 00035 if len(a) == 2: self.portport = int(a[1]) 00036 else: self.portport = 2915 00037 00038 def GetServices(self): 00039 """Connect to the daemon and request its service 00040 definitions which are returned as a bs_definitions class. 00041 """ 00042 import urllib 00043 url = 'http://%s:%d/definitions' % (self.addressaddress, self.portport) 00044 try: 00045 data = urllib.urlopen(url) 00046 except IOError: 00047 return None 00048 00049 definitions = self.parserparser.Parse(data.read()) 00050 if definitions == None or self.parserparser.error != None: 00051 self.errorerror = self.parserparser.error 00052 return None 00053 else: 00054 return definitions 00055 00056 def RequestService(self, bsrequest): 00057 """Make a service request to a Bio-SPHERE daemon. 00058 The resulting response is returned or None if there was an 00059 error. 00060 00061 Args: 00062 bsrequest -- A bs_service_request class with the request. 00063 """ 00064 import httplib 00065 00066 xmlrequest = bsrequest.toXML() 00067 conn = httplib.HTTPConnection(self.addressaddress, self.portport) 00068 conn.set_debuglevel = 1 00069 conn.putrequest('POST', '/request', skip_host = True, 00070 skip_accept_encoding = True) 00071 conn.putheader('User-Agent', 'BioSPHERE-python/0.0.2') 00072 conn.putheader('Content-Type', 'text/xml') 00073 conn.putheader('Content-Length', str(len(xmlrequest))) 00074 conn.endheaders() 00075 conn.send(xmlrequest) 00076 00077 response = conn.getresponse() 00078 if response.status != 200: 00079 self.errorerror = (response.status, response.reason) 00080 conn.close() 00081 return None 00082 else: 00083 xmlresp = response.read() 00084 conn.close() 00085 resp = self.parserparser.Parse(xmlresp) 00086 if resp == None or self.parserparser.error != None: 00087 self.errorerror = self.parserparser.error 00088 return None 00089 else: 00090 self.errorerror = None 00091 return resp