Ejemplo n.º 1
0
def stats():
    # Get API Key: Requires user to have initialized Planet CLI
    try:
        api_key = find_api_key()
        os.environ['PLANET_API_KEY'] = find_api_key()
    except Exception as e:
        print('Failed to get Planet Key: Try planet init')
        sys.exit()


    SESSION = requests.Session()
    SESSION.auth = (api_key, '')
    print('Checking on all running orders...')
    result = SESSION.get('https://api.planet.com/compute/ops/stats/orders/v2')
    if int(result.status_code)==200:
        page=result.json()
        try:
            print('\n'+'Total queued order for organization: '+str(page['organization']['queued_orders']))
            print('Total running orders for organization: '+str(page['organization']['running_orders']))
            print('\n'+'Total queued orders for user: '******'user']['queued_orders']))
            print('Total running orders for user: '******'user']['running_orders']))
        except Exception as e:
            print(e)
    elif int(result.status_code)==401:
        print('Access denied - insufficient privileges')
    elif int(result.status_code)==500:
        print('Server Error')
    else:
        print('Failed with '+str(result.status_code)+' '+str(result.text))
Ejemplo n.º 2
0
def download(name,asset,path,limit=None):
    try:
        PL_API_KEY = find_api_key()
        os.environ['PLANET_API_KEY']=find_api_key()
    except:
        print('Failed to get Planet Key')
        sys.exit()
    try:
        k = PL_API_KEY
        main = requests.get(
            'https://api.planet.com/data/v1/searches/?search_type=saved',
            auth=HTTPBasicAuth(
                k, ''))
        if main.status_code == 200:
            content = main.json()
            for items in content['searches']:
                if (items['name']==name and limit is not None):
                    print("Processing limited assets of size "+str(limit)+" with name "+str(items['name'])+" with id "+str(items['id']))
                    subprocess.call('planet data download --search-id '+'"'+str(items['id'])+'"'+' --asset-type '+'"'+asset+'"'+' --limit '+'"'+str(limit)+'"'+' --dest '+'"'+str(path)+'"',shell=True)
                elif (items['name']==name and limit is None):
                    print("Processing all assets for "+str(items['name'])+" with id "+str(items['id']))
                    subprocess.call('planet data download --search-id '+'"'+str(items['id'])+'"'+' --asset-type '+'"'+asset+'"'+' --dest '+'"'+str(path)+'"',shell=True)
                elif items['name'] !=name:
                    pass
        else:
            print('Failed with exception code: ' + str(
                main.status_code))
    except IOError:
        print('Initialize client or provide API Key')
Ejemplo n.º 3
0
def stats():
    # Get API Key: Requires user to have initialized Planet CLI
    try:
        api_key = find_api_key()
        os.environ["PLANET_API_KEY"] = find_api_key()
    except Exception as e:
        print("Failed to get Planet Key: Try planet init")
        sys.exit()

    SESSION = requests.Session()
    SESSION.auth = (api_key, "")
    print("Checking on all running orders...")
    result = SESSION.get("https://api.planet.com/compute/ops/stats/orders/v2")
    if int(result.status_code) == 200:
        page = result.json()
        try:
            print("\n" + "Total queued order for organization: " +
                  str(page["organization"]["queued_orders"]))
            print("Total running orders for organization: " +
                  str(page["organization"]["running_orders"]))
            print("\n" + "Total queued orders for user: "******"user"]["queued_orders"]))
            print("Total running orders for user: "******"user"]["running_orders"]))
        except Exception as e:
            print(e)
    elif int(result.status_code) == 401:
        print("Access denied - insufficient privileges")
    elif int(result.status_code) == 500:
        print("Server Error")
    else:
        print("Failed with " + str(result.status_code) + " " +
              str(result.text))
