Skip to content

Commit

Permalink
Merge pull request #34 from GeoNodeUserGroup-DE/issue_#33_refector_Ge…
Browse files Browse the repository at this point in the history
…onodeEnv_to_be_more_useable_lib_mode

[Fixes #33] refector GeonodeEnv to be more useable lib mode
  • Loading branch information
mwallschlaeger authored Apr 11, 2024
2 parents 62b935b + 0a4b6fb commit dfd76b6
Show file tree
Hide file tree
Showing 6 changed files with 74 additions and 36 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ usage: geonodectl [-h] [--not-verify-ssl] [--raw] [--page-size PAGE_SIZE]
geonodectl is a cmd client for the geonodev4 rest-apiv2.
To use this tool you have to set the following environment variables before starting:
GEONODECTL_URL: https://geonode.example.com/api/v2/ -- path to the v2 endpoint of your target geonode instance
GEONODECTL_BASIC: YWRtaW46YWRtaW4= -- you can generate this string like: echo -n user:password | base64
GEONODE_API_URL: https://geonode.example.com/api/v2/ -- path to the v2 endpoint of your target geonode instance
GEONODE_API_BASIC_AUTH: YWRtaW46YWRtaW4= -- you can generate this string like: echo -n user:password | base64
positional arguments:
{resources,resource,dataset,ds,documents,doc,document,maps,geoapps,apps,people,users,user,uploads,executionrequest}
Expand Down Expand Up @@ -64,8 +64,8 @@ pip install -e 'git+https://github.com/GeoNodeUserGroup-DE/geonodectl.git@main#

Additionally to package install, **geonodectl** requires to set two environment variables to connect to a geonode instance like:
```
GEONODECTL_URL: https://master.demo.geonode.org/api/v2/ # make sure to supply full api url
GEONODECTL_BASIC: dXNlcjpwYXNzd29yZA== # you can generate this string like: echo -n user:password | base64
GEONODE_API_URL: https://master.demo.geonode.org/api/v2/ # make sure to supply full api url
GEONODE_API_BASIC_AUTH: dXNlcjpwYXNzd29yZA== # you can generate this string like: echo -n user:password | base64
```

Now you are ready to go. upload shape file:
Expand Down
8 changes: 4 additions & 4 deletions geonodectl
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ from typing import List, Union
from argparse import RawTextHelpFormatter
from pathlib import Path

from geonoderest.geonodetypes import GeonodeEnv
from geonoderest.apiconf import GeonodeApiConf
from geonoderest.geonodeobject import GeonodeObjectHandler
from geonoderest.datasets import GeonodeDatasetsHandler
from geonoderest.resources import GeonodeResourceHandler, SUPPORTED_METADATA_TYPES, DEFAULT_METADATA_TYPE
Expand All @@ -19,8 +19,8 @@ from geonoderest.geoapps import GeonodeGeoappsHandler
from geonoderest.uploads import GeonodeUploadsHandler
from geonoderest.executionrequest import GeonodeExecutionRequestHandler

GEONODECTL_URL_ENV_VAR: str = "GEONODECTL_URL"
GEONODECTL_BASIC_ENV_VAR: str = "GEONODECTL_BASIC"
GEONODECTL_URL_ENV_VAR: str = "GEONODE_API_URL"
GEONODECTL_BASIC_ENV_VAR: str = "GEONODE_API_BASIC_AUTH"

DEFAULT_CHARSET: str = "UTF-8"

Expand Down Expand Up @@ -493,7 +493,7 @@ To use this tool you have to set the following environment variables before star
f"provided geonode url: {url} not ends with 'api/v2/'. Please make sure to provide full rest v2api url ..."
)

geonode_env = GeonodeEnv(url=url, auth_basic=basic, verify=args.ssl_verify)
geonode_env = GeonodeApiConf(url=url, auth_basic=basic, verify=args.ssl_verify)
g_obj: Union[GeonodeObjectHandler, GeonodeExecutionRequestHandler]
match args.command:
case "resources" | "resource":
Expand Down
46 changes: 46 additions & 0 deletions geonoderest/apiconf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from pathlib import Path
import os

from dataclasses import dataclass


@dataclass
class GeonodeApiConf:
url: str
auth_basic: str
verify: bool

@staticmethod
def from_env_file(path: Path) -> "GeonodeApiConf":
"""
Creates a new GeonodeApiConf object from a .env file
"""
with path.open("r") as f:
for line in f:
if line.startswith("#"):
continue
if "=" not in line:
continue
key, value = line.split("=")
if key == "GEONODE_API_URL":
url = value
if key == "GEONODE_API_BASIC_AUTH":
auth_basic = value
if key == "GEONODE_API_VERIFY":
verify = value == "True"
return GeonodeApiConf(url=url, auth_basic=auth_basic, verify=verify)

