-
Notifications
You must be signed in to change notification settings - Fork 77
/
Geoserver.py
1776 lines (1464 loc) · 57.6 KB
/
Geoserver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
from typing import Optional
import requests
from xmltodict import unparse, parse
from .Calculation_gdal import raster_value
from .Style import catagorize_xml, classified_xml, coverage_style_xml, outline_only_xml
from .supports import prepare_zip_file
# call back class for read the data
class DataProvider(object):
def __init__(self, data):
self.data = data
self.finished = False
def read_cb(self, size):
assert len(self.data) <= size
if not self.finished:
self.finished = True
return self.data
else:
# Nothing more to read
return ""
# callback class for reading the files
class FileReader:
def __init__(self, fp):
self.fp = fp
def read_callback(self, size):
return self.fp.read(size)
class Geoserver:
"""
Attributes
----------
service_url : str
The URL for the GeoServer instance.
username : str
Login name for session.
password: str
Password for session.
"""
def __init__(
self,
service_url="http://localhost:8080/geoserver",
username="admin",
password="geoserver",
):
self.service_url = service_url
self.username = username
self.password = password
def get_manifest(self):
"""
Returns the manifest of the geoserver.
"""
try:
url = "{}/rest/about/manifest.json".format(self.service_url)
r = requests.get(url, auth=(self.username, self.password))
return r.json()
except Exception as e:
return "get_manifest error: ", e
def get_version(self):
"""
Returns the version of the geoserver.
"""
try:
url = "{}/rest/about/version.json".format(self.service_url)
r = requests.get(url, auth=(self.username, self.password))
return r.json()
except Exception as e:
return "get_version error: ", e
def get_status(self):
"""
Returns the status of the geoserver.
"""
try:
url = "{}/rest/about/status.json".format(self.service_url)
r = requests.get(url, auth=(self.username, self.password))
return r.json()
except Exception as e:
return "get_status error: ", e
def get_system_status(self):
"""
It returns the system status of the geoserver
"""
try:
url = "{}/rest/about/system-status.json".format(self.service_url)
r = requests.get(url, auth=(self.username, self.password))
return r.json()
except Exception as e:
return "get_system_status error: ", e
def reload(self):
"""
Reloads the GeoServer catalog and configuration from disk.
This operation is used in cases where an external tool has modified the on-disk configuration.
This operation will also force GeoServer to drop any internal caches and reconnect to all data stores.
curl -X POST http://localhost:8080/geoserver/rest/reload -H "accept: application/json" -H "content-type: application/json"
"""
try:
url = "{}/rest/reload".format(self.service_url)
r = requests.post(url, auth=(self.username, self.password))
return "Status code: {}".format(r.status_code)
except Exception as e:
return "reload error: {}".format(e)
def reset(self):
"""
Resets all store, raster, and schema caches. This operation is used to force GeoServer to drop all caches and
store connections and reconnect to each of them the next time they are needed by a request. This is useful in
case the stores themselves cache some information about the data structures they manage that may have changed
in the meantime.
curl -X POST http://localhost:8080/geoserver/rest/reset -H "accept: application/json" -H "content-type: application/json"
"""
try:
url = "{}/rest/reset".format(self.service_url)
r = requests.post(url, auth=(self.username, self.password))
return "Status code: {}".format(r.status_code)
except Exception as e:
return "reload error: {}".format(e)
def get_datastore(self, store_name: str, workspace: Optional[str] = None):
"""
Return the data store in a given workspace.
If workspace is not provided, it will take the default workspace
curl -X GET http://localhost:8080/geoserver/rest/workspaces/demo/datastores -H "accept: application/xml" -H "content-type: application/json"
"""
try:
if workspace is None:
workspace = "default"
url = "{}/rest/workspaces/{}/datastores/{}".format(
self.service_url, workspace, store_name
)
r = requests.get(url, auth=(self.username, self.password))
return r.json()
except Exception as e:
return "get_datastores error: {}".format(e)
def get_datastores(self, workspace: Optional[str] = None):
"""
List all data stores in a workspace.
If workspace is not provided, it will listout all the datastores inside default workspace
curl -X GET http://localhost:8080/geoserver/rest/workspaces/demo/datastores -H "accept: application/xml" -H "content-type: application/json"
"""
try:
if workspace is None:
workspace = "default"
url = "{}/rest/workspaces/{}/datastores.json".format(
self.service_url, workspace
)
r = requests.get(url, auth=(self.username, self.password))
return r.json()
except Exception as e:
return "get_datastores error: {}".format(e)
def get_coveragestore(
self, coveragestore_name: str, workspace: Optional[str] = None
):
"""
Returns the store name if it exists.
"""
try:
payload = {"recurse": "true"}
if workspace is None:
workspace = "default"
url = "{}/rest/workspaces/{}/coveragestores/{}.json".format(
self.service_url, workspace, coveragestore_name
)
r = requests.get(url, auth=(self.username, self.password), params=payload)
print("Status code: {}, Get coverage store".format(r.status_code))
return r.json()
except Exception as e:
return "Error: {}".format(e)
def get_coveragestores(self, workspace: str = None):
"""
Returns all the coveragestores inside a specific workspace.
"""
try:
if workspace is None:
workspace = "default"
url = "{}/rest/workspaces/{}/coveragestores".format(
self.service_url, workspace
)
r = requests.get(url, auth=(self.username, self.password))
return r.json()
except Exception as e:
return "get_coveragestores error: {}".format(e)
def get_layer(self, layer_name: str, workspace: Optional[str] = None):
"""
Returns the layer by layer name.
"""
try:
url = "{}/rest/layers/{}".format(self.service_url, layer_name)
if workspace is not None:
url = "{}/rest/workspaces/{}/layers/{}".format(
self.service_url, workspace, layer_name
)
r = requests.get(url, auth=(self.username, self.password))
return r.json()
except Exception as e:
return "get_layer error: {}".format(e)
def get_layers(self, workspace: Optional[str] = None):
"""
Get all the layers from geoserver
If workspace is None, it will listout all the layers from geoserver
"""
try:
url = "{}/rest/layers".format(self.service_url)
if workspace is not None:
url = "{}/rest/workspaces/{}/layers".format(self.service_url, workspace)
r = requests.get(url, auth=(self.username, self.password))
return r.json()
except Exception as e:
return "get_layers error: {}".format(e)
def get_layergroups(self, workspace: Optional[str] = None):
"""
Returns all the layer groups from geoserver.
Notes
-----
If workspace is None, it will list all the layer groups from geoserver.
"""
try:
url = "{}/rest/layergroups".format(self.service_url)
if workspace is not None:
url = "{}/rest/workspaces/{}/layergroups".format(
self.service_url, workspace
)
r = requests.get(url, auth=(self.username, self.password))
return r.json()
except Exception as e:
return "get_layers error: {}".format(e)
def get_layergroup(self, layer_name: str, workspace: Optional[str] = None):
"""
Returns the layer group by layer group name.
"""
try:
url = "{}/rest/layergroups/{}".format(self.service_url, layer_name)
if workspace is not None:
url = "{}/rest/workspaces/{}/layergroups/{}".format(
self.service_url, workspace, layer_name
)
r = requests.get(url, auth=(self.username, self.password))
return r.json()
except Exception as e:
return "get_layer error: {}".format(e)
def get_style(self, style_name, workspace: Optional[str] = None):
"""
Returns the style by style name.
"""
try:
url = "{}/rest/styles/{}.json".format(self.service_url, style_name)
if workspace is not None:
url = "{}/rest/workspaces/{}/styles/{}.json".format(
self.service_url, workspace, style_name
)
r = requests.get(url, auth=(self.username, self.password))
return r.json()
except Exception as e:
return "get_style error: {}".format(e)
def get_styles(self, workspace: Optional[str] = None):
"""
Returns all loaded styles from geoserver.
"""
try:
url = "{}/rest/styles.json".format(self.service_url)
if workspace is not None:
url = "{}/rest/workspaces/{}/styles.json".format(
self.service_url, workspace
)
r = requests.get(url, auth=(self.username, self.password))
return r.json()
except Exception as e:
return "get_styles error: {}".format(e)
def get_default_workspace(self):
"""
Returns the default workspace.
"""
try:
url = "{}/rest/workspaces/default".format(self.service_url)
r = requests.get(url, auth=(self.username, self.password))
return r.json()
except Exception as e:
return "get_default_workspace error: {}".format(e)
def get_workspace(self, workspace):
'''
get name workspace if exist
Example: curl -v -u admin:admin -XGET -H "Accept: text/xml" http://localhost:8080/geoserver/rest/workspaces/acme.xml
'''
try:
payload = {'recurse': 'true'}
url = '{0}/rest/workspaces/{1}.json'.format(
self.service_url, workspace)
r = requests.get(url, auth=(
self.username, self.password), params=payload)
if r.status_code == 200:
return r.json()
else:
return None
except Exception as e:
return 'Error: {}'.format(e)
def get_workspaces(self):
"""
Returns all the workspaces.
"""
try:
url = "{}/rest/workspaces".format(self.service_url)
r = requests.get(url, auth=(self.username, self.password))
return r.json()
except Exception as e:
return "get_workspaces error: {}".format(e)
def set_default_workspace(self, workspace: str):
"""
Set the default workspace.
"""
try:
url = "{}/rest/workspaces/default".format(self.service_url)
data = "<workspace><name>{}</name></workspace>".format(workspace)
print(url, data)
r = requests.put(
url,
data,
auth=(self.username, self.password),
headers={"content-type": "text/xml"},
)
if r.status_code == 200:
return "Status code: {}, default workspace {} set!".format(
r.status_code, workspace
)
except Exception as e:
return "reload error: {}".format(e)
def create_workspace(self, workspace: str):
"""
Create a new workspace in geoserver.
The geoserver workspace url will be same as the name of the workspace.
"""
try:
url = "{}/rest/workspaces".format(self.service_url)
data = "<workspace><name>{}</name></workspace>".format(workspace)
headers = {"content-type": "text/xml"}
r = requests.post(
url, data, auth=(self.username, self.password), headers=headers
)
if r.status_code == 201:
return "{} Workspace {} created!".format(r.status_code, workspace)
if r.status_code == 401:
raise Exception("The workspace already exist")
else:
raise Exception("The workspace can not be created")
except Exception as e:
return "Error: {}".format(e)
def get_workspace(self, workspace: str):
"""
Get workspace name if it exists.
Example: curl -v -u admin:admin -XGET -H "Accept: text/xml" http://localhost:8080/geoserver/rest/workspaces/acme.xml
"""
try:
payload = {"recurse": "true"}
url = "{}/rest/workspaces/{}.json".format(self.service_url, workspace)
r = requests.get(url, auth=(self.username, self.password), params=payload)
if r.status_code == 200:
return r.json()
else:
return None
except Exception as e:
return "Error: {}".format(e)
def create_coveragestore(
self,
path,
workspace: Optional[str] = None,
layer_name: Optional[str] = None,
file_type: str = "GeoTIFF",
content_type: str = "image/tiff",
):
"""
Creates the coveragestore; Data will uploaded to the server.
Parameters
----------
path : str
workspace : str, optional
layer_name : str, optional
The name of coveragestore. If not provided, parsed from the file name.
file_type : str
content_type : str
overwrite : bool
Notes
-----
the path to the file and file_type indicating it is a geotiff, arcgrid or other raster type
"""
if path is None:
raise Exception('You must provide the full path to the raster')
if workspace is None:
workspace = 'default'
if layer_name is None:
layer_name = os.path.basename(path)
f = layer_name.split(".")
if len(f) > 0:
layer_name = f[0]
file_type = file_type.lower()
url = '{0}/rest/workspaces/{1}/coveragestores/{2}/file.{3}?coverageName={2}'.format(
self.service_url, workspace, layer_name, file_type)
headers = {
"content-type": content_type
}
r = None
try:
with open(path, 'rb') as f:
r = requests.put(url, data=f, auth=(
self.username, self.password), headers=headers)
if r.status_code != 201:
return '{}: The coveragestore can not be created!'.format(r.status_code)
except Exception as e:
return "Error: {}".format(e)
def publish_time_dimension_to_coveragestore(
self,
store_name: Optional[str] = None,
workspace: Optional[str] = None,
presentation: Optional[str] = 'LIST',
units: Optional[str] = 'ISO8601',
default_value: Optional[str] = 'MINIMUM',
content_type: str = "application/xml; charset=UTF-8"
):
"""
Create time dimension in coverage store to publish time series in geoserver.
Parameters
----------
store_name : str, optional
workspace : str, optional
presentation : str, optional
units : str, optional
default_value : str, optional
content_type : str
Notes
-----
More about time support in geoserver WMS you can read here:
https://docs.geoserver.org/master/en/user/services/wms/time.html
"""
url = '{0}/rest/workspaces/{1}/coveragestores/{2}/coverages/{2}'.format(
self.service_url, workspace, store_name)
headers = {
"content-type": content_type
}
time_dimension_data = (
"<coverage>"
"<enabled>true</enabled>"
"<metadata>"
"<entry key='time'>"
"<dimensionInfo>"
"<enabled>true</enabled>"
"<presentation>{0}</presentation>"
"<units>{1}</units>"
"<defaultValue>"
"<strategy>{2}</strategy>"
"</defaultValue>"
"</dimensionInfo>"
"</entry>"
"</metadata>"
"</coverage>".format(
presentation, units, default_value
)
)
r = None
try:
r = requests.put(url, data=time_dimension_data, auth=(
self.username, self.password), headers=headers)
if r.status_code not in [200, 201]:
return '{}: The coveragestore can not have time dimension! {}'.format(r.status_code, r.content)
except Exception as e:
return "Error: {}".format(e)
def create_featurestore(
self,
store_name: str,
workspace: Optional[str] = None,
db: str = "postgres",
host: str = "localhost",
port: int = 5432,
schema: str = "public",
pg_user: str = "postgres",
pg_password: str = "admin",
overwrite: bool = False,
expose_primary_keys: str = "false",
description: Optional[str] = None,
evictor_run_periodicity: Optional[int] = 300,
max_open_prepared_statements: Optional[int] = 50,
encode_functions: Optional[str] = "false",
primary_key_metadata_table: Optional[str] = None,
batch_insert_size: Optional[int] = 1,
preparedstatements: Optional[str] = "false",
loose_bbox: Optional[str] = "true",
estimated_extends: Optional[str] = "true",
fetch_size: Optional[int] = 1000,
validate_connections: Optional[str] = "true",
support_on_the_fly_geometry_simplification: Optional[str] = "true",
connection_timeout: Optional[int] = 20,
create_database: Optional[str] = "false",
min_connections: Optional[int] = 1,
max_connections: Optional[int] = 10,
evictor_tests_per_run: Optional[int] = 3,
test_while_idle: Optional[str] = "true",
max_connection_idle_time: Optional[int] = 300
):
"""
Create PostGIS store for connecting postgres with geoserver.
Parameters
----------
store_name : str
workspace : str, optional
db : str
host : str
port : int
schema : str
pg_user : str
pg_password : str
overwrite : bool
expose_primary_keys: str
description : str, optional
evictor_run_periodicity : str
max_open_prepared_statements : int
encode_functions : str
primary_key_metadata_table : str
batch_insert_size : int
preparedstatements : str
loose_bbox : str
estimated_extends : str
fetch_size : int
validate_connections : str
support_on_the_fly_geometry_simplification : str
connection_timeout : int
create_database : str
min_connections : int
max_connections : int
evictor_tests_per_run : int
test_while_idle : str
max_connection_idle_time : int
Notes
-----
After creating feature store, you need to publish it. See the layer publish guidline here: https://geoserver-rest.readthedocs.io/en/latest/how_to_use.html#creating-and-publishing-featurestores-and-featurestore-layers
"""
url = "{}/rest/workspaces/{}/datastores".format(self.service_url, workspace)
headers = {
'content-type': 'text/xml'
}
database_connection = ("""
<dataStore>
<name>{0}</name>
<description>{1}</description>
<connectionParameters>
<entry key="Expose primary keys">{2}</entry>
<entry key="host">{3}</entry>
<entry key="port">{4}</entry>
<entry key="user">{5}</entry>
<entry key="passwd">{6}</entry>
<entry key="dbtype">postgis</entry>
<entry key="schema">{7}</entry>
<entry key="database">{8}</entry>
<entry key="Evictor run periodicity">{9}</entry>
<entry key="Max open prepared statements">{10}</entry>
<entry key="encode functions">{11}</entry>
<entry key="Primary key metadata table">{12}</entry>
<entry key="Batch insert size">{13}</entry>
<entry key="preparedStatements">{14}</entry>
<entry key="Estimated extends">{15}</entry>
<entry key="fetch size">{16}</entry>
<entry key="validate connections">{17}</entry>
<entry key="Support on the fly geometry simplification">{18}</entry>
<entry key="Connection timeout">{19}</entry>
<entry key="create database">{20}</entry>
<entry key="min connections">{21}</entry>
<entry key="max connections">{22}</entry>
<entry key="Evictor tests per run">{23}</entry>
<entry key="Test while idle">{24}</entry>
<entry key="Max connection idle time">{25}</entry>
<entry key="Loose bbox">{26}</entry>
</connectionParameters>
</dataStore>
""".format(
store_name, description, expose_primary_keys, host, port, pg_user, pg_password, schema, db,
evictor_run_periodicity, max_open_prepared_statements, encode_functions, primary_key_metadata_table,
batch_insert_size, preparedstatements, estimated_extends, fetch_size, validate_connections,
batch_insert_size, preparedstatements, estimated_extends, fetch_size, validate_connections,
batch_insert_size, preparedstatements, estimated_extends, fetch_size, validate_connections,
support_on_the_fly_geometry_simplification, connection_timeout, create_database, min_connections,
max_connections, evictor_tests_per_run, test_while_idle, max_connection_idle_time, loose_bbox
)
)
r = None
try:
if overwrite:
url = "{0}/rest/workspaces/{1}/datastores/{2}".format(
self.service_url, workspace, store_name)
r = requests.put(url, data=database_connection, auth=(
self.username, self.password), headers=headers)
if r.status_code not in [200, 201]:
return '{}: Datastore can not be updated. {}'.format(r.status_code, r.content)
else:
r = requests.post(url, data=database_connection, auth=(
self.username, self.password), headers=headers)
if r.status_code not in [200, 201]:
return '{}: Data store can not be created! {}'.format(r.status_code, r.content)
except Exception as e:
return "Error: {}".format(e)
def create_datastore(
self,
name: str,
path: str,
workspace: Optional[str] = None,
overwrite: bool = False,
):
"""
Create a datastore within the GeoServer.
Parameters
----------
name : str
Name of datastore to be created.
After creating the datastore, you need to publish it by using publish_featurestore function.
path : str
Path to shapefile (.shp) file, GeoPackage (.gpkg) file, WFS url
(e.g. http://localhost:8080/geoserver/wfs?request=GetCapabilities) or directory containing shapefiles.
workspace : str, optional default value = "default".
overwrite : bool
Notes
-----
If you have PostGIS datastore, please use create_featurestore function
"""
if workspace is None:
workspace = "default"
if path is None:
raise Exception("You must provide a full path to the data")
data_url = "<url>file:{}</url>".format(path)
if "http://" in path:
data_url = "<GET_CAPABILITIES_URL>{}</GET_CAPABILITIES_URL>".format(path)
data = "<dataStore><name>{}</name><connectionParameters>{}</connectionParameters></dataStore>".format(
name, data_url
)
headers = {"content-type": "text/xml"}
try:
if overwrite:
url = "{}/rest/workspaces/{}/datastores/{}".format(
self.service_url, workspace, name
)
r = requests.put(
url, data, auth=(self.username, self.password), headers=headers
)
else:
url = "{}/rest/workspaces/{}/datastores".format(
self.service_url, workspace
)
r = requests.post(
url, data, auth=(self.username, self.password), headers=headers
)
if r.status_code in [200, 201]:
return "Data store created/updated successfully"
else:
raise Exception("datastore can not be created. Status code: {}, {}".format(
r.status_code, r.content))
except Exception as e:
return "Error create_datastore: {}".format(e)
def create_shp_datastore(
self,
path: str,
store_name: Optional[str] = None,
workspace: Optional[str] = None,
file_extension: str = "shp",
):
"""
Create datastore for a shapefile.
Parameters
----------
path : str
Path to the zipped shapefile (.shp).
store_name : str, optional
Name of store to be created. If None, parses from the filename stem.
workspace: str, optional
Name of workspace to be used. Default: "default".
file_extension : str
Notes
-----
The layer name will be assigned according to the shp name
"""
try:
if path is None:
raise Exception("You must provide a full path to shapefile")
if workspace is None:
workspace = "default"
if store_name is None:
store_name = os.path.basename(path)
f = store_name.split(".")
if len(f) > 0:
store_name = f[0]
headers = {
"Content-type": "application/zip",
"Accept": "application/xml",
}
if isinstance(path, dict):
path = prepare_zip_file(store_name, path)
url = "{0}/rest/workspaces/{1}/datastores/{2}/file.{3}?filename={2}&update=overwrite".format(
self.service_url, workspace, store_name, file_extension
)
with open(path, "rb") as f:
r = requests.put(
url,
data=f.read(),
auth=(self.username, self.password),
headers=headers,
)
if r.status_code in [200, 201]:
return "The shapefile datastore created successfully!"
else:
return "{}: The shapefile datastore can not be created! {}".format(
r.status_code, r.content
)
except Exception as e:
return "Error: {}".format(e)
def publish_featurestore(self, store_name: str, pg_table: str, workspace: Optional[str] = None):
"""
Parameters
----------
store_name : str
pg_table : str
workspace : str, optional
Returns
-------
Notes
-----
Only user for postgis vector data
input parameters: specify the name of the table in the postgis database to be published, specify the store,workspace name, and the Geoserver user name, password and URL
"""
if workspace is None:
workspace = "default"
url = "{}/rest/workspaces/{}/datastores/{}/featuretypes/".format(
self.service_url, workspace, store_name)
layer_xml = "<featureType><name>{}</name></featureType>".format(pg_table)
headers = {"content-type": "text/xml"}
try:
r = requests.post(url, data=layer_xml, auth=(
self.username, self.password), headers=headers)
if r.status_code not in [200, 201]:
return '{}: Data can not be published! {}'.format(r.status_code, r.content)
except Exception as e:
return "Error: {}".format(e)
def edit_featuretype(self,
store_name: str,
workspace: Optional[str],
pg_table: str,
name: str,
title: str
):
"""
Parameters
----------
store_name : str
workspace : str, optional
pg_table : str
name : str
title : str
Returns
-------
Notes
-----
"""
if workspace is None:
workspace = "default"
url = "{}/rest/workspaces/{}/datastores/{}/featuretypes/{}.xml".format(
self.service_url, workspace, store_name, pg_table)
layer_xml = """<featureType>
<name>{}</name>
<title>{}</title>
</featureType>""".format(name, title)
headers = {"content-type": "text/xml"}
try:
r = requests.put(url, data=layer_xml, auth=(
self.username, self.password), headers=headers)
if r.status_code not in [200, 201]:
return '{}: Data has not been edited! {}'.format(r.status_code, r.content)
except Exception as e:
return "Error: {}".format(e)
def publish_featurestore_sqlview(
self,
name: str,
store_name: str,
sql: str,
geom_name: str = "geom",
geom_type: str = "Geometry",
srid: Optional[int] = 4326,
workspace: Optional[str] = None,
):
"""
Parameters
----------
name : str
store_name : str
sql : str
geom_name : str
geom_type : str
workspace : str, optional
"""
if workspace is None:
workspace = "default"
layer_xml = """<featureType>
<name>{0}</name>
<enabled>true</enabled>
<namespace>
<name>{4}</name>
</namespace>
<title>{0}</title>
<srs>EPSG:{5}</srs>
<metadata>
<entry key="JDBC_VIRTUAL_TABLE">
<virtualTable>
<name>{0}</name>
<sql>{1}</sql>
<escapeSql>true</escapeSql>
<geometry>
<name>{2}</name>
<type>{3}</type>
<srid>{5}</srid>
</geometry>
</virtualTable>
</entry>
</metadata>
</featureType>""".format(name, sql, geom_name, geom_type, workspace, srid)
url = "{0}/rest/workspaces/{1}/datastores/{2}/featuretypes".format(
self.service_url, workspace, store_name)
headers = {"content-type": "text/xml"}
try:
r = requests.post(url, data=layer_xml, auth=(
self.username, self.password), headers=headers)
if r.status_code not in [200, 201]:
return '{}: Data can not be published! {}'.format(r.status_code, r.content)
except Exception as e:
return "Error: {}".format(e)
def upload_style(
self,
path: str,
name: Optional[str] = None,
workspace: Optional[str] = None,
sld_version: str = "1.0.0",
):
"""
Parameters
----------
path : str
name : str, optional
workspace : str, optional
sld_version : str, optional
Notes
-----
The name of the style file will be, sld_name:workspace
This function will create the style file in a specified workspace.