Ejemplo n.º 4
0
def planet_quota():
    # Get API Key: Requires user to have initialized Planet CLI
    try:
        api_key = find_api_key()
        os.environ['PLANET_API_KEY'] = find_api_key()
    except Exception as e:
        print('Failed to get Planet Key: Try planet init')
        sys.exit()
    '''Print allocation and remaining quota in Sqkm.'''
    try:
        main = requests.get('https://api.planet.com/auth/v1/experimental/public/my/subscriptions', auth=(api_key, ''))
        if main.status_code == 200:
            content = main.json()
            for item_id in content:
                print(" ")
                print(
                    'Subscription ID: %s'
                    % item_id['id'])
                print(
                    'Plan ID: %s'
                    % item_id['plan_id'])
                print(
                    'Allocation Name: %s'
                    % item_id['organization']['name'])
                print(
                    'Allocation active from: %s'
                    % item_id['active_from'].split("T")[0])
                print(
                    'Quota Enabled: %s'
                    % item_id['quota_enabled'])
                print(
                    'Total Quota in SqKm: %s'
                    % item_id['quota_sqkm'])
                print(
                    'Total Quota used: %s'
                    % item_id['quota_used'])
                if (item_id['quota_sqkm'])is not None:
                    leftquota = (float(
                        item_id['quota_sqkm'] - float(item_id['quota_used'])))
                    print(
                        'Remaining Quota in SqKm: %s' % leftquota)
                else:
                    print('No Quota Allocated')
                print('')
        elif main.status_code == 500:
            print('Temporary issue: Try again')
        else:
            print('Failed with exception code: ' + str(
                main.status_code))

    except IOError:
        print('Initialize client or provide API Key')
Ejemplo n.º 5
0
def planet_quota():
    # Get API Key: Requires user to have initialized Planet CLI
    try:
        api_key = find_api_key()
        os.environ["PLANET_API_KEY"] = find_api_key()
    except Exception as e:
        print("Failed to get Planet Key: Try planet init")
        sys.exit()
    """Print allocation and remaining quota in Sqkm."""
    try:
        main = requests.get(
            "https://api.planet.com/auth/v1/experimental/public/my/subscriptions",
            auth=(api_key, ""),
        )
        if main.status_code == 200:
            content = main.json()
            for item_id in content:
                try:
                    print(" ")
                    print("Subscription ID: %s" % item_id["id"])
                    print("Plan ID: %s" % item_id["plan_id"])
                    print("Allocation Name: %s" % item_id["organization"]["name"])
                    print(
                        "Allocation active from: %s"
                        % item_id["active_from"].split("T")[0]
                    )
                    if item_id["active_to"] is not None:
                        print(
                            "Allocation active to: %s"
                            % item_id["active_to"].split("T")[0]
                        )
                    print("Quota Enabled: %s" % item_id["quota_enabled"])
                    print("Total Quota in SqKm: %s" % item_id["quota_sqkm"])
                    print("Total Quota used: %s" % item_id["quota_used"])
                    if (item_id["quota_sqkm"]) is not None:
                        leftquota = float(
                            item_id["quota_sqkm"] - float(item_id["quota_used"])
                        )
                        print("Remaining Quota in SqKm: %s" % leftquota)
                    else:
                        print("No Quota Allocated")
                    print("")
                except Exception as e:
                    pass
        elif main.status_code == 500:
            print("Temporary issue: Try again")
        else:
            print("Failed with exception code: " + str(main.status_code))

    except IOError:
        print("Initialize client or provide API Key")
def _get_json_or_raise(url, timeout=11):
    api_key = find_api_key()
    headers = {'User-Agent': _get_user_agent(),
               'Authorization': 'api-key %s' % api_key}
    resp = requests.get(url, timeout=timeout, headers=headers)
    resp.raise_for_status()
    return resp.json()
Ejemplo n.º 7
0
def cancel(id):
    headers = {"Content-Type": "application/json"}
    # Get API Key: Requires user to have initialized Planet CLI
    try:
        api_key = find_api_key()
    except Exception as e:
        print("Failed to get Planet Key: Try planet init")
        sys.exit()
    if id == "all":
        url = "https://api.planet.com/compute/ops/bulk/orders/v2/cancel"
        resp = requests.post(url,
                             data="{}",
                             headers=headers,
                             auth=(api_key, ""))
        if resp.status_code == 200:
            print("Number of orders failed to cancel: " +
                  str(resp.json()["result"]["failed"]["count"]))
            print("Number of orders successfully cancelled: " +
                  str(resp.json()["result"]["succeeded"]["count"]))
        else:
            print("Failed wth status code & error: " + str(resp.status_code) +
                  " : " + str(resp.json()))
    else:
        url = "https://api.planet.com/compute/ops/orders/v2/" + str(id)
        resp = requests.put(url, headers=headers, auth=(api_key, ""))
        if resp.status_code == 200:
            print("Orders ID " + str(id) + " successfully cancelled")
        else:
            print("Failed wth status code & error: " + str(resp.status_code) +
                  " : " + str(resp.json()))
def download(name, asset, path, limit=None):
    try:
        PL_API_KEY = find_api_key()
        os.environ["PLANET_API_KEY"] = find_api_key()
    except:
        print("Failed to get Planet Key")
        sys.exit()
    try:
        k = PL_API_KEY
        main = requests.get(
            "https://api.planet.com/data/v1/searches/?search_type=saved",
            auth=HTTPBasicAuth(k, ""),
        )
        if main.status_code == 200:
            content = main.json()
            for items in content["searches"]:
                if items["name"] == name and limit is not None:
                    print("Processing limited assets of size " + str(limit) +
                          " with name " + str(items["name"]) + " with id " +
                          str(items["id"]))
                    subprocess.call(
                        "planet data download --search-id " + '"' +
                        str(items["id"]) + '"' + " --asset-type " + '"' +
                        asset + '"' + " --limit " + '"' + str(limit) + '"' +
                        " --dest " + '"' + str(path) + '"',
                        shell=True,
                    )
                elif items["name"] == name and limit is None:
                    print("Processing all assets for " + str(items["name"]) +
                          " with id " + str(items["id"]))
                    subprocess.call(
                        "planet data download --search-id " + '"' +
                        str(items["id"]) + '"' + " --asset-type " + '"' +
                        asset + '"' + " --dest " + '"' + str(path) + '"',
                        shell=True,
                    )
                elif items["name"] != name:
                    pass
        else:
            print("Failed with exception code: " + str(main.status_code))
    except IOError:
        print("Initialize client or provide API Key")
Ejemplo n.º 9
0
__license__ = "Apache 2.0"

import requests
import time
import progressbar
import json
import os
import sys
import csv
from retrying import retry
from planet.api.utils import read_planet_json
from planet.api.auth import find_api_key

#Get Planet API and Authenticate SESSION
try:
    PL_API_KEY = find_api_key()
except:
    print('Failed to get Planet Key')
    sys.exit()
SESSION = requests.Session()
SESSION.auth = (PL_API_KEY, '')


# To get redirect link
@retry(wait_exponential_multiplier=1000, wait_exponential_max=10000)
def check_for_redirects(url):
    try:
        r = SESSION.get(url, allow_redirects=False, timeout=0.5)
        if 300 <= r.status_code < 400:
            return r.headers['location']
        elif r.status_code == 429:
Ejemplo n.º 10
0
import shapely.geometry as geom
from requests.auth import HTTPBasicAuth
from planet.api.auth import find_api_key
from shapely.geometry import Point, box, Polygon, MultiPoint
os.chdir(os.path.dirname(os.path.realpath(__file__)))
path = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, path)
try:
    ee.Initialize()
except Exception, e:
    print 'Authenticate Earth Engine first and rerun program'
    time.sleep(2)
    os.system('earthengine authenticate')
src = os.path.dirname(os.path.realpath(__file__))
try:
    api_key = find_api_key()
    os.environ['PLANET_API_KEY'] = find_api_key()
except:
    print 'Failed to get Planet Key'
    sys.exit()
l = []

for items in os.listdir(src):
    if items.endswith('.csv'):
        input_file = csv.DictReader(open(os.path.join(src, items)))
        for rows in input_file:
            l.append(rows['id'])


def intersect(start, end, geometry, operator, output):
    with open(output, 'wb') as csvfile: