def getSMILES(self, id): ''' Retreive cid given a smiles input ''' uri = 'http://' + _base +\ '/rest/pug/compound/smiles/%s/cids/TXT' % (id,) txt = urlopen(uri).read().rstrip() self.cid = txt
def DataFromURI (uri, archive_directory=None): """Retrieve the contents of the uri as raw data. If the uri does not include a scheme (e.g., C{http:}), it is assumed to be a file path on the local system.""" from pyxb.utils.six.moves.urllib.request import urlopen stream = None exc = None # Only something that has a colon is a non-file URI. Some things # that have a colon are a file URI (sans schema). Prefer urllib2, # but allow urllib (which apparently works better on Windows). if 0 <= uri.find(':'): try: stream = urlopen(uri) except Exception as e: exc = e if (stream is None) and six.PY2: import urllib try: stream = urllib.urlopen(uri) exc = None except: # Prefer urllib exception pass if stream is None: # No go as URI; give file a chance try: stream = open(uri, 'rb') exc = None except Exception as e: if exc is None: exc = e if exc is not None: _log.error('open %s', uri, exc_info=exc) raise exc try: # Protect this in case whatever stream is doesn't have an fp # attribute. if isinstance(stream, six.file) or isinstance(stream.fp, six.file): archive_directory = None except: pass xmld = stream.read() if archive_directory: base_name = os.path.basename(os.path.normpath(urlparse.urlparse(uri)[2])) counter = 1 dest_file = os.path.join(archive_directory, base_name) while os.path.isfile(dest_file): dest_file = os.path.join(archive_directory, '%s.%d' % (base_name, counter)) counter += 1 try: OpenOrCreate(dest_file).write(xmld) except OSError as e: _log.warning('Unable to save %s in %s: %s', uri, dest_file, e) return xmld
def synonym(self, label): ''' Retreives the best PubChem id using a registered synonym CAS # is an example of a synonym that works well. ''' uri = _base + 'pug/compound/name/%s/xrefs/RegistryID/XML' % (label,) xml = urlopen(uri).read() xml = xml.replace('xmlns=' + _pug_rest, '') order = pug_rest.CreateFromDOM(domutils.StringToDOM(xml)) o = order.Information[0].CID[0] self.cid = str(o)
def pubchem_xrefs(self, id): ''' Retrieves the external references, given a PubChem identifier ''' uri = _base + 'pug/compound/cid/%s/xrefs/SBURL/xml' % (id, ) xml = urlopen(uri).read() xml = xml.replace('xmlns=' + _pug_rest, '') order = pug_rest.CreateFromDOM(domutils.StringToDOM(xml)) o = order.Information[0] urls = o.SBURL self.urls = urls
def pubchem_xrefs(self, id): ''' Retrieves the external references, given a PubChem identifier ''' uri = _base + 'pug/compound/cid/%s/xrefs/SBURL/xml' % (id,) xml = urlopen(uri).read() xml = xml.replace('xmlns=' + _pug_rest, '') order = pug_rest.CreateFromDOM(domutils.StringToDOM(xml)) o = order.Information[0] urls = o.SBURL self.urls = urls
def getCAS(self, id): ''' Retrieves the CAS from PubChem Identifier. ''' uri = _base + 'pug_view/data/compound/%s/XML' % (id, ) xml = urlopen(uri).read() xml_soup = BeautifulSoup(xml, "lxml") self.xml = xml_soup value = None iupac = None for x in xml_soup.find_all('name'): name = x.get_text() if name == "CAS" and value is None: value = x.find_next_sibling('stringvalue').get_text() if name == 'IUPAC Name' and iupac is None: iupac = x.find_next_sibling('stringvalue').get_text() self.cas = value self.iupac = iupac
def getCAS(self, id): ''' Retrieves the CAS from PubChem Identifier. ''' uri = _base + 'pug_view/data/compound/%s/XML' % (id,) xml = urlopen(uri).read() xml_soup = BeautifulSoup(xml, "lxml") self.xml = xml_soup value = None iupac = None for x in xml_soup.find_all('name'): name = x.get_text() if name == "CAS" and value is None: value = x.find_next_sibling('stringvalue').get_text() if name == 'IUPAC Name' and iupac is None: iupac = x.find_next_sibling('stringvalue').get_text() self.cas = value self.iupac = iupac
import collections import sys # Get the next seven days forecast for two locations zip = [ 85711, 55108 ] if 1 < len(sys.argv): zip = sys.argv[1:] begin = xsd.dateTime.today() end = xsd.dateTime(begin + datetime.timedelta(7)) # Create the REST URI for this query uri = 'http://www.weather.gov/forecasts/xml/sample_products/browser_interface/ndfdXMLclient.php?zipCodeList=%s&product=time-series&begin=%s&end=%s&maxt=maxt&mint=mint' % ("+".join([ str(_zc) for _zc in zip ]), begin.xsdLiteral(), end.xsdLiteral()) print(uri) # Retrieve the data xmld = urlopen(uri).read() open('forecast.xml', 'wb').write(xmld) #print xmld # Convert it to DWML object r = DWML.CreateFromDocument(xmld) product = r.head.product print('%s %s' % (product.title, product.category)) source = r.head.source print(", ".join(source.production_center.content())) data = r.data if isinstance(data, collections.MutableSequence): data = data.pop(0) print(data)
import sys # Get the next seven days forecast for two locations zip = [85711, 55108] if 1 < len(sys.argv): zip = sys.argv[1:] begin = xsd.dateTime.today() end = xsd.dateTime(begin + datetime.timedelta(7)) # Create the REST URI for this query uri = 'http://www.weather.gov/forecasts/xml/sample_products/browser_interface/ndfdXMLclient.php?zipCodeList=%s&product=time-series&begin=%s&end=%s&maxt=maxt&mint=mint' % ( "+".join([str(_zc) for _zc in zip]), begin.xsdLiteral(), end.xsdLiteral()) print(uri) # Retrieve the data xmld = urlopen(uri).read() open('forecast.xml', 'wb').write(xmld) #print xmld # Convert it to DWML object r = DWML.CreateFromDocument(xmld) product = r.head.product print('%s %s' % (product.title, product.category)) source = r.head.source print(", ".join(source.production_center.content())) data = r.data if isinstance(data, collections.MutableSequence): data = data.pop(0) print(data)
spec_ns = spec.namespaceContext().targetNamespace() binding = spec_ns.createExpandedName('ndfdXMLBinding').binding() operation = binding.operationMap()['NDFDgen'] soap_op = operation.wildcardElements()[0] soap_action = soap_op.soapAction service = spec_ns.createExpandedName('ndfdXML').service() soap_addr = service.port[0].wildcardElements()[0] endpoint = soap_addr.location # Execute the request uri = urllib_request.Request(endpoint, soap_message, { 'SOAPAction': soap_action, 'Content-Type': 'text/xml' }) rxml = urllib_request.urlopen(uri).read() #rxml = open('rawresp.xml').read() # Save the raw SOAP-wrapped response open('rawresp.xml', 'w').write(rxml) # The NDFD interface is "interesting" in that the response message for # the SOAP interface is encoded as a text string, rather than being # provided as XML directly. The noise below extracts it. rdom = domutils.StringToDOM(rxml) resp = soapenv.CreateFromDOM(rdom) v = resp.Body.wildcardElements()[0] rxml = v.childNodes[0].childNodes[0].value # Save the extracted response open('resp.xml', 'w').write(rxml) #rxml = open('resp.xml').read()
import weather zip = 55113 if 1 < len(sys.argv): zip = int(sys.argv[1]) # Create an envelope, and give it a body that is the request for the # service we want. env = soapenv.Envelope(soapenv.Body(weather.GetCityForecastByZIP(ZIP=str(zip)))) open('request.xml', 'w').write(env.toxml("utf-8")) # Invoke the service uri = urllib_request.Request('http://wsf.cdyne.com/WeatherWS/Weather.asmx', env.toxml("utf-8"), { 'SOAPAction' : "http://ws.cdyne.com/WeatherWS/GetCityForecastByZIP", 'Content-Type': 'text/xml' } ) rxml = urllib_request.urlopen(uri).read() open('response.xml', 'w').write(rxml) # Convert the response to a SOAP envelope, then extract the actual # response from the wildcard elements of the body. Note that because # the weather namespace was registered, PyXB already created the # binding for the response. soap_resp = soapenv.CreateFromDocument(rxml) resp = soap_resp.Body.wildcardElements()[0] fc_return = resp.GetCityForecastByZIPResult if fc_return.Success: print('Got response for %s, %s:' % (fc_return.City, fc_return.State)) for fc in fc_return.ForecastResult.Forecast: when = time.strftime('%A, %B %d %Y', fc.Date.timetuple()) outlook = fc.Desciption # typos in WSDL left unchanged
from __future__ import print_function import dict from pyxb.utils.six.moves.urllib.request import urlopen import pyxb.utils.domutils as domutils from xml.dom import minidom # Get the list of dictionaries available from the service. port_uri = 'http://services.aonaware.com/DictService/DictService.asmx' uri = port_uri + '/DictionaryList' dle_xml = urlopen(uri).read() dle_dom = domutils.StringToDOM(dle_xml) dle = dict.ArrayOfDictionary.createFromDOM(dle_dom) op_path = '/DictionaryInfo' for d in dle.Dictionary: # Create a REST-style query to retrieve the information about this dictionary. uri = '%s%s?dictId=%s' % (port_uri, op_path, d.Id) resp = urlopen(uri).read() # The response is a simple type derived from string, so we can # just extract and print it. di_resp = dict.CreateFromDOM(domutils.StringToDOM(resp)) # Do the "encode" garbage because one of these dictionaries has a # non-ASCII character print("%s (%s)\n%s\n" % (d.Name.encode('utf-8'), d.Id.encode('utf-8'), di_resp.encode('utf-8')))
from __future__ import print_function import dict from pyxb.utils.six.moves.urllib.request import urlopen import sys from pyxb.utils import domutils word = 'xml' if 1 < len(sys.argv): word = sys.argv[1] # Create a REST-style query to retrieve the information about this dictionary. uri = 'http://services.aonaware.com/DictService/DictService.asmx/Define?word=%s' % ( word, ) rxml = urlopen(uri).read() resp = dict.CreateFromDOM(domutils.StringToDOM(rxml)) print('Definitions of %s:' % (resp.Word, )) for definition in resp.Definitions.Definition: print('From %s (%s):' % (definition.Dictionary.Name, definition.Dictionary.Id)) print(definition.WordDefinition) print()
from __future__ import print_function import dict from pyxb.utils.six.moves.urllib.request import urlopen import sys from pyxb.utils import domutils word = 'xml' if 1 < len(sys.argv): word = sys.argv[1] # Create a REST-style query to retrieve the information about this dictionary. uri = 'http://services.aonaware.com/DictService/DictService.asmx/Define?word=%s' % (word,) rxml = urlopen(uri).read() resp = dict.CreateFromDOM(domutils.StringToDOM(rxml)) print('Definitions of %s:' % (resp.Word,)) for definition in resp.Definitions.Definition: print('From %s (%s):' % (definition.Dictionary.Name, definition.Dictionary.Id)) print(definition.WordDefinition) print()