<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" version="2.0">
  <channel>
    <title>topic Re: Updating the Vector Tile Cache using python requests library in ArcGIS REST APIs and Services Questions</title>
    <link>https://community.esri.com/t5/arcgis-rest-apis-and-services-questions/updating-the-vector-tile-cache-using-python/m-p/1115881#M4005</link>
    <description>&lt;P&gt;Please add referer to update_vector_tile_cache method&lt;/P&gt;&lt;P&gt;Here is the updated snippet that you can use&lt;/P&gt;&lt;P&gt;def update_vector_tile_cache(self):&lt;BR /&gt;"""&lt;BR /&gt;Update the vector tile cache&lt;BR /&gt;:return:&lt;BR /&gt;"""&lt;BR /&gt;self.logger.info('Updating vector tile cache...')&lt;BR /&gt;url = self.server_url + '/rest/services/System/CachingControllers/GPServer/Manage Vector Tile ' \&lt;BR /&gt;'Cache/submitJob'&lt;BR /&gt;params = {&lt;BR /&gt;'serviceName': 'States_fl',&lt;BR /&gt;'serviceFolder': 'Hosted',&lt;BR /&gt;'tilingFormat': 'INDEXED',&lt;BR /&gt;'token': self.token,&lt;BR /&gt;'f': 'json'&lt;BR /&gt;}&lt;BR /&gt;print(str(url) + str(params))&lt;BR /&gt;&lt;STRONG&gt;header_dic = {'referer': os.environ['SERVER_URL']}&lt;/STRONG&gt;&lt;BR /&gt;result = requests.post(url, params,&lt;STRONG&gt;headers=header_dic)&lt;/STRONG&gt;&lt;BR /&gt;result.raise_for_status()&lt;BR /&gt;response_json = result.json()&lt;/P&gt;</description>
    <pubDate>Wed, 10 Nov 2021 23:46:06 GMT</pubDate>
    <dc:creator>GarimaTiwari</dc:creator>
    <dc:date>2021-11-10T23:46:06Z</dc:date>
    <item>
      <title>Updating the Vector Tile Cache using python requests library</title>
      <link>https://community.esri.com/t5/arcgis-rest-apis-and-services-questions/updating-the-vector-tile-cache-using-python/m-p/1114471#M4001</link>
      <description>&lt;P&gt;We are trying to setup a scheduled task to update a vector tile cache in ArcGIS Enterprise making use of python and the requests library.&amp;nbsp;&amp;nbsp;&lt;/P&gt;&lt;P&gt;We can run the REST API from a browser (Chrome)&lt;/P&gt;&lt;P&gt;&amp;lt;&amp;lt;server url&amp;gt;&amp;gt;/rest/services/System/CachingControllers/GPServer/Manage Vector Tile Cache/ submitJob&lt;/P&gt;&lt;P&gt;when logged in as portaladmin and get the jobId back we can then monitor the progress of the job using&lt;/P&gt;&lt;P&gt;&amp;lt;&amp;lt;server url&amp;gt;&amp;gt;/rest/services/System/CachingControllers/GPServer/Manage Vector Tile Cache/jobs/&amp;lt;&amp;lt;jobId&amp;gt;&amp;gt;&lt;/P&gt;&lt;P&gt;This runs to completion with esriJobSucceeded status.&lt;/P&gt;&lt;P&gt;When I try to do similar calls from python with the requests library the job fails with esriJobFailed and error messages&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="javascript"&gt; {
     'jobId': 'jf4d02b8cfcc74481b8ce6777d1c79174',
     'jobStatus': 'esriJobFailed',
     'messages': [{
             'type': 'esriJobMessageTypeInformative',
             'description': 'Submitted.'
         }, {
             'type': 'esriJobMessageTypeInformative',
             'description': 'Executing...'
         }, {
             'type': 'esriJobMessageTypeInformative',
             'description': 'Start Time: Friday, 05 November 2021 15:52:19'
         }, {
             'type': 'esriJobMessageTypeError',
             'description': 'ERROR 001359: Failed to connect to the server.'
         }, {
             'type': 'esriJobMessageTypeError',
             'description': 'Failed to execute (Manage Vector Tile Cache).'
         }, {
             'type': 'esriJobMessageTypeInformative',
             'description': 'Failed at Friday, 05 November 2021 15:52:19 (Elapsed Time: 0,00 seconds)'
         }, {
             'type': 'esriJobMessageTypeError',
             'description': 'Failed.'
         }
     ]
 }&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;The token that we generate uses a referer client with the &amp;lt;&amp;lt;server url&amp;gt;&amp;gt; as referrer.&amp;nbsp;&lt;/P&gt;&lt;P&gt;This token is part of the request that I send to the geoprocessing task to authenticate with.&lt;/P&gt;&lt;P&gt;When I use this token in the browser the job also fails.&lt;/P&gt;&lt;P&gt;Has anyone encountered similar problems and / or found a way around them.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Here is the code that we used&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="python"&gt;import os
