Skip to content

Commit 9d88596

Browse files
author
OCurdy
committed
add arcpy and proxy
1 parent 11b9c62 commit 9d88596

File tree

2 files changed

+55
-44
lines changed

2 files changed

+55
-44
lines changed

geopycat/geocat.py

Lines changed: 51 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import requests
1111
import urllib3
1212
from dotenv import load_dotenv
13-
import psycopg2
13+
import arcpy
1414
from geopycat import settings
1515
from geopycat import utils
1616

@@ -101,9 +101,8 @@ def __get_token(self) -> object:
101101
return session
102102

103103
def db_connect(self) -> object:
104-
"""Connect to geocat DB and returns a psycopg2 connection object"""
104+
"""Connect to geocat DB and returns an arcpy connection object"""
105105

106-
# Access database credentials from env variable if exists
107106
db_username = os.getenv('DB_USERNAME')
108107
db_password = os.getenv('DB_PASSWORD')
109108

@@ -113,11 +112,9 @@ def db_connect(self) -> object:
113112

114113
_env = [k for k, v in settings.ENV.items() if v == self.env][0]
115114

116-
connection = psycopg2.connect(
117-
host="database-lb.geocat.swisstopo.cloud",
118-
database=f"geocat-{_env}",
119-
user=db_username,
120-
password=db_password)
115+
connection_string = f"DATABASE_PLATFORM=POSTGRESQL;DATABASE={_env};DBCLIENT=postgresql;DB_CONNECTION_PROPERTIES=database-lb.geocat.swisstopo.cloud;USER={db_username};PASSWORD={db_password};VERSION=sde.DEFAULT"
116+
117+
connection = arcpy.ArcSDESQLExecute(connection_string)
121118

122119
return connection
123120

