Select to view content in your preferred language

AGOL/Portal login in Python 3.8

10-25-2020 02:56 PM
New Contributor


I cannot login to AGOL/Portal since moving to Python 3.8.

The sample code is:

from IPython.display import displayfrom arcgis.gis import GISimport osusername = "arcgis_python"password = "P@ssword123"gis = GIS("", username, password)

I have replaced with my values, and have a token.

But keep getting a tokenURL or the token is not valid error??

I also tried:

from arcgis.features import FeatureLayer, GeoAccessor, GeoSeriesAccessor
from arcgis.geoenrichment import enrich
from arcgis import dissolve_boundaries
from arcgis.geometry import project
from arcgis.gis import GIS

# Organization Login
## gis = GIS('', 'username', 'password')

portal_url = url

gis = portal_url+token

print("Logged IN to portal URL")


cfa_fl = FeatureLayer(cfa_url+token)
dc_df = GeoAccessor.from_layer(cfa_fl)

I want to automatically login to AGOL/Portal to home or contents, to browse the MapServices, FeatureServices, etc..

Any assistance is appreciated.

0 Kudos
5 Replies
Esri Contributor

is the token you are using current / not expired? 

If logging in to ArcGIS Enterprise, check that there are no ssl certificate errors (this should not be the case with AGOL) if there is, see if adding verify_cert=False fixes the problem. if this fixes the problem with AGOL logins this could be an issue with python SSL handling. 

