gdata.photos.service (version 176)
index
/home/jscudder/svn/gdata-python-client/src/gdata/photos/service.py

Google PhotoService provides a human-friendly interface to
Google Photo (a.k.a Picasa Web) services[1].
 
It extends gdata.service.GDataService and as such hides all the
nasty details about authenticating, parsing and communicating with
Google Photos. 
 
[1]: http://code.google.com/apis/picasaweb/gdata.html
 
Example:
  import gdata.photos, gdata.photos.service
  pws = gdata.photos.service.PhotosService()
  pws.ClientLogin(username, password)
  #Get all albums
  albums = pws.GetUserFeed().entry
  # Get all photos in second album
  photos = pws.GetFeed(albums[1].GetPhotosUri()).entry
  # Get all tags for photos in second album and print them
  tags = pws.GetFeed(albums[1].GetTagsUri()).entry
  print [ tag.summary.text for tag in tags ]
  # Get all comments for the first photos in list and print them
  comments = pws.GetCommentFeed(photos[0].GetCommentsUri()).entry
  print [ c.summary.text for c in comments ]
 
  # Get a photo to work with
  photo = photos[0]
  # Update metadata
 
  # Attributes from the <gphoto:*> namespace
  photo.summary.text = u'A nice view from my veranda'
  photo.title.text = u'Verandaview.jpg'
 
  # Attributes from the <media:*> namespace
  photo.media.keywords.text = u'Home, Long-exposure, Sunset' # Comma-separated
 
  # Adding attributes to media object
 
  # Rotate 90 degrees clockwise
  photo.rotation = gdata.photos.Rotation(text='90') 
 
  # Submit modified photo object
  photo = pws.UpdatePhotoMetadata(photo)
  
  # Make sure you only modify the newly returned object, else you'll get
  # versioning errors. See Optimistic-concurrency
 
  # Add comment to a picture
  comment = pws.InsertComment(photo, u'I wish the water always was this warm')
 
  # Remove comment because it was silly
  print "*blush*"
  pws.Delete(comment.GetEditLink().href)

 
Modules
       
cElementTree
StringIO
atom
gdata
os
sys
time

 
Classes
       
exceptions.Exception
GooglePhotosException
gdata.service.GDataService(atom.service.AtomService)
PhotosService

 
class GooglePhotosException(exceptions.Exception)
     Methods defined here:
__init__(self, response)

Methods inherited from exceptions.Exception:
__getitem__(...)
__str__(...)

 
class PhotosService(gdata.service.GDataService)
    
Method resolution order:
PhotosService
gdata.service.GDataService
atom.service.AtomService
__builtin__.object

Methods defined here:
Delete(self, object_or_uri, *args, **kwargs)
Delete an object.
 
Re-implementing the GDataService.Delete method, to add some
convenience.
 
Arguments:
object_or_uri: Any object that has a GetEditLink() method that
  returns a link, or a uri to that object.
 
Returns:
? or GooglePhotosException on errors
GetContacts(self, user='default', limit=None)
Retrieve a feed that contains a list of your contacts
 
Arguments:
user: Username of the user whose contacts you want
 
Returns
gdata.photos.UserFeed, with UserEntry entries
 
See:
http://groups.google.com/group/Google-Picasa-Data-API/msg/819b0025b5ff5e38
GetEntry(self, uri, limit=None, start_index=None)
Get an Entry.
 
Arguments:
uri: the uri to the entry
limit (optional): the maximum number of entries to return. Defaults to what
  the server returns.
 
Returns:
one of gdata.photos.AlbumEntry,
       gdata.photos.UserEntry,
       gdata.photos.PhotoEntry,
       gdata.photos.CommentEntry,
       gdata.photos.TagEntry,
  depending on the results of the query.
Raises:
GooglePhotosException
GetFeed(self, uri, limit=None, start_index=None)
Get a feed.
 
 The results are ordered by the values of their `updated' elements,
 with the most recently updated entry appearing first in the feed.
 
Arguments:
uri: the uri to fetch
limit (optional): the maximum number of entries to return. Defaults to what
  the server returns.
 
Returns:
one of gdata.photos.AlbumFeed,
       gdata.photos.UserFeed,
       gdata.photos.PhotoFeed,
       gdata.photos.CommentFeed,
       gdata.photos.TagFeed,
  depending on the results of the query.
Raises:
GooglePhotosException
 
See:
http://code.google.com/apis/picasaweb/gdata.html#Get_Album_Feed_Manual
GetTaggedPhotos(self, tag, user='default', limit=None)
Get all photos belonging to a specific user, tagged by the given keyword
 
Arguments:
tag: The tag you're looking for, e.g. `dog'
user (optional): Whose images/videos you want to search, defaults
  to current user
