This Python script uses the requests and simplejson libraries to fetch data from the GeoNames wikipediaSearchJSON web service, and the GDAL/OGR library to store geographic information inside the PostGIS database.
First, you create a PostGIS point table to store the geographic data. This is made using the GDAL/OGR bindings. You need to instantiate an OGR PostGIS driver (http://www.gdal.org/drv_pg.html) from where it is possible to instantiate a dataset to connect to your postgis_cookbook database using a specified connection string.
The update parameter in the connection string specifies to the GDAL driver that you will open the dataset for updating.
From the PostGIS dataset, we created a PostGIS layer named wikiplaces that will store points (geom_type=ogr.wkbPoint) using the WGS 84 spatial reference system (srs.ImportFromEPSG(4326)). When creating the layer, we specified other parameters as well, such as dimension (3, as you want to store the z values), GEOMETRY_NAME (name of the geometric field), and schema. After creating the layer, you can use the CreateField layer method to create all the fields that are needed to store the information. Each field will have a specific name and datatype (all of them are ogr.OFTString in this case).
After the layer has been created (note that we need to have the pg_ds and pg_layer objects always in context for the whole script, as noted at http://trac.osgeo.org/gdal/wiki/PythonGotchas), you can query the GeoNames web services for each place name in the names.txt file using the urllib2 library.
We parsed the JSON response using the simplejson library, then iterated the JSON objects list and added a feature to the PostGIS layer for each of the objects in the JSON output. For each element, we created a feature with a point wkt geometry (using the lng, lat, and elevation object attributes) using the ogr.CreateGeometryFromWkt method, and updated the other fields using the other object attributes returned by GeoNames, using the feature setField method (title, countryCode, and so on).
You can get more information on programming with GDAL Python bindings by using the following great resource by Chris Garrard: