In [1]:
%%bash
apt-get update
apt-get install -y libffi-dev libssl-dev python-dev python-pip python-imaging python-gdal
pip install cryptography google-api-python-client earthengine-api
This walks through the same flow that is used by the "earthengine authenticate
" command, but it works even when you do not have easy access to an interactive shell on the remote host. These should become available as helper functions in the Earth Engine client library, but for now you can still do it by hand.
Start by importing the Python libraries that we're going to use to configure the Earth Engine credentials.
In [2]:
import ee
import errno
import IPython
import json
import os
import urllib
import urllib2
These helper functions implement the authentication flow.
In [3]:
def get_authorization_url():
# This redirect_uri prompts you to copy and paste a code after successful authorization.
return 'https://accounts.google.com/o/oauth2/auth?' + urllib.urlencode({
'client_id': ee.oauthinfo.OAuthInfo.CLIENT_ID,
'scope': ee.oauthinfo.OAuthInfo.SCOPE,
'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',
'response_type': 'code',
})
def get_refresh_token(auth_code):
args = {
'code': auth_code,
'client_id': ee.oauthinfo.OAuthInfo.CLIENT_ID,
'client_secret': ee.oauthinfo.OAuthInfo.CLIENT_SECRET,
'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',
'grant_type': 'authorization_code',
}
response = urllib2.urlopen('https://accounts.google.com/o/oauth2/token',
urllib.urlencode(args)).read()
return json.loads(response)['refresh_token']
def save_token(refresh_token):
credentials_path = ee.oauthinfo.OAuthInfo.credentials_path()
try:
os.makedirs(os.path.dirname(credentials_path))
except OSError, e:
if e.errno != errno.EEXIST:
raise
json.dump({'refresh_token': refresh_token}, open(credentials_path, 'w'))
print 'Successfully saved authorization to %s' % credentials_path
Running this next command will print a URL that you can click on to begin the authentication flow. Copy the code that it generates and come back here for the next step.
In [4]:
print(get_authorization_url())
Finally, paste the auth code that you were given into this next command (in place of "YOUR_AUTH_TOKEN_GOES_HERE
") and run it to save your credentials on this Datalab instance.
In [6]:
save_token(get_refresh_token('https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fearthengine+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdevstorage.read_write&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&response_type=code&client_id=517222506229-vsmmajv00ul0bs7p89v5m89qs8eb9359.apps.googleusercontent.com'))
In [7]:
ee.Initialize()
srtm = ee.Image('USGS/SRTMGL1_003')
srtm_vis = srtm.visualize(min=0, max=5000, gamma=1.6)
srtm_thumb = ee.data.getThumbnail({'image':srtm_vis.serialize()})
IPython.display.display(IPython.display.Image(srtm_thumb))
In [8]:
!ls
In [ ]: