Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Updating a Google Site Listpage/Listitem


Here is a quick and dirty (by fully functional) sample of updating a listpage/listitem in Google Sites using the Data API.

#!/usr/bin/python

import getpass
import gdata.sites.client
import gdata.sites.data

USER = 'test@example.com'
SITE = 'YOUR_SITE_NAME'
DOMAIN = 'YOUR_DOMAIN'  # or 'site' if you're not using a Google Apps domain.

# Setup our client.
client = gdata.sites.client.SitesClient(source='google-SitesListeItemUpdateTest', site=SITE, domain=DOMAIN)
client.ClientLogin(USER, getpass.getpass(), client.source)
client.ssl = True
client.http_client.debug = False

# Only fetch listpages.
feed = client.GetContentFeed(uri=client.MakeContentFeedUri() + '?kind=listpage')

# Work with first listpage we found.
lp = feed.GetListPages()[0]

print 'Listpage columns:'
for col in lp.data.column:
  print 'index: %s, name: %s' % (col.index, col.name)

# Query the listpage's listems and work with first row found.
li = client.GetContentFeed(uri=lp.feed_link.href).entry[0]

print 'Row contents:'
for field in li.field:
  print 'index: %s, name: %s, value: %s' % (field.index, field.name, field.text)

# Update the first fields/column's value.
li.field[0].text = 'Someone else'
entry = client.Update(li)

# Update the listpage's column heading.
#lp.data.column[0].name = 'New Heading'
#entry2 = client.Update(lp)

OAuth in Google App Engine


This sample demonstrates a basic structure that you can use to perform 3-legged OAuth using the Google Data Python client library in Google App Engine. This particular example talks to the Documents List Data API.

App Engine (Python) + OAuth sample

Note: The sample is available in two versions, one that signs requests with RSA-SHA1 and another that signs with HMAC-SHA1.

2 Legged OAuth in Python


Google Apps Premier/Education administrators can take advantage of 2 legged OAuth to communicate with the Google Data APIs. If you're using the Google Data Python client library 1.2.3+: An updated sample is here available here. Otherwise, if you're stuck with an older version of the library (< 1.2.3), you can use the Python OAuth library from oauth.net.
import urllib
import oauth
import gdata.contacts
import gdata.contacts.service

CONSUMER_KEY = 'yourdomain.com'
CONSUMER_SECRET = 'YOUR_CONSUMER_SECRET'
CONTACTS_URL = 'http://www.google.com/m8/feeds/contacts/default/full'

# Setup 2 legged OAuth consumer based on our admin "credentials"
consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)

user = 'any.user@yourdomain.com'
params = {'max-results': 50, 'xoauth_requestor_id': user}

# Construct the request manually and sign it using HMAC-SHA1
# Note: The params dictionary needs to be passed in separately from the base URL
request = oauth.OAuthRequest.from_consumer_and_token(
   consumer, http_method='GET', http_url=CONTACTS_URL, parameters=params)
request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer, None)

# See patch @ http://code.google.com/p/oauth/issues/detail?id=31
headers = request.to_header()

client = gdata.contacts.service.ContactsService()

# Query the user's contacts and print their name & email
uri = '%s?%s' % (request.http_url, urllib.urlencode(params))
feed = client.GetFeed(uri, extra_headers=headers, converter=gdata.contacts.ContactsFeedFromString)
for entry in feed.entry:
 print '%s, %s' % (entry.title.text, entry.email[0].address)

Paging Through Feeds in Python


If you have a feed object you use

feed.GetNextLink().href

to find the URL of the next page of results. Then you can use that to query for more like so:

nextPageFeed = service.Query(feed.GetNextLink().href) 

Using AuthSub on App Engine


For a full explanation, see this article: Retrieving Authenticated Google Data Feeds with Google App Engine
    # Initialize a client to talk to Google Data API services.
    client = gdata.service.GDataService()
    gdata.alt.appengine.run_on_appengine(client)

    session_token = None
    # Find the AuthSub token and upgrade it to a session token.
    auth_token = gdata.auth.extract_auth_sub_token_from_url(self.request.uri)
    if auth_token:
      # Upgrade the single-use AuthSub token to a multi-use session token.
      session_token = client.upgrade_to_session_token(auth_token)
    if session_token and users.get_current_user():
      # If there is a current user, store the token in the datastore and
      # associate it with the current user. Since we told the client to
      # run_on_appengine, the add_token call will automatically store the
      # session token if there is a current_user.
      client.token_store.add_token(session_token)
    elif session_token:
      # Since there is no current user, we will put the session token
      # in a property of the client. We will not store the token in the
      # datastore, since we wouldn't know which user it belongs to.
      # Since a new client object is created with each get call, we don't
      # need to worry about the anonymous token being used by other users.
      client.current_token = session_token

Retrieving a user profile image in YouTube using Python


import gdata.youtube
import gdata.youtube.service

yt_service = gdata.youtube.service.YouTubeService()
user_entry = yt_service.GetYouTubeUserEntry(username='GoogleDevelopers')
print user_entry.thumbnail.url

Catching Exceptions from the Python Client Library


If you're using the Python client library and encounter a server error, an exception will be generated, causing Python to stop in its tracks and print out the contents of the exception. While this is useful for debugging, in a production application you'll probably want your application to fail gracefully, perhaps displaying a nice error message to your users.

You can do this by wrapping your code in a try block and using an except statement:

try:
  # Do something that accesses the network
except gdata.service.RequestError, inst:
  response = inst[0]
  status = response['status']
  reason = response['reason']
  body = response['body']
  # Handle the error here

