overpass-0.6.1/0000755SGl 0000000000013341665241017635 5ustar martijnvTELENAV\Domain Users00000000000000overpass-0.6.1/LICENSE.txt0000644SGl 0000002607413157771032021472 0ustar martijnvTELENAV\Domain Users00000000000000Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. overpass-0.6.1/MANIFEST.in0000644SGl 0000000006613341662154021375 0ustar martijnvTELENAV\Domain Users00000000000000include LICENSE.txt include tests/* include examples/*overpass-0.6.1/PKG-INFO0000644SGl 0000000143313341665241020733 0ustar martijnvTELENAV\Domain Users00000000000000Metadata-Version: 2.1 Name: overpass Version: 0.6.1 Summary: Python wrapper for the OpenStreetMap Overpass API Home-page: https://github.com/mvexel/overpass-api-python-wrapper Author: Martijn van Exel Author-email: m@rtijn.org License: Apache Description: See README.md Keywords: openstreetmap,overpass,wrapper Platform: UNKNOWN Classifier: License :: OSI Approved :: Apache Software License Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Topic :: Scientific/Engineering :: GIS Classifier: Topic :: Utilities Provides-Extra: test overpass-0.6.1/README.md0000644SGl 0000001064113341572646021124 0ustar martijnvTELENAV\Domain Users00000000000000Overpass API python wrapper =========================== Python bindings for the OpenStreetMap [Overpass API](http://wiki.openstreetmap.org/wiki/Overpass_API). [![Build Status](https://travis-ci.org/mvexel/overpass-api-python-wrapper.svg?branch=master)](https://travis-ci.org/mvexel/overpass-api-python-wrapper) Install it ========== `pip install overpass` ## Usage ### `API()` constructor First, create an API object. ```python import overpass api = overpass.API() ``` The API constructor takes several parameters, all optional: #### `endpoint` The default endpoint is `https://overpass-api.de/api/interpreter` but you can pass in another instance: ```python api = overpass.API(endpoint=https://overpass.myserver/interpreter) ``` #### `timeout` The default timeout is 25 seconds, but you can set it to whatever you want. ```python api = overpass.API(timeout=600) ``` #### `debug` Setting this to `True` will get you debug output. ### Getting data from Overpass: `get()` Most users will only ever need to use the `get()` method. There are some convenience query methods for common queries as well, see below. ```python response = api.get('node["name"="Salt Lake City"]') ``` `response` will be a dictionary representing the JSON output you would get [from the Overpass API directly](https://overpass-api.de/output_formats.html#json). **Note that the Overpass query passed to `get()` should not contain any `out` or other meta statements.** See `verbosity` below for how to control the output. Another example: ```python >>> print [( ... feature['properties']['name'], ... feature['id']) for feature in response["features"]] [(u'Salt Lake City', 150935219), (u'Salt Lake City', 585370637)] ``` You can find more examples in the `examples/` directory of this repository. The `get()` method takes a few parameters, all optional having sensible defaults. #### `verbosity` You can set the verbosity of the [Overpass query `out` directive](https://wiki.openstreetmap.org/wiki/Overpass_API/Overpass_QL#out) using the same keywords Overpass does. In order of increased verbosity: `ids`, `skel`, `body`, `tags`, `meta`. As is the case with the Overpass API itself, `body` is the default. ```python >>> import overpass >>> api = overpass.API() >>> data = api.get('way(42.819,-73.881,42.820,-73.880);(._;>;)', verbosity='geom') >>> [f for f in data.features if f.geometry['type'] == "LineString"] ``` (from [a question on GIS Stackexchange](https://gis.stackexchange.com/questions/294152/getting-all-information-about-ways-from-python-overpass-library/294358#294358)) #### `responseformat` You can set the response type of your query using `get()`'s `responseformat` parameter to GeoJSON (`geojson`, the default), plain JSON (`json`), CSV (`csv`), and OSM XML (`xml`). ```python response = api.get('node["name"="Salt Lake City"]', responseformat="xml") ``` #### `build` We will construct a valid Overpass QL query from the parameters you set by default. This means you don't have to include 'meta' statements like `[out:json]`, `[timeout:60]`, `[out body]`, etcetera. You just supply the meat of the query, the part that actually tells Overpass what to query for. If for whatever reason you want to override this and supply a full, valid Overpass QL query, you can set `build` to `False` to make the API not do any pre-processing. ### Pre-cooked Queries: `MapQuery`, `WayQuery` In addition to just sending your query and parse the result, `overpass` provides shortcuts for often used map queries. To use them, just pass them like to normal query to the API. #### MapQuery This is a shorthand for a [complete ways and relations](https://wiki.openstreetmap.org/wiki/Overpass_API/Language_Guide#Recursing_up_and_down:_Completed_ways_and_relations) query in a bounding box (the 'map call'). You just pass the bounding box to the constructor: ```python MapQuery = overpass.MapQuery(50.746,7.154,50.748,7.157) response = api.get(MapQuery) ``` #### WayQuery This is shorthand for getting a set of ways and their child nodes that satisfy certain criteria. Pass the criteria as a Overpass QL stub to the constructor: ```python WayQuery = overpass.WayQuery('[name="Highway 51"]') response = api.get(WayQuery) ``` ## Testing Using `pytest`. `py.test` ## FAQ ### I need help or have an idea for a feature Create a [new issue](https://github.com/mvexel/overpass-api-python-wrapper/issues). ### Where did the CLI tool go? The command line tool was deprecated in version 0.4.0. overpass-0.6.1/README.rst0000644SGl 0000000624113341572646021335 0ustar martijnvTELENAV\Domain Users00000000000000Overpass API python wrapper =========================== This is a thin wrapper around the OpenStreetMap `Overpass API `__. |Build Status| Install it ========== ``pip install overpass`` Usage ----- Simplest example: .. code:: python import overpass api = overpass.API() response = api.get('node["name"="Salt Lake City"]') ``response`` will be a dictionary representing the JSON output you would get `from the Overpass API directly `__. Note that the Overpass query passed to ``get()`` should not contain any ``out`` or other meta statements. Another example: .. code:: python >>> print [( ... feature['properties']['name'], ... feature['id']) for feature in response["features"]] [(u'Salt Lake City', 150935219), (u'Salt Lake City', 585370637)] You can find more examples in the ``examples/`` directory of this repository. Response formats ~~~~~~~~~~~~~~~~ You can set the response type of your query using ``get()``\ ’s ``responseformat`` parameter to GeoJSON (``geojson``, the default), plain JSON (``json``), CSV (``csv``), and OSM XML (``xml``). .. code:: python response = api.get('node["name"="Salt Lake City"]', responseformat="xml") Parameters ~~~~~~~~~~ The API object takes a few parameters: ``endpoint`` ^^^^^^^^^^^^ The default endpoint is ``https://overpass-api.de/api/interpreter`` but you can pass in another instance: .. code:: python api = overpass.API(endpoint=https://overpass.myserver/interpreter) ``timeout`` ^^^^^^^^^^^ The default timeout is 25 seconds, but you can set it to whatever you want. .. code:: python api = overpass.API(timeout=600) ``debug`` ^^^^^^^^^ Setting this to ``True`` will get you debug output. Simple queries ~~~~~~~~~~~~~~ In addition to just sending your query and parse the result, the wrapper provides shortcuts for often used map queries. To use them, just pass them like to normal query to the API. MapQuery ^^^^^^^^ This is a shorthand for a `complete ways and relations `__ query in a bounding box (the ‘map call’). You just pass the bounding box to the constructor: .. code:: python MapQuery = overpass.MapQuery(50.746,7.154,50.748,7.157) response = api.get(MapQuery) WayQuery ^^^^^^^^ This is shorthand for getting a set of ways and their child nodes that satisfy certain criteria. Pass the criteria as a Overpass QL stub to the constructor: .. code:: python WayQuery = overpass.WayQuery('[name="Highway 51"]') response = api.get(WayQuery) Testing ------- Using ``pytest``. ``py.test`` FAQ --- I need help or have an idea for a feature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Create a `new issue `__. Where did the CLI tool go? ~~~~~~~~~~~~~~~~~~~~~~~~~~ The command line tool was deprecated in version 0.4.0. .. |Build Status| image:: https://travis-ci.org/mvexel/overpass-api-python-wrapper.svg?branch=master :target: https://travis-ci.org/mvexel/overpass-api-python-wrapper overpass-0.6.1/examples/0000755SGl 0000000000013341665241021453 5ustar martijnvTELENAV\Domain Users00000000000000overpass-0.6.1/examples/README.md0000644SGl 0000000067413157771032022742 0ustar martijnvTELENAV\Domain Users00000000000000# Examples Please contribute your examples, submit a pull request! ## Turn restrictions as a list File: `turn_restriction_relations_as_list.py` This example requests a CSV response from an Overpass query for turn restrictions within the Toronto city limits. The result is then converted to a Python list and printed to stdout. Sample output: ```python ['6809605', 'hoream_telenav', '2016-12-21T15:05:42Z', '', 'no_left_turn'], ... ``` overpass-0.6.1/examples/overpassify_example.py0000644SGl 0000000126113341572646026120 0ustar martijnvTELENAV\Domain Users00000000000000#!/usr/bin/env python # Copyright 2015-2018 Martijn van Exel. # This file is part of the overpass-api-python-wrapper project # which is licensed under Apache 2.0. # See LICENSE.txt for the full license text. """An as yet not working example of using overpassify.""" import overpass from overpassify import overpassify api = overpass.API() @api.Get @overpassify def response(): Settings(timeout=1400) search = Area(3600134503) + Area(3600134502) ways = Way( search, maxspeed=None, highway=NotRegex("cycleway|footway|path|service"), access=NotRegex("private"), ) out(ways, body=True, geom=True, qt=True) noop() print(response) overpass-0.6.1/examples/readme_example.py0000755SGl 0000000061613341572646025011 0ustar martijnvTELENAV\Domain Users00000000000000#!/usr/bin/env python # Copyright 2015-2018 Martijn van Exel. # This file is part of the overpass-api-python-wrapper project # which is licensed under Apache 2.0. # See LICENSE.txt for the full license text. import overpass api = overpass.API() response = api.get('node["name"="Salt Lake City"]') print( [(feature["id"], feature["properties"]["name"]) for feature in response["features"]] ) overpass-0.6.1/examples/turn_restriction_relations_as_list.py0000755SGl 0000000115013341572646031246 0ustar martijnvTELENAV\Domain Users00000000000000#!/usr/bin/env python # Copyright 2015-2018 Martijn van Exel. # This file is part of the overpass-api-python-wrapper project # which is licensed under Apache 2.0. # See LICENSE.txt for the full license text. # Retrieves a list of turn restriction relations in Toronto. import overpass api = overpass.API() turn_restrictions_query = "relation[type=restriction](area:3600324211)" turn_restrictions_list = [] overpass_response = api.get( turn_restrictions_query, responseformat='csv(::"id",::"user",::"timestamp",restriction,"restriction:conditional")', verbosity="meta", ) print(overpass_response) overpass-0.6.1/examples/unique_users_for_area.py0000755SGl 0000000173413341572646026430 0ustar martijnvTELENAV\Domain Users00000000000000#!/usr/bin/env python # Copyright 2015-2018 Martijn van Exel. # This file is part of the overpass-api-python-wrapper project # which is licensed under Apache 2.0. # See LICENSE.txt for the full license text. # Retrieves a list of unique usernames and user IDs for a named area. import overpass # Change this to the name of the area you're interested in. # Keep it small to not abuse the Overpass server. area_name = "Kanab" query = """area[name="{}"]->.a;(node(area.a);<;);""".format(area_name) users = {"ids": [], "usernames": []} message_urls = [] api = overpass.API(debug=False) result = api.Get(query, responseformat="csv(::uid,::user)", verbosity="meta") del result[0] # header for row in result: uid = int(row[0]) username = row[1] if uid in users["ids"]: continue users["ids"].append(uid) users["usernames"].append(username) message_urls.append("https://www.openstreetmap.org/message/new/{}".format(username)) print(users) print(message_urls) overpass-0.6.1/overpass/0000755SGl 0000000000013341665241021477 5ustar martijnvTELENAV\Domain Users00000000000000overpass-0.6.1/overpass/__init__.py0000644SGl 0000000111213341662256023606 0ustar martijnvTELENAV\Domain Users00000000000000# -*- coding: utf-8 -*- # Copyright 2015-2018 Martijn van Exel. # This file is part of the overpass-api-python-wrapper project # which is licensed under Apache 2.0. # See LICENSE.txt for the full license text. """Thin wrapper around the OpenStreetMap Overpass API.""" __title__ = "overpass" __version__ = "0.6.1" __license__ = "Apache 2.0" from .api import API from .queries import MapQuery, WayQuery from .errors import ( OverpassError, OverpassSyntaxError, TimeoutError, MultipleRequestsError, ServerLoadError, UnknownOverpassError, ) from .utils import * overpass-0.6.1/overpass/api.py0000644SGl 0000001422713341661610022624 0ustar martijnvTELENAV\Domain Users00000000000000# Copyright 2015-2018 Martijn van Exel. # This file is part of the overpass-api-python-wrapper project # which is licensed under Apache 2.0. # See LICENSE.txt for the full license text. import requests import json import csv import geojson import logging from io import StringIO from .errors import ( OverpassSyntaxError, TimeoutError, MultipleRequestsError, ServerLoadError, UnknownOverpassError, ServerRuntimeError, ) class API(object): """A simple Python wrapper for the OpenStreetMap Overpass API.""" SUPPORTED_FORMATS = ["geojson", "json", "xml", "csv"] # defaults for the API class _timeout = 25 # second _endpoint = "https://overpass-api.de/api/interpreter" _debug = False _proxies = None _QUERY_TEMPLATE = "[out:{out}];{query}out {verbosity};" _GEOJSON_QUERY_TEMPLATE = "[out:json];{query}out {verbosity};" def __init__(self, *args, **kwargs): self.endpoint = kwargs.get("endpoint", self._endpoint) self.timeout = kwargs.get("timeout", self._timeout) self.debug = kwargs.get("debug", self._debug) self.proxies = kwargs.get("proxies", self._proxies) self._status = None if self.debug: # https://stackoverflow.com/a/16630836 try: import http.client as http_client except ImportError: # Python 2 import httplib as http_client http_client.HTTPConnection.debuglevel = 1 # You must initialize logging, # otherwise you'll not see debug output. logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) requests_log = logging.getLogger("requests.packages.urllib3") requests_log.setLevel(logging.DEBUG) requests_log.propagate = True def get(self, query, responseformat="geojson", verbosity="body", build=True): """Pass in an Overpass query in Overpass QL.""" # Construct full Overpass query if build: full_query = self._construct_ql_query( query, responseformat=responseformat, verbosity=verbosity ) else: full_query = query if self.debug: logging.getLogger().info(query) # Get the response from Overpass r = self._get_from_overpass(full_query) content_type = r.headers.get("content-type") if self.debug: print(content_type) if content_type == "text/csv": result = [] reader = csv.reader(StringIO(r.text), delimiter="\t") for row in reader: result.append(row) return result elif content_type in ("text/xml", "application/xml", "application/osm3s+xml"): return r.text elif content_type == "application/json": response = json.loads(r.text) if not build: return response # Check for valid answer from Overpass. # A valid answer contains an 'elements' key at the root level. if "elements" not in response: raise UnknownOverpassError("Received an invalid answer from Overpass.") # If there is a 'remark' key, it spells trouble. overpass_remark = response.get("remark", None) if overpass_remark and overpass_remark.startswith("runtime error"): raise ServerRuntimeError(overpass_remark) if responseformat is not "geojson": return response # construct geojson return self._as_geojson(response["elements"]) def search(self, feature_type, regex=False): """Search for something.""" raise NotImplementedError() # deprecation of upper case functions Get = get Search = search def _construct_ql_query(self, userquery, responseformat, verbosity): raw_query = str(userquery).rstrip() if not raw_query.endswith(";"): raw_query += ";" if responseformat == "geojson": template = self._GEOJSON_QUERY_TEMPLATE complete_query = template.format(query=raw_query, verbosity=verbosity) else: template = self._QUERY_TEMPLATE complete_query = template.format( query=raw_query, out=responseformat, verbosity=verbosity ) if self.debug: print(complete_query) return complete_query def _get_from_overpass(self, query): payload = {"data": query} try: r = requests.post( self.endpoint, data=payload, timeout=self.timeout, proxies=self.proxies, headers={"Accept-Charset": "utf-8;q=0.7,*;q=0.7"}, ) except requests.exceptions.Timeout: raise TimeoutError(self._timeout) self._status = r.status_code if self._status != 200: if self._status == 400: raise OverpassSyntaxError(query) elif self._status == 429: raise MultipleRequestsError() elif self._status == 504: raise ServerLoadError(self._timeout) raise UnknownOverpassError( "The request returned status code {code}".format(code=self._status) ) else: r.encoding = "utf-8" return r def _as_geojson(self, elements): features = [] geometry = None for elem in elements: elem_type = elem.get("type") if elem_type and elem_type == "node": geometry = geojson.Point((elem.get("lon"), elem.get("lat"))) elif elem_type and elem_type == "way": points = [] geom = elem.get("geometry") if geom: for coords in elem.get("geometry"): points.append((coords["lon"], coords["lat"])) geometry = geojson.LineString(points) else: continue feature = geojson.Feature( id=elem["id"], geometry=geometry, properties=elem.get("tags") ) features.append(feature) return geojson.FeatureCollection(features) overpass-0.6.1/overpass/errors.py0000644SGl 0000000246513341572646023402 0ustar martijnvTELENAV\Domain Users00000000000000# Copyright 2015-2018 Martijn van Exel. # This file is part of the overpass-api-python-wrapper project # which is licensed under Apache 2.0. # See LICENSE.txt for the full license text. class OverpassError(Exception): """An error during your request occurred. Super class for all Overpass api errors.""" pass class OverpassSyntaxError(OverpassError, ValueError): """The request contains a syntax error.""" def __init__(self, request): self.request = request class TimeoutError(OverpassError): """A request timeout occurred.""" def __init__(self, timeout): self.timeout = timeout class MultipleRequestsError(OverpassError): """You are trying to run multiple requests at the same time.""" pass class ServerLoadError(OverpassError): """The Overpass server is currently under load and declined the request. Try again later or retry with reduced timeout value.""" def __init__(self, timeout): self.timeout = timeout class UnknownOverpassError(OverpassError): """An unknown kind of error happened during the request.""" def __init__(self, message): self.message = message class ServerRuntimeError(OverpassError): """The Overpass server returned a runtime error""" def __init__(self, message): self.message = message overpass-0.6.1/overpass/queries.py0000644SGl 0000000256313341572646023542 0ustar martijnvTELENAV\Domain Users00000000000000# -*- coding: utf-8 -*- # Copyright 2015-2018 Martijn van Exel. # This file is part of the overpass-api-python-wrapper project # which is licensed under Apache 2.0. # See LICENSE.txt for the full license text. class MapQuery(object): """Query to retrieve complete ways and relations in an area.""" _QUERY_TEMPLATE = "(node({south},{west},{north},{east});<;>;);" def __init__(self, south, west, north, east): """ Initialize query with given bounding box. :param bbox Bounding box with limit values in format west, south, east, north. """ self.west = west self.south = south self.east = east self.north = north def __str__(self): return self._QUERY_TEMPLATE.format( west=self.west, south=self.south, east=self.east, north=self.north ) class WayQuery(object): """Query to retrieve a set of ways and their dependent nodes satisfying the input parameters.""" _QUERY_TEMPLATE = "(way{query_parameters});(._;>;);" def __init__(self, query_parameters): """Initialize a query for a set of ways satisfying the given parameters. :param query_parameters Overpass QL query parameters """ self.query_parameters = query_parameters def __str__(self): return self._QUERY_TEMPLATE.format(query_parameters=self.query_parameters) overpass-0.6.1/overpass/utils.py0000644SGl 0000000067213341573645023224 0ustar martijnvTELENAV\Domain Users00000000000000# Copyright 2015-2018 Martijn van Exel. # This file is part of the overpass-api-python-wrapper project # which is licensed under Apache 2.0. # See LICENSE.txt for the full license text. class Utils(object): @classmethod def to_overpass_id(cls, osmid, area=False): area_base = 2400000000 relation_base = 3600000000 if area: return int(osmid) + area_base return int(osmid) + relation_base overpass-0.6.1/overpass.egg-info/0000755SGl 0000000000013341665241023171 5ustar martijnvTELENAV\Domain Users00000000000000overpass-0.6.1/overpass.egg-info/PKG-INFO0000644SGl 0000000143313341665241024267 0ustar martijnvTELENAV\Domain Users00000000000000Metadata-Version: 2.1 Name: overpass Version: 0.6.1 Summary: Python wrapper for the OpenStreetMap Overpass API Home-page: https://github.com/mvexel/overpass-api-python-wrapper Author: Martijn van Exel Author-email: m@rtijn.org License: Apache Description: See README.md Keywords: openstreetmap,overpass,wrapper Platform: UNKNOWN Classifier: License :: OSI Approved :: Apache Software License Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Topic :: Scientific/Engineering :: GIS Classifier: Topic :: Utilities Provides-Extra: test overpass-0.6.1/overpass.egg-info/SOURCES.txt0000644SGl 0000000103613341665241025055 0ustar martijnvTELENAV\Domain Users00000000000000LICENSE.txt MANIFEST.in README.md README.rst setup.cfg setup.py examples/README.md examples/overpassify_example.py examples/readme_example.py examples/turn_restriction_relations_as_list.py examples/unique_users_for_area.py overpass/__init__.py overpass/api.py overpass/errors.py overpass/queries.py overpass/utils.py overpass.egg-info/PKG-INFO overpass.egg-info/SOURCES.txt overpass.egg-info/dependency_links.txt overpass.egg-info/requires.txt overpass.egg-info/top_level.txt tests/test_api.py tests/__pycache__/test_api.cpython-27-PYTEST.pycoverpass-0.6.1/overpass.egg-info/dependency_links.txt0000644SGl 0000000000113341665241027237 0ustar martijnvTELENAV\Domain Users00000000000000 overpass-0.6.1/overpass.egg-info/requires.txt0000644SGl 0000000005613341665241025572 0ustar martijnvTELENAV\Domain Users00000000000000requests>=2.3.0 geojson>=1.0.9 [test] pytest overpass-0.6.1/overpass.egg-info/top_level.txt0000644SGl 0000000001113341665241025713 0ustar martijnvTELENAV\Domain Users00000000000000overpass overpass-0.6.1/setup.cfg0000644SGl 0000000011713341665241021455 0ustar martijnvTELENAV\Domain Users00000000000000[metadata] description-file = README.md [egg_info] tag_build = tag_date = 0 overpass-0.6.1/setup.py0000644SGl 0000000172613341662242021353 0ustar martijnvTELENAV\Domain Users00000000000000from setuptools import setup setup( name="overpass", packages=["overpass"], version="0.6.1", description="Python wrapper for the OpenStreetMap Overpass API", long_description="See README.md", author="Martijn van Exel", author_email="m@rtijn.org", url="https://github.com/mvexel/overpass-api-python-wrapper", license="Apache", keywords=["openstreetmap", "overpass", "wrapper"], classifiers=[ "License :: OSI Approved :: Apache Software License", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Topic :: Scientific/Engineering :: GIS", "Topic :: Utilities", ], install_requires=["requests>=2.3.0", "geojson>=1.0.9"], extras_require={"test": ["pytest"]}, ) overpass-0.6.1/tests/0000755SGl 0000000000013341665241020777 5ustar martijnvTELENAV\Domain Users00000000000000overpass-0.6.1/tests/__pycache__/0000755SGl 0000000000013341665241023207 5ustar martijnvTELENAV\Domain Users00000000000000overpass-0.6.1/tests/__pycache__/test_api.cpython-27-PYTEST.pyc0000644SGl 0000000564413302035014030466 0ustar martijnvTELENAV\Domain Users00000000000000 9[c@s@ddlZddljjZddlZdZdZdS(iNcCstj}tj}t||}|sddidtjksUtjtrdtjtndd6dtjkstj|rtj|ndd6dtjkstjtrtjtndd6tj|d 6tj|d 6}ttj |nd}}|j }|t k}|stj d|fd|t fidtjks|tj|rtj|ndd6tj|d6d tjkstjt rtjt nd d 6}di|d 6}ttj |nd}}dS(NtsNassert %(py6)s {%(py6)s = %(py0)s(%(py1)s, %(py4)s {%(py4)s = %(py2)s.API }) }t isinstancetpy0tapitpy1toverpasstpy2tpy4tpy6tiss-%(py2)s {%(py2)s = %(py0)s.debug } is %(py4)stFalsesassert %(py6)s(R (s-%(py2)s {%(py2)s = %(py0)s.debug } is %(py4)ssassert %(py6)s(RtAPIRt @py_builtinstlocalst @pytest_art_should_repr_global_namet _safereprtAssertionErrort_format_explanationtNonetdebugR t_call_reprcompare(Rt @py_assert3t @py_assert5t @py_format7t @py_assert1t @py_format5((sA/Users/martijnv/dev/overpass-api-python-wrapper/tests/test_api.pyttest_initialize_api s    c Cs6tjdt}tjdddd}|j|}|d}t|}d}||k}|stjd|fd||fid tj kstj trtj tnd d 6tj |d 6tj |d 6tj |d6}di|d6}t tj |nd}}}}|jd}|d}t|}d}||k}|s tjd|fd||fid tj kstj trtj tnd d 6tj |d 6tj |d 6tj |d6}di|d6}t tj |nd}}}}dS(NRg{B@g\wb^gB@g?^tfeaturesit>s/%(py4)s {%(py4)s = %(py0)s(%(py2)s) } > %(py7)stlenRRRtpy7Rsassert %(py9)stpy9s#node(area:3602758138)[amenity=cafe](R(s/%(py4)s {%(py4)s = %(py0)s(%(py2)s) } > %(py7)ssassert %(py9)s(R(s/%(py4)s {%(py4)s = %(py0)s(%(py2)s) } > %(py7)ssassert %(py9)s(RR tTruetMapQuerytgetRRRR R RRRRR( Rt map_querytosm_geoRRt @py_assert6Rt @py_format8t @py_format10((sA/Users/martijnv/dev/overpass-api-python-wrapper/tests/test_api.pyt test_geojsons,    ( t __builtin__R t_pytest.assertion.rewritet assertiontrewriteRRRR)(((sA/Users/martijnv/dev/overpass-api-python-wrapper/tests/test_api.pyts   overpass-0.6.1/tests/test_api.py0000644SGl 0000000117713341572646023175 0ustar martijnvTELENAV\Domain Users00000000000000# Copyright 2015-2018 Martijn van Exel. # This file is part of the overpass-api-python-wrapper project # which is licensed under Apache 2.0. # See LICENSE.txt for the full license text. import overpass def test_initialize_api(): api = overpass.API() assert isinstance(api, overpass.API) assert api.debug is False def test_geojson(): api = overpass.API(debug=True) map_query = overpass.MapQuery(37.86517, -122.31851, 37.86687, -122.31635) osm_geo = api.get(map_query) assert len(osm_geo["features"]) > 1 osm_geo = api.get("node(area:3602758138)[amenity=cafe]") assert len(osm_geo["features"]) > 1