@@ -511,8 +508,6 @@ def backup_metadata(self, uuids: list, backup_dir: str = None, with_related: boo
511508
print(f"{utils.warningred('The following Metadata could not be backup : ') + uuid}")
512509
continue
513510

514-
uuid = uuid.replace(":", "_").replace("/", "_").replace("\\", "_").replace("'", "_").replace('"', "_")
515-
516511
with open(os.path.join(backup_dir, f"{uuid}.zip"), "wb") as output:
517512
output.write(response.content)
518513

@@ -561,8 +556,6 @@ def backup_metadata_xml(self, uuids: list, backup_dir: str = None):
561556
print(f"{utils.warningred('The following Metadata could not be backup : ') + uuid}")
562557
continue
563558

564-
uuid = uuid.replace(":", "_").replace("/", "_").replace("\\", "_").replace("'", "_").replace('"', "_")
565-
566559
with open(os.path.join(backup_dir, f"{uuid}.xml"), "wb") as output:
567560
output.write(response.content)
568561

@@ -751,52 +744,58 @@ def search_and_replace(self, search: str, replace: str, escape_wildcard: bool =
751744

752745
try:
753746
connection = self.db_connect()
754-
with connection.cursor() as cursor:
755747

756-
cursor.execute("SELECT uuid FROM public.metadata where (istemplate='n' OR istemplate='y')" \
757-
f"AND data like '%{search_sql}%'")
748+
query = f"""
749+
SELECT uuid FROM public.metadata
750+
WHERE (istemplate = 'n' OR istemplate = 'y')
751+
AND data LIKE '%{search_sql}%'
752+
"""
758753

759-
for row in cursor:
760-
metadata_uuids.append(row[0])
754+
result = connection.execute(query)
761755

762-
except (Exception, psycopg2.Error) as error:
763-
print("Error while fetching data from PostgreSQL", error)
756+
for row in result:
757+
metadata_uuids.append(row[0])
764758

765-
finally:
766-
if connection:
767-
connection.close()
759+
except arcpy.ExecuteError:
760+
msgs = arcpy.GetMessages(2)
761+
print(f"Error while fetching data from the geodatabase: {msgs}")
762+
except Exception as error:
763+
print(f"Unexpected error: {error}")
768764

769765
headers = {"accept": "application/json", "Content-Type": "application/json"}
770766

771767
if len(metadata_uuids) == 0:
772-
print(utils.warningred(f"{search} not found in any metadata"))
768+
print(f"Warning: '{search}' not found in any metadata")
773769
return
774770

775771
for uuid in metadata_uuids:
776-
777772
params = {
778773
"search": search,
779774
"replace": replace,
780775
"uuids": [uuid],
781776
"updateDateStamp": False
782777
}
783778

784-
response = self.session.post(self.env + "/geonetwork/srv/api/processes/db/search-and-replace",
785-
params=params, headers=headers)
779+
response = self.session.post(
780+
self.env + "/geonetwork/srv/api/processes/db/search-and-replace",
781+
params=params,
782+
headers=headers
783+
)
786784

787-
if utils.process_ok(response):
788-
print(utils.okgreen(f"Metadata {uuid} : {search} successfully replaced by {replace}"))
785+
if hasattr(response, 'ok') and response.ok:
786+
print(f"Metadata {uuid}: '{search}' successfully replaced by '{replace}'")
789787
else:
790-
print(utils.warningred(f"Metadata {uuid} : {search} unsuccessfully replaced by {replace}"))
788+
print(f"Metadata {uuid}: '{search}' unsuccessfully replaced by '{replace}'")
789+
791790

792791
def search_db(self, search: str, escape_wildcard: bool = True) -> list:
793792
"""
794-
Performs search at the DB level. Returns list of metadata UUID where search
795-
input was found.
793+
Performs search at the DB level using arcpy.ArcSDESQLExecute.
794+
Returns a list of metadata UUIDs where the search input was found.
796795
797796
Parameters:
798-
search (str): value to search for
799-
escape_wildcard (bool): if True, "%" wildcard are escaped "\%"
797+
search (str): Value to search for.
798+
escape_wildcard (bool): If True, "%" wildcards are escaped as "\%".
800799
"""
801800

802801
if not self.check_admin():
@@ -810,22 +809,30 @@ def search_db(self, search: str, escape_wildcard: bool = True) -> list:
810809
search_sql = search
811810

812811
try:
812+
# Establish the database connection
813813
connection = self.db_connect()
814-
with connection.cursor() as cursor:
815814

816-
cursor.execute("SELECT uuid FROM public.metadata where (istemplate='n' OR istemplate='y')" \
817-
f"AND data like '%{search_sql}%'")
815+
# Build the SQL query
816+
query = f"""
817+
SELECT uuid FROM public.metadata
818+
WHERE (istemplate = 'n' OR istemplate = 'y')
819+
AND data LIKE '%{search_sql}%'
820+
"""
818821

819-
for row in cursor:
820-
metadata_uuids.append(row[0])
822+
# Execute the query using arcpy.ArcSDESQLExecute
823+
result = connection.execute(query)
821824

822-
except (Exception, psycopg2.Error) as error:
823-
print("Error while fetching data from PostgreSQL", error)
825+
# Fetch the results
826+
for row in result:
827+
metadata_uuids.append(row[0])
828+
829+
except arcpy.ExecuteError:
830+
# Retrieve arcpy-specific error messages
831+
msgs = arcpy.GetMessages(2)
832+
print(f"Error while fetching data from the geodatabase: {msgs}")
833+
except Exception as error:
834+
print(f"Unexpected error: {error}")
824835

825-
finally:
826-
if connection:
827-
connection.close()
828-
829836
return metadata_uuids
830837

831838
def delete_metadata(self, uuid: str) -> object:

geopycat/settings.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,10 @@
2828
{
2929
"http": "proxy.admin.ch:8080",
3030
"https": "proxy.admin.ch:8080",
31+
},
32+
{
33+
"http": "prxp01.admin.ch:8080",
34+
"https": "prxp01.admin.ch:8080",
3135
},
3236
{}
3337
]

0 commit comments

Comments
 (0)