Other exceptions may be thrown depending on the situation. For more information, see the gdata.service documentation.

Finding the total number of comments for a Video Entry with the Python Client Library


The snippet below shows how to retrieve the total number of comments for a video entry by examining the comment feed object using the interactive shell:
>>> import gdata.youtube.service
>>> client = gdata.youtube.service.YouTubeService()
>>> feed = client.GetRecentlyFeaturedVideoFeed()
>>> # fetching the first entry from the recently featured video feed
>>> entry = feed.entry[0]
>>> entry.title.text
"Follow Obama's nomination week: youtube.com/2008conventions"
>>> # fetching the comment feed
>>> comments = client.GetYouTubeVideoCommentFeed(video_id='9N4GOpSt5OI')
>>> # printing the text contents of the total_results element
>>> # note that this element is part of every feed
>>> comments.total_results.text
'578'
Alternatively, if you want to eliminate the actual request to catch the comment feed itself, you can parse out the number of comments by examining the 'countHint' attribute of the comment feedLink:
>>> entry.comments.feed_link[0].count_hint
'50'

Getting the worksheet feed for a given spreadsheet


This code snippet demonstrates how to obtain a feed of worksheet entries, given an authenticated gdata.spreadsheet.service.SpreadsheetsService() client object and a worksheet key. For the sake of the example, we are going to extract the worksheets feed for the first spreadsheet in our spreadsheets feed. The example uses the interactive Python interpreter. To obtain the worksheet feed for a private spreadsheet:
>>> import gdata
>>> import gdata.docs
>>> import gdata.spreadsheet
>>> import gdata.spreadsheet.service
>>> client = gdata.spreadsheet.service.SpreadsheetsService()
>>> client.email = 'me@gmail.com'
>>> client.password = 'mypassword'
>>> client.ProgrammaticLogin()
>>> spreadsheet_feed = client.GetFeed('http://spreadsheets.google.com/feeds/spreadsheets/private/full')
>>> first_entry = spreadsheet_feed.entry[0]
>>> key = first_entry.id.text.rsplit('/')[-1]
>>> worksheets_feed = client.GetWorksheetsFeed(key)
>>> for entry in worksheets_feed.entry:
...     print entry.title.text
... 
To do the same without authentication for public spreadsheets: To obtain the worksheet feed for a private spreadsheet:
>>> import gdata.spreadsheet
>>> import gdata.spreadsheet.service
>>> client = gdata.spreadsheet.service.SpreadsheetsService()
>>> key = 'p123345abcDEF'
>>> worksheets_feed = client.GetWorksheetsFeed(key, visibility='public', projection='values')
>>> for entry in worksheets_feed.entry:
...     print entry.title.text
... 

Edit contact phone numbers using Python


This sample shows the creation of a contact using the Google Contacts API. The phone number for the contact is then removed by editing the local contact entry object and uploading. At the ned, the script asks you to press enter before deleting the test contact.
import gdata.contacts.service
import atom
import gdata.contacts
import getpass

client = gdata.contacts.service.ContactsService()
client.email = raw_input('Please enter your email address')
client.password = getpass.getpass()
client.source = 'Google-ContactsGetTest-1.0'
client.ProgrammaticLogin()

name = 'Fred'
notes = 'Test entry'
primary_email = 'test2903488769871632@example.com'
new_contact = gdata.contacts.ContactEntry(title=atom.Title(text=name))
new_contact.content = atom.Content(text=notes)
new_contact.email.append(gdata.contacts.Email(address=primary_email,
                         primary='true', rel=gdata.contacts.REL_WORK))
new_contact.phone_number.append(gdata.contacts.PhoneNumber(
    rel=gdata.contacts.REL_OTHER, text='555-1212-3242'))
entry = client.CreateContact(new_contact)

if entry:
  print 'Creation successful!'
  print 'Edit link for the new contact:', entry.GetEditLink().href
else:
  print 'Upload error.'

# Remove the phone number
del entry.phone_number[0]

updated = client.UpdateContact(entry.GetEditLink().href, entry)
if updated:
  print 'Update successful!'
  print 'Edit link for the updated contact:', updated.GetEditLink().href
else:
  print 'Upload error.'

raw_input('enter to delete')
client.Delete(updated.GetEditLink().href)

Batch update spreadsheet cells using Python


Using the gdata-python-client, you can change the value in multiple cells with one HTTP request. Here is an example:
import gdata.spreadsheet
import gdata.spreadsheet.service

client = gdata.spreadsheet.service.SpreadsheetsService()
client.email = 'your email address'
client.password = 'your password'
client.ProgrammaticLogin()

# Use the spreadsheet key and worksheet ID for the worksheet you want to edit.
cells = client.GetCellsFeed('pKq0C...', wksht_id='od6')

batchRequest = gdata.spreadsheet.SpreadsheetsCellsFeed()

# This sample changes the first four cells in the spreadsheet.
cells.entry[0].cell.inputValue = 'x'
batchRequest.AddUpdate(cells.entry[0])
cells.entry[1].cell.inputValue = 'y'
batchRequest.AddUpdate(cells.entry[1])
cells.entry[2].cell.inputValue = 'z'
batchRequest.AddUpdate(cells.entry[2])
cells.entry[3].cell.inputValue = '=sum(3,5)'
batchRequest.AddUpdate(cells.entry[3])

updated = client.ExecuteBatch(batchRequest, cells.GetBatchLink().href)

Access Spreadsheets list feed elements in Python


# print out dictionary of row information for each row
for entry in worksheet_list_feed.entry:
  for key in entry.custom:
    print '%s: %s' % (key, entry.custom[key].text)