Skip to content

Commit

Permalink
Merge pull request #83 from nasa/harmony-1752
Browse files Browse the repository at this point in the history
Harmony 1752
  • Loading branch information
indiejames authored Apr 25, 2024
2 parents d6b20c1 + 0c70317 commit 740c37c
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 6 deletions.
25 changes: 22 additions & 3 deletions examples/tutorial.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"import sys; sys.path.append('..')\n",
"!{sys.executable} -m pip install -q -r ../requirements/examples.txt\n",
"\n",
"# Install harmony-py requirements. Not necessary if you ran `pip install harmony-py` in your kernel \n",
"# Install harmony-py requirements. Not necessary if you ran `pip install harmony-py` in your kernel\n",
"!{sys.executable} -m pip install -q -r ../requirements/core.txt\n",
"\n",
"import datetime as dt\n",
Expand Down Expand Up @@ -174,12 +174,31 @@
" rasterio.plot.show(rasterio.open(r.result()))"
]
},
{
"cell_type": "markdown",
"id": "f97fa92f",
"metadata": {},
"source": [
"We can also get a URL corresponding to our request that we can use in a browser. **Note:** This will not work if the request includes a shapefile."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f03e22a8",
"metadata": {},
"outputs": [],
"source": [
"url = harmony_client.request_as_url(request)\n",
"print(url)"
]
},
{
"cell_type": "markdown",
"id": "45a14473",
"metadata": {},
"source": [
"Let's build another request. This time, we'll request a specific granule and grid using the UMM grid name from the CMR. You can find grids in the CMR at https://cmr.uat.earthdata.nasa.gov/search/grids.umm_json. Include a query parameter `?name=LambertExample` to list detailed information about a specific grid."
"Let's build another request. This time, we'll request a specific granule and grid using the UMM grid name from the CMR. You can find grids in the CMR at https://cmr.uat.earthdata.nasa.gov/search/grids.umm_json. Include a query parameter `?grid=LambertExample` to list detailed information about a specific grid."
]
},
{
Expand Down Expand Up @@ -317,7 +336,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.2"
"version": "3.11.9"
},
"vscode": {
"interpreter": {
Expand Down
29 changes: 26 additions & 3 deletions harmony/harmony.py
Original file line number Diff line number Diff line change
Expand Up @@ -706,11 +706,13 @@ def _params_dict_to_files(self, params: Mapping[str, Any]) -> List[Tuple[None, s
result += [(key, (None, str(value), None)) for value in values]
return result

def _get_prepared_request(self, request: BaseRequest) -> requests.models.PreparedRequest:
def _get_prepared_request(
self, request: BaseRequest, for_browser=False) -> requests.models.PreparedRequest:
"""Returns a :requests.models.PreparedRequest: object for the given harmony Request
Args:
request: The Harmony Request to prepare
for_browser: if True only the url with query params will be returned
Returns:
A PreparedRequest
Expand All @@ -722,7 +724,7 @@ def _get_prepared_request(self, request: BaseRequest) -> requests.models.Prepare

method = self._http_method(request)
with self._files(request) as files:
if files or method == 'POST':
if (files or method == 'POST') and not for_browser:
# Ideally this should just be files=files, params=params but Harmony
# cannot accept both files and query params now. (HARMONY-290)
# Inflate params to a list of tuples that can be passed as multipart
Expand All @@ -742,17 +744,23 @@ def _get_prepared_request(self, request: BaseRequest) -> requests.models.Prepare
files=all_files,
headers=headers)
else:
if files:
raise Exception("Cannot include shapefile as URL query parameter")

r = requests.models.Request('GET',
self._submit_url(request),
params=params,
headers=headers)

prepped_request = session.prepare_request(r)
if for_browser:
prepped_request.headers = None

return prepped_request

def _handle_error_response(self, response: Response):
"""Raises the appropriate exception based on the response
received from Harmony. Trys to pull out an error message
received from Harmony. Tries to pull out an error message
from a Harmony JSON response when possible.
Args:
Expand Down Expand Up @@ -798,6 +806,21 @@ def request_as_curl(self, request: BaseRequest) -> str:
prepped_request.prepare_cookies(cooks)
return curlify.to_curl(prepped_request)

def request_as_url(self, request: BaseRequest) -> str:
"""Returns a URL string representation of the given request.
**Note** Headers and cookies are not included, just the URL.
Shapefiles are not supported.
Args:
request: The Request to build the URL string for
Returns:
A URL string that can be pasted into a browser.
:raises
Exception: if a shapefile is included in the request.
"""
return self._get_prepared_request(request, for_browser=True).url

def submit(self, request: BaseRequest) -> any:
"""Submits a request to Harmony and returns the Harmony Job ID.
Expand Down
22 changes: 22 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1502,6 +1502,28 @@ def test_request_as_curl_post(examples_dir):
f'/ogc-api-coverages/1.0.0/collections/all/coverage/rangeset' in curl_command
assert '-X POST' in curl_command

def test_request_as_url():
collection = Collection(id='C1940468263-POCLOUD')
request = Request(
collection=collection,
spatial=BBox(-107, 40, -105, 42)
)

url = Client(should_validate_auth=False).request_as_url(request)
assert url == 'https://harmony.earthdata.nasa.gov/C1940468263-POCLOUD/ogc-api-coverages/1.0.0/collections/all/coverage/rangeset?forceAsync=true&subset=lat%2840%3A42%29&subset=lon%28-107%3A-105%29'

def test_request_with_shapefile_as_url(examples_dir):
collection = Collection(id='C1940468263-POCLOUD')
request = Request(
collection=collection,
shape=os.path.join(examples_dir, 'asf_example.json'),
spatial=BBox(-107, 40, -105, 42)
)

with pytest.raises(Exception) as e:
Client(should_validate_auth=False).request_as_url(request)
assert str(e.value) == "Cannot include shapefile as URL query parameter"

@responses.activate
def test_collection_capabilities():
collection_id='C1940468263-POCLOUD'
Expand Down

0 comments on commit 740c37c

Please sign in to comment.