-
Notifications
You must be signed in to change notification settings - Fork 2
/
osmapis.py
2364 lines (1826 loc) · 73.6 KB
/
osmapis.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
# -*- coding: utf-8 -*-
"""
Osmapis is a set of tools for accessing and manipulating OSM data via OSM API,
Overpass API.
Variables:
wrappers --- Dictionary containing the classes to use for OSM element wrappers.
Classes:
OverpassAPI --- OSM Overpass API interface.
API --- OSM API interface.
HTTPClient --- Interface for accessing data over HTTP.
Node --- Node wrapper.
Way --- Way wrapper.
Relation --- Relation wrapper.
Changeset --- Changeset wrapper.
OSM --- OSM XML document wrapper.
OSC --- OSC XML document wrapper.
APIError --- OSM API exception.
"""
__author__ = "Petr Morávek ([email protected])"
__copyright__ = "Copyright (C) 2010-2012 Petr Morávek"
__license__ = "LGPL 3.0"
__version__ = "0.9.3"
from abc import ABCMeta, abstractmethod
from base64 import b64encode
from collections import MutableSet, MutableMapping
from itertools import chain
import logging
import os
import os.path
from time import sleep
import xml.etree.cElementTree as ET
try:
from http.client import HTTPConnection
except ImportError:
from httplib import HTTPConnection
try:
from urllib.parse import unquote, urlencode
except ImportError:
from urllib import unquote, urlencode
__all__ = ["wrappers",
"OverpassAPI",
"API",
"HTTPClient",
"Node",
"Way",
"Relation",
"Changeset",
"OSM",
"OSC",
"APIError"]
logging.getLogger('osmapis').addHandler(logging.NullHandler())
# Python 2.x compatibility
def abstractclass(cls):
d = dict(cls.__dict__)
d.pop("__dict__", None)
d.pop("__weakref__", None)
return ABCMeta(cls.__name__, cls.__bases__, d)
############################################################
### HTTPClient class. ###
############################################################
class HTTPClient(object):
"""
Interface for accessing data over HTTP.
Class attributes:
headers --- Default headers for HTTP request.
Class methods:
request --- Perform HTTP request and handle possible redirection, on error retry.
"""
def __new__(cls, *p, **k):
raise TypeError("This class cannot be instantionalized.")
headers = {}
headers["User-agent"] = "osmapis/{0}".format(__version__)
log = logging.getLogger("osmapis.http")
@classmethod
def request(cls, server, path, method="GET", headers={}, payload=None, retry=10):
"""
Perform HTTP request and handle possible redirection, on error retry.
Raise ValueError on invalid credentials and auth=True.
Return downloaded body as string or raise APIError.
Arguments:
server --- Domain name of HTTP server.
path --- Path on server.
Keyworded arguments:
method --- HTTP request method.
headers --- Additional HTTP headers.
payload --- Dictionary containing data to send with request.
retry --- Number of re-attempts on error.
"""
cls.log.debug("{}({}) {}{} << payload {}".format(method, retry, server, path, payload is not None))
req_headers = dict(cls.headers)
req_headers.update(headers)
if payload is not None and not isinstance(payload, bytes):
payload = payload.encode("utf-8")
connection = HTTPConnection(server)
connection.connect()
connection.request(method, path, payload, req_headers)
response = connection.getresponse()
if response.status == 200:
body = response.read()
connection.close()
if server == OverpassAPI.server and response.getheader("Content-Type") != "application/osm3s+xml":
# Overpass API returns always status 200, grr!
raise APIError("Unexpected Content-type {}".format(response.getheader("Content-Type")), payload)
return body
elif response.status in (301, 302, 303, 307):
# Try to redirect
connection.close()
url = response.getheader("Location")
if url is None:
cls.log.error("Got code {}, but no location header.".format(response.status))
raise APIError("Unable to redirect the request.", payload)
url = unquote(url)
cls.log.debug("Redirecting to {}".format(url))
url = url.split("/", 3)
server = url[2]
path = "/" + url[3]
return cls.request(server, path, method=method, headers=headers, payload=payload, retry=retry)
elif 400 <= response.status < 500:
body = response.read().decode("utf-8", "replace").strip()
if not isinstance(body, str):
body = body.encode("utf-8")
connection.close()
cls.log.error("Got error {} ({}).".format(response.reason, response.status))
raise APIError(body, payload, response.reason, response.status)
else:
body = response.read().decode("utf-8", "replace").strip()
if not isinstance(body, str):
body = body.encode("utf-8")
connection.close()
if retry <= 0:
cls.log.error("Could not download {}{}".format(server, path))
raise APIError(body, payload, response.reason, response.status)
else:
wait = 30
cls.log.warn("Got error {} ({})... will retry in {} seconds.".format(response.status, response.reason, wait))
cls.log.debug(body)
sleep(wait)
return cls.request(server, path, method=method, headers=headers, payload=payload, retry=retry-1)
############################################################
### API classes ###
############################################################
@abstractclass
class BaseReadAPI(object):
"""
Abstract class for read-only API operations.
Abstract methods:
get_bbox --- Download OSM data inside the specified bbox.
get_element --- Download node/way/relation by id and optionally version.
get_element_full --- Download way/relation by id and all elements that references.
get_elements --- Download nodes/ways/relations by ids.
get_element_rels --- Download relations that reference the node/way/relation by id.
get_node_ways --- Download ways that reference the node by id or wrapper.
Methods:
get_node --- Download node by id and optionally version.
get_way --- Download way by id and optionally version.
get_relation --- Download relation by id and optionally version.
get_history --- Download complete history of Node/Way/Relation wrapper.
get_way_full --- Download way by id and all referenced nodes.
get_relation_full --- Download relation by id and all referenced members.
get_full --- Download way/relation and all elements that references.
get_nodes --- Download nodes by ids.
get_ways --- Download ways by ids.
get_relations --- Download relations by ids.
get_node_rels --- Download relations that reference the node by id or wrapper.
get_way_rels --- Download relations that reference the way by id or wrapper.
get_relation_rels --- Download relations that reference the relation by id or wrapper.
get_rels --- Download relations that reference the Node/Way/Relation wrapper.
"""
@abstractmethod
def get_bbox(self, left, bottom, right, top):
"""
Download OSM data inside the specified bbox.
Return OSM wrapper.
Arguments:
left --- Left boundary.
bottom --- Bottom boundary.
right --- Right boundary.
top --- Top boundary.
"""
raise NotImplementedError
@abstractmethod
def get_element(self, type_, id_, version=None):
"""
Download node/way/relation by id and optionally version.
Return Node/Way/Relation wrapper.
Arguments:
type_ --- Element type (node/way/relation).
id_ --- Element id.
Keyworded arguments:
version --- Element version number, None (latest), or '*' (complete history).
"""
raise NotImplementedError
def get_node(self, id_, version=None):
"""
Download node by id and optionally version.
Return Node wrapper.
Arguments:
id_ --- Node id.
Keyworded arguments:
version --- Node version number, None (latest), or '*' (complete history).
"""
return self.get_element("node", id_, version=version)
def get_way(self, id_, version=None):
"""
Download way by id and optionally version.
Return Way wrapper.
Arguments:
id_ --- Way id.
Keyworded arguments:
version --- Way version number, None (latest), or '*' (complete history).
"""
return self.get_element("way", id_, version=version)
def get_relation(self, id_, version=None):
"""
Download relation by id and optionally version.
Return Relation wrapper.
Arguments:
id_ --- Relation id.
Keyworded arguments:
version --- Relation version number, None (latest), or '*' (complete history).
"""
return self.get_element("relation", id_, version=version)
def get_history(self, element):
"""
Download complete history of Node/Way/Relation wrapper.
Return Node/Way/Relation wrapper.
Arguments:
element --- Node/Way/Relation wrapper.
"""
if not isinstance(element, (Node, Way, Relation)):
raise TypeError("Element must be a Node, Way or Relation instance.")
return self.get_element(element.xml_tag, element.id, version="*")
@abstractmethod
def get_element_full(self, type_, id_):
"""
Download way/relation by id and all elements that references.
Return OSM wrapper.
Arguments:
type_ --- Element type (way/relation).
id_ --- Element id.
"""
raise NotImplementedError
def get_way_full(self, id_):
"""
Download way by id and all referenced nodes.
Return OSM wrapper.
Arguments:
id_ --- Way id.
"""
return self.get_element_full("way", id_)
def get_relation_full(self, id_):
"""
Download way by id and all referenced members.
Return OSM wrapper.
Arguments:
id_ --- Relation id.
"""
return self.get_element_full("relation", id_)
def get_full(self, element):
"""
Download way/relation and all elements that references.
Return OSM wrapper.
Arguments:
element --- Way/Relation wrapper.
"""
if not isinstance(element, (Way, Relation)):
raise TypeError("Element must be a Way or Relation instance.")
return self.get_element_full(element.xml_tag, element.id)
@abstractmethod
def get_elements(self, type_, ids):
"""
Download nodes/ways/relations by ids.
Return OSM wrapper.
Arguments:
type_ --- Elements type (node/way/relation).
ids --- Iterable with ids.
"""
raise NotImplementedError
def get_nodes(self, ids):
"""
Download nodes by ids.
Return OSM wrapper.
Arguments:
ids --- Iterable with ids.
"""
return self.get_elements("node", ids)
def get_ways(self, ids):
"""
Download ways by ids.
Return OSM wrapper.
Arguments:
ids --- Iterable with ids.
"""
return self.get_elements("way", ids)
def get_relations(self, ids):
"""
Download relations by ids.
Return OSM wrapper.
Arguments:
ids --- Iterable with ids.
"""
return self.get_elements("relation", ids)
@abstractmethod
def get_element_rels(self, type_, id_):
"""
Download relations that reference the node/way/relation by id.
Return OSM wrapper.
Arguments:
type_ --- Element type (node/way/relation).
id_ --- Element id.
"""
raise NotImplementedError
def get_node_rels(self, element):
"""
Download relations that reference the node by id or wrapper.
Return OSM wrapper.
Arguments:
element --- Node wrapper or id.
"""
if isinstance(element, Node):
element = element.id
return self.get_element_rels("node", element)
def get_way_rels(self, element):
"""
Download relations that reference the way by id or wrapper.
Return OSM wrapper.
Arguments:
element --- Way wrapper or id.
"""
if isinstance(element, Way):
element = element.id
return self.get_element_rels("way", element)
def get_relation_rels(self, element):
"""
Download relations that reference the relation by id or wrapper.
Return OSM wrapper.
Arguments:
element --- Relation wrapper or id.
"""
if isinstance(element, Relation):
element = element.id
return self.get_element_rels("relation", element)
def get_rels(self, element):
"""
Download relations that reference the Node/Way/Relation wrapper.
Return OSM wrapper.
Arguments:
element --- Node/Way/Relation wrapper.
"""
if not isinstance(element, (Node, Way, Relation)):
raise TypeError("Element must be a Node, Way or Relation instance.")
return self.get_element_rels(element.xml_tag, element.id)
@abstractmethod
def get_node_ways(self, element):
"""
Download ways that reference the node by id or wrapper.
Return OSM wrapper.
Arguments:
element --- Node wrapper or id.
"""
raise NotImplementedError
@abstractclass
class BaseWriteAPI(object):
"""
Abstract class for write API operations.
Abstract methods:
upload_diff --- OSC diff upload.
create_element --- Create node/way/relation.
update_element --- Update node/way/relation.
delete_element --- Delete node/way/relation.
Methods:
create_node --- Create node.
create_way --- Create way.
create_relation --- Create relation.
update_node --- Update node.
update_way --- Update way.
update_relation --- Update relation.
delete_node --- Delete node.
delete_way --- Delete way.
delete_relation --- Delete relation.
"""
@abstractmethod
def upload_diff(self, osc, changeset=None):
"""
OSC diff upload.
Return {type: {old_id: returned_data} }
Arguments:
osc --- OSC wrapper.
Keyworded arguments:
changeset --- Changeset wrapper, changeset id or None (create new).
"""
raise NotImplementedError
@abstractmethod
def create_element(self, element, changeset=None):
"""
Create node/way/relation.
Return Node/Way/Relation wrapper.
Arguments:
element --- Node/Way/Relation wrapper.
Keyworded arguments:
changeset --- Changeset wrapper, changeset id or None (create new).
"""
raise NotImplementedError
def create_node(self, element, changeset=None):
"""
Create node.
Return Node wrapper.
Arguments:
element --- Node wrapper.
Keyworded arguments:
changeset --- Changeset wrapper, changeset id or None (create new).
"""
if not isinstance(element, Node):
raise TypeError("Element must be Node instance.")
return self.create_element(element, changeset)
def create_way(self, element, changeset=None):
"""
Create way.
Return Way wrapper.
Arguments:
element --- Way wrapper.
Keyworded arguments:
changeset --- Changeset wrapper, changeset id or None (create new).
"""
if not isinstance(element, Way):
raise TypeError("Element must be Way instance.")
return self.create_element(element, changeset)
def create_relation(self, element, changeset=None):
"""
Create relation.
Return Relation wrapper.
Arguments:
element --- Relation wrapper.
Keyworded arguments:
changeset --- Changeset wrapper, changeset id or None (create new).
"""
if not isinstance(element, Relation):
raise TypeError("Element must be Relation instance.")
return self.create_element(element, changeset)
@abstractmethod
def update_element(self, element, changeset=None):
"""
Update node/way/relation.
Return Node/Way/Relation wrapper.
Arguments:
element --- Node/Way/Relation wrapper.
Keyworded arguments:
changeset --- Changeset wrapper, changeset id or None (create new).
"""
raise NotImplementedError
def update_node(self, element, changeset=None):
"""
Update node.
Return Node wrapper.
Arguments:
element --- Node wrapper.
Keyworded arguments:
changeset --- Changeset wrapper, changeset id or None (create new).
"""
if not isinstance(element, Node):
raise TypeError("Element must be Node instance.")
return self.update_element(element, changeset)
def update_way(self, element, changeset=None):
"""
Update way.
Return Way wrapper.
Arguments:
element --- Way wrapper.
Keyworded arguments:
changeset --- Changeset wrapper, changeset id or None (create new).
"""
if not isinstance(element, Way):
raise TypeError("Element must be Way instance.")
return self.update_element(element, changeset)
def update_relation(self, element, changeset=None):
"""
Update relation.
Return Relation wrapper.
Arguments:
element --- Relation wrapper.
Keyworded arguments:
changeset --- Changeset wrapper, changeset id or None (create new).
"""
if not isinstance(element, Relation):
raise TypeError("Element must be Relation instance.")
return self.update_element(element, changeset)
@abstractmethod
def delete_element(self, element, changeset=None):
"""
Delete node/way/relation.
Return Node/Way/Relation wrapper.
Arguments:
element --- Node/Way/Relation wrapper.
Keyworded arguments:
changeset --- Changeset wrapper, changeset id or None (create new).
"""
raise NotImplementedError
def delete_node(self, element, changeset=None):
"""
Delete node.
Return Node wrapper.
Arguments:
element --- Node wrapper.
Keyworded arguments:
changeset --- Changeset wrapper, changeset id or None (create new).
"""
if not isinstance(element, Node):
raise TypeError("Element must be Node instance.")
return self.delete_element(element, changeset)
def delete_way(self, element, changeset=None):
"""
Delete way.
Return Way wrapper.
Arguments:
element --- Way wrapper.
Keyworded arguments:
changeset --- Changeset wrapper, changeset id or None (create new).
"""
if not isinstance(element, Way):
raise TypeError("Element must be Way instance.")
return self.delete_element(element, changeset)
def delete_relation(self, element, changeset=None):
"""
Delete relation.
Return Relation wrapper.
Arguments:
element --- Relation wrapper.
Keyworded arguments:
changeset --- Changeset wrapper, changeset id or None (create new).
"""
if not isinstance(element, Relation):
raise TypeError("Element must be Relation instance.")
return self.delete_element(element, changeset)
class OverpassAPI(BaseReadAPI):
"""
OSM Overpass API interface.
Read calls are mostly compatible with standard API.
Class attributes:
http --- Interface for accessing data over HTTP.
server --- Domain name of OSM Overpass API.
basepath --- Path to the API on the server.
Methods:
request --- Low-level method to retrieve data from server.
interpreter --- Send request to interpreter and return OSM wrapper.
Methods (required by BaseReadAPI):
get_bbox --- Download OSM data inside the specified bbox.
get_element --- Download node/way/relation by id and optionally version.
get_element_full --- Download way/relation by id and all elements that references.
get_elements --- Download nodes/ways/relations by ids.
get_element_rels --- Download relations that reference the node/way/relation by id.
get_node_ways --- Download ways that reference the node by id or wrapper.
"""
http = HTTPClient
server = "www.overpass-api.de"
basepath = "/api/"
def request(self, path, data):
"""
Low-level method to retrieve data from server.
Arguments:
path --- One of 'interpreter', 'get_rule', 'add_rule', 'update_rule'.
data --- Data to send with the request.
"""
path = "{}{}".format(self.basepath, path)
payload = urlencode({"data": data})
return self.http.request(self.server, path, method="POST", payload=payload)
def interpreter(self, query):
"""
Send request to interpreter and return OSM wrapper.
Arguments:
query --- ET.Element or string.
"""
if ET.iselement(query):
query = ET.tostring(query, encoding="utf-8")
return wrappers["osm"].from_xml(self.request("interpreter", query))
##################################################
# READ API #
##################################################
def get_bbox(self, left, bottom, right, top):
"""
Download OSM data inside the specified bbox.
Return OSM wrapper.
Arguments:
left --- Left boundary.
bottom --- Bottom boundary.
right --- Right boundary.
top --- Top boundary.
"""
query = """<union>
<bbox-query w="{}" s="{}" e="{}" n="{}"/>
<recurse type="node-relation"/>
<recurse type="node-way"/>
<recurse type="way-relation"/>
<recurse type="way-node"/>
<recurse type="node-relation"/>
</union>
<print mode="meta" order="quadtile"/>""".format(left, bottom, right, top)
return self.interpreter(query)
def get_element(self, type_, id_, version=None):
"""
Download node/way/relation by id and optionally version.
Version and history calls are not supported.
Return Node/Way/Relation wrapper.
Arguments:
type_ --- Element type (node/way/relation).
id_ --- Element id.
Keyworded arguments:
version --- For compatibility only, must be None.
"""
if version is not None:
raise NotImplementedError("Version calls are not supported.")
if type_ not in ("node", "way", "relation"):
raise ValueError("Type must be 'node', 'way' or 'relation'.")
query = '<id-query type="{}" ref="{}"/>'.format(type_, id_)
query += '<print mode="meta"/>'
osm = self.interpreter(query)
return getattr(osm, type_ + "s")[id_]
def get_element_full(self, type_, id_):
"""
Download way/relation by id and all elements that references.
Return OSM wrapper.
Arguments:
type_ --- Element type (way/relation).
id_ --- Element id.
"""
if type_ not in ("way", "relation"):
raise ValueError("Type must be from {}.".format(", ".join(("way", "relation"))))
query = '<id-query type="{}" ref="{}"/>'.format(type_, id_)
if type_ == "way":
query += '<recurse type="way-node"/>'
else:
query += '<recurse type="relation-way"/>'
query += '<recurse type="relation-node"/>'
query += '<recurse type="relation-relation"/>'
query += '<recurse type="way-node"/>'
query += '<print mode="meta" order="quadtile"/>'
return self.interpreter(query)
def get_elements(self, type_, ids):
"""
Download nodes/ways/relations by ids.
Return OSM wrapper.
Arguments:
type_ --- Elements type (node/way/relation).
ids --- Iterable with ids.
"""
if type_ not in ("node", "way", "relation"):
raise ValueError("Type must be 'node', 'way' or 'relation'.")
query = ''
for id_ in ids:
query += '<id-query type="{}" ref="{}"/>'.format(type_, id_)
query += '<print mode="meta" order="quadtile"/>'
return self.interpreter(query)
def get_element_rels(self, type_, id_):
"""
Download relations that reference the node/way/relation by id.
Return OSM wrapper.
Arguments:
type_ --- Element type (node/way/relation).
id_ --- Element id.
"""
if type_ not in ("node", "way", "relation"):
raise ValueError("Type must be 'node', 'way' or 'relation'.")
query = '<id-query type="{}" ref="{}" into="child"/>'.format(type_, id_)
if type_ == "relation":
query += '<recurse type="relation-backwards" from="child"/>'
else:
query += '<recurse type="{}-relation" from="child"/>'.format(type_)
query += '<print mode="meta" order="quadtile"/>'
return self.interpreter(query)
def get_node_ways(self, element):
"""
Download ways that reference the node by id or wrapper.
Return OSM wrapper.
Arguments:
element --- Node wrapper or id.
"""
if isinstance(element, Node):
element = element.id
query = '<id-query type="node" ref="{}" into="parent"/>'.format(element)
query += '<recurse type="node-way" from="parent"/>'
query += '<print mode="meta" order="quadtile"/>'
return self.interpreter(query)
class API(BaseReadAPI, BaseWriteAPI):
"""
OSM API interface.
Class attributes:
http --- Interface for accessing data over HTTP.
server --- Domain name of OSM API.
basepath --- Path to the API on the server.
version --- Version of OSM API.
changeset_tags --- Default tags to use when creating changeset.
Attributes:
username --- Username for API authentication
password --- Password for API authentication.
capabilities --- OSM API capabilities, read-only.
changeset_autocreate --- Should we automagically create new changesets as needed?
changeset_maxsize --- Maximum size of automagically created changesets.
Methods:
request --- Low-level method to retrieve data from server.
get --- Low-level method for GET request.
put --- Low-level method for PUT request.
delete --- Low-level method for DELETE request.
post --- Low-level method for POST request.
get_changeset_id --- Return changeset id as string or raise Exception.
check_auto_changeset --- Check automagically created changeset and close it if needed.
get_changeset --- Download changeset by id.
get_changeset_full --- Download changeset contents by id.
search_changeset --- Search for changeset by given parameters.
create_changeset --- Create changeset.
update_changeset --- Update changeset.
close_changeset --- Close changeset.
Methods (required by BaseReadAPI):
get_capabilities --- Download and return dictionary with OSM API capabilities.
get_bbox --- Download OSM data inside the specified bbox.
get_element --- Download node/way/relation by id and optionally version.
get_element_full --- Download way/relation by id and all elements that references.
get_elements --- Download nodes/ways/relations by ids.
get_element_rels --- Download relations that reference the node/way/relation by id.
get_node_ways --- Download ways that reference the node by id or wrapper.
Methods (required by BaseWriteAPI):
upload_diff --- OSC diff upload.
create_element --- Create node/way/relation.
update_element --- Update node/way/relation.
delete_element --- Delete node/way/relation.
"""
http = HTTPClient
log = logging.getLogger("osmapis.api")
_capabilities = None
_changeset = None
version = 0.6
server = "api.openstreetmap.org"
basepath = "/api/{}/".format(version)
changeset_tags = {"created_by": "osmapis/{0}".format(__version__)}
def __init__(self, username="", password="", changeset_autocreate=True, changeset_maxsize=1000, changeset_tags={}):
"""
Keyworded arguments:
username --- Username for API authentication
password --- Password for API authentication
changeset_autocreate --- Should we automagically create new changesets as needed?
changeset_maxsize --- Maximum size of automagically creted changesets.
changeset_tags --- Default tags to use when creating changeset.
"""
self.username = username
self.password = password
self.changeset_autocreate = bool(changeset_autocreate)
self.changeset_maxsize = int(changeset_maxsize)
self.changeset_tags = dict(self.changeset_tags)
self.changeset_tags.update(changeset_tags)
def __del__(self):
self.check_auto_changeset(close=True)
return None
def get_changeset_id(self, changeset=None):
"""
Return changeset id as string or raise Exception.
If changeset_autocreate is enabled and no valid changeset or its id is passed,
return automagic changeset id.
Keyworded arguments:
changeset --- Changeset wrapper, changeset id or None (use autocreate).