Beispiel #1
0
    def publish_to_agol(self,
                        mxd_path,
                        service_name,
                        tags="None",
                        description="None"):
        """ publishes a service to AGOL """
        mxd = mapping.MapDocument(mxd_path)
        sddraftFolder = env.scratchFolder + os.sep + "draft"
        sdFolder = env.scratchFolder + os.sep + "sd"
        sddraft = sddraftFolder + os.sep + service_name + ".sddraft"
        sd = sdFolder + os.sep + "%s.sd" % service_name
        mxd = self._prep_mxd(mxd)
        if os.path.isdir(sddraftFolder) == False:
            os.makedirs(sddraftFolder)
        else:
            shutil.rmtree(sddraftFolder, ignore_errors=True)
            os.makedirs(sddraftFolder)
        if os.path.isfile(sddraft):
            os.remove(sddraft)
        analysis = mapping.CreateMapSDDraft(mxd, sddraft, service_name,
                                            "MY_HOSTED_SERVICES")
        sddraft = self._modify_sddraft(sddraft)
        analysis = mapping.AnalyzeForSD(sddraft)
        if os.path.isdir(sdFolder):
            shutil.rmtree(sdFolder, ignore_errors=True)
            os.makedirs(sdFolder)
        else:
            os.makedirs(sdFolder)
        if analysis['errors'] == {}:
            # Stage the service
            arcpy.StageService_server(sddraft, sd)
            print "Created {}".format(sd)

        else:
            # If the sddraft analysis contained errors, display them and quit.
            print analysis['errors']
            sys.exit()
        # POST data to site
        content = self.getUserContent()
        #Title, item
        for item in content['items']:
            if item['title'] == service_name and \
               item['item'] == os.path.basename(sd):
                print self.deleteItem(item['id'])
            elif item['title'] == service_name:
                print self.deleteItem(item['id'])

        self._agol_id = self._upload_sd_file(sd,
                                             service_name=service_name,
                                             tags=tags,
                                             description=description)

        if self._agol_id != "Error Uploadings":
            p_vals = self._publish(self._agol_id)
            for service in p_vals['services']:
                print self.enableSharing(service['serviceItemId'])
                del service
            del p_vals
        del mxd
def make_sd_draft(MXD, serviceName, tempDir):
    """Ceate a draft SD and modify the properties to overwrite an existing FS."""
    ARCPY.env.overwriteOutput = True
    # All paths are built by joining names to the tempPath
    SDdraft = OS.path.join(tempDir, "drought.sddraft")
    newSDdraft = OS.path.join(tempDir, "droughtupdated.sddraft")

    MAP.CreateMapSDDraft(MXD, SDdraft, serviceName, "MY_HOSTED_SERVICES")

    # Read the contents of the original SDDraft into an xml parser
    doc = ET.parse(SDdraft)

    root_elem = doc.getroot()
    if root_elem.tag != "SVCManifest":
        raise ValueError(
            "Root tag is incorrect. Is {} a .sddraft file?".format(SDDraft))

    # Change service type from map service to feature service
    for config in doc.findall("./Configurations/SVCConfiguration/TypeName"):
        if config.text == "MapServer":
            config.text = "FeatureServer"

    #Turn off caching
    for prop in doc.findall("./Configurations/SVCConfiguration/Definition/" +
                            "ConfigurationProperties/PropertyArray/" +
                            "PropertySetProperty"):
        if prop.find("Key").text == 'isCached':
            prop.find("Value").text = "false"

    for prop in doc.findall(
            "./Configurations/SVCConfiguration/Definition/Extensions/SVCExtension"
    ):
        if prop.find("TypeName").text == 'KmlServer':
            prop.find("Enabled").text = "false"

    # Turn on feature access capabilities
    for prop in doc.findall(
            "./Configurations/SVCConfiguration/Definition/Info/PropertyArray/PropertySetProperty"
    ):
        if prop.find("Key").text == 'WebCapabilities':
            prop.find(
                "Value").text = "Query,Create,Update,Delete,Uploads,Editing"

    # Add the namespaces which get stripped, back into the .SD
    root_elem.attrib[
        "xmlns:typens"] = 'http://www.esri.com/schemas/ArcGIS/10.1'
    root_elem.attrib["xmlns:xs"] = 'http://www.w3.org/2001/XMLSchema'

    # Write the new draft to disk
    with open(newSDdraft, 'w') as f:
        doc.write(f, 'utf-8')

    return newSDdraft