limit (optional): the maximum number of entries to return.
  Defaults to everything the server returns.
 
Returns:
gdata.photos.UserFeed containing PhotoEntry elements
GetUserFeed(self, kind='album', user='default', limit=None)
Get user-based feed, containing albums, photos, comments or tags;
  defaults to albums.
 
The entries are ordered by the values of their `updated' elements,
with the most recently updated entry appearing first in the feed.
 
Arguments:
kind: the kind of entries to get, either `album', `photo',
  `comment' or `tag', or a python list of these. Defaults to `album'.
user (optional): whose albums we're querying. Defaults to current user.
limit (optional): the maximum number of entries to return.
  Defaults to everything the server returns.
 
 
Returns:
gdata.photos.UserFeed, containing appropriate Entry elements
 
See:
http://code.google.com/apis/picasaweb/gdata.html#Get_Album_Feed_Manual
http://googledataapis.blogspot.com/2007/07/picasa-web-albums-adds-new-api-features.html
InsertAlbum(self, title, summary, location=None, access='public', commenting_enabled='true', timestamp=None)
Add an album.
 
Needs authentication, see ClientLogin()
 
Arguments:
title: Album title 
summary: Album summary / description
access (optional): `private' or `public'. Public albums are searchable
  by everyone on the internet. Defaults to `public'
commenting_enabled (optional): `true' or `false'. Defaults to `true'.
timestamp (optional): A date and time for the album, in milliseconds since
  Unix epoch[1] UTC. Defaults to now.
 
Returns:
The newly created gdata.photos.AlbumEntry
 
See:
http://code.google.com/apis/picasaweb/gdata.html#Add_Album_Manual_Installed
 
[1]: http://en.wikipedia.org/wiki/Unix_epoch
InsertComment(self, photo_or_uri, comment)
Add a comment to a photo.
 
Needs authentication, see ClientLogin()
 
Arguments:
photo_or_uri: a gdata.photos.PhotoEntry that is about to be commented
  , or a `post' uri pointing to it
(string) comment: The actual comment
 
Returns:
The new gdata.photos.CommentEntry
 
Example:
p = GetFeed(PhotoUri)
tag = InsertComment(p, 'OOOH! I would have loved to be there.
  Who's that in the back?')
InsertPhoto(self, album_or_uri, photo, filename_or_handle, content_type='image/jpeg')
Add a PhotoEntry
 
Needs authentication, see ClientLogin()
 
Arguments:
album_or_uri: AlbumFeed or uri of the album where the photo should go
photo: PhotoEntry to add
filename_or_handle: A file-like object or file name where the image/video
  will be read from
content_type (optional): Internet media type (a.k.a. mime type) of
  media object. Currently Google Photos supports these types:
   o image/bmp
   o image/gif
   o image/jpeg
   o image/png
   
  Images will be converted to jpeg on upload. Defaults to `image/jpeg'
InsertPhotoSimple(self, album_or_uri, title, summary, filename_or_handle, content_type='image/jpeg', keywords=None)
Add a photo without constructing a PhotoEntry.
 
Needs authentication, see ClientLogin()
 
Arguments:
album_or_uri: AlbumFeed or uri of the album where the photo should go
title: Photo title
summary: Photo summary / description
filename_or_handle: A file-like object or file name where the image/video
  will be read from
content_type (optional): Internet media type (a.k.a. mime type) of
  media object. Currently Google Photos supports these types:
   o image/bmp
   o image/gif
   o image/jpeg
   o image/png
   
  Images will be converted to jpeg on upload. Defaults to `image/jpeg'
keywords (optional): a 1) comma separated string or 2) a python list() of
  keywords (a.k.a. tags) to add to the image.
  E.g. 1) `dog, vacation, happy' 2) ['dog', 'happy', 'vacation']
 
Returns:
The newly created gdata.photos.PhotoEntry or GooglePhotosException on errors
 
See:
http://code.google.com/apis/picasaweb/gdata.html#Add_Album_Manual_Installed
[1]: http://en.wikipedia.org/wiki/Unix_epoch
InsertTag(self, photo_or_uri, tag)
Add a tag (a.k.a. keyword) to a photo.
 
Needs authentication, see ClientLogin()
 
Arguments:
photo_or_uri: a gdata.photos.PhotoEntry that will be tagged, or a
  `post' uri pointing to it