@staticmethod
def from_env_vars() -> "GeonodeApiConf":
"""
Creates a new GeonodeApiConf object from environment variables
"""
if not ["GEONODE_API_URL", "GEONODE_API_BASIC_AUTH"] in os.environ:
raise SystemExit(
"env vars not set: GEONODE_API_URL, GEONODE_API_BASIC_AUTH"
)

url = os.getenv("GEONODE_API_URL", "")
auth_basic = os.getenv("GEONODE_API_BASIC_AUTH", "")
verify = True if "True" == os.getenv("GEONODE_API_VERIFY", "True") else False
return GeonodeApiConf(url=url, auth_basic=auth_basic, verify=verify)
29 changes: 13 additions & 16 deletions geonoderest/geonodeobject.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,10 @@ def delete(self, pk: int, **kwargs):
def cmd_patch(
self,
pk: int,
fields: Optional[str] = None,
json_path: Optional[str] = None,
**kwargs,
):
"""
Tries to generate object from incoming json string
Tries to generate object from incoming json string
Args:
pk (int): pk of the object
fields (str): string of potential json object
Expand All @@ -63,6 +61,16 @@ def cmd_patch(
Raises:
ValueError: catches json.decoder.JSONDecodeError and raises ValueError as decoding is not working
"""
obj = self.patch(pk=pk, **kwargs)
print_json(obj)

def patch(
self,
pk: int,
fields: Optional[str] = None,
json_path: Optional[str] = None,
**kwargs,
):
if json_path:
with open(json_path, "r") as file:
fields_dict = json.load(file)
Expand All @@ -75,23 +83,12 @@ def cmd_patch(
endpoint=f"{self.ENDPOINT_NAME}/{pk}/", params=fields_dict
)
elif fields:
try:
json_data = json.loads(fields)
except ValueError:
raise (
ValueError(
f"unable to decode argument: | {fields} | to json object ..."
)
)
obj = self.http_patch(
endpoint=f"{self.ENDPOINT_NAME}/{pk}/", params=json_data
)
obj = self.http_patch(endpoint=f"{self.ENDPOINT_NAME}/{pk}/", params=fields)
else:
raise ValueError(
"At least one of 'fields' or 'json_path' must be provided."
)

print_json(obj)
return obj

def cmd_describe(self, pk: int, **kwargs):
obj = self.get(pk=pk, **kwargs)
Expand Down
7 changes: 0 additions & 7 deletions geonoderest/geonodetypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,3 @@ def get_key(self, ds: dict):
GeonodeHTTPFile: TypeAlias = Tuple[
str, Union[Tuple[str, io.BufferedReader], Tuple[str, io.BufferedReader, str]]
]


@dataclass
class GeonodeEnv:
url: str
auth_basic: str
verify: bool
12 changes: 7 additions & 5 deletions geonoderest/rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
import urllib3
import requests
import logging
from geonoderest.geonodetypes import GeonodeEnv, GeonodeHTTPFile

from geonoderest.geonodetypes import GeonodeHTTPFile
from geonoderest.apiconf import GeonodeApiConf

urllib3.disable_warnings()

Expand All @@ -15,7 +17,7 @@


class GeonodeRest(object):
def __init__(self, env: GeonodeEnv):
def __init__(self, env: GeonodeApiConf):
self.gn_credentials = env

@staticmethod
Expand All @@ -26,17 +28,17 @@ def inner(*args, **kwargs):
except requests.exceptions.ConnectionError:
raise SystemExit(
"connection error: Could not reach geonode api. please check if the endpoint up and available, "
"check also the env variable: GEONODECTL_URL ..."
"check also the env variable: GEONODE_API_URL ..."
)
except urllib3.exceptions.MaxRetryError:
raise SystemExit(
"max retries exceeded: Could not reach geonode api. please check if the endpoint up and available, "
"check also the env variable: GEONODECTL_URL ..."
"check also the env variable: GEONODE_API_URL ..."
)
except ConnectionRefusedError:
raise SystemExit(
"connection refused: Could not reach geonode api. please check if the endpoint up and available, "
"check also the env variable: GEONODECTL_URL ..."
"check also the env variable: GEONODE_API_URL ..."
)

return inner
Expand Down

0 comments on commit dfd76b6

Please sign in to comment.