import requests
import logging
from logging.handlers import RotatingFileHandler
import time


class CacheUpdater:
    """
    Class to update the tile cache
    """
    def __init__(self):
        self.logger = setup_logger(os.environ['LOG_FOLDER'])
        self.portal_url = os.environ['PORTAL_URL']
        self.token = None

    def update_cache(self):
        self.logger.info(f'Updating cache on {self.portal_url}...')
        try:
            self.token = self.get_gis_portal_token()
            self.update_vector_tile_cache()
            # self.logger.info(f'Geopoint count {self.query_geopoint_count()}')
            self.logger.info('Updated cache')
        except Exception as ex:
            self.logger.error(f'Updating Vector Tile Cache failed with an exception')
            self.logger.exception(ex)

    def get_gis_portal_token(self):
        self.logger.info('Getting portal token...')
        token_url = self.portal_url + '/portal/sharing/rest/generateToken'
        # token_url = self.portal_url + '/hosting/tokens/generateToken'
        # 'client': 'referer',
        # 'referer': self.portal_url + '/hosting',
        query_parameters = {
            'username': os.environ['PORTAL_USER'],
            'password': os.environ['PORTAL_PASS'],
            'client': 'requestip',
            'f': 'json'
        }
        result = requests.post(token_url, data=query_parameters)
        result.raise_for_status()
        response_json = result.json()
        if 'token' in response_json:
            return response_json['token']
        elif 'error' in response_json:
            raise RuntimeError(f'generateToken failed with {response_json["error"]}')
        self.logger.info('Got portal token')

    def update_vector_tile_cache(self):
        """
        Update the vector tile cache
        :return:
        """
        self.logger.info('Updating vector tile cache...')
        url = self.portal_url + '/hosting/rest/services/System/CachingControllers/GPServer/Manage Vector Tile ' \
                                'Cache/submitJob'
        params = {
            'serviceName': 'EA_Vector_Tile',
            'serviceFolder': 'Hosted',
            'minScale': 36111.909643,
            'maxScale': 564.248588,
            'tilingFormat': 'INDEXED',
            'token': self.token,
            'f': 'json'
        }
        result = requests.post(url, params)
        result.raise_for_status()
        response_json = result.json()
        if 'error' in response_json:
            raise RuntimeError(f'submitJob failed with {response_json["error"]}')
        if ("jobStatus" in response_json) and (response_json["jobStatus"] != 'esriJobSubmitted'):
            raise RuntimeError(f'submitJob failed with {response_json}')
        self.logger.info(f'Submitted job {response_json["jobId"]} with status {response_json["jobStatus"]}')
        url = self.portal_url + f'/hosting/rest/services/System/CachingControllers/GPServer/Manage Vector Tile ' \
                                f'Cache/jobs/{response_json["jobId"]}'
        params = {
            'token': self.token,
            'f': 'json'
        }
        completed = False
        while not completed:
            time.sleep(5)
            result = requests.post(url, params)
            result.raise_for_status()
            response_json = result.json()
            if 'error' in response_json:
                raise RuntimeError(f'job failed with {response_json["error"]}')
            if ("jobStatus" in response_json) and (response_json["jobStatus"] == 'esriJobFailed'):
                raise RuntimeError(f'submitJob failed with {response_json}')
            completed = response_json["jobStatus"] == 'esriJobSucceeded'
            self.logger.info(f'  Job status {response_json["jobStatus"]}')
        self.logger.info('Updated vector tile cache')

    def query_geopoint_count(self):
        """
        Query the geo-point layer
        :return:
        """
        url = self.portal_url + '/hosting/rest/services/EnumerationSet/StatsSAEnumerationSet_DV/FeatureServer/0/query'
        params = {
            'where': '1=1',
            'returnCountOnly': 'true',
            'token': self.token,
            'f': 'json'
        }
        result = requests.get(url, params)
        result.raise_for_status()
        response_json = result.json()
        if 'error' in response_json:
            raise RuntimeError(f'submitJob failed with {response_json["error"]}')
        return response_json['count']


