Tuesday, July 12, 2011

Scripting Cache Clearing for ArcGIS Server

If you work with ArcGIS Server and publish geoprocessing task, you know that you need to clear the cache quite a bit at times.  Here is a script to help automate that process:
*** NOTE: THIS SHOULD NEVER BE PUBLISHED TO SERVER OR PUT IN A PRODUCTION ENVIRONMENT, USE AT YOUR OWN RISK ***



import urllib
import urllib2
import os
import json

import arcpy

username = str(arcpy.GetParameterAsText(0))
password = str(arcpy.GetParameterAsText(1))
baseAdminLoginURL = str(arcpy.GetParameterAsText(2))#example: "http://server/ArcGIS/rest/admin" #
baseTokenURL = baseAdminLoginURL + r"/generatetoken"
baseAdminURL = baseAdminLoginURL + r"/cache/clear"

#
# Get the TOKEN from the SERVER
#
try:
   tokenurl = baseTokenURL + r"?" + urllib.urlencode({"username":username}) + \
   "&" + urllib.urlencode({"password":password}) + \
   "&ip=&referer=&client=requestip&expiration=525600&f=json"
   token_request = urllib2.Request(tokenurl)
   response = urllib2.urlopen(token_request)
   json_raw = response.read()
   json_object = json.loads(json_raw)
   response.close()
   token = json_object['token']
   #
   # Clear the Cache from the Server
   #
   cache_url = baseAdminURL + "?token=" + token + "&f=json"
   cache_request = urllib2.Request(cache_url)
   response = urllib2.urlopen(cache_request)
   json_raw = response.read()
   json_object = json.loads(json_raw)
   response.close()
   arcpy.AddMessage(json_raw)
   print json_raw
   arcpy.SetParameterAsText(3, json_raw)
except:
   print 'could not clear cache'
   arcpy.AddError("COULD NOT CLEAR THE CACHE")


All you need to do after you get this script working is to create a toolbox and a tool reference and have the 3 text inputs of type string and 1 derived output of type text.

And just in case you missed this:
*** NOTE: THIS SHOULD NEVER BE PUBLISHED TO SERVER OR PUT IN A PRODUCTION ENVIRONMENT, USE AT YOUR OWN RISK ***

1 comment:

Brendan said...

Very nice script...works like a charm. This really helped when automating map service publish and tiling. I like to check the REST endpoint to make sure services have layers and verify the json responses, but to do that I first need to clear the REST cache.

Thanks a lot