Example #1
0
 def _init(self):
     """initializer"""
     try:
         res = self._con.get(self._url, {'f': 'json'})
         self._property = PropertyMap(res)
     except Exception as e:
         self._property = PropertyMap({})
Example #2
0
 def _init(self, connection=None):
     """Loads the properties into the class."""
     if connection is None:
         connection = self._con
     attributes = [attr for attr in dir(self)
                   if not attr.startswith('__') and \
                   not attr.startswith('_')]
     params = {"f": "json"}
     try:
         result = connection.get(path=self._url, params=params)
         if isinstance(result, dict):
             if 'machines' in result:
                 self._machines = []
                 for m in result['machines']:
                     self._machines.append(
                         Machine(url=self._url + "/%s" % m['machineName'],
                                 gis=self._con))
             self._json_dict = result
             self._properties = PropertyMap(result)
         else:
             self._json_dict = {}
             self._properties = PropertyMap({})
     except:
         self._json_dict = {}
         self._properties = PropertyMap({})
Example #3
0
 def _init(self):
     """loads the properties"""
     try:
         params = {'f': 'json'}
         res = self._con.get(self._url, params)
         self._properties = PropertyMap(res)
     except:
         self._properties = PropertyMap({})
Example #4
0
 def _init(self):
     """loads the properties"""
     try:
         self._properties = PropertyMap(
             self._con.get(self._url, {'f': 'json'}))
     except:
         self._properties = PropertyMap(
             self._con.post(self._url, {'f': 'json'}))
Example #5
0
 def properties(self):
     """returns the properties of the IDP configuration"""
     if self._properties is None:
         params = {'f': 'json'}
         res = self._gis._con.get(path=self._url, params=params)
         try:
             self._properties = PropertyMap(res)
         except:
             self._properties = PropertyMap({})
     return self._properties
Example #6
0
 def properties(self):
     """returns the social providers configurations"""
     try:
         if self._properties is None:
             res = self._portal.con.get(path=self._url,
                                        params={'f': 'json'})
             self._properties = PropertyMap(res)
         return self._properties
     except:
         self._properties = PropertyMap({})
         return self._properties
Example #7
0
 def properties(self):
     """returns the properties of the datastore"""
     if self._properties is None:
         params = {'f' : 'json'}
         res = self._con.get(self._url, params)
         self._properties = PropertyMap(res)
     return self._properties
Example #8
0
    def properties(self) -> PropertyMap:
        """
        Returns the properties of the Layer.
        
        :returns: PropertyMap
        """
        if self._properties is None:

            if self._add_token:
                url = self._capabilities_url(
                    service_url=self._url,
                    vendor_kwargs={'token': self._con.token})
            else:
                url = self._capabilities_url(service_url=self._url)
            text = self._con.get(url, {}, try_json=False, add_token=False)
            if text.find("Invalid Token") > -1 or text.find("Get Token") > -1:
                url = self._capabilities_url(service_url=self._url)
                text = self._con.get(url, {}, try_json=False, add_token=False)
            elif text.lower().find("<html>") > -1:
                url = self._capabilities_url(service_url=self._url)
                text = self._con.get(url, {}, try_json=False, add_token=False)
            elif text.lower().find("<?xml version=\"1.0\" ?>") > -1:
                pass
            else:
                raise Exception("Could not connect to the Web Map Service")
            sss = BytesIO()
            sss.write(text.encode())
            sss.seek(0)
            tree = ET.XML(text=sss.read())
            d = self._xml_to_dictionary(tree)
            self._properties = PropertyMap(d)
        return self._properties
Example #9
0
    def properties(self):
        """returns the properties of the service"""
        if self._properties is None:

            res = self._con.get(self._url, {'f':'json'})
            self._properties = PropertyMap(res)
        return self._properties
Example #10
0
    def update(self, indicator_properties=None):
        """
        Updates properties of an initiative

        :return:
            A bool containing True (for success) or False (for failure). 

        .. code-block:: python

            USAGE EXAMPLE: Update an indicator successfully

            indicator1_data = indicator1.get_data()
            indicator1_data['optional'] = False
            indicator1.update(indicator_properties = indicator1_data)

            >> True

            Refer the indicator definition (`get_data()`) to learn about fields that can be 
            updated and their acceptable data format.

        """
        try:
            _indicatorId = indicator_properties['id']
        except:
            return 'Indicator properties must include id of indicator'
        if indicator_properties is not None:
            self._initiativedata['indicators'] = [dict(indicator_properties) if indicator['id']==_indicatorId else indicator for indicator in self._initiativedata['indicators']]
            _new_initiativedata = json.dumps(self._initiativedata)
            status = self._initiativeItem.update(item_properties={'text': _new_initiativedata})      
            if status:
                self.definition = PropertyMap(indicator_properties)
                return status