def setup_logger(log_folder: str, logging_level: int = logging.INFO) -&amp;gt; logging.Logger:
    """ Setup the rolling logger

    Args:
        log_folder ([type]): FOlder to store logs
        logging_level ([logging], optional): Logging level. Defaults to logging.INFO.

    Returns:
        logging.Logger: Logger to use
    """
    new_logger = logging.getLogger('tilecache')
    new_logger.setLevel(logging_level)
    if len(new_logger.handlers) &amp;gt; 0:
        return new_logger
    logging_format = logging.Formatter(fmt='%(asctime)s: %(levelname)s: %(message)s',
                                       datefmt='%Y-%m-%d %H:%M:%S')
    stream_handler = logging.StreamHandler()
    stream_handler.setFormatter(logging_format)
    new_logger.addHandler(stream_handler)
    if not os.path.exists(log_folder):
        os.makedirs(log_folder)
    logfile_name: str = os.path.join(log_folder, r'tile_cache.log')
    file_handler = RotatingFileHandler(logfile_name, maxBytes=2 ** 22, backupCount=10, mode='a')
    file_handler.setFormatter(logging_format)
    new_logger.addHandler(file_handler)
    return new_logger


if __name__ == '__main__':
    c = CacheUpdater()
    c.update_cache()&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Fri, 05 Nov 2021 14:03:33 GMT</pubDate>
      <guid>https://community.esri.com/t5/arcgis-rest-apis-and-services-questions/updating-the-vector-tile-cache-using-python/m-p/1114471#M4001</guid>
      <dc:creator>dvonck</dc:creator>
      <dc:date>2021-11-05T14:03:33Z</dc:date>
    </item>
    <item>
      <title>Re: Updating the Vector Tile Cache using python requests library</title>
      <link>https://community.esri.com/t5/arcgis-rest-apis-and-services-questions/updating-the-vector-tile-cache-using-python/m-p/1114807#M4002</link>
      <description>&lt;P&gt;&lt;a href="https://community.esri.com/t5/user/viewprofilepage/user-id/53755"&gt;@TommyFauvell&lt;/a&gt;&amp;nbsp;&lt;a href="https://community.esri.com/t5/user/viewprofilepage/user-id/2813"&gt;@GarimaTiwari&lt;/a&gt;&amp;nbsp;Do you perhaps have any ideas?&lt;/P&gt;</description>
      <pubDate>Mon, 08 Nov 2021 06:34:58 GMT</pubDate>
      <guid>https://community.esri.com/t5/arcgis-rest-apis-and-services-questions/updating-the-vector-tile-cache-using-python/m-p/1114807#M4002</guid>
      <dc:creator>DeonLengton</dc:creator>
      <dc:date>2021-11-08T06:34:58Z</dc:date>
    </item>
    <item>
      <title>Re: Updating the Vector Tile Cache using python requests library</title>
      <link>https://community.esri.com/t5/arcgis-rest-apis-and-services-questions/updating-the-vector-tile-cache-using-python/m-p/1115881#M4005</link>
      <description>&lt;P&gt;Please add referer to update_vector_tile_cache method&lt;/P&gt;&lt;P&gt;Here is the updated snippet that you can use&lt;/P&gt;&lt;P&gt;def update_vector_tile_cache(self):&lt;BR /&gt;"""&lt;BR /&gt;Update the vector tile cache&lt;BR /&gt;:return:&lt;BR /&gt;"""&lt;BR /&gt;self.logger.info('Updating vector tile cache...')&lt;BR /&gt;url = self.server_url + '/rest/services/System/CachingControllers/GPServer/Manage Vector Tile ' \&lt;BR /&gt;'Cache/submitJob'&lt;BR /&gt;params = {&lt;BR /&gt;'serviceName': 'States_fl',&lt;BR /&gt;'serviceFolder': 'Hosted',&lt;BR /&gt;'tilingFormat': 'INDEXED',&lt;BR /&gt;'token': self.token,&lt;BR /&gt;'f': 'json'&lt;BR /&gt;}&lt;BR /&gt;print(str(url) + str(params))&lt;BR /&gt;&lt;STRONG&gt;header_dic = {'referer': os.environ['SERVER_URL']}&lt;/STRONG&gt;&lt;BR /&gt;result = requests.post(url, params,&lt;STRONG&gt;headers=header_dic)&lt;/STRONG&gt;&lt;BR /&gt;result.raise_for_status()&lt;BR /&gt;response_json = result.json()&lt;/P&gt;</description>
      <pubDate>Wed, 10 Nov 2021 23:46:06 GMT</pubDate>
      <guid>https://community.esri.com/t5/arcgis-rest-apis-and-services-questions/updating-the-vector-tile-cache-using-python/m-p/1115881#M4005</guid>
      <dc:creator>GarimaTiwari</dc:creator>
      <dc:date>2021-11-10T23:46:06Z</dc:date>
    </item>
    <item>
      <title>Re: Updating the Vector Tile Cache using python requests library</title>
      <link>https://community.esri.com/t5/arcgis-rest-apis-and-services-questions/updating-the-vector-tile-cache-using-python/m-p/1115882#M4006</link>
      <description>&lt;P&gt;Thanks for tagging&amp;nbsp;&lt;a href="https://community.esri.com/t5/user/viewprofilepage/user-id/186941"&gt;@DeonLengton&lt;/a&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Wed, 10 Nov 2021 23:46:52 GMT</pubDate>
      <guid>https://community.esri.com/t5/arcgis-rest-apis-and-services-questions/updating-the-vector-tile-cache-using-python/m-p/1115882#M4006</guid>
      <dc:creator>GarimaTiwari</dc:creator>
      <dc:date>2021-11-10T23:46:52Z</dc:date>
    </item>
    <item>
      <title>Re: Updating the Vector Tile Cache using python requests library</title>
      <link>https://community.esri.com/t5/arcgis-rest-apis-and-services-questions/updating-the-vector-tile-cache-using-python/m-p/1115933#M4007</link>
      <description>&lt;P&gt;Thank you so much for your assistance&amp;nbsp;&lt;a href="https://community.esri.com/t5/user/viewprofilepage/user-id/2813"&gt;@GarimaTiwari&lt;/a&gt;&amp;nbsp;&lt;BR /&gt;It is really appreciated!&lt;/P&gt;&lt;P&gt;&lt;a href="https://community.esri.com/t5/user/viewprofilepage/user-id/473448"&gt;@dvonck&lt;/a&gt;&amp;nbsp;will test and we will hopefully be able to respond with an accepted solution soon&lt;/P&gt;</description>
      <pubDate>Thu, 11 Nov 2021 06:32:43 GMT</pubDate>
      <guid>https://community.esri.com/t5/arcgis-rest-apis-and-services-questions/updating-the-vector-tile-cache-using-python/m-p/1115933#M4007</guid>
      <dc:creator>DeonLengton</dc:creator>
      <dc:date>2021-11-11T06:32:43Z</dc:date>
    </item>
    <item>
      <title>Re: Updating the Vector Tile Cache using python requests library</title>
      <link>https://community.esri.com/t5/arcgis-rest-apis-and-services-questions/updating-the-vector-tile-cache-using-python/m-p/1115937#M4008</link>
      <description>&lt;P&gt;Thank you very much &lt;A href="https://community.esri.com/t5/user/viewprofilepage/user-id/2813" target="_blank"&gt;@GarimaTiwari&lt;/A&gt;&amp;nbsp;we can now get the Vector Tile Cache to update.&lt;/P&gt;</description>
      <pubDate>Thu, 11 Nov 2021 06:53:46 GMT</pubDate>
      <guid>https://community.esri.com/t5/arcgis-rest-apis-and-services-questions/updating-the-vector-tile-cache-using-python/m-p/1115937#M4008</guid>
      <dc:creator>dvonck</dc:creator>
      <dc:date>2021-11-11T06:53:46Z</dc:date>
    </item>
    <item>
      <title>Re: Updating the Vector Tile Cache using python requests library</title>
      <link>https://community.esri.com/t5/arcgis-rest-apis-and-services-questions/updating-the-vector-tile-cache-using-python/m-p/1378565#M4658</link>
      <description>&lt;P&gt;Hi,&lt;/P&gt;&lt;P&gt;we realize this is an old post, but since the functionality still does not exist out of the box in enterprise, we took inspiration from your workflow and made a custom FME transformer using HTTPCallers.&lt;/P&gt;&lt;P&gt;For anyone stumbling upon this thread (like we did) looking for a non coding solution:&amp;nbsp;&lt;A href="https://hub.safe.com/publishers/martin-ekstrand/transformers/arcgisenterprisevectortilerebuildcache" target="_blank"&gt;https://hub.safe.com/publishers/martin-ekstrand/transformers/arcgisenterprisevectortilerebuildcache&lt;/A&gt;&lt;/P&gt;&lt;P&gt;Thanks&amp;nbsp;&lt;a href="https://community.esri.com/t5/user/viewprofilepage/user-id/473448"&gt;@dvonck&lt;/a&gt; for the inspiration&amp;nbsp;&lt;span class="lia-unicode-emoji" title=":grinning_face:"&gt;😀&lt;/span&gt;&lt;/P&gt;</description>
      <pubDate>Tue, 06 Feb 2024 09:25:27 GMT</pubDate>
      <guid>https://community.esri.com/t5/arcgis-rest-apis-and-services-questions/updating-the-vector-tile-cache-using-python/m-p/1378565#M4658</guid>
      <dc:creator>StaffanstorpsKommun</dc:creator>
      <dc:date>2024-02-06T09:25:27Z</dc:date>
    </item>
  </channel>
</rss>

