Calling Python Code from ARC GIS Pro

333
4
02-11-2021 08:01 AM
NischalKashyap
New Contributor

Hello,

I'm new to using ArcGIS Pro, so if I have framed the question in the wrong manner, please oblige! Any kind of insights would be really helpful.

Query: I have a front end on the ArcGIS Pro which has a United States Map being displayed to the user. Ther is a layer of US Counties embedded onto the map. So now the user can see all the counties on the US Map. The user can interact with the map by clicking on the map. Now my question is as follows :

Let's say a User clicks on Wake County in NC. I have a python code that runs at the back end on a server, lets say I created this on an ArcGIS Server. Can I send an HTTP Request or any sort of API request from the front end to the Python Code in which one of the API accepts County Name as the input parameter. Here on clicking on Wake County, the API has to be called with the parameter as "Wake County".

Can we do this on ArcGIS Pro. If Yes, can you briefly explain? Also, it would be helpful If you could route me to the resources/videos/documentation which would actually help me understand by reading it.

If no, any alternatives?

0 Kudos
4 Replies
MatthewDriscoll
MVP Regular Contributor

Perhaps look into creating an add-in for this.

https://pro.arcgis.com/en/pro-app/latest/sdk/

 

JohannesLindner
MVP Regular Contributor
  • "I have a front end on the ArcGIS Pro" - Does this mean your users work with the actual ArcGIS Pro, or have you built a web map / web app?
  • "Can I send an HTTP Request or any sort of API request from the front end to the Python Code"
    • In ArcGIS Pro, your users could use the Python window to manually type in the code. AFAIK, there is no way to execute Python code by clicking on a feature.
    • If you built a custom web app, you might be able to do something like that by using the javascript API.
  • Alternatives:
    • Build an addon for ArcGIS Pro
    • Build a geoprocessing tool for ArcGIS Pro. The user selects a county in the map and then runs the tool. The tool searches the layer (either given as input by the user or hard coded if it's always the same) and only finds the selected feature(s). Then you can run your existing python code using the found values.
    • Depending on the complexity of what you want to do with the county, defining a popup might do the trick. Arcade can do some great stuff.

From your question, it sounds like the popup solution would be the most comfortable for your users. What does your Python code do?


Have a great day!
Johannes
0 Kudos
NischalKashyap
New Contributor

Does this mean your users work with the actual ArcGIS Pro, or have you built a web map / web app? - They have to work and choose on ArcGIS Pro!

 

From your question, it sounds like the popup solution would be the most comfortable for your users. What does your Python code do? - So u can imagine like this! A person clicks on Washington DC and one of my API In python receives this city as the input! The input is queried in a database(say MySQL or tables on geodatabase) and gives back various flight connections between Washington DC and other cities! I give these links back to the UI and the UI should display these links!

This is my main aim in the project!

Any leads will be helpful!

 

0 Kudos
JohannesLindner
MVP Regular Contributor

If your flight tables are in the same datastore as the county layer, it should be doable with a popup. I wouldn't do it, though, because it is quite complex, it would be lots of work converting your Python code to Arcade and the Arcade code wouldn't be very maintainable.

If you want to look into it, these would be starting points:

 

In your case, I would create a Python toolbox. This way, you can use your existing code, and it's not too much extra work for your users.

The only problem is that you can't display clickable HTML links in the tool messages. Possible workaround: Modify your existing code, so that it builds an HTML document and then open that document in the user's default browser.

 

# Toolbox.pyt
# File can be created from ArcGIS Pro Catalog

import arcpy
import os
import webbrowser


class Toolbox(object):
    def __init__(self):
        self.label = "Toolbox"
        self.alias = ""
        self.tools = [Tool]


class Tool(object):
    def __init__(self):
        self.label = "Tool"
        self.description = ""
        self.canRunInBackground = False


    def getParameterInfo(self):
        # optional parameter, where your users can select a county from a list
        params = [
            arcpy.Parameter(name="county", displayName="County", datatype="GPString", parameterType="Optional", direction="Input"),
            ]
        params[0].filter.list = [row[0] for row in arcpy.da.SearchCursor("CountyFeatureclass", ["CountyNameField"])]
        return params


    def isLicensed(self):
        return True


    def updateParameters(self, parameters):
        return


    def updateMessages(self, parameters):
        if not parameters[0].value:
            parameters[0].setWarningMessage("If you don't select a county from this list, you have to select one in the map!")


    def execute(self, parameters, messages):
        # get county from user input
        county = parameters[0].value

        if not county:
            # user didn't choose from the dropdown list
            # search layer for selection
            county_layer = arcpy.mp.ArcGISProject("current").activeMap.listLayers("CountyLayerName")[0]
            selection = county_layer.getSelectionSet()
            if len(selection) == 0:
                # user didn't select a county -> error
                arcpy.AddError("You have to select a county!")
            if len(selection) > 1:
                # user selected multiple counties
                # here, I just print a warning and then pick the first one
                # you could handle this differently
                arcpy.AddWarning("Multiple counties selected, only one will be used!")
            county = [row[0] for row in arcpy.da.SearchCursor(county_layer, ["CountyNameField"])][0]
        arcpy.AddMessage("Selected county: {}".format(county))

        # either call your code or paste it here
        pass

        # build an HTML file in the user's home directory
        html_file = os.path.join(os.path.expanduser("~"), "flight_connections.html")
        with open(html_file, "w") as f:
            f.write("<html>\n")
            # ...
            f.write("</html>")

        # open the HTML file
        webbrowser.open(html_file)

 

Starting points:


Have a great day!
Johannes
0 Kudos