Example #11
0
 def properties(self):
     """
     Returns the properties of the Layer.
     
     :returns: PropertyMap
     """
     return PropertyMap(self._esri_json)
Example #12
0
 def __init__(self, gis, eventObject):
     """
     Constructs an empty Event object
     """
     self._gis = gis
     self._eventgeometry = eventObject.geometry
     self._eventdict = eventObject.attributes
     pmap = PropertyMap(self._eventdict)
     self.definition = pmap
Example #13
0
 def __init__(self, initiativeItem, indicatorObject):
     """
     Constructs an empty Indicator object
     """
     self._initiativeItem = initiativeItem
     self._initiativedata = self._initiativeItem.get_data()
     self._indicatordict = indicatorObject
     pmap = PropertyMap(self._indicatordict)
     self.definition = pmap
    def info(self):
        """
        Returns information about the server site itself

        :returns: PropertyMap

        """
        url = self._url + "/info"
        params = {'f': 'json'}
        res = self._gis._con.get(url, params)
        return PropertyMap(res)
Example #15
0
 def __init__(self, gis, pageItem):
     """
     Constructs an empty Page object
     """
     self.item = pageItem
     self._gis = gis
     try:
         self._pagedict = self.item.get_data()
         pmap = PropertyMap(self._pagedict)
         self.definition = pmap
     except:
         self.definition = None
Example #16
0
    def settings(self):
        """
        Get/set the current log settings.

        :returns: PropertyMap
        """
        params = {"f": "json"}
        url = self._url + "/settings"
        try:
            res = self._con.get(url, params)
            return PropertyMap(res)
        except:
            return ""
 def _init(self, connection=None):
     """loads the properties into the class"""
     if connection is None:
         connection = self._con
     params = {"f": "json"}
     try:
         result = connection.get(path=self._url, params=params)
         if isinstance(result, dict):
             self._json_dict = result
             self._properties = PropertyMap(result)
         else:
             self._json_dict = {}
             self._properties = PropertyMap({})
     except HTTPError as err:
         raise RuntimeError(err)
     except:
         self._json_dict = {}
         self._properties = PropertyMap({})
class BaseServer(object):
    """class most server object inherit from"""
    _con = None
    _url = None
    _json_dict = None
    _json = None
    _properties = None

    def __init__(self, url, gis=None, initialize=True, **kwargs):
        """class initializer"""
        if gis is None and 'connection' in kwargs:
            connection = kwargs['connection']
            gis = kwargs.pop('connection', None)
        super(BaseServer, self).__init__()
        self._url = url

        #gis = kwargs.pop('gis', None)
        if gis is None and \
           isinstance(gis, GIS):
            gis = gis._portal.con

        if isinstance(gis, (ServerConnection, _ArcGISConnection)):
            self._con = gis
        elif hasattr(gis, '_con'):
            self._gis = gis._con
        else:
            raise ValueError("gis must be of type SiteConnection")
        if initialize:
            self._init(gis)

    #----------------------------------------------------------------------
    def _init(self, connection=None):
        """loads the properties into the class"""
        if connection is None:
            connection = self._con
        params = {"f": "json"}
        try:
            result = connection.get(path=self._url, params=params)
            if isinstance(result, dict):
                self._json_dict = result
                self._properties = PropertyMap(result)
            else:
                self._json_dict = {}
                self._properties = PropertyMap({})
        except HTTPError as err:
            raise RuntimeError(err)
        except:
            self._json_dict = {}
            self._properties = PropertyMap({})

    #----------------------------------------------------------------------
    def __str__(self):
        return '<%s at %s>' % (type(self).__name__, self._url)

    #----------------------------------------------------------------------
    def __repr__(self):
        return '<%s at %s>' % (type(self).__name__, self._url)

    #----------------------------------------------------------------------
    @property
    def properties(self):
        """
        returns the object properties
        """
        if self._properties is None:
            self._init()
        return self._properties

    #----------------------------------------------------------------------
    def __getattr__(self, name):
        """adds dot notation to any class"""
        if self._properties is None:
            self._init()
        try:
            return self._properties.__getitem__(name)
        except:
            for k, v in self._json_dict.items():
                if k.lower() == name.lower():
                    return v
            raise AttributeError("'%s' object has no attribute '%s'" %
                                 (type(self).__name__, name))

    #----------------------------------------------------------------------
    def __getitem__(self, key):
        """helps make object function like a dictionary object"""
        try:
            return self._properties.__getitem__(key)
        except KeyError:
            for k, v in self._json_dict.items():
                if k.lower() == key.lower():
                    return v
            raise AttributeError("'%s' object has no attribute '%s'" %
                                 (type(self).__name__, key))
        except:
            raise AttributeError("'%s' object has no attribute '%s'" %
                                 (type(self).__name__, key))

    #----------------------------------------------------------------------
    @property
    def url(self):
        """gets/sets the service url"""
        return self._url

    #----------------------------------------------------------------------
    @url.setter
    def url(self, value):
        """gets/sets the service url"""
        self._url = value
        self.refresh()

    #----------------------------------------------------------------------
    def __iter__(self):
        """creates iterable for classes properties"""
        for k, v in self._json_dict.items():
            yield k, v

    #----------------------------------------------------------------------
    def _refresh(self):
        """reloads all the properties of a given service"""
        self._init()