gis = GIS(", "arcgis_python", "P@ssword123", verify_cert=False)

alternatively you may need to generate a new token. (response.text in the example below will contain the token). note that in this example you will need to register a client id for your application

import requests url = ""

payload = "client_id=CLIENT_ID_FROM_YOUR_APPLICATION&client_secret=CLIENT_SECRET_FROM_YOUR_APPLICATION&grant_type=client_credentials"

headers = { 'content-type': "application/x-www-form-urlencoded", 'accept': "application/json", 'cache-control': "no-cache", 'postman-token': "11df29d1-17d3-c58c-565f-2ca4092ddf5f" }

response = requests.request("POST", url, data=payload, headers=headers)


Esri Regular Contributor

Can you please share the exact error message you get when logging in?

0 Kudos
Occasional Contributor II

Hi Joshua,

I updated the ESRI sample (Scripting with the ArcGIS REST API—Portal for ArcGIS | Documentation for ArcGIS Enterprise).

I can log into our Portal, but not our AGOL??

I am getting the following error now, when trying to login to our AGOL??

Error: This site can’t be reached

server IP address could not be found

0 Kudos
New Contributor

Hi Joshua,

I can login to our company AGOL now using..

agolUrl = GIS(portal_link, username = agolusername, password = agolpassword)
## print("Logged in as: " + str(
print('Login Succesful')

I am now getting an error logging into company Portal, it was working before??

Don't understand why I am getting an error, when it was working before??

ESRI documentation says that it only reads approx 16 characters, but the token generated is 192 chars long.

portalUrl = GIS(portal_link+token, username = agolusername, password = agolpassword, verify_cert=False)
##print("Logged IN")


File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\arcgis\gis\_imppy", line 1143, in _enterprise_token
res =,
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\arcgis\gis\_imppy", line 700, in post
raise Exception('A general error occurred: %s' % e)
Exception: A general error occurred: encoding with 'idna' codec failed (UnicodeError: label too lon
PS C:\Users\user\OneDrive - EKFB\Documents\Apps> & C:/Users/user/AppData/Local/Programs/Pon.exe "c:/Users/user/OneDrive - EKFB/Documents/Apps/Python Scripts/"
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\encodings\", line 167,
raise UnicodeError("label too long")
UnicodeError: label too long

0 Kudos
New Contributor

Hi Joshua,

Also getting the same error using Jupyter Notebooks: label to long??

This is an ESRI token!!

Jupyter Notebooks error:

UnicodeError                              Traceback (most recent call last)~\anaconda3\lib\encodings\ in encode(self, input, errors)    166             if len(labels[-1]) >= 64:--> 167                 raise UnicodeError("label too long")    168             return result, len(input)UnicodeError: label too long  The above exception was the direct cause of the following exception: UnicodeError                              Traceback (most recent call last)~\anaconda3\lib\site-packages\arcgis\gis\_impl\_con\ in post(self, path, params, files, **kwargs)    673             else:--> 674                 resp =,    675                                           data=params,~\anaconda3\lib\site-packages\requests\ in post(self, url, data, json, **kwargs)    577 --> 578         return self.request('POST', url, data=data, json=json, **kwargs)    579  ~\anaconda3\lib\site-packages\requests\ in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)    529         send_kwargs.update(settings)--> 530         resp = self.send(prep, **send_kwargs)    531  ~\anaconda3\lib\site-packages\requests\ in send(self, request, **kwargs)    642         # Send the request--> 643         r = adapter.send(request, **kwargs)    644  ~\anaconda3\lib\site-packages\requests\ in send(self, request, stream, timeout, verify, cert, proxies)    438             if not chunked:--> 439                 resp = conn.urlopen(    440                     method=request.method,~\anaconda3\lib\site-packages\urllib3\ in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)    669             # Make the request on the httplib connection object.--> 670             httplib_response = self._make_request(    671                 conn,~\anaconda3\lib\site-packages\urllib3\ in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)    380         try:--> 381             self._validate_conn(conn)    382         except (SocketTimeout, BaseSSLError) as e:~\anaconda3\lib\site-packages\urllib3\ in _validate_conn(self, conn)    975         if not getattr(conn, "sock", None):  # AppEngine might not have  `.sock`--> 976             conn.connect()    977  ~\anaconda3\lib\site-packages\urllib3\ in connect(self)    307         # Add certificate verification--> 308         conn = self._new_conn()    309         hostname = ~\anaconda3\lib\site-packages\urllib3\ in _new_conn(self)    158         try:--> 159             conn = connection.create_connection(    160                 (self._dns_host, self.port), self.timeout, **extra_kw ~\anaconda3\lib\site-packages\urllib3\util\ in create_connection(address, timeout, source_address, socket_options)     60 ---> 61     for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):     62         af, socktype, proto, canonname, sa = res ~\anaconda3\lib\ in getaddrinfo(host, port, family, type, proto, flags)    917     addrlist = []--> 918     for res in _socket.getaddrinfo(host, port, family, type, proto, flags):    919         af, socktype, proto, canonname, sa = res UnicodeError: encoding with 'idna' codec failed (UnicodeError: label too long)  During handling of the above exception, another exception occurred: Exception                                 Traceback (most recent call last)<ipython-input-2-0051d4567ffa> in <module>     21      22 ---> 23 portal = GIS(portalURL+token, username, password, verify_cert=False)     24      25 #### Get Users and Items~\anaconda3\lib\site-packages\arcgis\gis\ in __init__(self, url, username, password, key_file, cert_file, verify_cert, set_active, client_id, profile, **kwargs)    337                                    "argument when connecting to the GIS.")    338             else:--> 339                 raise e    340         try:    341             if url.lower().find("") > -1 and \~\anaconda3\lib\site-packages\arcgis\gis\ in __init__(self, url, username, password, key_file, cert_file, verify_cert, set_active, client_id, profile, **kwargs)    312             self._expiration = 60    313         try:--> 314             self._portal = _portalpy.Portal(self._url, self._username,    315                                            self._password, self._key_file,    316                                            self._cert_file,~\anaconda3\lib\site-packages\arcgis\gis\_impl\ in __init__(self, url, username, password, key_file, cert_file, expiration, referer, proxy_host, proxy_port, connection, workdir, tokenurl, verify_cert, client_id, custom_auth, token)    167                                       token=token)    168         #self.get_version(True)--> 169         self.get_properties(True)    170     171  ~\anaconda3\lib\site-packages\arcgis\gis\_impl\ in get_properties(self, force)   1107                     resp = self.con.get(path, ssl=True) # issue seen with key, cert auth   1108                 if not resp:-> 1109                     raise e   1110    1111             if resp:~\anaconda3\lib\site-packages\arcgis\gis\_impl\ in get_properties(self, force)   1095             resp = None   1096             try:-> 1097                 resp =, self._postdata(), ssl=True)   1098             except Exception as e:   1099                 if not self.con._verify_cert and \~\anaconda3\lib\site-packages\arcgis\gis\_impl\_con\ in post(self, path, params, files, **kwargs)    619                     params.pop('token', None)    620                     #pass--> 621             elif token_as_header == False and self.token is not None: #as ?token=    622                 params['token'] = self.token    623             elif token_as_header and self.token is not None:#(token and token != _DEFAULT_TOKEN): # as X-Esri-Auth header with given token~\anaconda3\lib\site-packages\arcgis\gis\_impl\_con\ in token(self)   1026                                    "AGO", "ENTERPRISE"] and \   1027                  self._auth == "BUILTIN":-> 1028                 self._token = self._enterprise_token()   1029                 return self._token   1030             else:~\anaconda3\lib\site-packages\arcgis\gis\_impl\_con\ in _enterprise_token(self)   1141                                                                                 path.split('/')[0])   1142 -> 1143         res =,   1144                         params=postdata,   1145                         add_token=False) ~\anaconda3\lib\site-packages\arcgis\gis\_impl\_con\ in post(self, path, params, files, **kwargs)    698                 "URL scheme must be provided: %s" % errMS)    699         except Exception as e:--> 700             raise Exception('A general error occurred: %s' % e)    701         except:    702             import traceback Exception: A general error occurred: encoding with 'idna' codec failed (UnicodeError: label too long)
0 Kudos