Base provider definition
Base classes of provider definition responsible for minimum set of methods and properties, that should be implemented or overridden in all nested providers.
This set of methods and properties guarantees working of all project features and minimum similarity of result of any provider usage.
Each provider itself can extend supported and extracted properties, available in direct instance access. For list of such extracted properties please read documentation for exact provider.
Base Multiple Results Query class
- class geocoder.base.MultipleResultsQuery(location, url=None, key=None, timeout=None, proxies=None, session=None, headers=None, params=None, **kwargs)[source]
Base results and query manager container
This class responsible for checking correct new provider files creation before it will be implemented in project. Such checks done in
__init_subclass__()
method and will not allow to initialize project without fix.Class variables:
Some class variables are mandatory for all nested subclasses.
- Variables
cls._URL (str) – Default URL for provider, can be overwritten with url input parameter
cls._RESULT_CLASS (OneResult) – Provider’s individual result class.
cls._KEY (str) – Provider’s default api_key. Usually map to ENV variable responsible for key parsing. Can be overwritten with key parameter on instance creation. Shows actually used key when requested from instance.
cls._KEY_MANDATORY (bool) – Special mark for check of mandatory presence of api key, for providers with mandatory key requirement
cls._METHOD (str) – Provider’s internal method, that should match with api.py
options
definition.cls._PROVIDER (str) – Provider’s internal name, that should match with api.py
options
definition.cls._TIMEOUT (float) – Default timeout for
requests.request()
configuration, can be overwritten on instance creation or instance callingcls._GEOCODER3_READY (bool) – Temporary value, representing is provider tested and finished migration to geocoder3. On default value will generate warning on any provider call.
Instance variables:
After creation each instance of
MultipleResultsQuery
has the following mandatory variables. For some providers this list can be extended by provider implementation.- Variables
self.results_list (list[OneResult]) – Hold all answers from provider in parsed state
self.url (str) – Final request url that will be/was used during request
self.location (str) – Object to geocode/reverse geocode
self.timeout (float) – Final request timeout that was used during request
self.proxies (Optional[dict]) – Final request proxies that was used during request
self.session (requests.Session) –
requests.Session
object, that was usedself.headers (dict) – Final request headers that was used during request
self.params (dict) – Final request query params that was used during request
self.status_code (Optional[int]) –
requests.Response
final HTTP answer code or None if request is not made yet, orrequests
failed during requestself.raw_response (requests.Response) – Contain raw
requests.Response
from providerself.raw_json (Union[dict, list]) – Contain raw
requests.Response.json()
from providerself.error (str) –
requests
detailed error, if was raised during requestself.is_called (bool) – False on instance initialization, become True after calling of
__call__()
method(i.e. instance call)self.current_result (OneResult) – Mapping to result, that are used for direct attributes retrieval in
__getattr__()
Init parameters:
For initialization parameters, please check
MultipleResultsQuery.__init__()
method documentation.- __call__(timeout=None, proxies=None, session=None)[source]
Query remote server and parse results
Any keyword argument of
__call__()
will have precedence over same argument in__init__()
method.
- __getattr__(name)[source]
Allow direct access to
MultipleResultsQuery.current_result
attributes from direct calling ofMultipleResultsQuery
Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self).
Note
If the attribute is found through the normal mechanism,
__getattr__()
is not called.- Parameters
name – Attribute name for lookup
- Raises
RuntimeError – If provider query was not made and
current_result
is still empty. (Fromhas_data()
)
- __init__(location, url=None, key=None, timeout=None, proxies=None, session=None, headers=None, params=None, **kwargs)[source]
Initialize a
MultipleResultsQuery
object.For class and instance variables description please refer to class docstrings.
- Parameters
location – Query content for geocode or reverse geocoding
url (Optional[str]) – Overwrite for default provider service url
key (Optional[str]) – API Key data for provider usage, if required. Passed to
_get_api_key()
, which result passed to_build_headers()
and_build_params()
, and may be passed to other custom provider’s implementation methods. Check exact provider docs.timeout (Union[None, float, Tuple[float, float], Tuple[float, None]]) – Max request answer wait time
proxies (Optional[MutableMapping[str, str]]) – Proxies for
requests.request()
session (Optional[requests.Session]) – Custom
requests.Session
for requestheaders (Optional[MutableMapping[str, str]]) – Additional headers for
requests.request()
params (Optional[dict]) – Additional query parameters
kwargs – Any other keyword arguments, that will be passed to internal
_build_headers()
,_build_params()
,_before_initialize()
or other custom provider’s implementation methods. Check exact provider docs
- Raises
ValueError – When provided custom
url
is not well-formattedValueError – If api key was not provided, but mandatory for provider use
- classmethod __init_subclass__(**kwargs)[source]
Responsible for setup check for
MultipleResultsQuery
subclasses.- Raises
ValueError – When subclass not define
cls._URL
value.ValueError – When subclass incorrectly define
cls._RESULT_CLASS
value.ValueError – When subclass incorrectly define
cls._METHOD
value.
- _adapt_results(json_response)[source]
Allow children classes to format json_response into
_parse_results()
expected formatThis required for correct iteration in
_parse_results()
- Parameters
json_response – Raw json from provider, usually same as in
raw_json
, by default invoked inside_parse_results()
- _before_initialize(location, **kwargs)[source]
Hook for children class to finalize their setup before the query
- Parameters
location – Query content for geocode or reverse geocoding
kwargs – All kwargs from
__init__()
method
- _build_headers(provider_key, **kwargs)[source]
Generate default query headers for provider
- Parameters
provider_key – Finalized api_key, from
_get_api_key()
methodkwargs – All kwargs from
__init__()
method
- _build_params(location, provider_key, **kwargs)[source]
Generate default query parameters mapping for provider
- Parameters
location – Query content for geocode or reverse geocoding
provider_key – Finalized api_key, from
_get_api_key()
methodkwargs – All kwargs from
__init__()
method
- _catch_errors(json_response)[source]
Checks the JSON returned from the provider and flag errors if necessary
- classmethod _get_api_key(key=None)[source]
Retrieves API Key from method argument first, then from Environment variables
- Parameters
key (Optional[str]) – Custom API Key data for provider usage, if required. Passed from
__init__()
method.- Raises
ValueError – If api key was not provided, but mandatory for provider use
- _parse_results(json_response)[source]
Responsible for parsing original json and separating it to
OneResult
objects
- debug()[source]
Display debug information for instance of
MultipleResultsQuery
- property geojson
Output all answers as GeoJSON FeatureCollection
- property has_data
Status of geocoding if request was made
- Raises
RuntimeError – When external request was not made before property call
- property status
Specify current summary status of instance
Possible statuses:
“External request was not made”
“OK” - when request was made, and any result retrieved
requests
error text representation, if request faced error“ERROR - No results found”
“ERROR - Unhandled Exception”
Base One Result class
- class geocoder.base.OneResult(json_content)[source]
Container for one (JSON) object returned by provider
Class variables:
- Variables
cls._TO_EXCLUDE – List of properties and attributes to exclude in
OneResult._parse_json_with_fieldnames()
cls._GEOCODER3_READY (bool) – Temporary value, representing is provider tested and finished migration to geocoder3. On default value will bypass some internal checks.
Instance variables:
After creation each instance of
OneResult
has the following mandatory variables. For some providers this list can be extended by provider implementation.- Variables
self.object_raw_json – Raw json for object, passed by
MultipleResultsQuery._parse_results()
self.object_json – Result of
OneResult._parse_json_with_fieldnames()
self.fieldnames – Fieldnames list generated in
OneResult._parse_json_with_fieldnames()
Init parameters:
For initialization parameters, please check
OneResult.__init__()
method documentation.- __init__(json_content)[source]
Initialize
OneResult
object and parse input json- Parameters
json_content (dict) – Dictionary, passed by
MultipleResultsQuery.__call__()
- _parse_json_with_fieldnames()[source]
Parse the instance object with all attributes/methods defined in the class, except for the ones defined starting with ‘_’ or flagged in
cls._TO_EXCLUDE
.The final result is stored in
self.object_json
andself.fieldnames
- abstract property address
Object simple string address.
- property bbox
Output answer as GeoJSON bbox if it can be calculated/retrieved.
- property bounds
Output answer as Google Maps API bounds if it can be calculated/retrieved.
- property confidence
Is as a measure of how confident we are that centre point coordinates returned for the result precisely reflect the result.
- property east
Return optional east coordinate of bbox, if available.
- property geojson
Output answer as GeoJSON Feature
- property geometry
Output answer as GeoJSON Point
- abstract property lat
Latitude of the object
- property latlng
Optional list of latitude and longitude values.
- abstract property lng
Longitude of the object
- property north
Return optional north coordinate of bbox, if available.
- property northeast
Return north-east list of coordinates for bounds, if available.
- property ok
Status of retrieving location/IP coordinates or reverse geocoding.
Usually should be replaced in reverse results class.
- property south
Return optional south coordinate of bbox, if available.
- property southwest
Return south-west list of coordinates for bounds, if available.
- property status
Specify current summary status of instance
- property west
Return optional west coordinate of bbox, if available.
- property wkt
Output coordinates in well-known text format, no SRID data.
- property x
Longitude of the object
- property xy
Optional list of longitude and latitude values.
- property y
Latitude of the object