Example #19
0
 def _refresh(self):
     params = {"f": "json"}
     dictdata = self._con.get(path=self.url,
                              params=params,
                              token=self._con.token)  # token=self._token)
     self.properties = PropertyMap(dictdata)
Example #20
0
 def _init(self):
     """initializer"""
     params = {'f': 'json'}
     res = self._con.get(self._url, params)
     self._properties = PropertyMap(res)
Example #21
0
def import_toolbox(url_or_item, gis=None, verbose=False):
    """
    Imports geoprocessing toolboxes as native Python modules.
    You can call the functions available in the imported module to invoke these tools.


        ================  ========================================================
        **Argument**      **Description**
        ----------------  --------------------------------------------------------
        url_or_item       location of toolbox, can be a geoprocessing server url
                          or Item of type: Geoprocessing Service
        ----------------  --------------------------------------------------------
        gis               optional GIS, the GIS used for running the tool.
                          arcgis.env.active_gis is used if not specified
        ----------------  --------------------------------------------------------
        verbose           optional bool, set to True to print the generated module
        ================  ========================================================

    Returns module with functions for the various tools in the toolbox

    """
    tbx = None
    url = url_or_item
    gis = arcgis.env.active_gis if gis is None else gis
    if isinstance(url_or_item, Item):
        #tbx = Toolbox.fromitem(url_or_item)
        url = url_or_item.url
    else:
        url = url_or_item

    if not url.endswith('/GPServer'):
        idx = url.index('/GPServer')
        url = url[0:idx + len('/GPServer')]

    tbx = _AsyncResource(url, gis)

    src_code = """import logging as _logging
import arcgis
from datetime import datetime
from arcgis.features import FeatureSet
from arcgis.mapping import MapImageLayer
from arcgis.geoprocessing import DataFile, LinearUnit, RasterData
from arcgis.geoprocessing._support import _execute_gp_tool
import concurrent.futures

_log = _logging.getLogger(__name__)
    """
    try:
        execution_type = tbx.properties.executionType
    except:
        from arcgis.gis import GIS
        return import_toolbox(url_or_item=url_or_item,
                              gis=GIS(),
                              verbose=verbose)
    use_async = True
    if execution_type == 'esriExecutionTypeSynchronous':
        use_async = False

    src_code += '\n_url = "' + url + '"'
    src_code += '\n_use_async = ' + str(use_async) + '\n\n'
    listed_params = {}
    if len(tbx.properties.tasks) < 4:
        for task in tbx.properties.tasks:
            fn_src, choice_list, func_name = _generate_fn(task, tbx)
            src_code += fn_src
            listed_params[func_name] = choice_list
    else:
        source = []
        import concurrent.futures
        with concurrent.futures.ThreadPoolExecutor(8) as executor:

            for task in tbx.properties.tasks:
                #_generate_fn(task, tbx)
                f = executor.submit(fn=_generate_fn,
                                    **{
                                        "task": task,
                                        "tbx": tbx
                                    })
                source.append(f)
        for fnsrc in source:
            fn_src, choice_list, func_name = fnsrc.result()
            src_code += fn_src
            listed_params[func_name] = choice_list
    if len(listed_params) == 0:
        listed_params = None
    else:
        listed_params = PropertyMap(listed_params)

    return _import_code(src_code, 'name', verbose, choice_list=listed_params)
Example #22
0
 def _init(self):
     result = self._con.get(self._url, {'f': 'json'})
     self._properties = PropertyMap(result)
Example #23
0
 def _init(self):
     """Constructor"""
     if self._properties is None:
         self._properties = PropertyMap(
             self._con.get(self._url, {'f': 'json'}))
Example #24
0
 def _init(self):
     """loads the properties"""
     self._properties = None
     res = self._con.get(self._url, {'f' : 'json'})
     self._properties = PropertyMap(res)