PKws1O%ɲgghkvportal/__init__.py"""hkvportal - module to access dataservices""" __version__ = '0.4' from .services import ServicePKKo1Oԝ%%hkvportal/services.py# coding: utf-8 ################################ #### Author: Mattijn van Hoek ## #### While working for HKV ## #### Date 2017-2019 ## #### Version: 0.4 ## ################################ import zeep import pandas as pd import io import json import requests import urllib.parse class Service(object): """ mangrove service to create/update databases, set and get entries. """ def __init__(self, dataservice, uid): """ set URL for dataservice to be used Parameters ---------- dataservice: str URL of dataservice instance (eg. 'https://tsws.hkvservices.nl/mangrove.ws/') uid: str User Identification ID. Request by IT """ self.dataservice(dataservice) self.uid = uid class errors(object): """ error class with different errors to provide for fewsPi """ def noset_dataservice(): raise AttributeError( "dataservice not known. set first using function setDataservice()" ) def database_not_exist(): raise AttributeError( "used database does not exist" ) def key_not_exist(): raise AttributeError( "used key does not exist in database" ) def input_data_type(): raise AttributeError( "input type of data is not recognized. Choose between type str, io.StringIO or io.BytesIO" ) def get_url(self, database, key, content_type='SET_BY_USER'): url = urllib.parse.urljoin( self._dataservice, "?function=dataportal.db.getdata¶meters={{database:'{}',key:'{}'}}&contentType={}".format(database, key, content_type) ) print("entry available at:\n{}".format(url)) return url def serialize_data(self, data): if isinstance(data, str): data = data.encode() elif isinstance(data, io.StringIO): data = data.getvalue().encode() elif isinstance(data, io.BytesIO): data = data.getvalue() elif isinstance(data, bytes): pass else: self.errors.input_data_type() return data def dataservice(self, dataservice, dump=False): """ function to set URL for dataservice to be used in other functions Parameters ---------- dataservice: str URL of dataservice instance (eg. 'https://tsws.hkvservices.nl/mangrove.ws/') """ self._dataservice = urllib.parse.urljoin(dataservice, "data.ashx") self._call = urllib.parse.urljoin(dataservice, "entry.asmx/Call?") self._wsdl = urllib.parse.urljoin(dataservice, "entry.asmx?WSDL") settings = zeep.Settings(strict=False, raw_response=True) self.client = zeep.Client(wsdl=self._wsdl, settings=settings) if dump == False: return print( "Dataservice is recognized.", self._wsdl, "will be used as portal", ) if dump == True: return self.client.wsdl.dump() def create_database(self, database): """ Create database Parameters ---------- database: str name of database instance (eg. 'Myanmar') """ if not hasattr(self, "dataservice"): self.errors.nosetDataservice() parameters = { "uid": self.uid, "database":database} payload = {'function':'dataportal.db.createdatabase','parameters':json.dumps(parameters)} r = requests.get(self._call, payload) return r.json() def info(self, database): """ Check database info Parameters ---------- database: str name of database instance (eg. 'Myanmar') """ if not hasattr(self, "dataservice"): self.errors.noset_dataservice() parameters = {"database":database} payload = {'function':'dataportal.db.getinfo','parameters':json.dumps(parameters)} r = requests.get(self._call, payload) return r.json() def new_entry(self, database, key, data, description="", info_db=False): """ Set/create/insert a NEW entry in database. This does not overwrite, or update existing entries. Use update_entry for updating existing entries Parameters ---------- database: str name of database instance (eg. 'Myanmar') key: str key to identify datarecord in the database (eg. 'parameter|location|unit') data: obj object to store in the datarecord (eg. JSON object) description: str description of the datarecord (default = '') info_db: boolean if True also output debug information from the database """ data = self.serialize_data(data) if not hasattr(self, "dataservice"): self.errors.noset_dataservice() parameters = { "uid":self.uid, "database":database, "key":key, "description":description} zeep_out = self.client.service.CallBytes(function="dataportal.db.createentry", parameters=json.dumps(parameters), bytes=data) self.get_url(database, key) if info_db: return json.loads(zeep_out.text) def update_entry(self, database, key, data, description="", info_db=False): """ Update existing entry in database Parameters ---------- database: str name of database instance (eg. 'Myanmar') key: str key to identify datarecord in the database (eg. 'parameter|location|unit') data: obj object to store in the datarecord (eg. JSON object) description: str description of the datarecord (default = '') info_db: boolean if True also output debug information from the database """ data = self.serialize_data(data) if not hasattr(self, "dataservice"): self.errors.noset_dataservice() parameters = { "uid": self.uid, "database":database, "key":key, "description":description} zeep_out = self.client.service.CallBytes(function="dataportal.db.UpdateEntry", parameters=json.dumps(parameters), bytes=data) self.get_url(database, key) if info_db: return json.loads(zeep_out.text) def get_entry( self, database, key, content_type="application/json" ): """ Get entry after create/insert Parameters ---------- database: str name of database instance (eg. 'Myanmar') key: str key to identify datarecord in the database (eg. 'parameter|location|unit') content_type: str set the contentType to make the browser render the output correctly csv : application/csv json : application/json html : text/html """ if not hasattr(self, "dataservice"): self.errors.noset_dataservice() url = self.get_url(database, key, content_type) r = requests.get(url) # check for errors if r.text == 'database does not exists': self.errors.database_not_exist() elif r.text == 'Object reference not set to an instance of an object.': self.errors.key_not_exist() # parse input dta if "json" in content_type: output = pd.read_json(r.content.decode()) elif "html" in content_type: from IPython.display import IFrame output = IFrame(url, width='100%', height=350) elif "csv" in content_type: output = pd.read_csv(io.StringIO(r.content.decode("utf-8"))) elif "png" in content_type: from PIL import Image from IPython.display import display img = Image.open(io.BytesIO(r.content)) output = display(img) elif "svg" in content_type: from IPython.display import SVG, display output = display(SVG(r.content.decode())) elif "xml" in content_type: from .untangle import parse_raw output = parse_raw(r.content.decode()) else: try: output = r.content.decode() except UnicodeDecodeError: import chardet output = chardet.detect(r.content) return output def delete_entry(self, database, key): """ Delete entry from database Parameters ---------- database: str name of database instance (eg. 'Myanmar') key: str key to identify datarecord in the database (eg. 'parameter|location|unit') """ # delete data from database parameters = { "uid": self.uid, "database":database, "key":key} payload = {'function':'dataportal.db.DeleteEntry','parameters':json.dumps(parameters)} r = requests.get(self._call, payload) return r.json() PKJK,+hkvportal/untangle.py#!/usr/bin/env python """ untangle Converts xml to python objects. The only method you need to call is parse() Partially inspired by xml2obj (http://code.activestate.com/recipes/149368-xml2obj/) Author: Christian Stefanescu (http://0chris.com) License: MIT License - http://www.opensource.org/licenses/mit-license.php """ import os from xml.sax import make_parser, handler try: from StringIO import StringIO except ImportError: from io import StringIO try: from types import StringTypes is_string = lambda x: isinstance(x, StringTypes) except ImportError: is_string = lambda x: isinstance(x, str) __version__ = '1.1.1' class Element(object): """ Representation of an XML element. """ def __init__(self, name, attributes): self._name = name self._attributes = attributes self.children = [] self.is_root = False self.cdata = '' def add_child(self, element): """ Store child elements. """ self.children.append(element) def add_cdata(self, cdata): """ Store cdata """ self.cdata = self.cdata + cdata def get_attribute(self, key): """ Get attributes by key """ return self._attributes.get(key) def get_elements(self, name=None): """ Find a child element by name """ if name: return [e for e in self.children if e._name == name] else: return self.children def __getitem__(self, key): return self.get_attribute(key) def __getattr__(self, key): matching_children = [x for x in self.children if x._name == key] if matching_children: if len(matching_children) == 1: self.__dict__[key] = matching_children[0] return matching_children[0] else: self.__dict__[key] = matching_children return matching_children else: raise AttributeError( "'%s' has no attribute '%s'" % (self._name, key) ) def __hasattribute__(self, name): if name in self.__dict__: return True return any(self.children, lambda x: x._name == name) def __iter__(self): yield self def __str__(self): return ( "Element <%s> with attributes %s, children %s and cdata %s" % (self._name, self._attributes, self.children, self.cdata) ) def __repr__(self): return ( "Element(name = %s, attributes = %s, cdata = %s)" % (self._name, self._attributes, self.cdata) ) def __nonzero__(self): return self.is_root or self._name is not None def __eq__(self, val): return self.cdata == val def __dir__(self): children_names = [x._name for x in self.children] return children_names def __len__(self): return len(self.children) class Handler(handler.ContentHandler): """ SAX handler which creates the Python object structure out of ``Element``s """ def __init__(self): self.root = Element(None, None) self.root.is_root = True self.elements = [] def startElement(self, name, attributes): name = name.replace('-', '_') name = name.replace('.', '_') name = name.replace(':', '_') attrs = dict() for k, v in attributes.items(): attrs[k] = v element = Element(name, attrs) if len(self.elements) > 0: self.elements[-1].add_child(element) else: self.root.add_child(element) self.elements.append(element) def endElement(self, name): self.elements.pop() def characters(self, cdata): self.elements[-1].add_cdata(cdata) def parse(filename, **parser_features): """ Interprets the given string as a filename, URL or XML data string, parses it and returns a Python object which represents the given document. Extra arguments to this function are treated as feature values to pass to ``parser.setFeature()``. For example, ``feature_external_ges=False`` will set ``xml.sax.handler.feature_external_ges`` to False, disabling the parser's inclusion of external general (text) entities such as DTDs. Raises ``ValueError`` if the first argument is None / empty string. Raises ``AttributeError`` if a requested xml.sax feature is not found in ``xml.sax.handler``. Raises ``xml.sax.SAXParseException`` if something goes wrong during parsing. """ if (filename is None or (is_string(filename) and filename.strip()) == ''): raise ValueError('parse() takes a filename, URL or XML string') parser = make_parser() for feature, value in parser_features.items(): parser.setFeature(getattr(handler, feature), value) sax_handler = Handler() parser.setContentHandler(sax_handler) if is_string(filename) and (os.path.exists(filename) or is_url(filename)): parser.parse(filename) else: if hasattr(filename, 'read'): parser.parse(filename) else: parser.parse(StringIO(filename)) return sax_handler.root def parse_raw(xml, **parser_features): """ Parses the given string as an XML data string, returning a Python object which represents the document. Raises ``ValueError`` if the argument is None / empty string. Raises ``xml.sax.SAXParseException`` if something goes wrong during parsing. """ if (xml is None or not is_string(xml) or xml.strip() == ''): raise ValueError('parse_raw() takes an XML string') parser = make_parser() sax_handler = Handler() parser.setContentHandler(sax_handler) parser.parse(StringIO(xml)) return sax_handler.root def is_url(string): """ Checks if the given string starts with 'http(s)'. """ try: return string.startswith('http://') or string.startswith('https://') except AttributeError: return False # vim: set expandtab ts=4 sw=4: PK|Kmhkvportal-0.4.dist-info/LICENSEBSD 3-Clause License Copyright (c) 2017, All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. PK!Hp!Qahkvportal-0.4.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,zd&Y)r$[)T&UD"PK!H r? hkvportal-0.4.dist-info/METADATAMN0~=|␠iu?Hpo4bQ)&ItHpcVE'0~A d 8jM) M)J7"Rd]zAXZ;>Ŕ4EK_e4e?̻;?[xӫJӣ'.Ss I&Bp[Z^Q/vm@L6JHC'u:z#@&:͸'\KL+['IW[]6+>$I#mnumOu+Re`߷+'h/);yc݂ 0oM>` 5A2^IכJK927hьm3[|PKws1O%ɲgghkvportal/__init__.pyPKKo1Oԝ%%hkvportal/services.pyPKJK,+&hkvportal/untangle.pyPK|Km>hkvportal-0.4.dist-info/LICENSEPK!Hp!QaEhkvportal-0.4.dist-info/WHEELPK!H r? Ehkvportal-0.4.dist-info/METADATAPK!HibYFhkvportal-0.4.dist-info/RECORDPK@H