|
| 1 | +import requests |
| 2 | +import json |
| 3 | +from django.core.management.base import BaseCommand |
| 4 | +from hs_data_services import settings |
| 5 | +from hs_data_services_sync import utilities |
| 6 | + |
| 7 | + |
| 8 | +class Command(BaseCommand): |
| 9 | + help = "Unregister resource in GeoServer" |
| 10 | + |
| 11 | + def add_arguments(self, parser): |
| 12 | + parser.add_argument('resource_ids', nargs='*', type=str) |
| 13 | + |
| 14 | + def handle(self, *args, **options): |
| 15 | + resource_ids = options['resource_ids'] |
| 16 | + if len(resource_ids) > 0: |
| 17 | + for resource_id in resource_ids: |
| 18 | + print(f"Unregistering resource: {resource_id}") |
| 19 | + result = utilities.unregister_geoserver_databases(resource_id) |
| 20 | + print(result) |
| 21 | + else: |
| 22 | + resources = self.get_list_of_public_geo_resources() |
| 23 | + num_resources = len(resources) |
| 24 | + print(f"Unregistering {num_resources} public resources") |
| 25 | + counter = 1 |
| 26 | + for res_id in resources: |
| 27 | + print(f"{counter}/{num_resources} - Unregistering: {res_id}") |
| 28 | + result = utilities.unregister_geoserver_databases(res_id) |
| 29 | + print(result) |
| 30 | + counter += 1 |
| 31 | + print("Done unregistering resources") |
| 32 | + |
| 33 | + def get_list_of_public_geo_resources(self): |
| 34 | + hydroshare_url = "/".join(settings.HYDROSHARE_URL.split("/")[:-1]) |
| 35 | + types = ["Geographic Feature (ESRI Shapefiles)", "Geographic Raster"] |
| 36 | + # replace spaces with + for the query string |
| 37 | + types = [t.replace(" ", "+") for t in types] |
| 38 | + params = { |
| 39 | + "type": types, |
| 40 | + "availability": ["public"], |
| 41 | + "geofilter": "false" |
| 42 | + } |
| 43 | + rest_url = f"{hydroshare_url}/discoverapi/?filter={json.dumps(params)}" |
| 44 | + rest_url = rest_url.replace(" ", "") |
| 45 | + print(f"Getting list of public geospatial resources from: {rest_url}") |
| 46 | + response = requests.get(rest_url) |
| 47 | + response_json = response.json() |
| 48 | + page_count = response_json.get('pagecount', 0) |
| 49 | + rescount = response_json.get('rescount', 0) |
| 50 | + perpage = response_json.get('perpage', 0) |
| 51 | + res_ids = [] |
| 52 | + print(f"Iterating over {page_count} pages of {perpage} resources each, total resources: {rescount}") |
| 53 | + for i in range(1, page_count + 1): |
| 54 | + print(f"Getting page {i}") |
| 55 | + response = requests.get(f"{rest_url}&pnum={i}") |
| 56 | + response_json = response.json() |
| 57 | + resources = json.loads(response_json.get('resources', [])) |
| 58 | + new_ids = [resource["short_id"] for resource in resources if resource.get('short_id', None)] |
| 59 | + res_ids.extend(new_ids) |
| 60 | + print(f"Found {len(res_ids)} public geospatial resources") |
| 61 | + print(f"Should match {rescount}") |
| 62 | + return res_ids |
0 commit comments