(string) tag: The tag/keyword
 
Returns:
The new gdata.photos.TagEntry
 
Example:
p = GetFeed(PhotoUri)
tag = InsertTag(p, 'Beautiful sunsets')
SearchCommunityPhotos(self, query, limit=100)
Search through all public photos and return a feed.
This will look for matches in file names and image tags (a.k.a. keywords)
 
Arguments:
query: The string you're looking for, e.g. `vacation'
limit (optional): Don't return more than `limit' hits, defaults to 100
 
Returns:
gdata.GDataFeed with PhotoEntry elements
SearchContactsPhotos(self, user='default', search=None, limit=None)
Search over your contacts' photos and return a feed
 
Arguments:
user: Username of the user whose contacts you want
search (optional): What to search for (photo title, description and keywords)
 
Returns
gdata.photos.UserFeed, with PhotoEntry elements
 
See:
http://groups.google.com/group/Google-Picasa-Data-API/msg/819b0025b5ff5e38
SearchUserPhotos(self, query, user='default', limit=100)
Search through all photos for a specific user and return a feed.
This will look for matches in file names and image tags (a.k.a. keywords)
 
Arguments:
query: The string you're looking for, e.g. `vacation'
user (optional): The username of whose photos you want to search, defaults
  to current user.
limit (optional): Don't return more than `limit' hits, defaults to 100
 
Only public photos are searched, unless you are authenticated and
searching through your own photos.
 
Returns:
gdata.photos.UserFeed with PhotoEntry elements
UpdatePhotoBlob(self, photo_or_uri, filename_or_handle, content_type='image/jpeg')
Update a photo's binary data.
 
Needs authentication, see ClientLogin()
 
Arguments:
photo_or_uri: a gdata.photos.PhotoEntry that will be updated, or a
  `edit-media' uri pointing to it
filename_or_handle:  A file-like object or file name where the image/video
  will be read from
content_type (optional): Internet media type (a.k.a. mime type) of
  media object. Currently Google Photos supports these types:
   o image/bmp
   o image/gif
   o image/jpeg
   o image/png
Images will be converted to jpeg on upload. Defaults to `image/jpeg'
 
Returns:
The modified gdata.photos.PhotoEntry
 
Example:
p = GetFeed(PhotoUri)
p = UpdatePhotoBlob(p, '/tmp/newPic.jpg')
 
It is important that you don't keep the old object around, once
it has been updated. See
http://code.google.com/apis/gdata/reference.html#Optimistic-concurrency
UpdatePhotoMetadata(self, photo)
Update a photo's metadata. 
 
Needs authentication, see ClientLogin()
 
You can update any or all of the following metadata properties:
 * <title>
 * <media:description>
 * <gphoto:checksum>
 * <gphoto:client>
 * <gphoto:rotation>
 * <gphoto:timestamp>
 * <gphoto:commentingEnabled>
 
 Arguments:
 photo: a gdata.photos.PhotoEntry object with updated elements
 
 Returns:
 The modified gdata.photos.PhotoEntry
 
 Example:
 p = GetFeed(uri).entry[0]
 p.title.text = u'My new text'
 p.commentingEnabled.text = 'false'
 p = UpdatePhotoMetadata(p)
 
 It is important that you don't keep the old object around, once
 it has been updated. See
 http://code.google.com/apis/gdata/reference.html#Optimistic-concurrency
__init__(self, email=None, password=None, source=None, server='picasaweb.google.com', additional_headers=None)
GooglePhotosService constructor.
  
Arguments:
email: string (optional) The e-mail address of the account to use for
       authentication.
password: string (optional) The password of the account to use for
          authentication.
source: string (optional) The name of the user's application.
server: string (optional) The server the feed is hosted on.
additional_headers: dict (optional) Any additional HTTP headers to be
                    transmitted to the service in the form of key-value
                    pairs.
 
Returns:
PhotosService object used to communicate with the Google Photos
service.

Data and other attributes defined here:
userUri = '/data/feed/api/user/%s'

Methods inherited from gdata.service.GDataService:
ClientLogin(self, username, password, account_type=None, service=None, source=None, captcha_token=None, captcha_response=None)
Convenience method for authenticating using ProgrammaticLogin. 
 
Sets values for email, password, and other optional members.
 
Args:
  username:
  password:
  account_type: string (optional)
  service: string (optional)
  captcha_token: string (optional)
  captcha_response: string (optional)
