项目作者: pvlbzn

项目描述 :
Pythonic Google Geocode API wrapper
高级语言: Python
项目地址: git://github.com/pvlbzn/gobject.git
创建时间: 2017-02-10T13:07:30Z
项目社区:https://github.com/pvlbzn/gobject

开源协议:

下载


Test Coverage

Gobject

Google Geocode API wrapper supercharged with Python Data Model,
which makes Gobject behave like a first class citizen.

Install

  1. pip install gobject

Example

Assume we are working in Python REPL environement

Import modules: requests to make a request, json as a utility, gobject. Note that gobject dependency free library.
It does not care about a source of JSON containing response from Google Geocode API.

  1. import gobject, requests, json

Get JSON response from Google API

  1. resp = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address=Jakarta&key=YOUR_API_KEY')
  2. resp
  3. > <Response [200]>

We got the response from API, now lets initialize gobject. It can be done in two ways, first one is preffered.

  1. gobj = gobject.load(resp.text)
  2. # Or another way using the class Gobject
  3. gobj_alt = gobject.Gobject(resp.text)

Beeing a Pythonic, gobject leverages Python Data Model to be first-class citizen in your code.

  1. gobj == gobj_alt
  2. > True

Important feature: gobject.load has an inverse function gobject.serialize. There exists a bijection relation.
Wrap the data into an object, serialize it and compare to original data.

  1. (gobject.load(resp.text)).serialize() == json.loads(resp.text)
  2. > True

gobject API follows Google Geocode API, just read Geocode docs and you will find it in Gobject too

  1. gobj.bounds
  2. > <northeast: <lat: -5.1843219 ; lng: 106.972825>, southwest: <lat: -6.3708331 ; lng: 106.3831259>>
  3. gobj.bounds.northeast
  4. > <lat: -5.1843219 ; lng: 106.972825>
  5. gobj.bounds.northeast == gobj.bounds.southwest
  6. > False
  7. gobj.bounds.northeast = gobj.bounds.southwest
  8. gobj.bounds.northeast == gobj.bounds.southwest
  9. > True
  10. len(gobj.address_components)
  11. > 2

Errors

Gobject handles all (5 kinds) errors which may occur in ‘status’ field of a JSON
response from Google Geocode API.

Lets make a request with non-existent place, such as Cappleble.

  1. resp = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address=Cappleble&key=API_KEY')
  2. resp
  3. > <Response [200]>

And load its data into the gobject

  1. wobj = gobject.load(resp.text)
  2. > Traceback (most recent call last):
  3. > ...
  4. > gobject.exception.ZeroResultsError: The geocode was successful but returned no results.
  5. This may occur if the geocoder was passed a non-existent address.

Exception message says exactly what we did, the cause of it is a non-existent place.

gobject supports all exceptions from Google API with their explanation messages.

Code Quality

Code quality is measured by codeclimate, you can find badge on a first line.

To test the code run:

  1. py.test