Skip to content Skip to sidebar Skip to footer

How Do I Insert A Row In My Google Fusion Table Using Python

I am working on a project and part of it involves inserting rows in to a Google Fusion Table for the Project from a python script. I have spent the last couple days trying to figur

Solution 1:

If your application needs offline access to a Google API, then the request for an authorization code should include the access_type parameter, where the value of that parameter is offline.

https://developers.google.com/accounts/docs/OAuth2WebServer#offline

Then, to obtain an access token using the refresh token you send a POST request including grant_type with value refresh_token.

Basically, the way SQL works is you send POST requests using a subset of SQL statements https://www.googleapis.com/fusiontables/v1/query?sql=STATEMENT_HERE

Refer to

https://developers.google.com/fusiontables/docs/v1/reference/queryhttps://developers.google.com/fusiontables/docs/v1/sql-reference

Edit:

Since you are using urllib2 without a data parameter, it defaults to GET. To fix this you should either use another HTTP library that allows for explicitly specifying method (like requests or httplib) or do something like this:

query = "INSERT INTO %s(EXAMPLE_COL1,EXAMPLE_COL2) VALUES"\
        "('EXAMPLE_INFO1','EXAMPLE_INFO2')" % table_id # Single quotes
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request('https://www.google.com/fusiontables/api/query?%s' % \
    (urllib.urlencode({'access_token': access_token,
                       'sql': query})),
    headers={'Content-Length':0})      # Manually set length to avoid 411 error
request.get_method = lambda: 'POST'# Change HTTP request method
response = opener.open(request).read()
print response

Important to notice:

  1. Monkey patch the method to do what we want (POST with an empty body) otherwise we would receive HTTP Error 400: HTTP GET can only be used for SELECT queries.

  2. Manually specify that we do not have a body (Content-Length is 0) otherwise we would receive HTTP Error 411: Length Required.

  3. Must use double quotes with single quotes inside or escape the inner quotes to submit strings via the query. In other words, "INSERT INTO %s(EXAMPLE_COL1,EXAMPLE_COL2) VALUES(EXAMPLE_INFO1,EXAMPLE_INFO2)" % table_id does not work.

    If we tried to use the previous line we would get something like HTTP Error 400: Parse error near 'SOME_STRING' (line X, position Y)

See for info on changing method with urllib2:

Is there any way to do HTTP PUT in python

Post a Comment for "How Do I Insert A Row In My Google Fusion Table Using Python"