GenerateAuthSubURL(self, next, scope, secure=False, session=True)
Generate a URL at which the user will login and be redirected back.
 
Users enter their credentials on a Google login page and a token is sent
to the URL specified in next. See documentation for AuthSub login at:
http://code.google.com/apis/accounts/AuthForWebApps.html
 
Args:
  next: string The URL user will be sent to after logging in.
  scope: string The URL of the service to be accessed.
  secure: boolean (optional) Determines whether or not the issued token
          is a secure token.
  session: boolean (optional) Determines whether or not the issued token
           can be upgraded to a session token.
Get(self, uri, extra_headers=None, redirects_remaining=4, encoding='UTF-8', converter=None)
Query the GData API with the given URI
 
The uri is the portion of the URI after the server value 
(ex: www.google.com).
 
To perform a query against Google Base, set the server to 
'base.google.com' and set the uri to '/base/feeds/...', where ... is 
your query. For example, to find snippets for all digital cameras uri 
should be set to: '/base/feeds/snippets?bq=digital+camera'
 
Args:
  uri: string The query in the form of a URI. Example:
       '/base/feeds/snippets?bq=digital+camera'.
  extra_headers: dictionary (optional) Extra HTTP headers to be included
                 in the GET request. These headers are in addition to 
                 those stored in the client's additional_headers property.
                 The client automatically sets the Content-Type and 
                 Authorization headers.
  redirects_remaining: int (optional) Tracks the number of additional
      redirects this method will allow. If the service object receives
      a redirect and remaining is 0, it will not follow the redirect. 
      This was added to avoid infinite redirect loops.
  encoding: string (optional) The character encoding for the server's
      response. Default is UTF-8
  converter: func (optional) A function which will transform
      the server's results before it is returned. Example: use 
      GDataFeedFromString to parse the server response as if it
      were a GDataFeed.
 
Returns:
  If there is no ResultsTransformer specified in the call, a GDataFeed 
  or GDataEntry depending on which is sent from the server. If the 
  response is niether a feed or entry and there is no ResultsTransformer,
  return a string. If there is a ResultsTransformer, the returned value 
  will be that of the ResultsTransformer function.
GetAuthSubToken(self)
GetClientLoginToken(self)
GetMedia(self, uri, extra_headers=None)
Returns a MediaSource containing media and its metadata from the given
URI string.
GetNext(self, feed)
Requests the next 'page' of results in the feed.
 
This method uses the feed's next link to request an additional feed
and uses the class of the feed to convert the results of the GET request.
 
Args:
  feed: atom.Feed or a subclass. The feed should contain a next link and
      the type of the feed will be applied to the results from the 
      server. The new feed which is returned will be of the same class
      as this feed which was passed in.
 
Returns:
  A new feed representing the next set of results in the server's feed.
  The type of this feed will match that of the feed argument.
Post(self, data, uri, extra_headers=None, url_params=None, escape_params=True, redirects_remaining=4, media_source=None, converter=None)
Insert data into a GData service at the given URI.
 
Args:
  data: string, ElementTree._Element, atom.Entry, or gdata.GDataEntry The
        XML to be sent to the uri. 
  uri: string The location (feed) to which the data should be inserted. 
       Example: '/base/feeds/items'. 
  extra_headers: dict (optional) HTTP headers which are to be included. 
                 The client automatically sets the Content-Type,
                 Authorization, and Content-Length headers.
  url_params: dict (optional) Additional URL parameters to be included
              in the URI. These are translated into query arguments
              in the form '&dict_key=value&...'.
              Example: {'max-results': '250'} becomes &max-results=250
  escape_params: boolean (optional) If false, the calling code has already
                 ensured that the query will form a valid URL (all
                 reserved characters have been escaped). If true, this
                 method will escape the query and any URL parameters
                 provided.
  media_source: MediaSource (optional) Container for the media to be sent
      along with the entry, if provided.
  converter: func (optional) A function which will be executed on the 
      server's response. Often this is a function like 
      GDataEntryFromString which will parse the body of the server's 
      response and return a GDataEntry.
 
Returns:
  If the post succeeded, this method will return a GDataFeed, GDataEntry,
  or the results of running converter on the server's result body (if
  converter was specified).
ProgrammaticLogin(self, captcha_token=None, captcha_response=None)
Authenticates the user and sets the GData Auth token.
 
Login retreives a temporary auth token which must be used with all
requests to GData services. The auth token is stored in the GData client
object.
 
