1
- from collections import OrderedDict
2
1
from datetime import datetime
3
2
from decimal import Decimal
3
+ from functools import partial
4
4
from urllib .request import urlopen
5
5
from urllib .error import HTTPError
6
6
from xml .sax import handler , make_parser
@@ -121,43 +121,31 @@ def query(self, query: Union[bytes, str]) -> "Result":
121
121
if not isinstance (query , bytes ):
122
122
query = query .encode ("utf-8" )
123
123
124
- retry_num : int = 0
125
124
retry_exceptions : List [exception .OverPyException ] = []
126
- do_retry : bool = True if self . max_retry_count > 0 else False
127
- while retry_num <= self .max_retry_count :
128
- if retry_num > 0 :
125
+
126
+ for run in range ( self .max_retry_count + 1 ) :
127
+ if run :
129
128
time .sleep (self .retry_timeout )
130
- retry_num += 1
129
+
130
+ response = b""
131
131
try :
132
- f = urlopen (self .url , query )
133
- except HTTPError as e :
134
- f = e
135
-
136
- response = f .read (self .read_chunk_size )
137
- while True :
138
- data = f .read (self .read_chunk_size )
139
- if len (data ) == 0 :
140
- break
141
- response = response + data
142
- f .close ()
132
+ with urlopen (self .url , query ) as f :
133
+ f_read = partial (f .read , self .read_chunk_size )
134
+ for data in iter (f_read , b"" ):
135
+ response += data
136
+ except HTTPError as exc :
137
+ f = exc
143
138
144
139
current_exception : exception .OverPyException
145
140
if f .code == 200 :
146
141
content_type = f .getheader ("Content-Type" )
147
-
148
142
if content_type == "application/json" :
149
143
return self .parse_json (response )
150
-
151
- if content_type == "application/osm3s+xml" :
144
+ elif content_type == "application/osm3s+xml" :
152
145
return self .parse_xml (response )
153
-
154
- current_exception = exception .OverpassUnknownContentType (content_type )
155
- if not do_retry :
156
- raise current_exception
157
- retry_exceptions .append (current_exception )
158
- continue
159
-
160
- if f .code == 400 :
146
+ else :
147
+ current_exception = exception .OverpassUnknownContentType (content_type )
148
+ elif f .code == 400 :
161
149
msgs : List [str ] = []
162
150
for msg_raw in self ._regex_extract_error_msg .finditer (response ):
163
151
msg_clean_bytes = self ._regex_remove_tag .sub (b"" , msg_raw .group ("msg" ))
@@ -166,37 +154,17 @@ def query(self, query: Union[bytes, str]) -> "Result":
166
154
except UnicodeDecodeError :
167
155
msg = repr (msg_clean_bytes )
168
156
msgs .append (msg )
169
-
170
- current_exception = exception .OverpassBadRequest (
171
- query ,
172
- msgs = msgs
173
- )
174
- if not do_retry :
175
- raise current_exception
176
- retry_exceptions .append (current_exception )
177
- continue
178
-
179
- if f .code == 429 :
157
+ current_exception = exception .OverpassBadRequest (query , msgs = msgs )
158
+ elif f .code == 429 :
180
159
current_exception = exception .OverpassTooManyRequests ()
181
- if not do_retry :
182
- raise current_exception
183
- retry_exceptions .append (current_exception )
184
- continue
185
-
186
- if f .code == 504 :
160
+ elif f .code == 504 :
187
161
current_exception = exception .OverpassGatewayTimeout ()
188
- if not do_retry :
189
- raise current_exception
190
- retry_exceptions .append (current_exception )
191
- continue
192
-
193
- current_exception = exception .OverpassUnknownHTTPStatusCode (f .code )
194
- if not do_retry :
162
+ else :
163
+ current_exception = exception .OverpassUnknownHTTPStatusCode (f .code )
164
+ if not self .max_retry_count :
195
165
raise current_exception
196
166
retry_exceptions .append (current_exception )
197
- continue
198
-
199
- raise exception .MaxRetriesReached (retry_count = retry_num , exceptions = retry_exceptions )
167
+ raise exception .MaxRetriesReached (retry_count = run + 1 , exceptions = retry_exceptions )
200
168
201
169
def parse_json (self , data : Union [bytes , str ], encoding : str = "utf-8" ) -> "Result" :
202
170
"""
@@ -250,18 +218,18 @@ def __init__(
250
218
"""
251
219
if elements is None :
252
220
elements = []
253
- self ._areas : Dict [int , Union ["Area" , "Node" , "Relation" , "Way" ]] = OrderedDict (
254
- ( element .id , element ) for element in elements if is_valid_type (element , Area )
255
- )
256
- self ._nodes = OrderedDict (
257
- ( element .id , element ) for element in elements if is_valid_type (element , Node )
258
- )
259
- self ._ways = OrderedDict (
260
- ( element .id , element ) for element in elements if is_valid_type (element , Way )
261
- )
262
- self ._relations = OrderedDict (
263
- ( element .id , element ) for element in elements if is_valid_type (element , Relation )
264
- )
221
+ self ._areas : Dict [int , Union ["Area" , "Node" , "Relation" , "Way" ]] = {
222
+ element .id : element for element in elements if is_valid_type (element , Area )
223
+ }
224
+ self ._nodes = {
225
+ element .id : element for element in elements if is_valid_type (element , Node )
226
+ }
227
+ self ._ways = {
228
+ element .id : element for element in elements if is_valid_type (element , Way )
229
+ }
230
+ self ._relations = {
231
+ element .id : element for element in elements if is_valid_type (element , Relation )
232
+ }
265
233
self ._class_collection_map : Dict [Any , Any ] = {
266
234
Node : self ._nodes ,
267
235
Way : self ._ways ,
@@ -438,12 +406,9 @@ def get_area(self, area_id: int, resolve_missing: bool = False) -> "Area":
438
406
439
407
query = ("\n "
440
408
"[out:json];\n "
441
- "area({area_id});\n "
409
+ f "area({ area_id } );\n "
442
410
"out body;\n "
443
411
)
444
- query = query .format (
445
- area_id = area_id
446
- )
447
412
tmp_result = self .api .query (query )
448
413
self .expand (tmp_result )
449
414
@@ -480,12 +445,9 @@ def get_node(self, node_id: int, resolve_missing: bool = False) -> "Node":
480
445
481
446
query = ("\n "
482
447
"[out:json];\n "
483
- "node({node_id});\n "
448
+ f "node({ node_id } );\n "
484
449
"out body;\n "
485
450
)
486
- query = query .format (
487
- node_id = node_id
488
- )
489
451
tmp_result = self .api .query (query )
490
452
self .expand (tmp_result )
491
453
@@ -523,12 +485,9 @@ def get_relation(self, rel_id: int, resolve_missing: bool = False) -> "Relation"
523
485
524
486
query = ("\n "
525
487
"[out:json];\n "
526
- "relation({relation_id });\n "
488
+ f "relation({ rel_id } );\n "
527
489
"out body;\n "
528
490
)
529
- query = query .format (
530
- relation_id = rel_id
531
- )
532
491
tmp_result = self .api .query (query )
533
492
self .expand (tmp_result )
534
493
@@ -565,12 +524,9 @@ def get_way(self, way_id: int, resolve_missing: bool = False) -> "Way":
565
524
566
525
query = ("\n "
567
526
"[out:json];\n "
568
- "way({way_id});\n "
527
+ f "way({ way_id } );\n "
569
528
"out body;\n "
570
529
)
571
- query = query .format (
572
- way_id = way_id
573
- )
574
530
tmp_result = self .api .query (query )
575
531
self .expand (tmp_result )
576
532
@@ -950,13 +906,10 @@ def get_nodes(self, resolve_missing: bool = False) -> List[Node]:
950
906
951
907
query = ("\n "
952
908
"[out:json];\n "
953
- "way({way_id });\n "
909
+ f "way({ self . id } );\n "
954
910
"node(w);\n "
955
911
"out body;\n "
956
912
)
957
- query = query .format (
958
- way_id = self .id
959
- )
960
913
tmp_result = self ._result .api .query (query )
961
914
self ._result .expand (tmp_result )
962
915
resolved = True
@@ -1423,9 +1376,9 @@ def startElement(self, name: str, attrs: dict):
1423
1376
if name in self .ignore_start :
1424
1377
return
1425
1378
try :
1426
- handler = getattr (self , ' _handle_start_%s' % name )
1379
+ handler = getattr (self , f" _handle_start_{ name } " )
1427
1380
except AttributeError :
1428
- raise KeyError ("Unknown element start '%s'" % name )
1381
+ raise KeyError (f "Unknown element start { name !r } " )
1429
1382
handler (attrs )
1430
1383
1431
1384
def endElement (self , name : str ):
@@ -1437,9 +1390,9 @@ def endElement(self, name: str):
1437
1390
if name in self .ignore_end :
1438
1391
return
1439
1392
try :
1440
- handler = getattr (self , ' _handle_end_%s' % name )
1393
+ handler = getattr (self , f" _handle_end_{ name } " )
1441
1394
except AttributeError :
1442
- raise KeyError ("Unknown element end '%s'" % name )
1395
+ raise KeyError (f "Unknown element end { name !r } " )
1443
1396
handler ()
1444
1397
1445
1398
def _handle_start_center (self , attrs : dict ):
@@ -1617,7 +1570,7 @@ def _handle_start_member(self, attrs: dict):
1617
1570
}
1618
1571
cls : Type [RelationMember ] = cls_map .get (attrs ["type" ])
1619
1572
if cls is None :
1620
- raise ValueError ("Undefined type for member: '%s'" % attrs ['type' ])
1573
+ raise ValueError (f "Undefined type for member: { attrs ['type' ]!r } " )
1621
1574
1622
1575
self .cur_relation_member = cls (** params )
1623
1576
self ._curr ['members' ].append (self .cur_relation_member )
0 commit comments