2 votos

Listar los nombres de las capas desde el servicio de Mapas usando python

Estoy tratando de obtener una lista de nombres de capas dentro de nuestros servicios de descanso para todos los servicios y carpetas. Tengo dos códigos que estoy tratando de poner juntos y por alguna razón el código de la capa no se ve a trabajar dentro del código de servicio de mapa. Cualquier sugerencia sería genial. Estoy corriendo en un servidor 10.2.

import urllib2, json

server = "hcs084mcgida901"
port = "6080"
baseUrl = "http://gisdev.mcgi.state.mi.us/arcgis/rest/services".format(server, port)

def serviceLayers(URL): 
    fURL = URL + "/" + "?f=json"
    openURL = urllib2.urlopen(fURL, '').read()   
    outJson = json.loads(openURL)   
    return outJson["services"]   

if __name__ == "__main__":
    URL = "http://gisdev.mcgi.state.mi.us/arcgis/rest/services".format(folder)

def getCatalog():
    catalog = json.load(urllib2.urlopen(baseUrl + "/" + "?f=json"))
    print 'ROOT' 
    if "error" in catalog: return
    services = catalog['services']
    for service in services:
    response = json.load(urllib2.urlopen(baseUrl + '/' + service['name'] + '/' + service['type'] + "?f=json"))
    print '  %s %s (%s)' % (service['name'], service['type'], 'ERROR' if "error" in response else 'SUCCESS')
    folders = catalog['folders']      
    for folderName in folders:
        catalog = json.load(urllib2.urlopen(baseUrl + "/" + folderName + "?f=json"))
        print folderName
        if "error" in catalog: return
        services = catalog['services']
    for service in services: 
        response = json.load(urllib2.urlopen(baseUrl + '/' + service['name'] + '/' + service['type'] + "?f=json"))
        services = serviceLayers(URL)
    for f in services:   
       print '  %s %s (%s)' % (service['name'], service['type'], 'ERROR' if "error" in response else 'SUCCESS'), "Layer : {}".format(f["name"])   

getCatalog()

4voto

steveax Puntos 316

Yo uso solicita para hacer cosas como esta:

import requests

def _post(service, _params={'f': 'pjson'}, ret_json=True):
    """Post Request to REST Endpoint

    Required:
    service -- full path to REST endpoint of service

    Optional:
    _params -- parameters for posting a request
    ret_json -- return the response as JSON.  Default is True.
    """
    r = requests.post(service, params=_params, verify=False)

    # make sure return
    if r.status_code != 200:
        raise NameError('"{0}" service not found!\n{1}'.format(service, r.raise_for_status()))
    else:
        if ret_json:
            return r.json()
        else:
            return r

def list_services(service='http://server.arcgisonline.com/arcgis/rest/services'):
    """returns a list of all services

    Optional:
    service -- full path to a rest service
    """
    all_services = []
    r = _post(service)
    for s in r['services']:
        all_services.append('/'.join([service, s['name'], s['type']]))
    for s in r['folders']:
        new = '/'.join([service, s])
        endpt = _post(new)
        for serv in endpt['services']:
           all_services.append('/'.join([service, serv['name'], serv['type']]))
    return all_services

def list_layers(service):
    """lists all layers in a mapservice

    Returns a list of field objects with the following properties:
        name -- name of layer
        id -- layer id (int)
        minScale -- minimum scale range at which layer draws
        maxScale -- maximum scale range at which layer draws
        defaultVisiblity -- the layer is visible (bool)
        parentLayerId -- layer id of parent layer if in group layer (int)
        subLayerIds -- list of id's of all child layers if group layer (list of int's)

    Required:
    service -- full path to mapservice
    """
    r = _post(service)
    if 'layers' in r:
        return [layer(p) for p in r['layers']]
    return

def list_tables(service):
    """List all tables in a MapService"""
    r = _post(service)
    if 'tables' in r:
        return [table(p) for p in r['tables']]
    return None

class layer:
    """class to handle layer info"""
    def __init__(self, lyr_dict):
        for key, value in lyr_dict.items():
            setattr(self, key, value)

class table:
    """class to handle table info"""
    def __init__(self, tab_dict):
        for key, value in tab_dict.items():
            setattr(self, key, value)

if __name__ == '__main__':

    for serv in list_services():
        print serv
        print 'Layers:\n'
        for lyr in [l.name for l in list_layers(serv)]:
            print lyr
        print '\n\n'

i-Ciencias.com

I-Ciencias es una comunidad de estudiantes y amantes de la ciencia en la que puedes resolver tus problemas y dudas.
Puedes consultar las preguntas de otros usuarios, hacer tus propias preguntas o resolver las de los demás.

Powered by:

X