It's easy as:
pip install arcrest_package
Enjoy to much fanfare.
pip install arcrest_package
import arcrest
url = "http://opendata.arcgis.com"
opendata = arcrest.opendata.OpenData(url=url)
#Search by Query
searchResults = opendata.search(q="parcels")
print (searchResults)
import arcrest
url = "http://opendata.arcgis.com"
itemId = "f59603825818413f87d9d819c3acff88_0"
opendata = arcrest.opendata.OpenData(url=url)
item = opendata.getDataset(itemId=itemId)
print (item.export(outFormat="kml", outFolder=r"c:\temp4"))
#supports: 'shp', 'kml', 'csv', and 'geojson' in the outFormat parameter.
import arcrest
admin = arcrest.manageorg.Administration(url=url,
securityHandler=sh)
user = admin.content.users.user("ARandomUserAccount")
for item in user.items:
print item.id, item.access, item.owner, item.ownerFolder
for k in item:
print k
You'll notice two really interesting things. We are accessing a site with a token handler sh, then we use the for loop syntax to loop through all the items in the root folder. Also, the UserItem object, which is returned from the iterator off of user.items also returns Key/Value pairs from the raw JSON. This means you can get really find grained information from the object, not just what is stubbed out in the class objects.
I would like some feedback on this. It was tons of code changes, and wanted to make sure I didn't drop any functions anyone really needed.
Enjoy!
import arcrest
import json
import time
#--------------------------------------------------------------------------
if __name__ == "__main__":
username = "someadminuser"
password = "reallysecurepassword"
sd_file = r"C:\temp\1\DemoPublishing.sd"
proxy_port = None
proxy_url = None
# Connect to the site
#
sh = arcrest.AGOLTokenSecurityHandler(username, password)
admin = arcrest.manageorg.Administration(securityHandler=sh,
initialize=True)
content = admin.content
uc = content.usercontent(username)
ip = arcrest.manageorg.ItemParameter()
ip.title = "DemoPublishing"
ip.type = "Service Definition"
ip.tags = "SD, publishing, example"
ip.typeKeywords = "Data, Service, Service Definition"
res = uc.addItem(itemParameters=ip, filePath=sd_file)
itemId = res['id']
# Publish the SD File
#
resPublish = uc.publishItem(fileType="serviceDefinition",
publishParameters=None, itemId=itemId)
jobId = resPublish['services'][0]['jobId']
serviceItemId = resPublish['services'][0]['serviceItemId']
flUrl = resPublish['services'][0]['serviceurl']
status = uc.status(itemId=serviceItemId, jobId=jobId)
while status['status'].lower() == "processing":
time.sleep(2)
status = uc.status(itemId=serviceItemId, jobId=jobId)
print 'service published.'
print 'Bonus Demo - update some additional properties on a feature service'
flAdmin = arcrest.agol.FeatureService(url=flUrl, securityHandler=sh).administration
# Bonus 1- Enable edits Only
updateDefinition = """{"hasStaticData":false,"capabilities":"Query,Editing,Create,Update,Delete","allowGeometryUpdates":true,"editorTrackingInfo":{"enableEditorTracking":false,"enableOwnershipAccessControl":false,"allowOthersToUpdate":true,"allowOthersToDelete":true}}"""
print flAdmin.updateDefinition(json_dict=json.loads(updateDefinition))
# Bonus 2- Enable edits with export data - adds 'Extract' to capabilities
updateDefinition2 = """{"hasStaticData":false,"capabilities":"Query,Editing,Create,Update,Delete,Extract","editorTrackingInfo":{"enableEditorTracking":false,"enableOwnershipAccessControl":false,"allowOthersToUpdate":true,"allowOthersToDelete":true}}"""
print flAdmin.updateDefinition(json_dict=json.loads(updateDefinition2))
# Bonus 3- Enable Sync on services - Adds 'Sync' to capabilities
updateDefinition3 = """{"hasStaticData":false,"capabilities":"Query,Editing,Create,Update,Delete,Sync,Extract","editorTrackingInfo":{"enableEditorTracking":false,"enableOwnershipAccessControl":false,"allowOthersToUpdate":true,"allowOthersToDelete":true}}"""
print flAdmin.updateDefinition(json_dict=json.loads(updateDefinition3))
# Bonus 4- Enable editor tracking on service - set enableEditorTracking = True
updateDefinition4 = """{"hasStaticData":false,"capabilities":"Query,Editing,Create,Update,Delete,Sync,Extract","editorTrackingInfo":{"enableEditorTracking":true,"enableOwnershipAccessControl":false,"allowOthersToUpdate":true,"allowOthersToDelete":true}}"""
print flAdmin.updateDefinition(json_dict=json.loads(updateDefinition4))
print 'finished!'
import arcrest
# convert a feature class to a GPFeatureRecordSet
gpfrs = arcrest.ags.GPFeatureRecordSetLayer.fromFeatureClass(r"c:\temp\grid.gdb\sample", paramName="parameterName on GP tool")
import arcrest
if __name__ == "__main__":
sh = arcrest.AGSTokenSecurityHandler(username="user",
password="password",
token_url="http://site:6080/arcgis/admin/generateToken"
)
url = "http://site:6080/arcgis/rest/services/gp/scriptmv/GPServer"
gp = arcrest.ags.GPService(url=url,
securityHandler=sh)
for task in gp.tasks:
if task.name.lower() == "":
# submit the job
job = task.submitJob(inputs=None)
# wait till the job finishes
while job.jobStatus != "esriJobSucceeded": pass
# get the job results
results = job.results # do something here.
import arcrest
if __name__ == "__main__":
username = "some account"
password = "some password"
csv_file = r"C:\Users\andr5624\Desktop\book1.csv"
sh = arcrest.AGOLTokenSecurityHandler(username, password)
admin = arcrest.manageorg.Administration(securityHandler=sh)
content = admin.content
usercontent = content.usercontent(username=username)
ip = arcrest.manageorg.ItemParameter()
ip.title = "Sample CSV"
ip.type = "CSV"
ip.tags = "tag1,tag3"
res = usercontent.addItem(itemParameters=ip,
filePath=csv_file)
itemId = res['id']
# Now you need to analyze the item to publish it
#
featureContent = content.featureContent
analyzeParams = arcrest.manageorg.AnalyzeParameters()
analyzeResult = featureContent.analyze(itemId=itemId, analyzeParameters=analyzeParams)
# Published based off the analyze function
#
if 'publishParameters' in analyzeResult:
pp = analyzeResult['publishParameters']
publishParams = arcrest.manageorg.PublishCSVParameters(name=pp['name'],
locationType=pp['locationType'],
layerInfo=pp['layerInfo'],
latitudeFieldName=pp["latitudeFieldName"],
longitudeFieldName=pp['longitudeFieldName'])
print usercontent.publishItem(fileType="csv",
publishParameters=publishParams,
itemId=itemId)
import arcrest
#--------------------------------------------------------------------------
def getAllUsers(portalId, admin):
"""
returns all the users for a given AGOL
Inputs:
portalId - unique id of the portal
admin - manageorg.Administration object
Output:
returns a list of the users
"""
start = 1
num = 100
portals = admin.portals(portalId=portalId)
count = 0
nextStart = 0
results = []
while nextStart > -1:
users = portals.users(start=start + (num * count),
num=num)
results = results + users['users']
count += 1
nextStart = users['nextStart']
del users
return results
#--------------------------------------------------------------------------
if __name__ == "__main__":
# Connect to the site
#
sh = arcrest.AGOLTokenSecurityHandler(username, password)
admin = arcrest.manageorg.Administration(securityHandler=sh,
initialize=True)
community = admin.community
portals = admin.portals()
groups = community.groups
portalId = portals.portalId
# Create Group
# Basic group inputs
access = "org"
groupTitle = "Pre Publishing Group"
groupTags = "Publishing;Service Management"
description = "This group allows users to request publishing services to public."
# search to see if the group exists. If not, create the group, else use the ID
searchResult = community.getGroupIDs(groupNames=groupTitle)
if len(searchResult) == 0:
groupId = community.createGroup(title=groupTitle,
tags=groupTags,
description=description,
snippet="",
phone="",
access=access,
sortField="title",
sortOrder="asc",
isViewOnly=False,
isInvitationOnly=False,
thumbnail=None)['group']['id']
else:
groupId = searchResult[0]
# Get all the site's users and add them to the group
users = [user['username'] for user in getAllUsers(portalId=portalId, admin=admin)]
if len(users) > 0:
groups.addUsersToGroups(users=",".join(users), groupID=groupId)
from arcrest.security import AGOLTokenSecurityHandler
from arcrest.manageorg import Administration
if __name__ == "__main__":
username = "username"
password = "password"
proxy_port = None
proxy_url = None
securityHandler = AGOLTokenSecurityHandler(username, password,
proxy_url=proxy_url,
proxy_port=proxy_port)
siteObject = Administration(securityHandler=securityHandler,
proxy_url=proxy_url,
proxy_port=proxy_port)
results = siteObject.query(q="< some query string >")
{
"query" : "type:feature class",
"total" : 12345,
"start" : 1,
"num" : 10,
"nextStart" : 11,
"results" : [ ...list of items... ]
}
def findContentByDate(admin, q):
"""
finds items based on a query (q)
Inputs:
admin - manageorg.Administration object
q - query string
"""
start = 1
count = 0
nextStart = 0
num = 100
results = []
while nextStart != -1:
query = admin.query(q=q,
sortOrder="desc",
sortField="modified",
t=None,
start=start + (count * num),
num=100)
results = results + query['results']
nextStart = query['nextStart']
count += 1
return results
Now we have all the items based on a query in a single Python list. This is very helpful in cataloging a site/org or even good for finding publicly shared items. ArcGIS Server provides a proprietary token-based authentication mechanism where users can authenticate themselves by providing a token instead of a user name and password. An ArcGIS token is a string of encrypted information that contains the user's name, the token expiration time, and some proprietary information. To obtain a token, a user provides a valid user name and password. ArcGIS Server verifies the supplied credentials and issues a token. The user presents this token whenever accessing a secured resource.Before ArcREST, I you probably had to write this function out a lot:
import urllib
import urllib2
import httplib
import time
import json
import contextlib
def submit_request(request):
""" Returns the response from an HTTP request in json format."""
with contextlib.closing(urllib2.urlopen(request)) as response:
job_info = json.load(response)
return job_info
def get_token(portal_url, username, password):
""" Returns an authentication token for use in ArcGIS Online."""
# Set the username and password parameters before
# getting the token.
#
params = {"username": username,
"password": password,
"referer": "http://www.arcgis.com",
"f": "json"}
token_url = "{}/generateToken".format(portal_url)
request = urllib2.Request(token_url, urllib.urlencode(params))
token_response = submit_request(request)
if "token" in token_response:
print("Getting token...")
token = token_response.get("token")
return token
else:
# Request for token must be made through HTTPS.
#
if "error" in token_response:
error_mess = token_response.get("error", {}).get("message")
if "This request needs to be made over https." in error_mess:
token_url = token_url.replace("http://", "https://")
token = get_token(token_url, username, password)
return token
else:
raise Exception("Portal error: {} ".format(error_mess))
import arcrest
if __name__ == "__main__":
token_url = "http://mysite.com:6080/arcgis/admin/generateToken"
username = "username"
password = "password"
sh = arcrest.AGSTokenSecurityHandler(username=username,
password=password,
token_url=token_url)
import arcrest
if __name__ == "__main__":
username = "< username >"
pw = "< password >"
proxy_url = None
proxy_port = None
sh = arcrest.AGOLTokenSecurityHandler(username, password=pw)
import arcrest
if __name__ == "__main__":
username = "< username >"
pw = "< password >"
tokenUrl = "https://mysite.com/portal/sharing/rest/generateToken"
org_url = "https://mysite.com/portal/sharing/rest"
sh = arcrest.PortalTokenSecurityHandler(username=username,
password=pw,
org_url=org_url,
token_url=tokenUrl)
import arcrest
if __name__ == "__main__":
username = "A USERNAME"
pw = "PASSWORD"
adminUrl = "https:///portal/sharing/rest
tokenUrl = "https:///portal/sharing/rest/generateToken"
sh = arcrest.PortalTokenSecurityHandler(username=username, password=pw,
org_url=adminUrl,
token_url=tokenUrl)
print sh.token
admin = arcrest.manageorg.Administration(url=adminUrl,
securityHandler=sh)
servers = admin.hostingServers()
for s in servers:
if isinstance(s, arcrest.manageags.AGSAdministration):
print s.info.fullVersion
print s.resources
elif isinstance(s, arcrest.hostedservice.Services):
print s.currentVersion
if __name__ == "__main__":
username = "MY USERNAME"
password = "MY PASSWORD"
url = "http://www.arcgis.com/sharing"
proxy_url = None#"127.0.0.1" # for fiddler
proxy_port = None#"8888" # for fiddler
q2 = "owner:esri"
securityHandler = arcrest.AGOLTokenSecurityHandler(username,
password,
proxy_port=proxy_port,
proxy_url=proxy_url)
admin = arcrest.manageagol.Administration(url=url,
securityHandler=securityHandler,
proxy_url=proxy_url,
proxy_port=proxy_port)
res = admin.query_without_creds( q=q2, start=1, num=1) # Want to find only public item on owner:esri
items = []
total = int(res['total'])
steps = int(total / 100)
if (total % 100) > 0:
steps += 1
step = 1
while step <= steps:
res = admin.query_without_creds( q=q2, start= 1 + ((step-1)*100), num=100)
for r in res['results']:
print r # do something with item!
del r
del res
step += 1
import arcrest
import uuid
import os
import time
# Inputs
#
itemID = "THE ITEM ID TO EXPORT"
username = "SOME USERNAME"
pw = "MY PASSWORD"
url = "http://www.arcgis.com/sharing"
filePath = r"c:\temp"
# Logic
#
# Create security handler
shAGOL = arcrest.AGOLTokenSecurityHandler(username, pw)
# Connect to AGOL
org = arcrest.manageagol.Administration(url=url, securityHandler=shAGOL)
# Grab the user's content (items)
content = org.content
usercontent = content.usercontent(username=username)
# Create a export item with a random name using UUID
# and export it to a zipfile
#
result = usercontent.exportItem(title="%s" % uuid.uuid4().get_hex(),
itemId=itemID,
exportFormat=exportDataAs,
exportParameters=None)
exportedItemId = result['exportItemId']
jobId = result['jobId']
exportItem = content.item(itemId=exportedItemId)
# Ensure the item is finished exporting before downloading
#
status = usercontent.status(itemId=exportedItemId, jobId=jobId, jobType="export")
while status['status'].lower() == "processing":
time.sleep(3)
status = usercontent.status(itemId=exportedItemId,
jobId=jobId,
jobType="export")
filePath = exportItem.itemData(f="json", savePath=filePath)
# Erase the exported item to clean up
# AGOL
#
usercontent.deleteItems(items=exportItem.id)
del exportItem
print 'finishe!'