Login is also used to respond to a captcha challenge. If the user's login
attempt failed with a CaptchaRequired error, the user can respond by
calling Login with the captcha token and the answer to the challenge.
 
Args:
  captcha_token: string (optional) The identifier for the captcha challenge
                 which was presented to the user.
  captcha_response: string (optional) The user's answer to the captch 
                    challenge.
 
Raises:
  CaptchaRequired if the login service will require a captcha response
  BadAuthentication if the login service rejected the username or password
  Error if the login service responded with a 403 different from the above
Put(self, data, uri, extra_headers=None, url_params=None, escape_params=True, redirects_remaining=3, media_source=None, converter=None)
Updates an entry at the given URI.
 
Args:
  data: string, ElementTree._Element, or xml_wrapper.ElementWrapper The 
        XML containing the updated data.
  uri: string A URI indicating entry to which the update will be applied.
       Example: '/base/feeds/items/ITEM-ID'
  extra_headers: dict (optional) HTTP headers which are to be included.
                 The client automatically sets the Content-Type,
                 Authorization, and Content-Length headers.
  url_params: dict (optional) Additional URL parameters to be included
              in the URI. These are translated into query arguments
              in the form '&dict_key=value&...'.
              Example: {'max-results': '250'} becomes &max-results=250
  escape_params: boolean (optional) If false, the calling code has already
                 ensured that the query will form a valid URL (all
                 reserved characters have been escaped). If true, this
                 method will escape the query and any URL parameters
                 provided.
  converter: func (optional) A function which will be executed on the 
      server's response. Often this is a function like 
      GDataEntryFromString which will parse the body of the server's 
      response and return a GDataEntry.
 
Returns:
  If the put succeeded, this method will return a GDataFeed, GDataEntry,
  or the results of running converter on the server's result body (if
  converter was specified).
RevokeAuthSubToken(self)
Revokes an existing AuthSub token.
 
Raises:
  NonAuthSubToken if the user's auth token is not an AuthSub token
SetAuthSubToken(self, token)
SetClientLoginToken(self, token)
UpgradeToSessionToken(self)
Upgrades a single use AuthSub token to a session token.
 
Raises:
  NonAuthSubToken if the user's auth token is not an AuthSub token

Properties inherited from gdata.service.GDataService:
auth_token
Get or set the token used for authentication.
get = __GetAuthToken(self)
set = __SetAuthSubToken(self, auth_token)
captcha_token
Get the captcha token for a login request.
get = __GetCaptchaToken(self)
captcha_url
Get the captcha URL for a login request.
get = __GetCaptchaURL(self)
source
The source is the name of the application making the request. 
It should be in the form company_id-app_name-app_version
get = __GetSource(self)
# Private methods to create the source property.
set = __SetSource(self, new_source)

Methods inherited from atom.service.AtomService:
UseBasicAuth(self, username, password, for_proxy=False)
Sets an Authenticaiton: Basic HTTP header containing plaintext.
 
The username and password are base64 encoded and added to an HTTP header
which will be included in each request. Note that your username and 
password are sent in plaintext.
 
Args:
  username: str
  password: str

Data and other attributes inherited from atom.service.AtomService:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'AtomService' objects>
list of weak references to the object (if defined)
debug = False
port = 80
ssl = False

 
Functions
       
ConvertAtomTimestampToEpoch(timestamp)
Helper function to convert a timestamp string, for instance
from atom:updated or atom:published, to milliseconds since Unix epoch
(a.k.a. POSIX time).
 
`2007-07-22T00:45:10.000Z' ->
GetSmallestThumbnail(media_thumbnail_list)
Helper function to get the smallest thumbnail of a list of
  gdata.photos.media.Thumbnail.
Returns gdata.photos.media.Thumbnail

 
Data
        GPHOTOS_BAD_REQUEST = 400
GPHOTOS_CONFLICT = 409
GPHOTOS_INTERNAL_SERVER_ERROR = 500
GPHOTOS_INVALID_ARGUMENT = 601
GPHOTOS_INVALID_CONTENT_TYPE = 602
GPHOTOS_INVALID_KIND = 604
GPHOTOS_NOT_AN_IMAGE = 603
SUPPORTED_UPLOAD_TYPES = ('bmp', 'jpeg', 'jpg', 'gif', 'png')
UNKOWN_ERROR = 1000
__author__ = u'havard@gulldahl.no'
__license__ = 'Apache License v2'
__version__ = '176'

 
Author
        havard@gulldahl.no