Beispiel #3
0
    def CreateSddraft(self,mapDocPath,con,serviceName,copy_data_to_server=True,folder=None):
        """
        :param mapDocPath: mxd path
        :param con: arcgis server connection file
        :param serviceName: service name
        :param clusterName: cluster name
        :param folder: folder to contain the publishing service
        :return: the file path of the sddraft
        """

        mapDoc=mapping.MapDocument(mapDocPath)
        sddraft=mapDocPath.replace(".mxd",".sddraft")
        result= mapping.CreateMapSDDraft(mapDoc, sddraft, serviceName, 'ARCGIS_SERVER', con, copy_data_to_server, folder)
        return sddraft
Beispiel #4
0
def MXDtoFeatureServiceDef(
        mxd_path,
        service_name=None,
        tags=None,
        description=None,
        folder_name=None,
        capabilities='Query,Create,Update,Delete,Uploads,Editing,Sync',
        maxRecordCount=1000,
        server_type='MY_HOSTED_SERVICES'):
    """
        converts an MXD to a service defenition
        Inputs:
            mxd_path - Path to the ArcMap Map Document(MXD)
            service_name - Name of the Feature Service
            tags - Tags for the service, if none, the tags from the MXD are used
            description - Summary for the Feature Service, if none, info from the MXD is used
            folder_name - Folder in the Data store
            capabilities - A Comma delimited list of feature service capabolities 'Query,Create,Update,Delete,Uploads,Editing,Sync'
            maxRecordCount - The max returned record count for the feature service
            server_type - The type of connection or publishing server
                  Values: ARCGIS_SERVER | FROM_CONNECTION_FILE | SPATIAL_DATA_SERVER | MY_HOSTED_SERVICES
        Output:
            Service Definition File - *.sd

    """
    if not os.path.isabs(mxd_path):
        sciptPath = os.getcwd()
        mxd_path = os.path.join(sciptPath, mxd_path)

    mxd = mapping.MapDocument(mxd_path)
    sddraftFolder = env.scratchFolder + os.sep + "draft"
    sdFolder = env.scratchFolder + os.sep + "sd"
    sddraft = sddraftFolder + os.sep + service_name + ".sddraft"
    sd = sdFolder + os.sep + "%s.sd" % service_name
    mxd = _prep_mxd(mxd)

    res = {}

    if service_name is None:
        service_name = mxd.title.strip().replace(' ', '_')
    if tags is None:
        tags = mxd.tags.strip()

    if description is None:
        description = mxd.description.strip()

    if os.path.isdir(sddraftFolder) == False:
        os.makedirs(sddraftFolder)
    else:
        shutil.rmtree(sddraftFolder, ignore_errors=True)
        os.makedirs(sddraftFolder)
    if os.path.isfile(sddraft):
        os.remove(sddraft)

    res['service_name'] = service_name
    res['tags'] = tags
    res['description'] = description
    analysis = mapping.CreateMapSDDraft(map_document=mxd,
                                        out_sddraft=sddraft,
                                        service_name=service_name,
                                        server_type=server_type,
                                        connection_file_path=None,
                                        copy_data_to_server=False,
                                        folder_name=folder_name,
                                        summary=description,
                                        tags=tags)

    sddraft = _modify_sddraft(sddraft=sddraft,
                              capabilities=capabilities,
                              maxRecordCount=maxRecordCount)
    analysis = mapping.AnalyzeForSD(sddraft)
    if os.path.isdir(sdFolder):
        shutil.rmtree(sdFolder, ignore_errors=True)
        os.makedirs(sdFolder)
    else:
        os.makedirs(sdFolder)
    if analysis['errors'] == {}:
        # Stage the service
        arcpy.StageService_server(sddraft, sd)
        res['servicedef'] = sd
        return res
    else:
        # If the sddraft analysis contained errors, display them and quit.
        print analysis['errors']
        return None
import arcpy
import arcpy.mapping as mapping
wrkspc =r'D:\\bysj\\data\\service'
mxd=mapping.MapDocument(wrkspc+r'\\max4.mxd')
service='max4'
sddraft=wrkspc+service+'.sddraft'
mapping.CreateMapSDDraft(mxd,sddraft,service)
analysis=mapping.AnalyzeForSD(wrkspc+'max4.sddraft')
if analysis['errors']=={}:
    arcpy.StageService_server(sddraft,sd)