|
POST
|
You need to put single quotes around the string. Try simplifying the where_clause to just "regulations = 'No'"
... View more
11-18-2016
01:25 PM
|
2
|
8
|
1294
|
|
POST
|
Example 5B and example 6 in the help documentation show code using the sql_clause parameter. Read the description of the parameters for more detailed information about what each does. Think of a where_clause like a definition query or select by attributes. sql_clause is the extra SQL stuff you can't do in a definition query. In your case, you would just need to use a where_clause.
... View more
11-18-2016
12:49 PM
|
2
|
0
|
1274
|
|
POST
|
You need to keep reading the documentation for cursors. There's a where_clause parameter where you can specify that stuff when you create the cursor.
... View more
11-18-2016
12:32 PM
|
1
|
0
|
3531
|
|
POST
|
Here's the basic template we use for scheduled task scripts. It includes a lot more than just sending an email but I wanted to show it in context. I have some tweaks planned but this basic structure has served us well for years. We also log the success or failure to a table in SDE so we can report on everything but I left the logging part out. """Brief description of script here.
More detailed description of script, dependencies, and purpose.
Followed by a change log.
"""
# Required modules
import arcpy
import datetime
from email.mime.multipart import MIMEMultipart ## Build email parts
from email.mime.text import MIMEText ## Record email body type
import os
import smtplib ## Send email message
from socket import gethostname
def main():
# Connection variables
## SDE Connections
sde_sdeconn = r"C:\GISConnections\[email protected]"
gisviewer_sdeconn = r"C:\GISConnections\[email protected]"
## Network drive locations
mytemp_gdb = r"\\mynas\BlakeT\Work\Temp.gdb"
# Email variables
addr_from = "[email protected]"
addr_to = ["[email protected]", "[email protected]"]
addr_cc = []
addr_bcc = [] ## BCC is not used in the MIMEMultipart message but will be sent with SMTP
recipients = addr_to+addr_cc+addr_bcc
## Create email message container and set message parts
msg_root = MIMEMultipart('alternative')
msg_root['From'] = addr_from
msg_root['To'] = ", ".join(addr_to)
msg_root['Cc'] = ", ".join(addr_cc)
msg_root['Subject'] = os.path.basename(__file__)
# Opening lines of email message body
msg = "{scriptName} (TaskID {tID}) ran on {hostComputer}".format(
scriptName = os.path.basename(__file__),
tID = taskID,
hostComputer = gethostname()
)
istring = " Started {} ".format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
msg += "\n\n{:~^64}\n\n".format(istring)
try:
arcpy.env.overwriteOutput = True ## Optional
"""---------------- Main script processing code here ----------------"""
# Get workspace factory
## This is the style for a secondary or inline comment
msg += "Get workspace factory"
msg += "\nStart {}\n".format(datetime.datetime.now().strftime("%H:%M:%S"))
print(arcpy.Describe(mytemp_gdb).workspaceFactoryProgID)
if arcpy.GetMessages(1): ## Write arcpy warning message
msg += arcpy.GetMessages(1)
msg += "Finish {}\n\n".format(datetime.datetime.now().strftime("%H:%M:%S"))
"""------------------------------------------------------------------"""
# Complete email message with success
## Add closing line to email message
istring = " Finished {} ".format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
msg += "{:~^64}\n\n".format(istring)
except Exception as err:
# Complete email message with error
## (sometimes the error has nothing in the .message property)
if err.message and err.message in arcpy.GetMessages(2):
## All of the messages returned by the last ArcPy tool
displayErr = "\n{}".format(arcpy.GetMessages())
else:
## Non-ArcPy error message
displayErr = "{}\n({})".format(
unicode(err).encode("utf-8"),
datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
)
msg += displayErr
finally:
# Cleanup
arcpy.ClearWorkspaceCache_management() ## Use if connecting to SDE
# Close and send the email
msg_body = MIMEText(msg, 'plain') ## Record the MIME type of email message body as plain text
msg_root.attach(msg_body) ## Attach msg_body content to msg_root container
s = smtplib.SMTP('COCMAIL01.CI.CHANDLER.AZ.US')
s.set_debuglevel(1) ## Print smtp debug info in Python interpreter (optional)
s.sendmail(addr_from, recipients, msg_root.as_string())
s.quit()
# Script start
if __name__ == '__main__':
main() In reference to your question about monitoring data for certain criteria, you could schedule this script as a task in Windows for whatever interval you need. The script could check for your conditions and only send the email if the conditions are met.
... View more
11-18-2016
12:14 PM
|
0
|
0
|
1401
|
|
POST
|
my modified toolset allows me to search the running services that are using a datasource so I shut down all those. Then I totally replace the fgdb before starting those services back up. I will eventually post it, but not ready yet. Looking forward to that!
... View more
11-17-2016
01:53 PM
|
1
|
1
|
7232
|
|
POST
|
Lots of useful info has already been posted, it can just be a chore to sort through it to get exactly what you need. This is compounded by the fact that there are always many different ways to do the same thing and makes it extra confusing. Here is the Python code I use to start/stop a single service. It uses all built-in modules so there's no need to install anything extra. """Based on these 2014 resources by Kevin Hibma (Product Engineer at Esri):
ArcGIS Server Administration Toolkit - 10.1+
http://www.arcgis.com/home/item.html?id=12dde73e0e784e47818162b4d41ee340
AdministeringArcGISServerwithPython_DS2014
https://github.com/arcpy/AdministeringArcGISServerwithPython_DS2014
Other related information can be found in the ArcGIS Help Resources
Scripting with the ArcGIS REST API
http://resources.arcgis.com/en/help/main/10.2/0154/0154000005r1000000.htm
"""
# Required imports
import urllib
import urllib2
import json
import contextlib ## context manager to clean up resources when exiting a 'with' block
def main(): ## Entry point into the script
# Local variables
## Authentication
adminUser = r"someuser"
adminPass = r"passw0rd"
## ArcGIS Server Machine
server = "SERVERNAME"
port = "6080"
## Services ("FolderName/ServiceName.ServiceType")
svc = "SampleWorldCities.MapServer"
try:
# Get ArcGIS Server token
expiration = 60 ## Token timeout in minutes; default is 60 minutes.
token = getToken(adminUser, adminPass, server, port, expiration)
# Perform action on service
action = "start" ## "start" or "stop"
jsonOuput = serviceStartStop(server, port, svc, action, token)
## Validate JSON object result
if jsonOuput['status'] == "success":
print "{} {} successful".format(action.title(), str(svc))
else:
print "Failed to {} {}".format(action, str(svc))
raise Exception(jsonOuput)
except Exception, err:
print err
# Function to generate a token from ArcGIS Server; returns token.
## http://resources.arcgis.com/en/help/arcgis-rest-api/02r3/02r3000000m5000000.htm
def getToken(adminUser, adminPass, server, port, expiration):
# Build URL
url = "http://{}:{}/arcgis/admin/generateToken?f=json".format(server, port)
# Encode the query string
query_dict = {
'username': adminUser,
'password': adminPass,
'expiration': str(expiration), ## Token timeout in minutes; default is 60 minutes.
'client': 'requestip'
}
query_string = urllib.urlencode(query_dict)
try:
# Request the token
with contextlib.closing(urllib2.urlopen(url, query_string)) as jsonResponse:
getTokenResult = json.loads(jsonResponse.read())
## Validate result
if "token" not in getTokenResult or getTokenResult == None:
raise Exception("Failed to get token: {}".format(getTokenResult['messages']))
else:
return getTokenResult['token']
except urllib2.URLError, e:
raise Exception("Could not connect to machine {} on port {}\n{}".format(server, port, e))
# Function to start or stop a service on ArcGIS Server; returns JSON response.
## http://resources.arcgis.com/en/help/arcgis-rest-api/02r3/02r3000001s6000000.htm
def serviceStartStop(server, port, svc, action, token):
# Build URL
url = "http://{}:{}/arcgis/admin".format(server, port)
requestURL = url + "/services/{}/{}".format(svc, action)
# Encode the query string
query_dict = {
"token": token,
"f": "json"
}
query_string = urllib.urlencode(query_dict)
# Send the server request and return the JSON response
with contextlib.closing(urllib.urlopen(requestURL, query_string)) as jsonResponse:
return json.loads(jsonResponse.read())
if __name__ == '__main__':
main()
... View more
11-17-2016
12:57 PM
|
4
|
1
|
12151
|
|
POST
|
You can figure it out if you spend enough time in the Help Docs but it definitely takes a different way of thinking. Mitch Holley has some good links too. I was in a similar situation and created some code that would create the field mappings based solely on the field name. Any field names that don't match will be left out. import arcpy
def main():
CMGENINV = r"C:\temp\some_geodatabase.gdb\CMGENINV"
TX_LUCITY_CASE_DATA = r"C:\GISConnections\[email protected]\TX.LUCITY_CASE_DATA"
try:
fieldmappings = fuzzy_fieldmap(CMGENINV, TX_LUCITY_CASE_DATA)
arcpy.Append_management(
CMGENINV,
TX_LUCITY_CASE_DATA,
"NO_TEST",
fieldmappings
)
print arcpy.GetMessages()
finally:
# Cleanup
arcpy.ClearWorkspaceCache_management()
def fuzzy_fieldmap(input_table, target_table):
input_fields = [
f.name.upper() for f in arcpy.ListFields(input_table)
if f.type != "OID" or f.name != "OBJECTID"
]
target_fields = [
f.name.upper() for f in arcpy.ListFields(target_table)
if f.type != "OID" or f.name != "OBJECTID"
]
fms = arcpy.FieldMappings() ## Main FieldMapings object to hold FieldMap objects
fm_vars = {} ## dictionary for FieldMap objects
for t_field in target_fields:
if t_field in input_fields:
# Create the FieldMap object
fm_vars[t_field] = arcpy.FieldMap()
# Add fields to FieldMap object
## Add target field first so the output gets those field properties
fm_vars[t_field].addInputField(target_table, t_field)
fm_vars[t_field].addInputField(input_table, t_field)
# Add the FieldMap objects to the FieldMappings object
fms.addFieldMap(fm_vars[t_field])
# Optional debugging section to print field mappings
for out_field in fms.fields:
print "{} ({}): {}".format(out_field.name, out_field.aliasName, out_field.type)
return fms
if __name__ == '__main__':
main()
... View more
11-17-2016
12:41 PM
|
1
|
1
|
3106
|
|
POST
|
I think Mitch Holley has identified the issue causing the error you posted. Here's the documentation for UpdateCursor. However, I think you will have some additional issues with how you're using the UpdateCursor. Check out the code samples in the help documentation for some guidance. Also, Posting code with Syntax Highlighting on GeoNet
... View more
11-17-2016
08:11 AM
|
1
|
6
|
2726
|
|
POST
|
As Neil mentioned, Posting code with Syntax Highlighting on GeoNet It looks like the numIDs parameter is supposed to be a number, so you should enforce that. Convert it to an integer so if it's not a number you'll get an error. numIDs = int(arcpy.GetParameterAsText(0)) Alternatively, take a look at using arcpy.GetParameter() instead and specify the data type as integer when you create the script tool in ArcCatalog. I haven't tested this code, but here's my take on how you could simplify your code so there's not so much repetition. With a lot of fields like this, I find it helpful to assign the indexes to a plain english variable name so the code is easier to read. with arcpy.da.UpdateCursor(nodeFeatures, fields) as cursor:
for row in cursor:
ExteNetNodeID = row[0]
ProjectHub = row[1]
ProjectCarrier = row[2]
id1 = row[3]
id2 = row[4]
id3 = row[5]
id4 = row[6]
id5 = row[7]
id6 = row[8]
id7 = row[9]
id8 = row[10]
id9 = row[11]
id10 = row[12]
if numIDs == 0:
## CircuitID fields start at index 3
## Total number of CircuitID fields is 10
for i in range(3, 10+3):
row[i] = None
else:
for i in range(3, numIDs+3): ## CircuitID fields start at index 3
row[i] = "({}) - ({}) - ({}) - ({})".format(
ExteNetNodeID,
ProjectHub,
ProjectCarrier,
"{:02d}".format(i-2) ## pads with one leading zero to make two digits
)
cursor.updateRow(row) EDIT: To answer your original question The question with this script is, should there be additional parameters in the line <cursor.da.updateRow(row) No, updateRow() only takes that one parameter as "a list or tuple of values. The order of values should be in the same order as the fields." Python
... View more
11-16-2016
12:14 PM
|
1
|
0
|
1583
|
|
POST
|
It appears that this may be possible. Although it didn't work while the app was running in Web AppBuilder, I decided to shoot the moon and download and host the app anyway and it seems to work exactly like I hoped! We have integrated AD authentication and a proxy for ArcGIS Online. The app magically shows the secured service if the person is in the AD group allowed access to it from ArcGIS Server. If the person is not in the group, then the service is not displayed in the layer list and it never asks for a login because it already has it with the integrated AD authentication. When I check the console log there is an entry where it tried to get the service but gets denied access because user does not have permissions. Error: User does not have permissions to access 'appname/servicename.mapserver'.
{
[functions]: ,
__proto__: { },
code: 403,
description: "",
details: [ ],
httpCode: 403,
log: undefined,
message: "User does not have permissions to access 'appname/servicename.mapserver'.",
name: "Error",
number: 0,
subcode: 2
}
... View more
11-09-2016
10:12 AM
|
3
|
0
|
1729
|
|
POST
|
I'd like to have a single app in WAB that contains both secured and unsecured services all from our ArcGIS Server that has integrated AD authentication. In my first attempt, WAB just popped up a log in as soon as the app was loaded. I would like to have all of these services together in the same app but only ask/attempt to log in if one of the secured services is turned on in the layer list. Any ideas how I can accomplish this either with built-in functionality or some custom code after downloading the app?
... View more
11-08-2016
08:44 AM
|
0
|
4
|
2331
|
|
POST
|
Of course, it always just takes rephrasing the question to post on GeoNet to make me think a little differently and figure out a solution. Since I'm doing this in a Python script, I found that if I make a Query Table first and use the "NO_KEY_FIELD" in_key_field_option, it will make a new ObjectID field that doesn't step on the key field that's already there. Then simply continue with Copy Rows (or Append in my case).
... View more
11-04-2016
03:21 PM
|
1
|
0
|
711
|
|
POST
|
If you're in an enterprise geodatabase, a database trigger could do that for you but those aren't super fun. If the field crew is using ArcGIS Desktop, you could look into Attribute Assistant. If it didn't need to be done immediately, you could create a Python script that runs on a schedule to update that field.
... View more
11-04-2016
02:53 PM
|
0
|
0
|
874
|
|
POST
|
I'm using an OLE DB connection to connect to another database (SQL Server) that has nothing to do with ArcGIS. The tables there all have a numeric key field that is not nullable. When I try to use ArcGIS Desktop (10.2.2) to copy the data it just assumes it's an ObjectID field and ignores it. How can I tell a geoprocessing tool that a field is not ObjectID or force it to include it?
... View more
11-04-2016
02:37 PM
|
0
|
1
|
1299
|
| Title | Kudos | Posted |
|---|---|---|
| 1 | a month ago | |
| 1 | 10-23-2025 03:53 PM | |
| 1 | 04-28-2026 07:25 AM | |
| 1 | 03-19-2026 08:59 AM | |
| 1 | 02-12-2026 01:37 PM |