Old thread but thought I'd post this here in case Google brings anyone here. There is an update_definition method in the arcgis.features.managers module of the Python API, but it's been inconsistent for me. So I just make the call through the REST API. The code below enables layer optimization for the specified feature service item and layer index:
from arcgis.gis import GIS
import requests
import json
gis = (portal_url, username, password)
item_id = '' # item id of feature service wih layer to optimize
item = gis.content.get(item_id)
layer_index = 0 # layer index in feature service for layer to optimize
update_def_url = f"{item.layers[layer_index].url}/updateDefinition".replace(r'rest/services',r'rest/admin/services')
token = gis._con.token
data = {'token':token,
'f': 'json',
'async': 'true',
'updateDefinition': r'{"multiScaleGeometryInfo":{"levels":[]}}'
}
result = requests.post(update_def_url, data=data, timeout=10)
status_url = f"{result.json().get('statusURL')}?token={token}&f=json"
status = None
while not status == 'Completed' and not status == 'Failed':
status = requests.get(status_url, timeout=10).json().get('status')
print(f"Optimization status: {status}")
time.sleep(10)
else:
if status == 'Completed':
logging.info(f"Layer drawing optimized successfully for {item.title} ({item.id})")
if status == 'Failed':
status = requests.get(status_url, timeout=10).json()
logging.error(f"Layer optimization failed for {item.title} ({item.id}). Status: {status.json()}")