code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
#!/usr/bin/python
#
# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""YouTubeService extends GDataService to streamline YouTube operations.
YouTubeService: Provides methods to perform CRUD operations on YouTube feeds.
Extends GDataService.
"""
__author__ = ('api.stephaniel@gmail.com (Stephanie Liu), '
'api.jhartmann@gmail.com (Jochen Hartmann)')
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import os
import urllib
import atom
import gdata
import gdata.service
import gdata.youtube
YOUTUBE_SERVER = 'gdata.youtube.com'
YOUTUBE_SERVICE = 'youtube'
YOUTUBE_SUPPORTED_UPLOAD_TYPES = ('mov', 'avi', 'wmv', 'mpg', 'quicktime')
YOUTUBE_QUERY_VALID_TIME_PARAMETERS = ('today', 'this_week', 'this_month',
'all_time')
YOUTUBE_QUERY_VALID_ORDERBY_PARAMETERS = ('published', 'viewCount', 'rating',
'relevance')
YOUTUBE_QUERY_VALID_RACY_PARAMETERS = ('include', 'exclude')
YOUTUBE_QUERY_VALID_FORMAT_PARAMETERS = ('1', '5', '6')
YOUTUBE_STANDARDFEEDS = ('most_recent', 'recently_featured',
'top_rated', 'most_viewed','watch_on_mobile')
YOUTUBE_UPLOAD_URI = 'http://uploads.gdata.youtube.com/feeds/api/users'
YOUTUBE_UPLOAD_TOKEN_URI = 'http://gdata.youtube.com/action/GetUploadToken'
YOUTUBE_VIDEO_URI = 'http://gdata.youtube.com/feeds/api/videos'
YOUTUBE_USER_FEED_URI = 'http://gdata.youtube.com/feeds/api/users'
YOUTUBE_PLAYLIST_FEED_URI = 'http://gdata.youtube.com/feeds/api/playlists'
YOUTUBE_STANDARD_FEEDS = 'http://gdata.youtube.com/feeds/api/standardfeeds'
YOUTUBE_STANDARD_TOP_RATED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'top_rated')
YOUTUBE_STANDARD_MOST_VIEWED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'most_viewed')
YOUTUBE_STANDARD_RECENTLY_FEATURED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'recently_featured')
YOUTUBE_STANDARD_WATCH_ON_MOBILE_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'watch_on_mobile')
YOUTUBE_STANDARD_TOP_FAVORITES_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'top_favorites')
YOUTUBE_STANDARD_MOST_RECENT_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'most_recent')
YOUTUBE_STANDARD_MOST_DISCUSSED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'most_discussed')
YOUTUBE_STANDARD_MOST_LINKED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'most_linked')
YOUTUBE_STANDARD_MOST_RESPONDED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'most_responded')
YOUTUBE_SCHEMA = 'http://gdata.youtube.com/schemas'
YOUTUBE_RATING_LINK_REL = '%s#video.ratings' % YOUTUBE_SCHEMA
YOUTUBE_COMPLAINT_CATEGORY_SCHEME = '%s/%s' % (YOUTUBE_SCHEMA,
'complaint-reasons.cat')
YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME = '%s/%s' % (YOUTUBE_SCHEMA,
'subscriptiontypes.cat')
YOUTUBE_COMPLAINT_CATEGORY_TERMS = ('PORN', 'VIOLENCE', 'HATE', 'DANGEROUS',
'RIGHTS', 'SPAM')
YOUTUBE_CONTACT_STATUS = ('accepted', 'rejected')
YOUTUBE_CONTACT_CATEGORY = ('Friends', 'Family')
UNKOWN_ERROR = 1000
YOUTUBE_BAD_REQUEST = 400
YOUTUBE_CONFLICT = 409
YOUTUBE_INTERNAL_SERVER_ERROR = 500
YOUTUBE_INVALID_ARGUMENT = 601
YOUTUBE_INVALID_CONTENT_TYPE = 602
YOUTUBE_NOT_A_VIDEO = 603
YOUTUBE_INVALID_KIND = 604
class Error(Exception):
"""Base class for errors within the YouTube service."""
pass
class RequestError(Error):
"""Error class that is thrown in response to an invalid HTTP Request."""
pass
class YouTubeError(Error):
"""YouTube service specific error class."""
pass
class YouTubeService(gdata.service.GDataService):
"""Client for the YouTube service.
Performs all documented Google Data YouTube API functions, such as inserting,
updating and deleting videos, comments, playlist, subscriptions etc.
YouTube Service requires authentication for any write, update or delete
actions.
Attributes:
email: An optional string identifying the user. Required only for
authenticated actions.
password: An optional string identifying the user's password.
source: An optional string identifying the name of your application.
server: An optional address of the YouTube API server. gdata.youtube.com
is provided as the default value.
additional_headers: An optional dictionary containing additional headers
to be passed along with each request. Use to store developer key.
client_id: An optional string identifying your application, required for
authenticated requests, along with a developer key.
developer_key: An optional string value. Register your application at
http://code.google.com/apis/youtube/dashboard to obtain a (free) key.
"""
def __init__(self, email=None, password=None, source=None,
server=YOUTUBE_SERVER, additional_headers=None, client_id=None,
developer_key=None):
if client_id is not None and developer_key is not None:
self.additional_headers = {'X-Gdata-Client': self.client_id,
'X-GData-Key': 'key=%s' % self.developer_key}
gdata.service.GDataService.__init__(
self, email=email, password=password, service=YOUTUBE_SERVICE,
source=source, server=server,
additional_headers=self.additional_headers)
elif developer_key and not client_id:
raise YouTubeError('You must also specify the clientId')
else:
gdata.service.GDataService.__init__(
self, email=email, password=password, service=YOUTUBE_SERVICE,
source=source, server=server, additional_headers=additional_headers)
def GetYouTubeVideoFeed(self, uri):
"""Retrieve a YouTubeVideoFeed.
Args:
uri: A string representing the URI of the feed that is to be retrieved.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.Get(uri, converter=gdata.youtube.YouTubeVideoFeedFromString)
def GetYouTubeVideoEntry(self, uri=None, video_id=None):
"""Retrieve a YouTubeVideoEntry.
Either a uri or a video_id must be provided.
Args:
uri: An optional string representing the URI of the entry that is to
be retrieved.
video_id: An optional string representing the ID of the video.
Returns:
A YouTubeVideoFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a video_id to the
GetYouTubeVideoEntry() method.
"""
if uri is None and video_id is None:
raise YouTubeError('You must provide at least a uri or a video_id '
'to the GetYouTubeVideoEntry() method')
elif video_id and not uri:
uri = '%s/%s' % (YOUTUBE_VIDEO_URI, video_id)
return self.Get(uri, converter=gdata.youtube.YouTubeVideoEntryFromString)
def GetYouTubeContactFeed(self, uri=None, username='default'):
"""Retrieve a YouTubeContactFeed.
Either a uri or a username must be provided.
Args:
uri: An optional string representing the URI of the contact feed that
is to be retrieved.
username: An optional string representing the username. Defaults to the
currently authenticated user.
Returns:
A YouTubeContactFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a username to the
GetYouTubeContactFeed() method.
"""
if uri is None:
uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'contacts')
return self.Get(uri, converter=gdata.youtube.YouTubeContactFeedFromString)
def GetYouTubeContactEntry(self, uri):
"""Retrieve a YouTubeContactEntry.
Args:
uri: A string representing the URI of the contact entry that is to
be retrieved.
Returns:
A YouTubeContactEntry if successfully retrieved.
"""
return self.Get(uri, converter=gdata.youtube.YouTubeContactEntryFromString)
def GetYouTubeVideoCommentFeed(self, uri=None, video_id=None):
"""Retrieve a YouTubeVideoCommentFeed.
Either a uri or a video_id must be provided.
Args:
uri: An optional string representing the URI of the comment feed that
is to be retrieved.
video_id: An optional string representing the ID of the video for which
to retrieve the comment feed.
Returns:
A YouTubeVideoCommentFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a video_id to the
GetYouTubeVideoCommentFeed() method.
"""
if uri is None and video_id is None:
raise YouTubeError('You must provide at least a uri or a video_id '
'to the GetYouTubeVideoCommentFeed() method')
elif video_id and not uri:
uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'comments')
return self.Get(
uri, converter=gdata.youtube.YouTubeVideoCommentFeedFromString)
def GetYouTubeVideoCommentEntry(self, uri):
"""Retrieve a YouTubeVideoCommentEntry.
Args:
uri: A string representing the URI of the comment entry that is to
be retrieved.
Returns:
A YouTubeCommentEntry if successfully retrieved.
"""
return self.Get(
uri, converter=gdata.youtube.YouTubeVideoCommentEntryFromString)
def GetYouTubeUserFeed(self, uri=None, username=None):
"""Retrieve a YouTubeUserFeed.
Either a uri or a username must be provided.
Args:
uri: An optional string representing the URI of the user feed that is
to be retrieved.
username: An optional string representing the username.
Returns:
A YouTubeUserFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a username to the
GetYouTubeUserFeed() method.
"""
if uri is None and username is None:
raise YouTubeError('You must provide at least a uri or a username '
'to the GetYouTubeUserFeed() method')
elif username and not uri:
uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'uploads')
return self.Get(uri, converter=gdata.youtube.YouTubeUserFeedFromString)
def GetYouTubeUserEntry(self, uri=None, username=None):
"""Retrieve a YouTubeUserEntry.
Either a uri or a username must be provided.
Args:
uri: An optional string representing the URI of the user entry that is
to be retrieved.
username: An optional string representing the username.
Returns:
A YouTubeUserEntry if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a username to the
GetYouTubeUserEntry() method.
"""
if uri is None and username is None:
raise YouTubeError('You must provide at least a uri or a username '
'to the GetYouTubeUserEntry() method')
elif username and not uri:
uri = '%s/%s' % (YOUTUBE_USER_FEED_URI, username)
return self.Get(uri, converter=gdata.youtube.YouTubeUserEntryFromString)
def GetYouTubePlaylistFeed(self, uri=None, username='default'):
"""Retrieve a YouTubePlaylistFeed (a feed of playlists for a user).
Either a uri or a username must be provided.
Args:
uri: An optional string representing the URI of the playlist feed that
is to be retrieved.
username: An optional string representing the username. Defaults to the
currently authenticated user.
Returns:
A YouTubePlaylistFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a username to the
GetYouTubePlaylistFeed() method.
"""
if uri is None:
uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'playlists')
return self.Get(uri, converter=gdata.youtube.YouTubePlaylistFeedFromString)
def GetYouTubePlaylistEntry(self, uri):
"""Retrieve a YouTubePlaylistEntry.
Args:
uri: A string representing the URI of the playlist feed that is to
be retrieved.
Returns:
A YouTubePlaylistEntry if successfully retrieved.
"""
return self.Get(uri, converter=gdata.youtube.YouTubePlaylistEntryFromString)
def GetYouTubePlaylistVideoFeed(self, uri=None, playlist_id=None):
"""Retrieve a YouTubePlaylistVideoFeed (a feed of videos on a playlist).
Either a uri or a playlist_id must be provided.
Args:
uri: An optional string representing the URI of the playlist video feed
that is to be retrieved.
playlist_id: An optional string representing the Id of the playlist whose
playlist video feed is to be retrieved.
Returns:
A YouTubePlaylistVideoFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a playlist_id to the
GetYouTubePlaylistVideoFeed() method.
"""
if uri is None and playlist_id is None:
raise YouTubeError('You must provide at least a uri or a playlist_id '
'to the GetYouTubePlaylistVideoFeed() method')
elif playlist_id and not uri:
uri = '%s/%s' % (YOUTUBE_PLAYLIST_FEED_URI, playlist_id)
return self.Get(
uri, converter=gdata.youtube.YouTubePlaylistVideoFeedFromString)
def GetYouTubeVideoResponseFeed(self, uri=None, video_id=None):
"""Retrieve a YouTubeVideoResponseFeed.
Either a uri or a playlist_id must be provided.
Args:
uri: An optional string representing the URI of the video response feed
that is to be retrieved.
video_id: An optional string representing the ID of the video whose
response feed is to be retrieved.
Returns:
A YouTubeVideoResponseFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a video_id to the
GetYouTubeVideoResponseFeed() method.
"""
if uri is None and video_id is None:
raise YouTubeError('You must provide at least a uri or a video_id '
'to the GetYouTubeVideoResponseFeed() method')
elif video_id and not uri:
uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'responses')
return self.Get(
uri, converter=gdata.youtube.YouTubeVideoResponseFeedFromString)
def GetYouTubeVideoResponseEntry(self, uri):
"""Retrieve a YouTubeVideoResponseEntry.
Args:
uri: A string representing the URI of the video response entry that
is to be retrieved.
Returns:
A YouTubeVideoResponseEntry if successfully retrieved.
"""
return self.Get(
uri, converter=gdata.youtube.YouTubeVideoResponseEntryFromString)
def GetYouTubeSubscriptionFeed(self, uri=None, username='default'):
"""Retrieve a YouTubeSubscriptionFeed.
Either the uri of the feed or a username must be provided.
Args:
uri: An optional string representing the URI of the feed that is to
be retrieved.
username: An optional string representing the username whose subscription
feed is to be retrieved. Defaults to the currently authenticted user.
Returns:
A YouTubeVideoSubscriptionFeed if successfully retrieved.
"""
if uri is None:
uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'subscriptions')
return self.Get(
uri, converter=gdata.youtube.YouTubeSubscriptionFeedFromString)
def GetYouTubeSubscriptionEntry(self, uri):
"""Retrieve a YouTubeSubscriptionEntry.
Args:
uri: A string representing the URI of the entry that is to be retrieved.
Returns:
A YouTubeVideoSubscriptionEntry if successfully retrieved.
"""
return self.Get(
uri, converter=gdata.youtube.YouTubeSubscriptionEntryFromString)
def GetYouTubeRelatedVideoFeed(self, uri=None, video_id=None):
"""Retrieve a YouTubeRelatedVideoFeed.
Either a uri for the feed or a video_id is required.
Args:
uri: An optional string representing the URI of the feed that is to
be retrieved.
video_id: An optional string representing the ID of the video for which
to retrieve the related video feed.
Returns:
A YouTubeRelatedVideoFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a video_id to the
GetYouTubeRelatedVideoFeed() method.
"""
if uri is None and video_id is None:
raise YouTubeError('You must provide at least a uri or a video_id '
'to the GetYouTubeRelatedVideoFeed() method')
elif video_id and not uri:
uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'related')
return self.Get(
uri, converter=gdata.youtube.YouTubeVideoFeedFromString)
def GetTopRatedVideoFeed(self):
"""Retrieve the 'top_rated' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_TOP_RATED_URI)
def GetMostViewedVideoFeed(self):
"""Retrieve the 'most_viewed' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_VIEWED_URI)
def GetRecentlyFeaturedVideoFeed(self):
"""Retrieve the 'recently_featured' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_RECENTLY_FEATURED_URI)
def GetWatchOnMobileVideoFeed(self):
"""Retrieve the 'watch_on_mobile' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_WATCH_ON_MOBILE_URI)
def GetTopFavoritesVideoFeed(self):
"""Retrieve the 'top_favorites' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_TOP_FAVORITES_URI)
def GetMostRecentVideoFeed(self):
"""Retrieve the 'most_recent' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_RECENT_URI)
def GetMostDiscussedVideoFeed(self):
"""Retrieve the 'most_discussed' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_DISCUSSED_URI)
def GetMostLinkedVideoFeed(self):
"""Retrieve the 'most_linked' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_LINKED_URI)
def GetMostRespondedVideoFeed(self):
"""Retrieve the 'most_responded' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_RESPONDED_URI)
def GetUserFavoritesFeed(self, username='default'):
"""Retrieve the favorites feed for a given user.
Args:
username: An optional string representing the username whose favorites
feed is to be retrieved. Defaults to the currently authenticated user.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
favorites_feed_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username,
'favorites')
return self.GetYouTubeVideoFeed(favorites_feed_uri)
def InsertVideoEntry(self, video_entry, filename_or_handle,
youtube_username='default',
content_type='video/quicktime'):
"""Upload a new video to YouTube using the direct upload mechanism.
Needs authentication.
Args:
video_entry: The YouTubeVideoEntry to upload.
filename_or_handle: A file-like object or file name where the video
will be read from.
youtube_username: An optional string representing the username into whose
account this video is to be uploaded to. Defaults to the currently
authenticated user.
content_type: An optional string representing internet media type
(a.k.a. mime type) of the media object. Currently the YouTube API
supports these types:
o video/mpeg
o video/quicktime
o video/x-msvideo
o video/mp4
Returns:
The newly created YouTubeVideoEntry if successful.
Raises:
AssertionError: video_entry must be a gdata.youtube.VideoEntry instance.
YouTubeError: An error occurred trying to read the video file provided.
gdata.service.RequestError: An error occurred trying to upload the video
to the API server.
"""
# We need to perform a series of checks on the video_entry and on the
# file that we plan to upload, such as checking whether we have a valid
# video_entry and that the file is the correct type and readable, prior
# to performing the actual POST request.
try:
assert(isinstance(video_entry, gdata.youtube.YouTubeVideoEntry))
except AssertionError:
raise YouTubeError({'status':YOUTUBE_INVALID_ARGUMENT,
'body':'`video_entry` must be a gdata.youtube.VideoEntry instance',
'reason':'Found %s, not VideoEntry' % type(video_entry)
})
majtype, mintype = content_type.split('/')
try:
assert(mintype in YOUTUBE_SUPPORTED_UPLOAD_TYPES)
except (ValueError, AssertionError):
raise YouTubeError({'status':YOUTUBE_INVALID_CONTENT_TYPE,
'body':'This is not a valid content type: %s' % content_type,
'reason':'Accepted content types: %s' %
['video/%s' % (t) for t in YOUTUBE_SUPPORTED_UPLOAD_TYPES]})
if (isinstance(filename_or_handle, (str, unicode))
and os.path.exists(filename_or_handle)):
mediasource = gdata.MediaSource()
mediasource.setFile(filename_or_handle, content_type)
elif hasattr(filename_or_handle, 'read'):
if hasattr(filename_or_handle, 'seek'):
filename_or_handle.seek(0)
file_handle = StringIO.StringIO(filename_or_handle.read())
name = 'video'
if hasattr(filename_or_handle, 'name'):
name = filename_or_handle.name
mediasource = gdata.MediaSource(file_handle, content_type,
content_length=file_handle.len, file_name=name)
else:
raise YouTubeError({'status':YOUTUBE_INVALID_ARGUMENT, 'body':
'`filename_or_handle` must be a path name or a file-like object',
'reason': ('Found %s, not path name or object '
'with a .read() method' % type(filename_or_handle))})
upload_uri = '%s/%s/%s' % (YOUTUBE_UPLOAD_URI, youtube_username,
'uploads')
self.additional_headers['Slug'] = mediasource.file_name
# Using a nested try statement to retain Python 2.4 compatibility
try:
try:
return self.Post(video_entry, uri=upload_uri, media_source=mediasource,
converter=gdata.youtube.YouTubeVideoEntryFromString)
except gdata.service.RequestError, e:
raise YouTubeError(e.args[0])
finally:
del(self.additional_headers['Slug'])
def CheckUploadStatus(self, video_entry=None, video_id=None):
"""Check upload status on a recently uploaded video entry.
Needs authentication. Either video_entry or video_id must be provided.
Args:
video_entry: An optional YouTubeVideoEntry whose upload status to check
video_id: An optional string representing the ID of the uploaded video
whose status is to be checked.
Returns:
A tuple containing (video_upload_state, detailed_message) or None if
no status information is found.
Raises:
YouTubeError: You must provide at least a video_entry or a video_id to the
CheckUploadStatus() method.
"""
if video_entry is None and video_id is None:
raise YouTubeError('You must provide at least a uri or a video_id '
'to the CheckUploadStatus() method')
elif video_id and not video_entry:
video_entry = self.GetYouTubeVideoEntry(video_id=video_id)
control = video_entry.control
if control is not None:
draft = control.draft
if draft is not None:
if draft.text == 'yes':
yt_state = control.extension_elements[0]
if yt_state is not None:
state_value = yt_state.attributes['name']
message = ''
if yt_state.text is not None:
message = yt_state.text
return (state_value, message)
def GetFormUploadToken(self, video_entry, uri=YOUTUBE_UPLOAD_TOKEN_URI):
"""Receives a YouTube Token and a YouTube PostUrl from a YouTubeVideoEntry.
Needs authentication.
Args:
video_entry: The YouTubeVideoEntry to upload (meta-data only).
uri: An optional string representing the URI from where to fetch the
token information. Defaults to the YOUTUBE_UPLOADTOKEN_URI.
Returns:
A tuple containing the URL to which to post your video file, along
with the youtube token that must be included with your upload in the
form of: (post_url, youtube_token).
"""
try:
response = self.Post(video_entry, uri)
except gdata.service.RequestError, e:
raise YouTubeError(e.args[0])
tree = ElementTree.fromstring(response)
for child in tree:
if child.tag == 'url':
post_url = child.text
elif child.tag == 'token':
youtube_token = child.text
return (post_url, youtube_token)
def UpdateVideoEntry(self, video_entry):
"""Updates a video entry's meta-data.
Needs authentication.
Args:
video_entry: The YouTubeVideoEntry to update, containing updated
meta-data.
Returns:
An updated YouTubeVideoEntry on success or None.
"""
for link in video_entry.link:
if link.rel == 'edit':
edit_uri = link.href
return self.Put(video_entry, uri=edit_uri,
converter=gdata.youtube.YouTubeVideoEntryFromString)
def DeleteVideoEntry(self, video_entry):
"""Deletes a video entry.
Needs authentication.
Args:
video_entry: The YouTubeVideoEntry to be deleted.
Returns:
True if entry was deleted successfully.
"""
for link in video_entry.link:
if link.rel == 'edit':
edit_uri = link.href
return self.Delete(edit_uri)
def AddRating(self, rating_value, video_entry):
"""Add a rating to a video entry.
Needs authentication.
Args:
rating_value: The integer value for the rating (between 1 and 5).
video_entry: The YouTubeVideoEntry to be rated.
Returns:
True if the rating was added successfully.
Raises:
YouTubeError: rating_value must be between 1 and 5 in AddRating().
"""
if rating_value < 1 or rating_value > 5:
raise YouTubeError('rating_value must be between 1 and 5 in AddRating()')
entry = gdata.GDataEntry()
rating = gdata.youtube.Rating(min='1', max='5')
rating.extension_attributes['name'] = 'value'
rating.extension_attributes['value'] = str(rating_value)
entry.extension_elements.append(rating)
for link in video_entry.link:
if link.rel == YOUTUBE_RATING_LINK_REL:
rating_uri = link.href
return self.Post(entry, uri=rating_uri)
def AddComment(self, comment_text, video_entry):
"""Add a comment to a video entry.
Needs authentication. Note that each comment that is posted must contain
the video entry that it is to be posted to.
Args:
comment_text: A string representing the text of the comment.
video_entry: The YouTubeVideoEntry to be commented on.
Returns:
True if the comment was added successfully.
"""
content = atom.Content(text=comment_text)
comment_entry = gdata.youtube.YouTubeVideoCommentEntry(content=content)
comment_post_uri = video_entry.comments.feed_link[0].href
return self.Post(comment_entry, uri=comment_post_uri)
def AddVideoResponse(self, video_id_to_respond_to, video_response):
"""Add a video response.
Needs authentication.
Args:
video_id_to_respond_to: A string representing the ID of the video to be
responded to.
video_response: YouTubeVideoEntry to be posted as a response.
Returns:
True if video response was posted successfully.
"""
post_uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id_to_respond_to,
'responses')
return self.Post(video_response, uri=post_uri)
def DeleteVideoResponse(self, video_id, response_video_id):
"""Delete a video response.
Needs authentication.
Args:
video_id: A string representing the ID of video that contains the
response.
response_video_id: A string representing the ID of the video that was
posted as a response.
Returns:
True if video response was deleted succcessfully.
"""
delete_uri = '%s/%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'responses',
response_video_id)
return self.Delete(delete_uri)
def AddComplaint(self, complaint_text, complaint_term, video_id):
"""Add a complaint for a particular video entry.
Needs authentication.
Args:
complaint_text: A string representing the complaint text.
complaint_term: A string representing the complaint category term.
video_id: A string representing the ID of YouTubeVideoEntry to
complain about.
Returns:
True if posted successfully.
Raises:
YouTubeError: Your complaint_term is not valid.
"""
if complaint_term not in YOUTUBE_COMPLAINT_CATEGORY_TERMS:
raise YouTubeError('Your complaint_term is not valid')
content = atom.Content(text=complaint_text)
category = atom.Category(term=complaint_term,
scheme=YOUTUBE_COMPLAINT_CATEGORY_SCHEME)
complaint_entry = gdata.GDataEntry(content=content, category=[category])
post_uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'complaints')
return self.Post(complaint_entry, post_uri)
def AddVideoEntryToFavorites(self, video_entry, username='default'):
"""Add a video entry to a users favorite feed.
Needs authentication.
Args:
video_entry: The YouTubeVideoEntry to add.
username: An optional string representing the username to whose favorite
feed you wish to add the entry. Defaults to the currently
authenticated user.
Returns:
The posted YouTubeVideoEntry if successfully posted.
"""
post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'favorites')
return self.Post(video_entry, post_uri,
converter=gdata.youtube.YouTubeVideoEntryFromString)
def DeleteVideoEntryFromFavorites(self, video_id, username='default'):
"""Delete a video entry from the users favorite feed.
Needs authentication.
Args:
video_id: A string representing the ID of the video that is to be removed
username: An optional string representing the username of the user's
favorite feed. Defaults to the currently authenticated user.
Returns:
True if entry was successfully deleted.
"""
edit_link = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'favorites',
video_id)
return self.Delete(edit_link)
def AddPlaylist(self, playlist_title, playlist_description,
playlist_private=None):
"""Add a new playlist to the currently authenticated users account.
Needs authentication.
Args:
playlist_title: A string representing the title for the new playlist.
playlist_description: A string representing the description of the
playlist.
playlist_private: An optional boolean, set to True if the playlist is
to be private.
Returns:
The YouTubePlaylistEntry if successfully posted.
"""
playlist_entry = gdata.youtube.YouTubePlaylistEntry(
title=atom.Title(text=playlist_title),
description=gdata.youtube.Description(text=playlist_description))
if playlist_private:
playlist_entry.private = gdata.youtube.Private()
playlist_post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, 'default',
'playlists')
return self.Post(playlist_entry, playlist_post_uri,
converter=gdata.youtube.YouTubePlaylistEntryFromString)
def UpdatePlaylist(self, playlist_id, new_playlist_title,
new_playlist_description, playlist_private=None,
username='default'):
"""Update a playlist with new meta-data.
Needs authentication.
Args:
playlist_id: A string representing the ID of the playlist to be updated.
new_playlist_title: A string representing a new title for the playlist.
new_playlist_description: A string representing a new description for the
playlist.
playlist_private: An optional boolean, set to True if the playlist is
to be private.
username: An optional string representing the username whose playlist is
to be updated. Defaults to the currently authenticated user.
Returns:
A YouTubePlaylistEntry if the update was successful.
"""
updated_playlist = gdata.youtube.YouTubePlaylistEntry(
title=atom.Title(text=new_playlist_title),
description=gdata.youtube.Description(text=new_playlist_description))
if playlist_private:
updated_playlist.private = gdata.youtube.Private()
playlist_put_uri = '%s/%s/playlists/%s' % (YOUTUBE_USER_FEED_URI, username,
playlist_id)
return self.Put(updated_playlist, playlist_put_uri,
converter=gdata.youtube.YouTubePlaylistEntryFromString)
def DeletePlaylist(self, playlist_uri):
"""Delete a playlist from the currently authenticated users playlists.
Needs authentication.
Args:
playlist_uri: A string representing the URI of the playlist that is
to be deleted.
Returns:
True if successfully deleted.
"""
return self.Delete(playlist_uri)
def AddPlaylistVideoEntryToPlaylist(
self, playlist_uri, video_id, custom_video_title=None,
custom_video_description=None):
"""Add a video entry to a playlist, optionally providing a custom title
and description.
Needs authentication.
Args:
playlist_uri: A string representing the URI of the playlist to which this
video entry is to be added.
video_id: A string representing the ID of the video entry to add.
custom_video_title: An optional string representing a custom title for
the video (only shown on the playlist).
custom_video_description: An optional string representing a custom
description for the video (only shown on the playlist).
Returns:
A YouTubePlaylistVideoEntry if successfully posted.
"""
playlist_video_entry = gdata.youtube.YouTubePlaylistVideoEntry(
atom_id=atom.Id(text=video_id))
if custom_video_title:
playlist_video_entry.title = atom.Title(text=custom_video_title)
if custom_video_description:
playlist_video_entry.description = gdata.youtube.Description(
text=custom_video_description)
return self.Post(playlist_video_entry, playlist_uri,
converter=gdata.youtube.YouTubePlaylistVideoEntryFromString)
def UpdatePlaylistVideoEntryMetaData(
self, playlist_uri, playlist_entry_id, new_video_title,
new_video_description, new_video_position):
"""Update the meta data for a YouTubePlaylistVideoEntry.
Needs authentication.
Args:
playlist_uri: A string representing the URI of the playlist that contains
the entry to be updated.
playlist_entry_id: A string representing the ID of the entry to be
updated.
new_video_title: A string representing the new title for the video entry.
new_video_description: A string representing the new description for
the video entry.
new_video_position: An integer representing the new position on the
playlist for the video.
Returns:
A YouTubePlaylistVideoEntry if the update was successful.
"""
playlist_video_entry = gdata.youtube.YouTubePlaylistVideoEntry(
title=atom.Title(text=new_video_title),
description=gdata.youtube.Description(text=new_video_description),
position=gdata.youtube.Position(text=str(new_video_position)))
playlist_put_uri = playlist_uri + '/' + playlist_entry_id
return self.Put(playlist_video_entry, playlist_put_uri,
converter=gdata.youtube.YouTubePlaylistVideoEntryFromString)
def DeletePlaylistVideoEntry(self, playlist_uri, playlist_video_entry_id):
"""Delete a playlist video entry from a playlist.
Needs authentication.
Args:
playlist_uri: A URI representing the playlist from which the playlist
video entry is to be removed from.
playlist_video_entry_id: A string representing id of the playlist video
entry that is to be removed.
Returns:
True if entry was successfully deleted.
"""
delete_uri = '%s/%s' % (playlist_uri, playlist_video_entry_id)
return self.Delete(delete_uri)
def AddSubscriptionToChannel(self, username_to_subscribe_to,
my_username = 'default'):
"""Add a new channel subscription to the currently authenticated users
account.
Needs authentication.
Args:
username_to_subscribe_to: A string representing the username of the
channel to which we want to subscribe to.
my_username: An optional string representing the name of the user which
we want to subscribe. Defaults to currently authenticated user.
Returns:
A new YouTubeSubscriptionEntry if successfully posted.
"""
subscription_category = atom.Category(
scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME,
term='channel')
subscription_username = gdata.youtube.Username(
text=username_to_subscribe_to)
subscription_entry = gdata.youtube.YouTubeSubscriptionEntry(
category=subscription_category,
username=subscription_username)
post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'subscriptions')
return self.Post(subscription_entry, post_uri,
converter=gdata.youtube.YouTubeSubscriptionEntryFromString)
def AddSubscriptionToFavorites(self, username, my_username = 'default'):
"""Add a new subscription to a users favorites to the currently
authenticated user's account.
Needs authentication
Args:
username: A string representing the username of the user's favorite feed
to subscribe to.
my_username: An optional string representing the username of the user
that is to be subscribed. Defaults to currently authenticated user.
Returns:
A new YouTubeSubscriptionEntry if successful.
"""
subscription_category = atom.Category(
scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME,
term='favorites')
subscription_username = gdata.youtube.Username(text=username)
subscription_entry = gdata.youtube.YouTubeSubscriptionEntry(
category=subscription_category,
username=subscription_username)
post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'subscriptions')
return self.Post(subscription_entry, post_uri,
converter=gdata.youtube.YouTubeSubscriptionEntryFromString)
def AddSubscriptionToQuery(self, query, my_username = 'default'):
"""Add a new subscription to a specific keyword query to the currently
authenticated user's account.
Needs authentication
Args:
query: A string representing the keyword query to subscribe to.
my_username: An optional string representing the username of the user
that is to be subscribed. Defaults to currently authenticated user.
Returns:
A new YouTubeSubscriptionEntry if successful.
"""
subscription_category = atom.Category(
scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME,
term='query')
subscription_query_string = gdata.youtube.QueryString(text=query)
subscription_entry = gdata.youtube.YouTubeSubscriptionEntry(
category=subscription_category,
query_string=subscription_query_string)
post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'subscriptions')
return self.Post(subscription_entry, post_uri,
converter=gdata.youtube.YouTubeSubscriptionEntryFromString)
def DeleteSubscription(self, subscription_uri):
"""Delete a subscription from the currently authenticated user's account.
Needs authentication.
Args:
subscription_uri: A string representing the URI of the subscription that
is to be deleted.
Returns:
True if deleted successfully.
"""
return self.Delete(subscription_uri)
def AddContact(self, contact_username, my_username='default'):
"""Add a new contact to the currently authenticated user's contact feed.
Needs authentication.
Args:
contact_username: A string representing the username of the contact
that you wish to add.
my_username: An optional string representing the username to whose
contact the new contact is to be added.
Returns:
A YouTubeContactEntry if added successfully.
"""
contact_category = atom.Category(
scheme = 'http://gdata.youtube.com/schemas/2007/contact.cat',
term = 'Friends')
contact_username = gdata.youtube.Username(text=contact_username)
contact_entry = gdata.youtube.YouTubeContactEntry(
category=contact_category,
username=contact_username)
contact_post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'contacts')
return self.Post(contact_entry, contact_post_uri,
converter=gdata.youtube.YouTubeContactEntryFromString)
def UpdateContact(self, contact_username, new_contact_status,
new_contact_category, my_username='default'):
"""Update a contact, providing a new status and a new category.
Needs authentication.
Args:
contact_username: A string representing the username of the contact
that is to be updated.
new_contact_status: A string representing the new status of the contact.
This can either be set to 'accepted' or 'rejected'.
new_contact_category: A string representing the new category for the
contact, either 'Friends' or 'Family'.
my_username: An optional string representing the username of the user
whose contact feed we are modifying. Defaults to the currently
authenticated user.
Returns:
A YouTubeContactEntry if updated succesfully.
Raises:
YouTubeError: New contact status must be within the accepted values. Or
new contact category must be within the accepted categories.
"""
if new_contact_status not in YOUTUBE_CONTACT_STATUS:
raise YouTubeError('New contact status must be one of %s' %
(' '.join(YOUTUBE_CONTACT_STATUS)))
if new_contact_category not in YOUTUBE_CONTACT_CATEGORY:
raise YouTubeError('New contact category must be one of %s' %
(' '.join(YOUTUBE_CONTACT_CATEGORY)))
contact_category = atom.Category(
scheme='http://gdata.youtube.com/schemas/2007/contact.cat',
term=new_contact_category)
contact_status = gdata.youtube.Status(text=new_contact_status)
contact_entry = gdata.youtube.YouTubeContactEntry(
category=contact_category,
status=contact_status)
contact_put_uri = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'contacts', contact_username)
return self.Put(contact_entry, contact_put_uri,
converter=gdata.youtube.YouTubeContactEntryFromString)
def DeleteContact(self, contact_username, my_username='default'):
"""Delete a contact from a users contact feed.
Needs authentication.
Args:
contact_username: A string representing the username of the contact
that is to be deleted.
my_username: An optional string representing the username of the user's
contact feed from which to delete the contact. Defaults to the
currently authenticated user.
Returns:
True if the contact was deleted successfully
"""
contact_edit_uri = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'contacts', contact_username)
return self.Delete(contact_edit_uri)
def _GetDeveloperKey(self):
"""Getter for Developer Key property.
Returns:
If the developer key has been set, a string representing the developer key
is returned or None.
"""
if 'X-GData-Key' in self.additional_headers:
return self.additional_headers['X-GData-Key'][4:]
else:
return None
def _SetDeveloperKey(self, developer_key):
"""Setter for Developer Key property.
Sets the developer key in the 'X-GData-Key' header. The actual value that
is set is 'key=' plus the developer_key that was passed.
"""
self.additional_headers['X-GData-Key'] = 'key=' + developer_key
developer_key = property(_GetDeveloperKey, _SetDeveloperKey,
doc="""The Developer Key property""")
def _GetClientId(self):
"""Getter for Client Id property.
Returns:
If the client_id has been set, a string representing it is returned
or None.
"""
if 'X-Gdata-Client' in self.additional_headers:
return self.additional_headers['X-Gdata-Client']
else:
return None
def _SetClientId(self, client_id):
"""Setter for Client Id property.
Sets the 'X-Gdata-Client' header.
"""
self.additional_headers['X-Gdata-Client'] = client_id
client_id = property(_GetClientId, _SetClientId,
doc="""The ClientId property""")
def Query(self, uri):
"""Performs a query and returns a resulting feed or entry.
Args:
uri: A string representing the URI of the feed that is to be queried.
Returns:
On success, a tuple in the form:
(boolean succeeded=True, ElementTree._Element result)
On failure, a tuple in the form:
(boolean succeeded=False, {'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response})
"""
result = self.Get(uri)
return result
def YouTubeQuery(self, query):
"""Performs a YouTube specific query and returns a resulting feed or entry.
Args:
query: A Query object or one if its sub-classes (YouTubeVideoQuery,
YouTubeUserQuery or YouTubePlaylistQuery).
Returns:
Depending on the type of Query object submitted returns either a
YouTubeVideoFeed, a YouTubeUserFeed, a YouTubePlaylistFeed. If the
Query object provided was not YouTube-related, a tuple is returned.
On success the tuple will be in this form:
(boolean succeeded=True, ElementTree._Element result)
On failure, the tuple will be in this form:
(boolean succeeded=False, {'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server response})
"""
result = self.Query(query.ToUri())
if isinstance(query, YouTubeVideoQuery):
return gdata.youtube.YouTubeVideoFeedFromString(result.ToString())
elif isinstance(query, YouTubeUserQuery):
return gdata.youtube.YouTubeUserFeedFromString(result.ToString())
elif isinstance(query, YouTubePlaylistQuery):
return gdata.youtube.YouTubePlaylistFeedFromString(result.ToString())
else:
return result
class YouTubeVideoQuery(gdata.service.Query):
"""Subclasses gdata.service.Query to represent a YouTube Data API query.
Attributes are set dynamically via properties. Properties correspond to
the standard Google Data API query parameters with YouTube Data API
extensions. Please refer to the API documentation for details.
Attributes:
vq: The vq parameter, which is only supported for video feeds, specifies a
search query term. Refer to API documentation for further details.
orderby: The orderby parameter, which is only supported for video feeds,
specifies the value that will be used to sort videos in the search
result set. Valid values for this parameter are relevance, published,
viewCount and rating.
time: The time parameter, which is only available for the top_rated,
top_favorites, most_viewed, most_discussed, most_linked and
most_responded standard feeds, restricts the search to videos uploaded
within the specified time. Valid values for this parameter are today
(1 day), this_week (7 days), this_month (1 month) and all_time.
The default value for this parameter is all_time.
format: The format parameter specifies that videos must be available in a
particular video format. Refer to the API documentation for details.
racy: The racy parameter allows a search result set to include restricted
content as well as standard content. Valid values for this parameter
are include and exclude. By default, restricted content is excluded.
lr: The lr parameter restricts the search to videos that have a title,
description or keywords in a specific language. Valid values for the lr
parameter are ISO 639-1 two-letter language codes.
restriction: The restriction parameter identifies the IP address that
should be used to filter videos that can only be played in specific
countries.
"""
def __init__(self, video_id=None, feed_type=None, text_query=None,
params=None, categories=None):
if feed_type in YOUTUBE_STANDARDFEEDS:
feed = 'http://%s/feeds/standardfeeds/%s' % (YOUTUBE_SERVER, feed_type)
elif feed_type is 'responses' or feed_type is 'comments' and video_id:
feed = 'http://%s/feeds/videos/%s/%s' % (YOUTUBE_SERVER, video_id,
feed_type)
else:
feed = 'http://%s/feeds/videos' % (YOUTUBE_SERVER)
gdata.service.Query.__init__(self, feed, text_query=text_query,
params=params, categories=categories)
def _GetVideoQuery(self):
if 'vq' in self:
return self['vq']
else:
return None
def _SetVideoQuery(self, val):
self['vq'] = val
vq = property(_GetVideoQuery, _SetVideoQuery,
doc="""The video query (vq) query parameter""")
def _GetOrderBy(self):
if 'orderby' in self:
return self['orderby']
else:
return None
def _SetOrderBy(self, val):
if val not in YOUTUBE_QUERY_VALID_ORDERBY_PARAMETERS:
raise YouTubeError('OrderBy must be one of: %s ' %
' '.join(YOUTUBE_QUERY_VALID_ORDERBY_PARAMETERS))
self['orderby'] = val
orderby = property(_GetOrderBy, _SetOrderBy,
doc="""The orderby query parameter""")
def _GetTime(self):
if 'time' in self:
return self['time']
else:
return None
def _SetTime(self, val):
if val not in YOUTUBE_QUERY_VALID_TIME_PARAMETERS:
raise YouTubeError('Time must be one of: %s ' %
' '.join(YOUTUBE_QUERY_VALID_TIME_PARAMETERS))
self['time'] = val
time = property(_GetTime, _SetTime,
doc="""The time query parameter""")
def _GetFormat(self):
if 'format' in self:
return self['format']
else:
return None
def _SetFormat(self, val):
if val not in YOUTUBE_QUERY_VALID_FORMAT_PARAMETERS:
raise YouTubeError('Format must be one of: %s ' %
' '.join(YOUTUBE_QUERY_VALID_FORMAT_PARAMETERS))
self['format'] = val
format = property(_GetFormat, _SetFormat,
doc="""The format query parameter""")
def _GetRacy(self):
if 'racy' in self:
return self['racy']
else:
return None
def _SetRacy(self, val):
if val not in YOUTUBE_QUERY_VALID_RACY_PARAMETERS:
raise YouTubeError('Racy must be one of: %s ' %
' '.join(YOUTUBE_QUERY_VALID_RACY_PARAMETERS))
self['racy'] = val
racy = property(_GetRacy, _SetRacy,
doc="""The racy query parameter""")
def _GetLanguageRestriction(self):
if 'lr' in self:
return self['lr']
else:
return None
def _SetLanguageRestriction(self, val):
self['lr'] = val
lr = property(_GetLanguageRestriction, _SetLanguageRestriction,
doc="""The lr (language restriction) query parameter""")
def _GetIPRestriction(self):
if 'restriction' in self:
return self['restriction']
else:
return None
def _SetIPRestriction(self, val):
self['restriction'] = val
restriction = property(_GetIPRestriction, _SetIPRestriction,
doc="""The restriction query parameter""")
class YouTubeUserQuery(YouTubeVideoQuery):
"""Subclasses YouTubeVideoQuery to perform user-specific queries.
Attributes are set dynamically via properties. Properties correspond to
the standard Google Data API query parameters with YouTube Data API
extensions.
"""
def __init__(self, username=None, feed_type=None, subscription_id=None,
text_query=None, params=None, categories=None):
uploads_favorites_playlists = ('uploads', 'favorites', 'playlists')
if feed_type is 'subscriptions' and subscription_id and username:
feed = "http://%s/feeds/users/%s/%s/%s" % (YOUTUBE_SERVER, username,
feed_type, subscription_id)
elif feed_type is 'subscriptions' and not subscription_id and username:
feed = "http://%s/feeds/users/%s/%s" % (YOUTUBE_SERVER, username,
feed_type)
elif feed_type in uploads_favorites_playlists:
feed = "http://%s/feeds/users/%s/%s" % (YOUTUBE_SERVER, username,
feed_type)
else:
feed = "http://%s/feeds/users" % (YOUTUBE_SERVER)
YouTubeVideoQuery.__init__(self, feed, text_query=text_query,
params=params, categories=categories)
class YouTubePlaylistQuery(YouTubeVideoQuery):
"""Subclasses YouTubeVideoQuery to perform playlist-specific queries.
Attributes are set dynamically via properties. Properties correspond to
the standard Google Data API query parameters with YouTube Data API
extensions.
"""
def __init__(self, playlist_id, text_query=None, params=None,
categories=None):
if playlist_id:
feed = "http://%s/feeds/playlists/%s" % (YOUTUBE_SERVER, playlist_id)
else:
feed = "http://%s/feeds/playlists" % (YOUTUBE_SERVER)
YouTubeVideoQuery.__init__(self, feed, text_query=text_query,
params=params, categories=categories)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""YouTubeService extends GDataService to streamline YouTube operations.
YouTubeService: Provides methods to perform CRUD operations on YouTube feeds.
Extends GDataService.
"""
__author__ = ('api.stephaniel@gmail.com (Stephanie Liu), '
'api.jhartmann@gmail.com (Jochen Hartmann)')
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import os
import urllib
import atom
import gdata
import gdata.service
import gdata.youtube
YOUTUBE_SERVER = 'gdata.youtube.com'
YOUTUBE_SERVICE = 'youtube'
YOUTUBE_SUPPORTED_UPLOAD_TYPES = ('mov', 'avi', 'wmv', 'mpg', 'quicktime')
YOUTUBE_QUERY_VALID_TIME_PARAMETERS = ('today', 'this_week', 'this_month',
'all_time')
YOUTUBE_QUERY_VALID_ORDERBY_PARAMETERS = ('published', 'viewCount', 'rating',
'relevance')
YOUTUBE_QUERY_VALID_RACY_PARAMETERS = ('include', 'exclude')
YOUTUBE_QUERY_VALID_FORMAT_PARAMETERS = ('1', '5', '6')
YOUTUBE_STANDARDFEEDS = ('most_recent', 'recently_featured',
'top_rated', 'most_viewed','watch_on_mobile')
YOUTUBE_UPLOAD_URI = 'http://uploads.gdata.youtube.com/feeds/api/users'
YOUTUBE_UPLOAD_TOKEN_URI = 'http://gdata.youtube.com/action/GetUploadToken'
YOUTUBE_VIDEO_URI = 'http://gdata.youtube.com/feeds/api/videos'
YOUTUBE_USER_FEED_URI = 'http://gdata.youtube.com/feeds/api/users'
YOUTUBE_PLAYLIST_FEED_URI = 'http://gdata.youtube.com/feeds/api/playlists'
YOUTUBE_STANDARD_FEEDS = 'http://gdata.youtube.com/feeds/api/standardfeeds'
YOUTUBE_STANDARD_TOP_RATED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'top_rated')
YOUTUBE_STANDARD_MOST_VIEWED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'most_viewed')
YOUTUBE_STANDARD_RECENTLY_FEATURED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'recently_featured')
YOUTUBE_STANDARD_WATCH_ON_MOBILE_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'watch_on_mobile')
YOUTUBE_STANDARD_TOP_FAVORITES_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'top_favorites')
YOUTUBE_STANDARD_MOST_RECENT_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'most_recent')
YOUTUBE_STANDARD_MOST_DISCUSSED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'most_discussed')
YOUTUBE_STANDARD_MOST_LINKED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'most_linked')
YOUTUBE_STANDARD_MOST_RESPONDED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'most_responded')
YOUTUBE_SCHEMA = 'http://gdata.youtube.com/schemas'
YOUTUBE_RATING_LINK_REL = '%s#video.ratings' % YOUTUBE_SCHEMA
YOUTUBE_COMPLAINT_CATEGORY_SCHEME = '%s/%s' % (YOUTUBE_SCHEMA,
'complaint-reasons.cat')
YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME = '%s/%s' % (YOUTUBE_SCHEMA,
'subscriptiontypes.cat')
YOUTUBE_COMPLAINT_CATEGORY_TERMS = ('PORN', 'VIOLENCE', 'HATE', 'DANGEROUS',
'RIGHTS', 'SPAM')
YOUTUBE_CONTACT_STATUS = ('accepted', 'rejected')
YOUTUBE_CONTACT_CATEGORY = ('Friends', 'Family')
UNKOWN_ERROR = 1000
YOUTUBE_BAD_REQUEST = 400
YOUTUBE_CONFLICT = 409
YOUTUBE_INTERNAL_SERVER_ERROR = 500
YOUTUBE_INVALID_ARGUMENT = 601
YOUTUBE_INVALID_CONTENT_TYPE = 602
YOUTUBE_NOT_A_VIDEO = 603
YOUTUBE_INVALID_KIND = 604
class Error(Exception):
"""Base class for errors within the YouTube service."""
pass
class RequestError(Error):
"""Error class that is thrown in response to an invalid HTTP Request."""
pass
class YouTubeError(Error):
"""YouTube service specific error class."""
pass
class YouTubeService(gdata.service.GDataService):
"""Client for the YouTube service.
Performs all documented Google Data YouTube API functions, such as inserting,
updating and deleting videos, comments, playlist, subscriptions etc.
YouTube Service requires authentication for any write, update or delete
actions.
Attributes:
email: An optional string identifying the user. Required only for
authenticated actions.
password: An optional string identifying the user's password.
source: An optional string identifying the name of your application.
server: An optional address of the YouTube API server. gdata.youtube.com
is provided as the default value.
additional_headers: An optional dictionary containing additional headers
to be passed along with each request. Use to store developer key.
client_id: An optional string identifying your application, required for
authenticated requests, along with a developer key.
developer_key: An optional string value. Register your application at
http://code.google.com/apis/youtube/dashboard to obtain a (free) key.
"""
def __init__(self, email=None, password=None, source=None,
server=YOUTUBE_SERVER, additional_headers=None, client_id=None,
developer_key=None):
if client_id is not None and developer_key is not None:
self.additional_headers = {'X-Gdata-Client': self.client_id,
'X-GData-Key': 'key=%s' % self.developer_key}
gdata.service.GDataService.__init__(
self, email=email, password=password, service=YOUTUBE_SERVICE,
source=source, server=server,
additional_headers=self.additional_headers)
elif developer_key and not client_id:
raise YouTubeError('You must also specify the clientId')
else:
gdata.service.GDataService.__init__(
self, email=email, password=password, service=YOUTUBE_SERVICE,
source=source, server=server, additional_headers=additional_headers)
def GetYouTubeVideoFeed(self, uri):
"""Retrieve a YouTubeVideoFeed.
Args:
uri: A string representing the URI of the feed that is to be retrieved.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.Get(uri, converter=gdata.youtube.YouTubeVideoFeedFromString)
def GetYouTubeVideoEntry(self, uri=None, video_id=None):
"""Retrieve a YouTubeVideoEntry.
Either a uri or a video_id must be provided.
Args:
uri: An optional string representing the URI of the entry that is to
be retrieved.
video_id: An optional string representing the ID of the video.
Returns:
A YouTubeVideoFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a video_id to the
GetYouTubeVideoEntry() method.
"""
if uri is None and video_id is None:
raise YouTubeError('You must provide at least a uri or a video_id '
'to the GetYouTubeVideoEntry() method')
elif video_id and not uri:
uri = '%s/%s' % (YOUTUBE_VIDEO_URI, video_id)
return self.Get(uri, converter=gdata.youtube.YouTubeVideoEntryFromString)
def GetYouTubeContactFeed(self, uri=None, username='default'):
"""Retrieve a YouTubeContactFeed.
Either a uri or a username must be provided.
Args:
uri: An optional string representing the URI of the contact feed that
is to be retrieved.
username: An optional string representing the username. Defaults to the
currently authenticated user.
Returns:
A YouTubeContactFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a username to the
GetYouTubeContactFeed() method.
"""
if uri is None:
uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'contacts')
return self.Get(uri, converter=gdata.youtube.YouTubeContactFeedFromString)
def GetYouTubeContactEntry(self, uri):
"""Retrieve a YouTubeContactEntry.
Args:
uri: A string representing the URI of the contact entry that is to
be retrieved.
Returns:
A YouTubeContactEntry if successfully retrieved.
"""
return self.Get(uri, converter=gdata.youtube.YouTubeContactEntryFromString)
def GetYouTubeVideoCommentFeed(self, uri=None, video_id=None):
"""Retrieve a YouTubeVideoCommentFeed.
Either a uri or a video_id must be provided.
Args:
uri: An optional string representing the URI of the comment feed that
is to be retrieved.
video_id: An optional string representing the ID of the video for which
to retrieve the comment feed.
Returns:
A YouTubeVideoCommentFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a video_id to the
GetYouTubeVideoCommentFeed() method.
"""
if uri is None and video_id is None:
raise YouTubeError('You must provide at least a uri or a video_id '
'to the GetYouTubeVideoCommentFeed() method')
elif video_id and not uri:
uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'comments')
return self.Get(
uri, converter=gdata.youtube.YouTubeVideoCommentFeedFromString)
def GetYouTubeVideoCommentEntry(self, uri):
"""Retrieve a YouTubeVideoCommentEntry.
Args:
uri: A string representing the URI of the comment entry that is to
be retrieved.
Returns:
A YouTubeCommentEntry if successfully retrieved.
"""
return self.Get(
uri, converter=gdata.youtube.YouTubeVideoCommentEntryFromString)
def GetYouTubeUserFeed(self, uri=None, username=None):
"""Retrieve a YouTubeUserFeed.
Either a uri or a username must be provided.
Args:
uri: An optional string representing the URI of the user feed that is
to be retrieved.
username: An optional string representing the username.
Returns:
A YouTubeUserFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a username to the
GetYouTubeUserFeed() method.
"""
if uri is None and username is None:
raise YouTubeError('You must provide at least a uri or a username '
'to the GetYouTubeUserFeed() method')
elif username and not uri:
uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'uploads')
return self.Get(uri, converter=gdata.youtube.YouTubeUserFeedFromString)
def GetYouTubeUserEntry(self, uri=None, username=None):
"""Retrieve a YouTubeUserEntry.
Either a uri or a username must be provided.
Args:
uri: An optional string representing the URI of the user entry that is
to be retrieved.
username: An optional string representing the username.
Returns:
A YouTubeUserEntry if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a username to the
GetYouTubeUserEntry() method.
"""
if uri is None and username is None:
raise YouTubeError('You must provide at least a uri or a username '
'to the GetYouTubeUserEntry() method')
elif username and not uri:
uri = '%s/%s' % (YOUTUBE_USER_FEED_URI, username)
return self.Get(uri, converter=gdata.youtube.YouTubeUserEntryFromString)
def GetYouTubePlaylistFeed(self, uri=None, username='default'):
"""Retrieve a YouTubePlaylistFeed (a feed of playlists for a user).
Either a uri or a username must be provided.
Args:
uri: An optional string representing the URI of the playlist feed that
is to be retrieved.
username: An optional string representing the username. Defaults to the
currently authenticated user.
Returns:
A YouTubePlaylistFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a username to the
GetYouTubePlaylistFeed() method.
"""
if uri is None:
uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'playlists')
return self.Get(uri, converter=gdata.youtube.YouTubePlaylistFeedFromString)
def GetYouTubePlaylistEntry(self, uri):
"""Retrieve a YouTubePlaylistEntry.
Args:
uri: A string representing the URI of the playlist feed that is to
be retrieved.
Returns:
A YouTubePlaylistEntry if successfully retrieved.
"""
return self.Get(uri, converter=gdata.youtube.YouTubePlaylistEntryFromString)
def GetYouTubePlaylistVideoFeed(self, uri=None, playlist_id=None):
"""Retrieve a YouTubePlaylistVideoFeed (a feed of videos on a playlist).
Either a uri or a playlist_id must be provided.
Args:
uri: An optional string representing the URI of the playlist video feed
that is to be retrieved.
playlist_id: An optional string representing the Id of the playlist whose
playlist video feed is to be retrieved.
Returns:
A YouTubePlaylistVideoFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a playlist_id to the
GetYouTubePlaylistVideoFeed() method.
"""
if uri is None and playlist_id is None:
raise YouTubeError('You must provide at least a uri or a playlist_id '
'to the GetYouTubePlaylistVideoFeed() method')
elif playlist_id and not uri:
uri = '%s/%s' % (YOUTUBE_PLAYLIST_FEED_URI, playlist_id)
return self.Get(
uri, converter=gdata.youtube.YouTubePlaylistVideoFeedFromString)
def GetYouTubeVideoResponseFeed(self, uri=None, video_id=None):
"""Retrieve a YouTubeVideoResponseFeed.
Either a uri or a playlist_id must be provided.
Args:
uri: An optional string representing the URI of the video response feed
that is to be retrieved.
video_id: An optional string representing the ID of the video whose
response feed is to be retrieved.
Returns:
A YouTubeVideoResponseFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a video_id to the
GetYouTubeVideoResponseFeed() method.
"""
if uri is None and video_id is None:
raise YouTubeError('You must provide at least a uri or a video_id '
'to the GetYouTubeVideoResponseFeed() method')
elif video_id and not uri:
uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'responses')
return self.Get(
uri, converter=gdata.youtube.YouTubeVideoResponseFeedFromString)
def GetYouTubeVideoResponseEntry(self, uri):
"""Retrieve a YouTubeVideoResponseEntry.
Args:
uri: A string representing the URI of the video response entry that
is to be retrieved.
Returns:
A YouTubeVideoResponseEntry if successfully retrieved.
"""
return self.Get(
uri, converter=gdata.youtube.YouTubeVideoResponseEntryFromString)
def GetYouTubeSubscriptionFeed(self, uri=None, username='default'):
"""Retrieve a YouTubeSubscriptionFeed.
Either the uri of the feed or a username must be provided.
Args:
uri: An optional string representing the URI of the feed that is to
be retrieved.
username: An optional string representing the username whose subscription
feed is to be retrieved. Defaults to the currently authenticted user.
Returns:
A YouTubeVideoSubscriptionFeed if successfully retrieved.
"""
if uri is None:
uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'subscriptions')
return self.Get(
uri, converter=gdata.youtube.YouTubeSubscriptionFeedFromString)
def GetYouTubeSubscriptionEntry(self, uri):
"""Retrieve a YouTubeSubscriptionEntry.
Args:
uri: A string representing the URI of the entry that is to be retrieved.
Returns:
A YouTubeVideoSubscriptionEntry if successfully retrieved.
"""
return self.Get(
uri, converter=gdata.youtube.YouTubeSubscriptionEntryFromString)
def GetYouTubeRelatedVideoFeed(self, uri=None, video_id=None):
"""Retrieve a YouTubeRelatedVideoFeed.
Either a uri for the feed or a video_id is required.
Args:
uri: An optional string representing the URI of the feed that is to
be retrieved.
video_id: An optional string representing the ID of the video for which
to retrieve the related video feed.
Returns:
A YouTubeRelatedVideoFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a video_id to the
GetYouTubeRelatedVideoFeed() method.
"""
if uri is None and video_id is None:
raise YouTubeError('You must provide at least a uri or a video_id '
'to the GetYouTubeRelatedVideoFeed() method')
elif video_id and not uri:
uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'related')
return self.Get(
uri, converter=gdata.youtube.YouTubeVideoFeedFromString)
def GetTopRatedVideoFeed(self):
"""Retrieve the 'top_rated' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_TOP_RATED_URI)
def GetMostViewedVideoFeed(self):
"""Retrieve the 'most_viewed' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_VIEWED_URI)
def GetRecentlyFeaturedVideoFeed(self):
"""Retrieve the 'recently_featured' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_RECENTLY_FEATURED_URI)
def GetWatchOnMobileVideoFeed(self):
"""Retrieve the 'watch_on_mobile' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_WATCH_ON_MOBILE_URI)
def GetTopFavoritesVideoFeed(self):
"""Retrieve the 'top_favorites' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_TOP_FAVORITES_URI)
def GetMostRecentVideoFeed(self):
"""Retrieve the 'most_recent' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_RECENT_URI)
def GetMostDiscussedVideoFeed(self):
"""Retrieve the 'most_discussed' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_DISCUSSED_URI)
def GetMostLinkedVideoFeed(self):
"""Retrieve the 'most_linked' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_LINKED_URI)
def GetMostRespondedVideoFeed(self):
"""Retrieve the 'most_responded' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_RESPONDED_URI)
def GetUserFavoritesFeed(self, username='default'):
"""Retrieve the favorites feed for a given user.
Args:
username: An optional string representing the username whose favorites
feed is to be retrieved. Defaults to the currently authenticated user.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
favorites_feed_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username,
'favorites')
return self.GetYouTubeVideoFeed(favorites_feed_uri)
def InsertVideoEntry(self, video_entry, filename_or_handle,
youtube_username='default',
content_type='video/quicktime'):
"""Upload a new video to YouTube using the direct upload mechanism.
Needs authentication.
Args:
video_entry: The YouTubeVideoEntry to upload.
filename_or_handle: A file-like object or file name where the video
will be read from.
youtube_username: An optional string representing the username into whose
account this video is to be uploaded to. Defaults to the currently
authenticated user.
content_type: An optional string representing internet media type
(a.k.a. mime type) of the media object. Currently the YouTube API
supports these types:
o video/mpeg
o video/quicktime
o video/x-msvideo
o video/mp4
Returns:
The newly created YouTubeVideoEntry if successful.
Raises:
AssertionError: video_entry must be a gdata.youtube.VideoEntry instance.
YouTubeError: An error occurred trying to read the video file provided.
gdata.service.RequestError: An error occurred trying to upload the video
to the API server.
"""
# We need to perform a series of checks on the video_entry and on the
# file that we plan to upload, such as checking whether we have a valid
# video_entry and that the file is the correct type and readable, prior
# to performing the actual POST request.
try:
assert(isinstance(video_entry, gdata.youtube.YouTubeVideoEntry))
except AssertionError:
raise YouTubeError({'status':YOUTUBE_INVALID_ARGUMENT,
'body':'`video_entry` must be a gdata.youtube.VideoEntry instance',
'reason':'Found %s, not VideoEntry' % type(video_entry)
})
majtype, mintype = content_type.split('/')
try:
assert(mintype in YOUTUBE_SUPPORTED_UPLOAD_TYPES)
except (ValueError, AssertionError):
raise YouTubeError({'status':YOUTUBE_INVALID_CONTENT_TYPE,
'body':'This is not a valid content type: %s' % content_type,
'reason':'Accepted content types: %s' %
['video/%s' % (t) for t in YOUTUBE_SUPPORTED_UPLOAD_TYPES]})
if (isinstance(filename_or_handle, (str, unicode))
and os.path.exists(filename_or_handle)):
mediasource = gdata.MediaSource()
mediasource.setFile(filename_or_handle, content_type)
elif hasattr(filename_or_handle, 'read'):
if hasattr(filename_or_handle, 'seek'):
filename_or_handle.seek(0)
file_handle = StringIO.StringIO(filename_or_handle.read())
name = 'video'
if hasattr(filename_or_handle, 'name'):
name = filename_or_handle.name
mediasource = gdata.MediaSource(file_handle, content_type,
content_length=file_handle.len, file_name=name)
else:
raise YouTubeError({'status':YOUTUBE_INVALID_ARGUMENT, 'body':
'`filename_or_handle` must be a path name or a file-like object',
'reason': ('Found %s, not path name or object '
'with a .read() method' % type(filename_or_handle))})
upload_uri = '%s/%s/%s' % (YOUTUBE_UPLOAD_URI, youtube_username,
'uploads')
self.additional_headers['Slug'] = mediasource.file_name
# Using a nested try statement to retain Python 2.4 compatibility
try:
try:
return self.Post(video_entry, uri=upload_uri, media_source=mediasource,
converter=gdata.youtube.YouTubeVideoEntryFromString)
except gdata.service.RequestError, e:
raise YouTubeError(e.args[0])
finally:
del(self.additional_headers['Slug'])
def CheckUploadStatus(self, video_entry=None, video_id=None):
"""Check upload status on a recently uploaded video entry.
Needs authentication. Either video_entry or video_id must be provided.
Args:
video_entry: An optional YouTubeVideoEntry whose upload status to check
video_id: An optional string representing the ID of the uploaded video
whose status is to be checked.
Returns:
A tuple containing (video_upload_state, detailed_message) or None if
no status information is found.
Raises:
YouTubeError: You must provide at least a video_entry or a video_id to the
CheckUploadStatus() method.
"""
if video_entry is None and video_id is None:
raise YouTubeError('You must provide at least a uri or a video_id '
'to the CheckUploadStatus() method')
elif video_id and not video_entry:
video_entry = self.GetYouTubeVideoEntry(video_id=video_id)
control = video_entry.control
if control is not None:
draft = control.draft
if draft is not None:
if draft.text == 'yes':
yt_state = control.extension_elements[0]
if yt_state is not None:
state_value = yt_state.attributes['name']
message = ''
if yt_state.text is not None:
message = yt_state.text
return (state_value, message)
def GetFormUploadToken(self, video_entry, uri=YOUTUBE_UPLOAD_TOKEN_URI):
"""Receives a YouTube Token and a YouTube PostUrl from a YouTubeVideoEntry.
Needs authentication.
Args:
video_entry: The YouTubeVideoEntry to upload (meta-data only).
uri: An optional string representing the URI from where to fetch the
token information. Defaults to the YOUTUBE_UPLOADTOKEN_URI.
Returns:
A tuple containing the URL to which to post your video file, along
with the youtube token that must be included with your upload in the
form of: (post_url, youtube_token).
"""
try:
response = self.Post(video_entry, uri)
except gdata.service.RequestError, e:
raise YouTubeError(e.args[0])
tree = ElementTree.fromstring(response)
for child in tree:
if child.tag == 'url':
post_url = child.text
elif child.tag == 'token':
youtube_token = child.text
return (post_url, youtube_token)
def UpdateVideoEntry(self, video_entry):
"""Updates a video entry's meta-data.
Needs authentication.
Args:
video_entry: The YouTubeVideoEntry to update, containing updated
meta-data.
Returns:
An updated YouTubeVideoEntry on success or None.
"""
for link in video_entry.link:
if link.rel == 'edit':
edit_uri = link.href
return self.Put(video_entry, uri=edit_uri,
converter=gdata.youtube.YouTubeVideoEntryFromString)
def DeleteVideoEntry(self, video_entry):
"""Deletes a video entry.
Needs authentication.
Args:
video_entry: The YouTubeVideoEntry to be deleted.
Returns:
True if entry was deleted successfully.
"""
for link in video_entry.link:
if link.rel == 'edit':
edit_uri = link.href
return self.Delete(edit_uri)
def AddRating(self, rating_value, video_entry):
"""Add a rating to a video entry.
Needs authentication.
Args:
rating_value: The integer value for the rating (between 1 and 5).
video_entry: The YouTubeVideoEntry to be rated.
Returns:
True if the rating was added successfully.
Raises:
YouTubeError: rating_value must be between 1 and 5 in AddRating().
"""
if rating_value < 1 or rating_value > 5:
raise YouTubeError('rating_value must be between 1 and 5 in AddRating()')
entry = gdata.GDataEntry()
rating = gdata.youtube.Rating(min='1', max='5')
rating.extension_attributes['name'] = 'value'
rating.extension_attributes['value'] = str(rating_value)
entry.extension_elements.append(rating)
for link in video_entry.link:
if link.rel == YOUTUBE_RATING_LINK_REL:
rating_uri = link.href
return self.Post(entry, uri=rating_uri)
def AddComment(self, comment_text, video_entry):
"""Add a comment to a video entry.
Needs authentication. Note that each comment that is posted must contain
the video entry that it is to be posted to.
Args:
comment_text: A string representing the text of the comment.
video_entry: The YouTubeVideoEntry to be commented on.
Returns:
True if the comment was added successfully.
"""
content = atom.Content(text=comment_text)
comment_entry = gdata.youtube.YouTubeVideoCommentEntry(content=content)
comment_post_uri = video_entry.comments.feed_link[0].href
return self.Post(comment_entry, uri=comment_post_uri)
def AddVideoResponse(self, video_id_to_respond_to, video_response):
"""Add a video response.
Needs authentication.
Args:
video_id_to_respond_to: A string representing the ID of the video to be
responded to.
video_response: YouTubeVideoEntry to be posted as a response.
Returns:
True if video response was posted successfully.
"""
post_uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id_to_respond_to,
'responses')
return self.Post(video_response, uri=post_uri)
def DeleteVideoResponse(self, video_id, response_video_id):
"""Delete a video response.
Needs authentication.
Args:
video_id: A string representing the ID of video that contains the
response.
response_video_id: A string representing the ID of the video that was
posted as a response.
Returns:
True if video response was deleted succcessfully.
"""
delete_uri = '%s/%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'responses',
response_video_id)
return self.Delete(delete_uri)
def AddComplaint(self, complaint_text, complaint_term, video_id):
"""Add a complaint for a particular video entry.
Needs authentication.
Args:
complaint_text: A string representing the complaint text.
complaint_term: A string representing the complaint category term.
video_id: A string representing the ID of YouTubeVideoEntry to
complain about.
Returns:
True if posted successfully.
Raises:
YouTubeError: Your complaint_term is not valid.
"""
if complaint_term not in YOUTUBE_COMPLAINT_CATEGORY_TERMS:
raise YouTubeError('Your complaint_term is not valid')
content = atom.Content(text=complaint_text)
category = atom.Category(term=complaint_term,
scheme=YOUTUBE_COMPLAINT_CATEGORY_SCHEME)
complaint_entry = gdata.GDataEntry(content=content, category=[category])
post_uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'complaints')
return self.Post(complaint_entry, post_uri)
def AddVideoEntryToFavorites(self, video_entry, username='default'):
"""Add a video entry to a users favorite feed.
Needs authentication.
Args:
video_entry: The YouTubeVideoEntry to add.
username: An optional string representing the username to whose favorite
feed you wish to add the entry. Defaults to the currently
authenticated user.
Returns:
The posted YouTubeVideoEntry if successfully posted.
"""
post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'favorites')
return self.Post(video_entry, post_uri,
converter=gdata.youtube.YouTubeVideoEntryFromString)
def DeleteVideoEntryFromFavorites(self, video_id, username='default'):
"""Delete a video entry from the users favorite feed.
Needs authentication.
Args:
video_id: A string representing the ID of the video that is to be removed
username: An optional string representing the username of the user's
favorite feed. Defaults to the currently authenticated user.
Returns:
True if entry was successfully deleted.
"""
edit_link = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'favorites',
video_id)
return self.Delete(edit_link)
def AddPlaylist(self, playlist_title, playlist_description,
playlist_private=None):
"""Add a new playlist to the currently authenticated users account.
Needs authentication.
Args:
playlist_title: A string representing the title for the new playlist.
playlist_description: A string representing the description of the
playlist.
playlist_private: An optional boolean, set to True if the playlist is
to be private.
Returns:
The YouTubePlaylistEntry if successfully posted.
"""
playlist_entry = gdata.youtube.YouTubePlaylistEntry(
title=atom.Title(text=playlist_title),
description=gdata.youtube.Description(text=playlist_description))
if playlist_private:
playlist_entry.private = gdata.youtube.Private()
playlist_post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, 'default',
'playlists')
return self.Post(playlist_entry, playlist_post_uri,
converter=gdata.youtube.YouTubePlaylistEntryFromString)
def UpdatePlaylist(self, playlist_id, new_playlist_title,
new_playlist_description, playlist_private=None,
username='default'):
"""Update a playlist with new meta-data.
Needs authentication.
Args:
playlist_id: A string representing the ID of the playlist to be updated.
new_playlist_title: A string representing a new title for the playlist.
new_playlist_description: A string representing a new description for the
playlist.
playlist_private: An optional boolean, set to True if the playlist is
to be private.
username: An optional string representing the username whose playlist is
to be updated. Defaults to the currently authenticated user.
Returns:
A YouTubePlaylistEntry if the update was successful.
"""
updated_playlist = gdata.youtube.YouTubePlaylistEntry(
title=atom.Title(text=new_playlist_title),
description=gdata.youtube.Description(text=new_playlist_description))
if playlist_private:
updated_playlist.private = gdata.youtube.Private()
playlist_put_uri = '%s/%s/playlists/%s' % (YOUTUBE_USER_FEED_URI, username,
playlist_id)
return self.Put(updated_playlist, playlist_put_uri,
converter=gdata.youtube.YouTubePlaylistEntryFromString)
def DeletePlaylist(self, playlist_uri):
"""Delete a playlist from the currently authenticated users playlists.
Needs authentication.
Args:
playlist_uri: A string representing the URI of the playlist that is
to be deleted.
Returns:
True if successfully deleted.
"""
return self.Delete(playlist_uri)
def AddPlaylistVideoEntryToPlaylist(
self, playlist_uri, video_id, custom_video_title=None,
custom_video_description=None):
"""Add a video entry to a playlist, optionally providing a custom title
and description.
Needs authentication.
Args:
playlist_uri: A string representing the URI of the playlist to which this
video entry is to be added.
video_id: A string representing the ID of the video entry to add.
custom_video_title: An optional string representing a custom title for
the video (only shown on the playlist).
custom_video_description: An optional string representing a custom
description for the video (only shown on the playlist).
Returns:
A YouTubePlaylistVideoEntry if successfully posted.
"""
playlist_video_entry = gdata.youtube.YouTubePlaylistVideoEntry(
atom_id=atom.Id(text=video_id))
if custom_video_title:
playlist_video_entry.title = atom.Title(text=custom_video_title)
if custom_video_description:
playlist_video_entry.description = gdata.youtube.Description(
text=custom_video_description)
return self.Post(playlist_video_entry, playlist_uri,
converter=gdata.youtube.YouTubePlaylistVideoEntryFromString)
def UpdatePlaylistVideoEntryMetaData(
self, playlist_uri, playlist_entry_id, new_video_title,
new_video_description, new_video_position):
"""Update the meta data for a YouTubePlaylistVideoEntry.
Needs authentication.
Args:
playlist_uri: A string representing the URI of the playlist that contains
the entry to be updated.
playlist_entry_id: A string representing the ID of the entry to be
updated.
new_video_title: A string representing the new title for the video entry.
new_video_description: A string representing the new description for
the video entry.
new_video_position: An integer representing the new position on the
playlist for the video.
Returns:
A YouTubePlaylistVideoEntry if the update was successful.
"""
playlist_video_entry = gdata.youtube.YouTubePlaylistVideoEntry(
title=atom.Title(text=new_video_title),
description=gdata.youtube.Description(text=new_video_description),
position=gdata.youtube.Position(text=str(new_video_position)))
playlist_put_uri = playlist_uri + '/' + playlist_entry_id
return self.Put(playlist_video_entry, playlist_put_uri,
converter=gdata.youtube.YouTubePlaylistVideoEntryFromString)
def DeletePlaylistVideoEntry(self, playlist_uri, playlist_video_entry_id):
"""Delete a playlist video entry from a playlist.
Needs authentication.
Args:
playlist_uri: A URI representing the playlist from which the playlist
video entry is to be removed from.
playlist_video_entry_id: A string representing id of the playlist video
entry that is to be removed.
Returns:
True if entry was successfully deleted.
"""
delete_uri = '%s/%s' % (playlist_uri, playlist_video_entry_id)
return self.Delete(delete_uri)
def AddSubscriptionToChannel(self, username_to_subscribe_to,
my_username = 'default'):
"""Add a new channel subscription to the currently authenticated users
account.
Needs authentication.
Args:
username_to_subscribe_to: A string representing the username of the
channel to which we want to subscribe to.
my_username: An optional string representing the name of the user which
we want to subscribe. Defaults to currently authenticated user.
Returns:
A new YouTubeSubscriptionEntry if successfully posted.
"""
subscription_category = atom.Category(
scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME,
term='channel')
subscription_username = gdata.youtube.Username(
text=username_to_subscribe_to)
subscription_entry = gdata.youtube.YouTubeSubscriptionEntry(
category=subscription_category,
username=subscription_username)
post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'subscriptions')
return self.Post(subscription_entry, post_uri,
converter=gdata.youtube.YouTubeSubscriptionEntryFromString)
def AddSubscriptionToFavorites(self, username, my_username = 'default'):
"""Add a new subscription to a users favorites to the currently
authenticated user's account.
Needs authentication
Args:
username: A string representing the username of the user's favorite feed
to subscribe to.
my_username: An optional string representing the username of the user
that is to be subscribed. Defaults to currently authenticated user.
Returns:
A new YouTubeSubscriptionEntry if successful.
"""
subscription_category = atom.Category(
scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME,
term='favorites')
subscription_username = gdata.youtube.Username(text=username)
subscription_entry = gdata.youtube.YouTubeSubscriptionEntry(
category=subscription_category,
username=subscription_username)
post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'subscriptions')
return self.Post(subscription_entry, post_uri,
converter=gdata.youtube.YouTubeSubscriptionEntryFromString)
def AddSubscriptionToQuery(self, query, my_username = 'default'):
"""Add a new subscription to a specific keyword query to the currently
authenticated user's account.
Needs authentication
Args:
query: A string representing the keyword query to subscribe to.
my_username: An optional string representing the username of the user
that is to be subscribed. Defaults to currently authenticated user.
Returns:
A new YouTubeSubscriptionEntry if successful.
"""
subscription_category = atom.Category(
scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME,
term='query')
subscription_query_string = gdata.youtube.QueryString(text=query)
subscription_entry = gdata.youtube.YouTubeSubscriptionEntry(
category=subscription_category,
query_string=subscription_query_string)
post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'subscriptions')
return self.Post(subscription_entry, post_uri,
converter=gdata.youtube.YouTubeSubscriptionEntryFromString)
def DeleteSubscription(self, subscription_uri):
"""Delete a subscription from the currently authenticated user's account.
Needs authentication.
Args:
subscription_uri: A string representing the URI of the subscription that
is to be deleted.
Returns:
True if deleted successfully.
"""
return self.Delete(subscription_uri)
def AddContact(self, contact_username, my_username='default'):
"""Add a new contact to the currently authenticated user's contact feed.
Needs authentication.
Args:
contact_username: A string representing the username of the contact
that you wish to add.
my_username: An optional string representing the username to whose
contact the new contact is to be added.
Returns:
A YouTubeContactEntry if added successfully.
"""
contact_category = atom.Category(
scheme = 'http://gdata.youtube.com/schemas/2007/contact.cat',
term = 'Friends')
contact_username = gdata.youtube.Username(text=contact_username)
contact_entry = gdata.youtube.YouTubeContactEntry(
category=contact_category,
username=contact_username)
contact_post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'contacts')
return self.Post(contact_entry, contact_post_uri,
converter=gdata.youtube.YouTubeContactEntryFromString)
def UpdateContact(self, contact_username, new_contact_status,
new_contact_category, my_username='default'):
"""Update a contact, providing a new status and a new category.
Needs authentication.
Args:
contact_username: A string representing the username of the contact
that is to be updated.
new_contact_status: A string representing the new status of the contact.
This can either be set to 'accepted' or 'rejected'.
new_contact_category: A string representing the new category for the
contact, either 'Friends' or 'Family'.
my_username: An optional string representing the username of the user
whose contact feed we are modifying. Defaults to the currently
authenticated user.
Returns:
A YouTubeContactEntry if updated succesfully.
Raises:
YouTubeError: New contact status must be within the accepted values. Or
new contact category must be within the accepted categories.
"""
if new_contact_status not in YOUTUBE_CONTACT_STATUS:
raise YouTubeError('New contact status must be one of %s' %
(' '.join(YOUTUBE_CONTACT_STATUS)))
if new_contact_category not in YOUTUBE_CONTACT_CATEGORY:
raise YouTubeError('New contact category must be one of %s' %
(' '.join(YOUTUBE_CONTACT_CATEGORY)))
contact_category = atom.Category(
scheme='http://gdata.youtube.com/schemas/2007/contact.cat',
term=new_contact_category)
contact_status = gdata.youtube.Status(text=new_contact_status)
contact_entry = gdata.youtube.YouTubeContactEntry(
category=contact_category,
status=contact_status)
contact_put_uri = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'contacts', contact_username)
return self.Put(contact_entry, contact_put_uri,
converter=gdata.youtube.YouTubeContactEntryFromString)
def DeleteContact(self, contact_username, my_username='default'):
"""Delete a contact from a users contact feed.
Needs authentication.
Args:
contact_username: A string representing the username of the contact
that is to be deleted.
my_username: An optional string representing the username of the user's
contact feed from which to delete the contact. Defaults to the
currently authenticated user.
Returns:
True if the contact was deleted successfully
"""
contact_edit_uri = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'contacts', contact_username)
return self.Delete(contact_edit_uri)
def _GetDeveloperKey(self):
"""Getter for Developer Key property.
Returns:
If the developer key has been set, a string representing the developer key
is returned or None.
"""
if 'X-GData-Key' in self.additional_headers:
return self.additional_headers['X-GData-Key'][4:]
else:
return None
def _SetDeveloperKey(self, developer_key):
"""Setter for Developer Key property.
Sets the developer key in the 'X-GData-Key' header. The actual value that
is set is 'key=' plus the developer_key that was passed.
"""
self.additional_headers['X-GData-Key'] = 'key=' + developer_key
developer_key = property(_GetDeveloperKey, _SetDeveloperKey,
doc="""The Developer Key property""")
def _GetClientId(self):
"""Getter for Client Id property.
Returns:
If the client_id has been set, a string representing it is returned
or None.
"""
if 'X-Gdata-Client' in self.additional_headers:
return self.additional_headers['X-Gdata-Client']
else:
return None
def _SetClientId(self, client_id):
"""Setter for Client Id property.
Sets the 'X-Gdata-Client' header.
"""
self.additional_headers['X-Gdata-Client'] = client_id
client_id = property(_GetClientId, _SetClientId,
doc="""The ClientId property""")
def Query(self, uri):
"""Performs a query and returns a resulting feed or entry.
Args:
uri: A string representing the URI of the feed that is to be queried.
Returns:
On success, a tuple in the form:
(boolean succeeded=True, ElementTree._Element result)
On failure, a tuple in the form:
(boolean succeeded=False, {'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response})
"""
result = self.Get(uri)
return result
def YouTubeQuery(self, query):
"""Performs a YouTube specific query and returns a resulting feed or entry.
Args:
query: A Query object or one if its sub-classes (YouTubeVideoQuery,
YouTubeUserQuery or YouTubePlaylistQuery).
Returns:
Depending on the type of Query object submitted returns either a
YouTubeVideoFeed, a YouTubeUserFeed, a YouTubePlaylistFeed. If the
Query object provided was not YouTube-related, a tuple is returned.
On success the tuple will be in this form:
(boolean succeeded=True, ElementTree._Element result)
On failure, the tuple will be in this form:
(boolean succeeded=False, {'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server response})
"""
result = self.Query(query.ToUri())
if isinstance(query, YouTubeVideoQuery):
return gdata.youtube.YouTubeVideoFeedFromString(result.ToString())
elif isinstance(query, YouTubeUserQuery):
return gdata.youtube.YouTubeUserFeedFromString(result.ToString())
elif isinstance(query, YouTubePlaylistQuery):
return gdata.youtube.YouTubePlaylistFeedFromString(result.ToString())
else:
return result
class YouTubeVideoQuery(gdata.service.Query):
"""Subclasses gdata.service.Query to represent a YouTube Data API query.
Attributes are set dynamically via properties. Properties correspond to
the standard Google Data API query parameters with YouTube Data API
extensions. Please refer to the API documentation for details.
Attributes:
vq: The vq parameter, which is only supported for video feeds, specifies a
search query term. Refer to API documentation for further details.
orderby: The orderby parameter, which is only supported for video feeds,
specifies the value that will be used to sort videos in the search
result set. Valid values for this parameter are relevance, published,
viewCount and rating.
time: The time parameter, which is only available for the top_rated,
top_favorites, most_viewed, most_discussed, most_linked and
most_responded standard feeds, restricts the search to videos uploaded
within the specified time. Valid values for this parameter are today
(1 day), this_week (7 days), this_month (1 month) and all_time.
The default value for this parameter is all_time.
format: The format parameter specifies that videos must be available in a
particular video format. Refer to the API documentation for details.
racy: The racy parameter allows a search result set to include restricted
content as well as standard content. Valid values for this parameter
are include and exclude. By default, restricted content is excluded.
lr: The lr parameter restricts the search to videos that have a title,
description or keywords in a specific language. Valid values for the lr
parameter are ISO 639-1 two-letter language codes.
restriction: The restriction parameter identifies the IP address that
should be used to filter videos that can only be played in specific
countries.
"""
def __init__(self, video_id=None, feed_type=None, text_query=None,
params=None, categories=None):
if feed_type in YOUTUBE_STANDARDFEEDS:
feed = 'http://%s/feeds/standardfeeds/%s' % (YOUTUBE_SERVER, feed_type)
elif feed_type is 'responses' or feed_type is 'comments' and video_id:
feed = 'http://%s/feeds/videos/%s/%s' % (YOUTUBE_SERVER, video_id,
feed_type)
else:
feed = 'http://%s/feeds/videos' % (YOUTUBE_SERVER)
gdata.service.Query.__init__(self, feed, text_query=text_query,
params=params, categories=categories)
def _GetVideoQuery(self):
if 'vq' in self:
return self['vq']
else:
return None
def _SetVideoQuery(self, val):
self['vq'] = val
vq = property(_GetVideoQuery, _SetVideoQuery,
doc="""The video query (vq) query parameter""")
def _GetOrderBy(self):
if 'orderby' in self:
return self['orderby']
else:
return None
def _SetOrderBy(self, val):
if val not in YOUTUBE_QUERY_VALID_ORDERBY_PARAMETERS:
raise YouTubeError('OrderBy must be one of: %s ' %
' '.join(YOUTUBE_QUERY_VALID_ORDERBY_PARAMETERS))
self['orderby'] = val
orderby = property(_GetOrderBy, _SetOrderBy,
doc="""The orderby query parameter""")
def _GetTime(self):
if 'time' in self:
return self['time']
else:
return None
def _SetTime(self, val):
if val not in YOUTUBE_QUERY_VALID_TIME_PARAMETERS:
raise YouTubeError('Time must be one of: %s ' %
' '.join(YOUTUBE_QUERY_VALID_TIME_PARAMETERS))
self['time'] = val
time = property(_GetTime, _SetTime,
doc="""The time query parameter""")
def _GetFormat(self):
if 'format' in self:
return self['format']
else:
return None
def _SetFormat(self, val):
if val not in YOUTUBE_QUERY_VALID_FORMAT_PARAMETERS:
raise YouTubeError('Format must be one of: %s ' %
' '.join(YOUTUBE_QUERY_VALID_FORMAT_PARAMETERS))
self['format'] = val
format = property(_GetFormat, _SetFormat,
doc="""The format query parameter""")
def _GetRacy(self):
if 'racy' in self:
return self['racy']
else:
return None
def _SetRacy(self, val):
if val not in YOUTUBE_QUERY_VALID_RACY_PARAMETERS:
raise YouTubeError('Racy must be one of: %s ' %
' '.join(YOUTUBE_QUERY_VALID_RACY_PARAMETERS))
self['racy'] = val
racy = property(_GetRacy, _SetRacy,
doc="""The racy query parameter""")
def _GetLanguageRestriction(self):
if 'lr' in self:
return self['lr']
else:
return None
def _SetLanguageRestriction(self, val):
self['lr'] = val
lr = property(_GetLanguageRestriction, _SetLanguageRestriction,
doc="""The lr (language restriction) query parameter""")
def _GetIPRestriction(self):
if 'restriction' in self:
return self['restriction']
else:
return None
def _SetIPRestriction(self, val):
self['restriction'] = val
restriction = property(_GetIPRestriction, _SetIPRestriction,
doc="""The restriction query parameter""")
class YouTubeUserQuery(YouTubeVideoQuery):
"""Subclasses YouTubeVideoQuery to perform user-specific queries.
Attributes are set dynamically via properties. Properties correspond to
the standard Google Data API query parameters with YouTube Data API
extensions.
"""
def __init__(self, username=None, feed_type=None, subscription_id=None,
text_query=None, params=None, categories=None):
uploads_favorites_playlists = ('uploads', 'favorites', 'playlists')
if feed_type is 'subscriptions' and subscription_id and username:
feed = "http://%s/feeds/users/%s/%s/%s" % (YOUTUBE_SERVER, username,
feed_type, subscription_id)
elif feed_type is 'subscriptions' and not subscription_id and username:
feed = "http://%s/feeds/users/%s/%s" % (YOUTUBE_SERVER, username,
feed_type)
elif feed_type in uploads_favorites_playlists:
feed = "http://%s/feeds/users/%s/%s" % (YOUTUBE_SERVER, username,
feed_type)
else:
feed = "http://%s/feeds/users" % (YOUTUBE_SERVER)
YouTubeVideoQuery.__init__(self, feed, text_query=text_query,
params=params, categories=categories)
class YouTubePlaylistQuery(YouTubeVideoQuery):
"""Subclasses YouTubeVideoQuery to perform playlist-specific queries.
Attributes are set dynamically via properties. Properties correspond to
the standard Google Data API query parameters with YouTube Data API
extensions.
"""
def __init__(self, playlist_id, text_query=None, params=None,
categories=None):
if playlist_id:
feed = "http://%s/feeds/playlists/%s" % (YOUTUBE_SERVER, playlist_id)
else:
feed = "http://%s/feeds/playlists" % (YOUTUBE_SERVER)
YouTubeVideoQuery.__init__(self, feed, text_query=text_query,
params=params, categories=categories)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = ('api.stephaniel@gmail.com (Stephanie Liu)'
', api.jhartmann@gmail.com (Jochen Hartmann)')
import atom
import gdata
import gdata.media as Media
import gdata.geo as Geo
YOUTUBE_NAMESPACE = 'http://gdata.youtube.com/schemas/2007'
YOUTUBE_FORMAT = '{http://gdata.youtube.com/schemas/2007}format'
YOUTUBE_DEVELOPER_TAG_SCHEME = '%s/%s' % (YOUTUBE_NAMESPACE,
'developertags.cat')
YOUTUBE_SUBSCRIPTION_TYPE_SCHEME = '%s/%s' % (YOUTUBE_NAMESPACE,
'subscriptiontypes.cat')
class Username(atom.AtomBase):
"""The YouTube Username element"""
_tag = 'username'
_namespace = YOUTUBE_NAMESPACE
class QueryString(atom.AtomBase):
"""The YouTube QueryString element"""
_tag = 'queryString'
_namespace = YOUTUBE_NAMESPACE
class FirstName(atom.AtomBase):
"""The YouTube FirstName element"""
_tag = 'firstName'
_namespace = YOUTUBE_NAMESPACE
class LastName(atom.AtomBase):
"""The YouTube LastName element"""
_tag = 'lastName'
_namespace = YOUTUBE_NAMESPACE
class Age(atom.AtomBase):
"""The YouTube Age element"""
_tag = 'age'
_namespace = YOUTUBE_NAMESPACE
class Books(atom.AtomBase):
"""The YouTube Books element"""
_tag = 'books'
_namespace = YOUTUBE_NAMESPACE
class Gender(atom.AtomBase):
"""The YouTube Gender element"""
_tag = 'gender'
_namespace = YOUTUBE_NAMESPACE
class Company(atom.AtomBase):
"""The YouTube Company element"""
_tag = 'company'
_namespace = YOUTUBE_NAMESPACE
class Hobbies(atom.AtomBase):
"""The YouTube Hobbies element"""
_tag = 'hobbies'
_namespace = YOUTUBE_NAMESPACE
class Hometown(atom.AtomBase):
"""The YouTube Hometown element"""
_tag = 'hometown'
_namespace = YOUTUBE_NAMESPACE
class Location(atom.AtomBase):
"""The YouTube Location element"""
_tag = 'location'
_namespace = YOUTUBE_NAMESPACE
class Movies(atom.AtomBase):
"""The YouTube Movies element"""
_tag = 'movies'
_namespace = YOUTUBE_NAMESPACE
class Music(atom.AtomBase):
"""The YouTube Music element"""
_tag = 'music'
_namespace = YOUTUBE_NAMESPACE
class Occupation(atom.AtomBase):
"""The YouTube Occupation element"""
_tag = 'occupation'
_namespace = YOUTUBE_NAMESPACE
class School(atom.AtomBase):
"""The YouTube School element"""
_tag = 'school'
_namespace = YOUTUBE_NAMESPACE
class Relationship(atom.AtomBase):
"""The YouTube Relationship element"""
_tag = 'relationship'
_namespace = YOUTUBE_NAMESPACE
class Recorded(atom.AtomBase):
"""The YouTube Recorded element"""
_tag = 'recorded'
_namespace = YOUTUBE_NAMESPACE
class Statistics(atom.AtomBase):
"""The YouTube Statistics element."""
_tag = 'statistics'
_namespace = YOUTUBE_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['viewCount'] = 'view_count'
_attributes['videoWatchCount'] = 'video_watch_count'
_attributes['subscriberCount'] = 'subscriber_count'
_attributes['lastWebAccess'] = 'last_web_access'
_attributes['favoriteCount'] = 'favorite_count'
def __init__(self, view_count=None, video_watch_count=None,
favorite_count=None, subscriber_count=None, last_web_access=None,
extension_elements=None, extension_attributes=None, text=None):
self.view_count = view_count
self.video_watch_count = video_watch_count
self.subscriber_count = subscriber_count
self.last_web_access = last_web_access
self.favorite_count = favorite_count
atom.AtomBase.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes, text=text)
class Status(atom.AtomBase):
"""The YouTube Status element"""
_tag = 'status'
_namespace = YOUTUBE_NAMESPACE
class Position(atom.AtomBase):
"""The YouTube Position element. The position in a playlist feed."""
_tag = 'position'
_namespace = YOUTUBE_NAMESPACE
class Racy(atom.AtomBase):
"""The YouTube Racy element."""
_tag = 'racy'
_namespace = YOUTUBE_NAMESPACE
class Description(atom.AtomBase):
"""The YouTube Description element."""
_tag = 'description'
_namespace = YOUTUBE_NAMESPACE
class Private(atom.AtomBase):
"""The YouTube Private element."""
_tag = 'private'
_namespace = YOUTUBE_NAMESPACE
class NoEmbed(atom.AtomBase):
"""The YouTube VideoShare element. Whether a video can be embedded or not."""
_tag = 'noembed'
_namespace = YOUTUBE_NAMESPACE
class Comments(atom.AtomBase):
"""The GData Comments element"""
_tag = 'comments'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
[gdata.FeedLink])
def __init__(self, feed_link=None, extension_elements=None,
extension_attributes=None, text=None):
self.feed_link = feed_link
atom.AtomBase.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes, text=text)
class Rating(atom.AtomBase):
"""The GData Rating element"""
_tag = 'rating'
_namespace = gdata.GDATA_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['min'] = 'min'
_attributes['max'] = 'max'
_attributes['numRaters'] = 'num_raters'
_attributes['average'] = 'average'
def __init__(self, min=None, max=None,
num_raters=None, average=None, extension_elements=None,
extension_attributes=None, text=None):
self.min = min
self.max = max
self.num_raters = num_raters
self.average = average
atom.AtomBase.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes, text=text)
class YouTubePlaylistVideoEntry(gdata.GDataEntry):
"""Represents a YouTubeVideoEntry on a YouTubePlaylist."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
[gdata.FeedLink])
_children['{%s}description' % YOUTUBE_NAMESPACE] = ('description',
Description)
_children['{%s}rating' % gdata.GDATA_NAMESPACE] = ('rating', Rating)
_children['{%s}comments' % gdata.GDATA_NAMESPACE] = ('comments', Comments)
_children['{%s}statistics' % YOUTUBE_NAMESPACE] = ('statistics', Statistics)
_children['{%s}location' % YOUTUBE_NAMESPACE] = ('location', Location)
_children['{%s}position' % YOUTUBE_NAMESPACE] = ('position', Position)
_children['{%s}group' % gdata.media.MEDIA_NAMESPACE] = ('media', Media.Group)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None, title=None,
updated=None, feed_link=None, description=None,
rating=None, comments=None, statistics=None,
location=None, position=None, media=None,
extension_elements=None, extension_attributes=None):
self.feed_link = feed_link
self.description = description
self.rating = rating
self.comments = comments
self.statistics = statistics
self.location = location
self.position = position
self.media = media
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id,
link=link, published=published, title=title,
updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
class YouTubeVideoCommentEntry(gdata.GDataEntry):
"""Represents a comment on YouTube."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
class YouTubeSubscriptionEntry(gdata.GDataEntry):
"""Represents a subscription entry on YouTube."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}username' % YOUTUBE_NAMESPACE] = ('username', Username)
_children['{%s}queryString' % YOUTUBE_NAMESPACE] = (
'query_string', QueryString)
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
[gdata.FeedLink])
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None, title=None,
updated=None, username=None, query_string=None, feed_link=None,
extension_elements=None, extension_attributes=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title, updated=updated)
self.username = username
self.query_string = query_string
self.feed_link = feed_link
def GetSubscriptionType(self):
"""Retrieve the type of this subscription.
Returns:
A string that is either 'channel, 'query' or 'favorites'
"""
for category in self.category:
if category.scheme == YOUTUBE_SUBSCRIPTION_TYPE_SCHEME:
return category.term
class YouTubeVideoResponseEntry(gdata.GDataEntry):
"""Represents a video response. """
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}rating' % gdata.GDATA_NAMESPACE] = ('rating', Rating)
_children['{%s}noembed' % YOUTUBE_NAMESPACE] = ('noembed', NoEmbed)
_children['{%s}statistics' % YOUTUBE_NAMESPACE] = ('statistics', Statistics)
_children['{%s}racy' % YOUTUBE_NAMESPACE] = ('racy', Racy)
_children['{%s}group' % gdata.media.MEDIA_NAMESPACE] = ('media', Media.Group)
def __init__(self, author=None, category=None, content=None, atom_id=None,
link=None, published=None, title=None, updated=None, rating=None,
noembed=None, statistics=None, racy=None, media=None,
extension_elements=None, extension_attributes=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title, updated=updated)
self.rating = rating
self.noembed = noembed
self.statistics = statistics
self.racy = racy
self.media = media or Media.Group()
class YouTubeContactEntry(gdata.GDataEntry):
"""Represents a contact entry."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}username' % YOUTUBE_NAMESPACE] = ('username', Username)
_children['{%s}status' % YOUTUBE_NAMESPACE] = ('status', Status)
def __init__(self, author=None, category=None, content=None, atom_id=None,
link=None, published=None, title=None, updated=None,
username=None, status=None, extension_elements=None,
extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title, updated=updated)
self.username = username
self.status = status
class YouTubeVideoEntry(gdata.GDataEntry):
"""Represents a video on YouTube."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}rating' % gdata.GDATA_NAMESPACE] = ('rating', Rating)
_children['{%s}comments' % gdata.GDATA_NAMESPACE] = ('comments', Comments)
_children['{%s}noembed' % YOUTUBE_NAMESPACE] = ('noembed', NoEmbed)
_children['{%s}statistics' % YOUTUBE_NAMESPACE] = ('statistics', Statistics)
_children['{%s}recorded' % YOUTUBE_NAMESPACE] = ('recorded', Recorded)
_children['{%s}racy' % YOUTUBE_NAMESPACE] = ('racy', Racy)
_children['{%s}group' % gdata.media.MEDIA_NAMESPACE] = ('media', Media.Group)
_children['{%s}where' % gdata.geo.GEORSS_NAMESPACE] = ('geo', Geo.Where)
def __init__(self, author=None, category=None, content=None, atom_id=None,
link=None, published=None, title=None, updated=None, rating=None,
noembed=None, statistics=None, racy=None, media=None, geo=None,
recorded=None, comments=None, extension_elements=None,
extension_attributes=None):
self.rating = rating
self.noembed = noembed
self.statistics = statistics
self.racy = racy
self.comments = comments
self.media = media or Media.Group()
self.geo = geo
self.recorded = recorded
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title, updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
def GetSwfUrl(self):
"""Return the URL for the embeddable Video
Returns:
URL of the embeddable video
"""
if self.media.content:
for content in self.media.content:
if content.extension_attributes[YOUTUBE_FORMAT] == '5':
return content.url
else:
return None
def AddDeveloperTags(self, developer_tags):
"""Add a developer tag for this entry.
Developer tags can only be set during the initial upload.
Arguments:
developer_tags: A list of developer tags as strings.
Returns:
A list of all developer tags for this video entry.
"""
for tag_text in developer_tags:
self.media.category.append(gdata.media.Category(
text=tag_text, label=tag_text, scheme=YOUTUBE_DEVELOPER_TAG_SCHEME))
return self.GetDeveloperTags()
def GetDeveloperTags(self):
"""Retrieve developer tags for this video entry."""
developer_tags = []
for category in self.media.category:
if category.scheme == YOUTUBE_DEVELOPER_TAG_SCHEME:
developer_tags.append(category)
if len(developer_tags) > 0:
return developer_tags
def GetYouTubeCategoryAsString(self):
"""Convenience method to return the YouTube category as string.
YouTubeVideoEntries can contain multiple Category objects with differing
schemes. This method returns only the category with the correct
scheme, ignoring developer tags.
"""
for category in self.media.category:
if category.scheme != YOUTUBE_DEVELOPER_TAG_SCHEME:
return category.text
class YouTubeUserEntry(gdata.GDataEntry):
"""Represents a user on YouTube."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}username' % YOUTUBE_NAMESPACE] = ('username', Username)
_children['{%s}firstName' % YOUTUBE_NAMESPACE] = ('first_name', FirstName)
_children['{%s}lastName' % YOUTUBE_NAMESPACE] = ('last_name', LastName)
_children['{%s}age' % YOUTUBE_NAMESPACE] = ('age', Age)
_children['{%s}books' % YOUTUBE_NAMESPACE] = ('books', Books)
_children['{%s}gender' % YOUTUBE_NAMESPACE] = ('gender', Gender)
_children['{%s}company' % YOUTUBE_NAMESPACE] = ('company', Company)
_children['{%s}description' % YOUTUBE_NAMESPACE] = ('description',
Description)
_children['{%s}hobbies' % YOUTUBE_NAMESPACE] = ('hobbies', Hobbies)
_children['{%s}hometown' % YOUTUBE_NAMESPACE] = ('hometown', Hometown)
_children['{%s}location' % YOUTUBE_NAMESPACE] = ('location', Location)
_children['{%s}movies' % YOUTUBE_NAMESPACE] = ('movies', Movies)
_children['{%s}music' % YOUTUBE_NAMESPACE] = ('music', Music)
_children['{%s}occupation' % YOUTUBE_NAMESPACE] = ('occupation', Occupation)
_children['{%s}school' % YOUTUBE_NAMESPACE] = ('school', School)
_children['{%s}relationship' % YOUTUBE_NAMESPACE] = ('relationship',
Relationship)
_children['{%s}statistics' % YOUTUBE_NAMESPACE] = ('statistics', Statistics)
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
[gdata.FeedLink])
_children['{%s}thumbnail' % gdata.media.MEDIA_NAMESPACE] = ('thumbnail',
Media.Thumbnail)
def __init__(self, author=None, category=None, content=None, atom_id=None,
link=None, published=None, title=None, updated=None,
username=None, first_name=None, last_name=None, age=None,
books=None, gender=None, company=None, description=None,
hobbies=None, hometown=None, location=None, movies=None,
music=None, occupation=None, school=None, relationship=None,
statistics=None, feed_link=None, extension_elements=None,
extension_attributes=None, text=None):
self.username = username
self.first_name = first_name
self.last_name = last_name
self.age = age
self.books = books
self.gender = gender
self.company = company
self.description = description
self.hobbies = hobbies
self.hometown = hometown
self.location = location
self.movies = movies
self.music = music
self.occupation = occupation
self.school = school
self.relationship = relationship
self.statistics = statistics
self.feed_link = feed_link
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id,
link=link, published=published,
title=title, updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
class YouTubeVideoFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a video feed on YouTube."""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [YouTubeVideoEntry])
class YouTubePlaylistEntry(gdata.GDataEntry):
"""Represents a playlist in YouTube."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}description' % YOUTUBE_NAMESPACE] = ('description',
Description)
_children['{%s}private' % YOUTUBE_NAMESPACE] = ('private',
Private)
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
[gdata.FeedLink])
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None, title=None,
updated=None, private=None, feed_link=None,
description=None, extension_elements=None,
extension_attributes=None):
self.description = description
self.private = private
self.feed_link = feed_link
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id,
link=link, published=published, title=title,
updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
class YouTubePlaylistFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a feed of a user's playlists """
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[YouTubePlaylistEntry])
class YouTubePlaylistVideoFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a feed of video entry on a playlist."""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[YouTubePlaylistVideoEntry])
class YouTubeContactFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a feed of a users contacts."""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[YouTubeContactEntry])
class YouTubeSubscriptionFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a feed of a users subscriptions."""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[YouTubeSubscriptionEntry])
class YouTubeVideoCommentFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a feed of comments for a video."""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[YouTubeVideoCommentEntry])
class YouTubeVideoResponseFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a feed of video responses."""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[YouTubeVideoResponseEntry])
def YouTubeVideoFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoFeed, xml_string)
def YouTubeVideoEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoEntry, xml_string)
def YouTubeContactFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeContactFeed, xml_string)
def YouTubeContactEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeContactEntry, xml_string)
def YouTubeVideoCommentFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoCommentFeed, xml_string)
def YouTubeVideoCommentEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoCommentEntry, xml_string)
def YouTubeUserFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoFeed, xml_string)
def YouTubeUserEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeUserEntry, xml_string)
def YouTubePlaylistFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubePlaylistFeed, xml_string)
def YouTubePlaylistVideoFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubePlaylistVideoFeed, xml_string)
def YouTubePlaylistEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubePlaylistEntry, xml_string)
def YouTubePlaylistVideoEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubePlaylistVideoEntry, xml_string)
def YouTubeSubscriptionFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeSubscriptionFeed, xml_string)
def YouTubeSubscriptionEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeSubscriptionEntry, xml_string)
def YouTubeVideoResponseFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoResponseFeed, xml_string)
def YouTubeVideoResponseEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoResponseEntry, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Provides HttpRequest function for gdata.service to use on Google App Engine
HttpRequest: Function that wraps google.appengine.api.urlfetch.Fetch in a
common interface which is used by gdata.service.GDataService. In other
words, this module can be used as the gdata service request handler so
that all HTTP requests will be performed by the hosting Google App Engine
server.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
import StringIO
import atom.service
from google.appengine.api import urlfetch
def HttpRequest(service, operation, data, uri, extra_headers=None,
url_params=None, escape_params=True, content_type='application/atom+xml'):
"""Performs an HTTP call to the server, supports GET, POST, PUT, and DELETE.
To use this module with gdata.service, you can set this module to be the
http_request_handler so that HTTP requests use Google App Engine's urlfetch.
import gdata.service
import gdata.urlfetch
gdata.service.http_request_handler = gdata.urlfetch
Args:
service: atom.AtomService object which contains some of the parameters
needed to make the request. The following members are used to
construct the HTTP call: server (str), additional_headers (dict),
port (int), and ssl (bool).
operation: str The HTTP operation to be performed. This is usually one of
'GET', 'POST', 'PUT', or 'DELETE'
data: filestream, list of parts, or other object which can be
converted to a string.
Should be set to None when performing a GET or PUT.
If data is a file-like object which can be read, this method will read
a chunk of 100K bytes at a time and send them.
If the data is a list of parts to be sent, each part will be evaluated
and sent.
uri: The beginning of the URL to which the request should be sent.
Examples: '/', '/base/feeds/snippets',
'/m8/feeds/contacts/default/base'
extra_headers: dict of strings. HTTP headers which should be sent
in the request. These headers are in addition to those stored in
service.additional_headers.
url_params: dict of strings. Key value pairs to be added to the URL as
URL parameters. For example {'foo':'bar', 'test':'param'} will
become ?foo=bar&test=param.
escape_params: bool default True. If true, the keys and values in
url_params will be URL escaped when the form is constructed
(Special characters converted to %XX form.)
content_type: str The MIME type for the data being sent. Defaults to
'application/atom+xml', this is only used if data is set.
"""
full_uri = atom.service.BuildUri(uri, url_params, escape_params)
(server, port, ssl, partial_uri) = atom.service.ProcessUrl(service, full_uri)
# Construct the full URL for the request.
if ssl:
full_url = 'https://%s%s' % (server, partial_uri)
else:
full_url = 'http://%s%s' % (server, partial_uri)
# Construct the full payload.
# Assume that data is None or a string.
data_str = data
if data:
if isinstance(data, list):
# If data is a list of different objects, convert them all to strings
# and join them together.
converted_parts = [__ConvertDataPart(x) for x in data]
data_str = ''.join(converted_parts)
else:
data_str = __ConvertDataPart(data)
# Construct the dictionary of HTTP headers.
headers = {}
if isinstance(service.additional_headers, dict):
headers = service.additional_headers.copy()
if isinstance(extra_headers, dict):
for header, value in extra_headers.iteritems():
headers[header] = value
# Add the content type header (we don't need to calculate content length,
# since urlfetch.Fetch will calculate for us).
if content_type:
headers['Content-Type'] = content_type
# Lookup the urlfetch operation which corresponds to the desired HTTP verb.
if operation == 'GET':
method = urlfetch.GET
elif operation == 'POST':
method = urlfetch.POST
elif operation == 'PUT':
method = urlfetch.PUT
elif operation == 'DELETE':
method = urlfetch.DELETE
else:
method = None
return HttpResponse(urlfetch.Fetch(url=full_url, payload=data_str,
method=method, headers=headers))
def __ConvertDataPart(data):
if not data or isinstance(data, str):
return data
elif hasattr(data, 'read'):
# data is a file like object, so read it completely.
return data.read()
# The data object was not a file.
# Try to convert to a string and send the data.
return str(data)
class HttpResponse(object):
"""Translates a urlfetch resoinse to look like an hhtplib resoinse.
Used to allow the resoinse from HttpRequest to be usable by gdata.service
methods.
"""
def __init__(self, urlfetch_response):
self.body = StringIO.StringIO(urlfetch_response.content)
self.headers = urlfetch_response.headers
self.status = urlfetch_response.status_code
self.reason = ''
def read(self, length=None):
if not length:
return self.body.read()
else:
return self.body.read(length)
def getheader(self, name):
if not self.headers.has_key(name):
return self.headers[name.lower()]
return self.headers[name]
| Python |
#!/usr/bin/python
#
# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Provides HttpRequest function for gdata.service to use on Google App Engine
HttpRequest: Function that wraps google.appengine.api.urlfetch.Fetch in a
common interface which is used by gdata.service.GDataService. In other
words, this module can be used as the gdata service request handler so
that all HTTP requests will be performed by the hosting Google App Engine
server.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
import StringIO
import atom.service
from google.appengine.api import urlfetch
def HttpRequest(service, operation, data, uri, extra_headers=None,
url_params=None, escape_params=True, content_type='application/atom+xml'):
"""Performs an HTTP call to the server, supports GET, POST, PUT, and DELETE.
To use this module with gdata.service, you can set this module to be the
http_request_handler so that HTTP requests use Google App Engine's urlfetch.
import gdata.service
import gdata.urlfetch
gdata.service.http_request_handler = gdata.urlfetch
Args:
service: atom.AtomService object which contains some of the parameters
needed to make the request. The following members are used to
construct the HTTP call: server (str), additional_headers (dict),
port (int), and ssl (bool).
operation: str The HTTP operation to be performed. This is usually one of
'GET', 'POST', 'PUT', or 'DELETE'
data: filestream, list of parts, or other object which can be
converted to a string.
Should be set to None when performing a GET or PUT.
If data is a file-like object which can be read, this method will read
a chunk of 100K bytes at a time and send them.
If the data is a list of parts to be sent, each part will be evaluated
and sent.
uri: The beginning of the URL to which the request should be sent.
Examples: '/', '/base/feeds/snippets',
'/m8/feeds/contacts/default/base'
extra_headers: dict of strings. HTTP headers which should be sent
in the request. These headers are in addition to those stored in
service.additional_headers.
url_params: dict of strings. Key value pairs to be added to the URL as
URL parameters. For example {'foo':'bar', 'test':'param'} will
become ?foo=bar&test=param.
escape_params: bool default True. If true, the keys and values in
url_params will be URL escaped when the form is constructed
(Special characters converted to %XX form.)
content_type: str The MIME type for the data being sent. Defaults to
'application/atom+xml', this is only used if data is set.
"""
full_uri = atom.service.BuildUri(uri, url_params, escape_params)
(server, port, ssl, partial_uri) = atom.service.ProcessUrl(service, full_uri)
# Construct the full URL for the request.
if ssl:
full_url = 'https://%s%s' % (server, partial_uri)
else:
full_url = 'http://%s%s' % (server, partial_uri)
# Construct the full payload.
# Assume that data is None or a string.
data_str = data
if data:
if isinstance(data, list):
# If data is a list of different objects, convert them all to strings
# and join them together.
converted_parts = [__ConvertDataPart(x) for x in data]
data_str = ''.join(converted_parts)
else:
data_str = __ConvertDataPart(data)
# Construct the dictionary of HTTP headers.
headers = {}
if isinstance(service.additional_headers, dict):
headers = service.additional_headers.copy()
if isinstance(extra_headers, dict):
for header, value in extra_headers.iteritems():
headers[header] = value
# Add the content type header (we don't need to calculate content length,
# since urlfetch.Fetch will calculate for us).
if content_type:
headers['Content-Type'] = content_type
# Lookup the urlfetch operation which corresponds to the desired HTTP verb.
if operation == 'GET':
method = urlfetch.GET
elif operation == 'POST':
method = urlfetch.POST
elif operation == 'PUT':
method = urlfetch.PUT
elif operation == 'DELETE':
method = urlfetch.DELETE
else:
method = None
return HttpResponse(urlfetch.Fetch(url=full_url, payload=data_str,
method=method, headers=headers))
def __ConvertDataPart(data):
if not data or isinstance(data, str):
return data
elif hasattr(data, 'read'):
# data is a file like object, so read it completely.
return data.read()
# The data object was not a file.
# Try to convert to a string and send the data.
return str(data)
class HttpResponse(object):
"""Translates a urlfetch resoinse to look like an hhtplib resoinse.
Used to allow the resoinse from HttpRequest to be usable by gdata.service
methods.
"""
def __init__(self, urlfetch_response):
self.body = StringIO.StringIO(urlfetch_response.content)
self.headers = urlfetch_response.headers
self.status = urlfetch_response.status_code
self.reason = ''
def read(self, length=None):
if not length:
return self.body.read()
else:
return self.body.read(length)
def getheader(self, name):
if not self.headers.has_key(name):
return self.headers[name.lower()]
return self.headers[name]
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
XML_ENTRY_1 = """<?xml version='1.0'?>
<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:g='http://base.google.com/ns/1.0'>
<category scheme="http://base.google.com/categories/itemtypes"
term="products"/>
<id> http://www.google.com/test/id/url </id>
<title type='text'>Testing 2000 series laptop</title>
<content type='xhtml'>
<div xmlns='http://www.w3.org/1999/xhtml'>A Testing Laptop</div>
</content>
<link rel='alternate' type='text/html'
href='http://www.provider-host.com/123456789'/>
<link rel='license'
href='http://creativecommons.org/licenses/by-nc/2.5/rdf'/>
<g:label>Computer</g:label>
<g:label>Laptop</g:label>
<g:label>testing laptop</g:label>
<g:item_type>products</g:item_type>
</entry>"""
TEST_BASE_ENTRY = """<?xml version='1.0'?>
<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:g='http://base.google.com/ns/1.0'>
<category scheme="http://base.google.com/categories/itemtypes"
term="products"/>
<title type='text'>Testing 2000 series laptop</title>
<content type='xhtml'>
<div xmlns='http://www.w3.org/1999/xhtml'>A Testing Laptop</div>
</content>
<app:control xmlns:app='http://purl.org/atom/app#'>
<app:draft>yes</app:draft>
<gm:disapproved xmlns:gm='http://base.google.com/ns-metadata/1.0'/>
</app:control>
<link rel='alternate' type='text/html'
href='http://www.provider-host.com/123456789'/>
<g:label>Computer</g:label>
<g:label>Laptop</g:label>
<g:label>testing laptop</g:label>
<g:item_type>products</g:item_type>
</entry>"""
BIG_FEED = """<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title type="text">dive into mark</title>
<subtitle type="html">
A <em>lot</em> of effort
went into making this effortless
</subtitle>
<updated>2005-07-31T12:29:29Z</updated>
<id>tag:example.org,2003:3</id>
<link rel="alternate" type="text/html"
hreflang="en" href="http://example.org/"/>
<link rel="self" type="application/atom+xml"
href="http://example.org/feed.atom"/>
<rights>Copyright (c) 2003, Mark Pilgrim</rights>
<generator uri="http://www.example.com/" version="1.0">
Example Toolkit
</generator>
<entry>
<title>Atom draft-07 snapshot</title>
<link rel="alternate" type="text/html"
href="http://example.org/2005/04/02/atom"/>
<link rel="enclosure" type="audio/mpeg" length="1337"
href="http://example.org/audio/ph34r_my_podcast.mp3"/>
<id>tag:example.org,2003:3.2397</id>
<updated>2005-07-31T12:29:29Z</updated>
<published>2003-12-13T08:29:29-04:00</published>
<author>
<name>Mark Pilgrim</name>
<uri>http://example.org/</uri>
<email>f8dy@example.com</email>
</author>
<contributor>
<name>Sam Ruby</name>
</contributor>
<contributor>
<name>Joe Gregorio</name>
</contributor>
<content type="xhtml" xml:lang="en"
xml:base="http://diveintomark.org/">
<div xmlns="http://www.w3.org/1999/xhtml">
<p><i>[Update: The Atom draft is finished.]</i></p>
</div>
</content>
</entry>
</feed>
"""
SMALL_FEED = """<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Example Feed</title>
<link href="http://example.org/"/>
<updated>2003-12-13T18:30:02Z</updated>
<author>
<name>John Doe</name>
</author>
<id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
<entry>
<title>Atom-Powered Robots Run Amok</title>
<link href="http://example.org/2003/12/13/atom03"/>
<id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
<updated>2003-12-13T18:30:02Z</updated>
<summary>Some text.</summary>
</entry>
</feed>
"""
GBASE_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:g='http://base.google.com/ns/1.0' xmlns:batch='http://schemas.google.com/gdata/batch'>
<id>http://www.google.com/base/feeds/snippets</id>
<updated>2007-02-08T23:18:21.935Z</updated>
<title type='text'>Items matching query: digital camera</title>
<link rel='alternate' type='text/html' href='http://base.google.com'>
</link>
<link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://www.google.com/base/feeds/snippets'>
</link>
<link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/snippets?start-index=1&max-results=25&bq=digital+camera'>
</link>
<link rel='next' type='application/atom+xml' href='http://www.google.com/base/feeds/snippets?start-index=26&max-results=25&bq=digital+camera'>
</link>
<generator version='1.0' uri='http://base.google.com'>GoogleBase </generator>
<openSearch:totalResults>2171885</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>http://www.google.com/base/feeds/snippets/13246453826751927533</id>
<published>2007-02-08T13:23:27.000Z</published>
<updated>2007-02-08T16:40:57.000Z</updated>
<category scheme='http://base.google.com/categories/itemtypes' term='Products'>
</category>
<title type='text'>Digital Camera Battery Notebook Computer 12v DC Power Cable - 5.5mm x 2.5mm (Center +) Camera Connecting Cables</title>
<content type='html'>Notebook Computer 12v DC Power Cable - 5.5mm x 2.1mm (Center +) This connection cable will allow any Digital Pursuits battery pack to power portable computers that operate with 12v power and have a 2.1mm power connector (center +) Digital ...</content>
<link rel='alternate' type='text/html' href='http://www.bhphotovideo.com/bnh/controller/home?O=productlist&A=details&Q=&sku=305668&is=REG&kw=DIDCB5092&BI=583'>
</link>
<link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/snippets/13246453826751927533'>
</link>
<author>
<name>B&H Photo-Video</name>
<email>anon-szot0wdsq0at@base.google.com</email>
</author>
<g:payment_notes type='text'>PayPal & Bill Me Later credit available online only.</g:payment_notes>
<g:condition type='text'>new</g:condition>
<g:location type='location'>420 9th Ave. 10001</g:location>
<g:id type='text'>305668-REG</g:id>
<g:item_type type='text'>Products</g:item_type>
<g:brand type='text'>Digital Camera Battery</g:brand>
<g:expiration_date type='dateTime'>2007-03-10T13:23:27.000Z</g:expiration_date>
<g:customer_id type='int'>1172711</g:customer_id>
<g:price type='floatUnit'>34.95 usd</g:price>
<g:product_type type='text'>Digital Photography>Camera Connecting Cables</g:product_type>
<g:item_language type='text'>EN</g:item_language>
<g:manufacturer_id type='text'>DCB5092</g:manufacturer_id>
<g:target_country type='text'>US</g:target_country>
<g:weight type='float'>1.0</g:weight>
<g:image_link type='url'>http://base.google.com/base_image?q=http%3A%2F%2Fwww.bhphotovideo.com%2Fimages%2Fitems%2F305668.jpg&dhm=ffffffff84c9a95e&size=6</g:image_link>
</entry>
<entry>
<id>http://www.google.com/base/feeds/snippets/10145771037331858608</id>
<published>2007-02-08T13:23:27.000Z</published>
<updated>2007-02-08T16:40:57.000Z</updated>
<category scheme='http://base.google.com/categories/itemtypes' term='Products'>
</category>
<title type='text'>Digital Camera Battery Electronic Device 5v DC Power Cable - 5.5mm x 2.5mm (Center +) Camera Connecting Cables</title>
<content type='html'>Electronic Device 5v DC Power Cable - 5.5mm x 2.5mm (Center +) This connection cable will allow any Digital Pursuits battery pack to power any electronic device that operates with 5v power and has a 2.5mm power connector (center +) Digital ...</content>
<link rel='alternate' type='text/html' href='http://www.bhphotovideo.com/bnh/controller/home?O=productlist&A=details&Q=&sku=305656&is=REG&kw=DIDCB5108&BI=583'>
</link>
<link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/snippets/10145771037331858608'>
</link>
<author>
<name>B&H Photo-Video</name>
<email>anon-szot0wdsq0at@base.google.com</email>
</author>
<g:location type='location'>420 9th Ave. 10001</g:location>
<g:condition type='text'>new</g:condition>
<g:weight type='float'>0.18</g:weight>
<g:target_country type='text'>US</g:target_country>
<g:product_type type='text'>Digital Photography>Camera Connecting Cables</g:product_type>
<g:payment_notes type='text'>PayPal & Bill Me Later credit available online only.</g:payment_notes>
<g:id type='text'>305656-REG</g:id>
<g:image_link type='url'>http://base.google.com/base_image?q=http%3A%2F%2Fwww.bhphotovideo.com%2Fimages%2Fitems%2F305656.jpg&dhm=7315bdc8&size=6</g:image_link>
<g:manufacturer_id type='text'>DCB5108</g:manufacturer_id>
<g:upc type='text'>838098005108</g:upc>
<g:price type='floatUnit'>34.95 usd</g:price>
<g:item_language type='text'>EN</g:item_language>
<g:brand type='text'>Digital Camera Battery</g:brand>
<g:customer_id type='int'>1172711</g:customer_id>
<g:item_type type='text'>Products</g:item_type>
<g:expiration_date type='dateTime'>2007-03-10T13:23:27.000Z</g:expiration_date>
</entry>
<entry>
<id>http://www.google.com/base/feeds/snippets/3128608193804768644</id>
<published>2007-02-08T02:21:27.000Z</published>
<updated>2007-02-08T15:40:13.000Z</updated>
<category scheme='http://base.google.com/categories/itemtypes' term='Products'>
</category>
<title type='text'>Digital Camera Battery Power Cable for Kodak 645 Pro-Back ProBack & DCS-300 Series Camera Connecting Cables</title>
<content type='html'>Camera Connection Cable - to Power Kodak 645 Pro-Back DCS-300 Series Digital Cameras This connection cable will allow any Digital Pursuits battery pack to power the following digital cameras: Kodak DCS Pro Back 645 DCS-300 series Digital Photography ...</content>
<link rel='alternate' type='text/html' href='http://www.bhphotovideo.com/bnh/controller/home?O=productlist&A=details&Q=&sku=305685&is=REG&kw=DIDCB6006&BI=583'>
</link>
<link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/snippets/3128608193804768644'>
</link>
<author>
<name>B&H Photo-Video</name>
<email>anon-szot0wdsq0at@base.google.com</email>
</author>
<g:weight type='float'>0.3</g:weight>
<g:manufacturer_id type='text'>DCB6006</g:manufacturer_id>
<g:image_link type='url'>http://base.google.com/base_image?q=http%3A%2F%2Fwww.bhphotovideo.com%2Fimages%2Fitems%2F305685.jpg&dhm=72f0ca0a&size=6</g:image_link>
<g:location type='location'>420 9th Ave. 10001</g:location>
<g:payment_notes type='text'>PayPal & Bill Me Later credit available online only.</g:payment_notes>
<g:item_type type='text'>Products</g:item_type>
<g:target_country type='text'>US</g:target_country>
<g:accessory_for type='text'>digital kodak camera</g:accessory_for>
<g:brand type='text'>Digital Camera Battery</g:brand>
<g:expiration_date type='dateTime'>2007-03-10T02:21:27.000Z</g:expiration_date>
<g:item_language type='text'>EN</g:item_language>
<g:condition type='text'>new</g:condition>
<g:price type='floatUnit'>34.95 usd</g:price>
<g:customer_id type='int'>1172711</g:customer_id>
<g:product_type type='text'>Digital Photography>Camera Connecting Cables</g:product_type>
<g:id type='text'>305685-REG</g:id>
</entry>
</feed>"""
EXTENSION_TREE = """<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<g:author xmlns:g="http://www.google.com">
<g:name>John Doe
<g:foo yes="no" up="down">Bar</g:foo>
</g:name>
</g:author>
</feed>
"""
TEST_AUTHOR = """<?xml version="1.0" encoding="utf-8"?>
<author xmlns="http://www.w3.org/2005/Atom">
<name xmlns="http://www.w3.org/2005/Atom">John Doe</name>
<email xmlns="http://www.w3.org/2005/Atom">johndoes@someemailadress.com</email>
<uri xmlns="http://www.w3.org/2005/Atom">http://www.google.com</uri>
</author>
"""
TEST_LINK = """<?xml version="1.0" encoding="utf-8"?>
<link xmlns="http://www.w3.org/2005/Atom" href="http://www.google.com"
rel="test rel" foo1="bar" foo2="rab"/>
"""
TEST_GBASE_ATTRIBUTE = """<?xml version="1.0" encoding="utf-8"?>
<g:brand type='text' xmlns:g="http://base.google.com/ns/1.0">Digital Camera Battery</g:brand>
"""
CALENDAR_FEED = """<?xml version='1.0' encoding='utf-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:gd='http://schemas.google.com/g/2005'
xmlns:gCal='http://schemas.google.com/gCal/2005'>
<id>http://www.google.com/calendar/feeds/default</id>
<updated>2007-03-20T22:48:57.833Z</updated>
<title type='text'>GData Ops Demo's Calendar List</title>
<link rel='http://schemas.google.com/g/2005#feed'
type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default'></link>
<link rel='http://schemas.google.com/g/2005#post'
type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default'></link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<generator version='1.0' uri='http://www.google.com/calendar'>
Google Calendar</generator>
<openSearch:startIndex>1</openSearch:startIndex>
<entry>
<id>
http://www.google.com/calendar/feeds/default/gdata.ops.demo%40gmail.com</id>
<published>2007-03-20T22:48:57.837Z</published>
<updated>2007-03-20T22:48:52.000Z</updated>
<title type='text'>GData Ops Demo</title>
<link rel='alternate' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/gdata.ops.demo%40gmail.com/private/full'>
</link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/gdata.ops.demo%40gmail.com'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:color value='#2952A3'></gCal:color>
<gCal:accesslevel value='owner'></gCal:accesslevel>
<gCal:hidden value='false'></gCal:hidden>
<gCal:timezone value='America/Los_Angeles'></gCal:timezone>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/jnh21ovnjgfph21h32gvms2758%40group.calendar.google.com</id>
<published>2007-03-20T22:48:57.837Z</published>
<updated>2007-03-20T22:48:53.000Z</updated>
<title type='text'>GData Ops Demo Secondary Calendar</title>
<summary type='text'></summary>
<link rel='alternate' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/jnh21ovnjgfph21h32gvms2758%40group.calendar.google.com/private/full'>
</link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/jnh21ovnjgfph21h32gvms2758%40group.calendar.google.com'>
</link>
<author>
<name>GData Ops Demo Secondary Calendar</name>
</author>
<gCal:color value='#528800'></gCal:color>
<gCal:accesslevel value='owner'></gCal:accesslevel>
<gCal:hidden value='false'></gCal:hidden>
<gCal:timezone value='America/Los_Angeles'></gCal:timezone>
<gd:where valueString=''></gd:where>
</entry>
</feed>
"""
CALENDAR_FULL_EVENT_FEED = """<?xml version='1.0' encoding='utf-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:gd='http://schemas.google.com/g/2005'
xmlns:gCal='http://schemas.google.com/gCal/2005'>
<id>
http://www.google.com/calendar/feeds/default/private/full</id>
<updated>2007-03-20T21:29:57.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>GData Ops Demo</title>
<subtitle type='text'>GData Ops Demo</subtitle>
<link rel='http://schemas.google.com/g/2005#feed'
type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full'>
</link>
<link rel='http://schemas.google.com/g/2005#post'
type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full'>
</link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full?updated-min=2001-01-01&max-results=25'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<generator version='1.0' uri='http://www.google.com/calendar'>
Google Calendar</generator>
<openSearch:totalResults>10</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<gCal:timezone value='America/Los_Angeles'></gCal:timezone>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/o99flmgmkfkfrr8u745ghr3100</id>
<published>2007-03-20T21:29:52.000Z</published>
<updated>2007-03-20T21:29:57.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>test deleted</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=bzk5ZmxtZ21rZmtmcnI4dTc0NWdocjMxMDAgZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/o99flmgmkfkfrr8u745ghr3100'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/o99flmgmkfkfrr8u745ghr3100/63310109397'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.canceled'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/o99flmgmkfkfrr8u745ghr3100/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:when startTime='2007-03-23T12:00:00.000-07:00'
endTime='2007-03-23T13:00:00.000-07:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/2qt3ao5hbaq7m9igr5ak9esjo0</id>
<published>2007-03-20T21:26:04.000Z</published>
<updated>2007-03-20T21:28:46.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>Afternoon at Dolores Park with Kim</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=MnF0M2FvNWhiYXE3bTlpZ3I1YWs5ZXNqbzAgZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/2qt3ao5hbaq7m9igr5ak9esjo0'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/2qt3ao5hbaq7m9igr5ak9esjo0/63310109326'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/2qt3ao5hbaq7m9igr5ak9esjo0/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.private'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:who rel='http://schemas.google.com/g/2005#event.organizer'
valueString='GData Ops Demo' email='gdata.ops.demo@gmail.com'>
<gd:attendeeStatus value='http://schemas.google.com/g/2005#event.accepted'>
</gd:attendeeStatus>
</gd:who>
<gd:who rel='http://schemas.google.com/g/2005#event.attendee'
valueString='Ryan Boyd (API)' email='api.rboyd@gmail.com'>
<gd:attendeeStatus value='http://schemas.google.com/g/2005#event.invited'>
</gd:attendeeStatus>
</gd:who>
<gd:when startTime='2007-03-24T12:00:00.000-07:00'
endTime='2007-03-24T15:00:00.000-07:00'>
<gd:reminder minutes='20'></gd:reminder>
</gd:when>
<gd:where valueString='Dolores Park with Kim'></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/uvsqhg7klnae40v50vihr1pvos</id>
<published>2007-03-20T21:28:37.000Z</published>
<updated>2007-03-20T21:28:37.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>Team meeting</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=dXZzcWhnN2tsbmFlNDB2NTB2aWhyMXB2b3NfMjAwNzAzMjNUMTYwMDAwWiBnZGF0YS5vcHMuZGVtb0Bt'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/uvsqhg7klnae40v50vihr1pvos'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/uvsqhg7klnae40v50vihr1pvos/63310109317'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gd:recurrence>DTSTART;TZID=America/Los_Angeles:20070323T090000
DTEND;TZID=America/Los_Angeles:20070323T100000
RRULE:FREQ=WEEKLY;BYDAY=FR;UNTIL=20070817T160000Z;WKST=SU
BEGIN:VTIMEZONE TZID:America/Los_Angeles
X-LIC-LOCATION:America/Los_Angeles BEGIN:STANDARD
TZOFFSETFROM:-0700 TZOFFSETTO:-0800 TZNAME:PST
DTSTART:19701025T020000 RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
END:STANDARD BEGIN:DAYLIGHT TZOFFSETFROM:-0800 TZOFFSETTO:-0700
TZNAME:PDT DTSTART:19700405T020000
RRULE:FREQ=YEARLY;BYMONTH=4;BYDAY=1SU END:DAYLIGHT
END:VTIMEZONE</gd:recurrence>
<gCal:sendEventNotifications value='true'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:visibility value='http://schemas.google.com/g/2005#event.public'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:reminder minutes='10'></gd:reminder>
<gd:where valueString=''></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/st4vk9kiffs6rasrl32e4a7alo</id>
<published>2007-03-20T21:25:46.000Z</published>
<updated>2007-03-20T21:25:46.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>Movie with Kim and danah</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=c3Q0dms5a2lmZnM2cmFzcmwzMmU0YTdhbG8gZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/st4vk9kiffs6rasrl32e4a7alo'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/st4vk9kiffs6rasrl32e4a7alo/63310109146'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/st4vk9kiffs6rasrl32e4a7alo/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:when startTime='2007-03-24T20:00:00.000-07:00'
endTime='2007-03-24T21:00:00.000-07:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/ofl1e45ubtsoh6gtu127cls2oo</id>
<published>2007-03-20T21:24:43.000Z</published>
<updated>2007-03-20T21:25:08.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>Dinner with Kim and Sarah</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=b2ZsMWU0NXVidHNvaDZndHUxMjdjbHMyb28gZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/ofl1e45ubtsoh6gtu127cls2oo'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/ofl1e45ubtsoh6gtu127cls2oo/63310109108'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/ofl1e45ubtsoh6gtu127cls2oo/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:when startTime='2007-03-20T19:00:00.000-07:00'
endTime='2007-03-20T21:30:00.000-07:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/b69s2avfi2joigsclecvjlc91g</id>
<published>2007-03-20T21:24:19.000Z</published>
<updated>2007-03-20T21:25:05.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>Dinner with Jane and John</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=YjY5czJhdmZpMmpvaWdzY2xlY3ZqbGM5MWcgZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/b69s2avfi2joigsclecvjlc91g'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/b69s2avfi2joigsclecvjlc91g/63310109105'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/b69s2avfi2joigsclecvjlc91g/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:when startTime='2007-03-22T17:00:00.000-07:00'
endTime='2007-03-22T19:30:00.000-07:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/u9p66kkiotn8bqh9k7j4rcnjjc</id>
<published>2007-03-20T21:24:33.000Z</published>
<updated>2007-03-20T21:24:33.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>Tennis with Elizabeth</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=dTlwNjZra2lvdG44YnFoOWs3ajRyY25qamMgZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/u9p66kkiotn8bqh9k7j4rcnjjc'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/u9p66kkiotn8bqh9k7j4rcnjjc/63310109073'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/u9p66kkiotn8bqh9k7j4rcnjjc/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:when startTime='2007-03-24T10:00:00.000-07:00'
endTime='2007-03-24T11:00:00.000-07:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/76oj2kceidob3s708tvfnuaq3c</id>
<published>2007-03-20T21:24:00.000Z</published>
<updated>2007-03-20T21:24:00.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>Lunch with Jenn</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=NzZvajJrY2VpZG9iM3M3MDh0dmZudWFxM2MgZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/76oj2kceidob3s708tvfnuaq3c'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/76oj2kceidob3s708tvfnuaq3c/63310109040'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/76oj2kceidob3s708tvfnuaq3c/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:when startTime='2007-03-20T11:30:00.000-07:00'
endTime='2007-03-20T12:30:00.000-07:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/5np9ec8m7uoauk1vedh5mhodco</id>
<published>2007-03-20T07:50:02.000Z</published>
<updated>2007-03-20T20:39:26.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>test entry</title>
<content type='text'>test desc</content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=NW5wOWVjOG03dW9hdWsxdmVkaDVtaG9kY28gZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/5np9ec8m7uoauk1vedh5mhodco'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/5np9ec8m7uoauk1vedh5mhodco/63310106366'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/5np9ec8m7uoauk1vedh5mhodco/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.private'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:who rel='http://schemas.google.com/g/2005#event.attendee'
valueString='Vivian Li' email='vli@google.com'>
<gd:attendeeStatus value='http://schemas.google.com/g/2005#event.declined'>
</gd:attendeeStatus>
</gd:who>
<gd:who rel='http://schemas.google.com/g/2005#event.organizer'
valueString='GData Ops Demo' email='gdata.ops.demo@gmail.com'>
<gd:attendeeStatus value='http://schemas.google.com/g/2005#event.accepted'>
</gd:attendeeStatus>
</gd:who>
<gd:when startTime='2007-03-21T08:00:00.000-07:00'
endTime='2007-03-21T09:00:00.000-07:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where valueString='anywhere'></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/fu6sl0rqakf3o0a13oo1i1a1mg</id>
<published>2007-02-14T23:23:37.000Z</published>
<updated>2007-02-14T23:25:30.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>test</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=ZnU2c2wwcnFha2YzbzBhMTNvbzFpMWExbWcgZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/fu6sl0rqakf3o0a13oo1i1a1mg'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/fu6sl0rqakf3o0a13oo1i1a1mg/63307178730'>
</link>
<link rel="http://schemas.google.com/gCal/2005/webContent" title="World Cup" href="http://www.google.com/calendar/images/google-holiday.gif" type="image/gif">
<gCal:webContent width="276" height="120" url="http://www.google.com/logos/worldcup06.gif" />
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/fu6sl0rqakf3o0a13oo1i1a1mg/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:when startTime='2007-02-15T08:30:00.000-08:00'
endTime='2007-02-15T09:30:00.000-08:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/h7a0haa4da8sil3rr19ia6luvc</id>
<published>2007-07-16T22:13:28.000Z</published>
<updated>2007-07-16T22:13:29.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event' />
<title type='text'></title>
<content type='text' />
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=aDdhMGhhYTRkYThzaWwzcnIxOWlhNmx1dmMgZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate' />
<link rel='http://schemas.google.com/gCal/2005/webContent'
type='application/x-google-gadgets+xml'
href='http://gdata.ops.demo.googlepages.com/birthdayicon.gif'
title='Date and Time Gadget'>
<gCal:webContent width='300' height='136'
url='http://google.com/ig/modules/datetime.xml'>
<gCal:webContentGadgetPref name='color' value='green' />
</gCal:webContent>
</link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/h7a0haa4da8sil3rr19ia6luvc' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/h7a0haa4da8sil3rr19ia6luvc/63320307209' />
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/h7a0haa4da8sil3rr19ia6luvc/comments' />
</gd:comments>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed' />
<gd:visibility value='http://schemas.google.com/g/2005#event.default' />
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque' />
<gd:when startTime='2007-03-14' endTime='2007-03-15' />
<gd:where />
</entry>
</feed>
"""
CALENDAR_BATCH_REQUEST = """<?xml version='1.0' encoding='utf-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:batch='http://schemas.google.com/gdata/batch'
xmlns:gCal='http://schemas.google.com/gCal/2005'>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<entry>
<batch:id>1</batch:id>
<batch:operation type='insert' />
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<title type='text'>Event inserted via batch</title>
</entry>
<entry>
<batch:id>2</batch:id>
<batch:operation type='query' />
<id>http://www.google.com/calendar/feeds/default/private/full/glcs0kv2qqa0gf52qi1jo018gc</id>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<title type='text'>Event queried via batch</title>
</entry>
<entry>
<batch:id>3</batch:id>
<batch:operation type='update' />
<id>http://www.google.com/calendar/feeds/default/private/full/ujm0go5dtngdkr6u91dcqvj0qs</id>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<title type='text'>Event updated via batch</title>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=dWptMGdvNWR0bmdka3I2dTkxZGNxdmowcXMgaGFyaXNodi50ZXN0QG0' title='alternate' />
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/ujm0go5dtngdkr6u91dcqvj0qs' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/ujm0go5dtngdkr6u91dcqvj0qs/63326098791' />
</entry>
<entry>
<batch:id>4</batch:id>
<batch:operation type='delete' />
<id>http://www.google.com/calendar/feeds/default/private/full/d8qbg9egk1n6lhsgq1sjbqffqc</id>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<title type='text'>Event deleted via batch</title>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=ZDhxYmc5ZWdrMW42bGhzZ3Exc2picWZmcWMgaGFyaXNodi50ZXN0QG0' title='alternate' />
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/d8qbg9egk1n6lhsgq1sjbqffqc' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/d8qbg9egk1n6lhsgq1sjbqffqc/63326018324' />
</entry>
</feed>
"""
CALENDAR_BATCH_RESPONSE = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:batch='http://schemas.google.com/gdata/batch'
xmlns:gCal='http://schemas.google.com/gCal/2005'>
<id>http://www.google.com/calendar/feeds/default/private/full</id>
<updated>2007-09-21T23:01:00.380Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>Batch Feed</title>
<link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full' />
<link rel='http://schemas.google.com/g/2005#post' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full' />
<link rel='http://schemas.google.com/g/2005#batch' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/batch' />
<entry>
<batch:id>1</batch:id>
<batch:status code='201' reason='Created' />
<batch:operation type='insert' />
<id>http://www.google.com/calendar/feeds/default/private/full/n9ug78gd9tv53ppn4hdjvk68ek</id>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<title type='text'>Event inserted via batch</title>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=bjl1Zzc4Z2Q5dHY1M3BwbjRoZGp2azY4ZWsgaGFyaXNodi50ZXN0QG0' title='alternate' />
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/n9ug78gd9tv53ppn4hdjvk68ek' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/n9ug78gd9tv53ppn4hdjvk68ek/63326098860' />
</entry>
<entry>
<batch:id>2</batch:id>
<batch:status code='200' reason='Success' />
<batch:operation type='query' />
<id>http://www.google.com/calendar/feeds/default/private/full/glsc0kv2aqa0ff52qi1jo018gc</id>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<title type='text'>Event queried via batch</title>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=Z2xzYzBrdjJhcWEwZmY1MnFpMWpvMDE4Z2MgaGFyaXNodi50ZXN0QG0' title='alternate' />
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/glsc0kv2aqa0ff52qi1jo018gc' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/glsc0kv2aqa0ff52qi1jo018gc/63326098791' />
</entry>
<entry xmlns:gCal='http://schemas.google.com/gCal/2005'>
<batch:id>3</batch:id>
<batch:status code='200' reason='Success' />
<batch:operation type='update' />
<id>http://www.google.com/calendar/feeds/default/private/full/ujm0go5dtngdkr6u91dcqvj0qs</id>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<title type='text'>Event updated via batch</title>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=dWptMGdvNWR0bmdka3I2dTkxZGNxdmowcXMgaGFyaXNodi50ZXN0QG0' title='alternate' />
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/ujm0go5dtngdkr6u91dcqvj0qs' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/ujm0go5dtngdkr6u91dcqvj0qs/63326098860' />
<batch:id>3</batch:id>
<batch:status code='200' reason='Success' />
<batch:operation type='update' />
</entry>
<entry>
<batch:id>4</batch:id>
<batch:status code='200' reason='Success' />
<batch:operation type='delete' />
<id>http://www.google.com/calendar/feeds/default/private/full/d8qbg9egk1n6lhsgq1sjbqffqc</id>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<title type='text'>Event deleted via batch</title>
<content type='text'>Deleted</content>
</entry>
</feed>
"""
GBASE_ATTRIBUTE_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gm='http://base.google.com/ns-metadata/1.0'>
<id>http://www.google.com/base/feeds/attributes</id>
<updated>2006-11-01T20:35:59.578Z</updated>
<category scheme='http://base.google.com/categories/itemtypes' term='online jobs'></category>
<category scheme='http://base.google.com/categories/itemtypes' term='jobs'></category>
<title type='text'>Attribute histogram for query: [item type:jobs]</title>
<link rel='alternate' type='text/html' href='http://base.google.com'></link>
<link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://www.google.com/base/feeds
/attributes'></link>
<link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/attributes/-/jobs'></link>
<generator version='1.0' uri='http://base.google.com'>GoogleBase</generator>
<openSearch:totalResults>16</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>16</openSearch:itemsPerPage>
<entry>
<id>http://www.google.com/base/feeds/attributes/job+industry%28text%29N%5Bitem+type%3Ajobs%5D</id>
<updated>2006-11-01T20:36:00.100Z</updated>
<title type='text'>job industry(text)</title>
<content type='text'>Attribute"job industry" of type text.
</content>
<link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/attributes/job+industry%28text
%29N%5Bitem+type%3Ajobs%5D'></link>
<gm:attribute name='job industry' type='text' count='4416629'>
<gm:value count='380772'>it internet</gm:value>
<gm:value count='261565'>healthcare</gm:value>
<gm:value count='142018'>information technology</gm:value>
<gm:value count='124622'>accounting</gm:value>
<gm:value count='111311'>clerical and administrative</gm:value>
<gm:value count='82928'>other</gm:value>
<gm:value count='77620'>sales and sales management</gm:value>
<gm:value count='68764'>information systems</gm:value>
<gm:value count='65859'>engineering and architecture</gm:value>
<gm:value count='64757'>sales</gm:value>
</gm:attribute>
</entry>
</feed>
"""
GBASE_ATTRIBUTE_ENTRY = """<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gm='http://base.google.com/ns-metadata/1.0'>
<id>http://www.google.com/base/feeds/attributes/job+industry%28text%29N%5Bitem+type%3Ajobs%5D</id>
<updated>2006-11-01T20:36:00.100Z</updated>
<title type='text'>job industry(text)</title>
<content type='text'>Attribute"job industry" of type text.
</content>
<link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/attributes/job+industry%28text%29N%5Bitem+type%3Ajobs%5D'></link>
<gm:attribute name='job industry' type='text' count='4416629'>
<gm:value count='380772'>it internet</gm:value>
<gm:value count='261565'>healthcare</gm:value>
<gm:value count='142018'>information technology</gm:value>
<gm:value count='124622'>accounting</gm:value>
<gm:value count='111311'>clerical and administrative</gm:value>
<gm:value count='82928'>other</gm:value>
<gm:value count='77620'>sales and sales management</gm:value>
<gm:value count='68764'>information systems</gm:value>
<gm:value count='65859'>engineering and architecture</gm:value>
<gm:value count='64757'>sales</gm:value>
</gm:attribute>
</entry>
"""
GBASE_LOCALES_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:gm='http://base.google.com/ns-metadata/1.0'>
<id> http://www.google.com/base/feeds/locales/</id>
<updated>2006-06-13T18:11:40.120Z</updated>
<title type="text">Locales</title>
<link rel="alternate" type="text/html" href="http://base.google.com"/>
<link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"
href="http://www.google.com/base/feeds/locales/"/>
<link rel="self" type="application/atom+xml" href="http://www.google.com/base/feeds/locales/"/>
<author>
<name>Google Inc.</name>
<email>base@google.com</email>
</author>
<generator version="1.0" uri="http://base.google.com">GoogleBase</generator>
<openSearch:totalResults>3</openSearch:totalResults>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>http://www.google.com/base/feeds/locales/en_US</id>
<updated>2006-03-27T22:27:36.658Z</updated>
<category scheme="http://base.google.com/categories/locales" term="en_US"/>
<title type="text">en_US</title>
<content type="text">en_US</content>
<link rel="self" type="application/atom+xml"
href="http://www.google.com/base/feeds/locales/en_US"></link>
<link rel="related" type="application/atom+xml"
href="http://www.google.com/base/feeds/itemtypes/en_US" title="Item types in en_US"/>
</entry>
<entry>
<id>http://www.google.com/base/feeds/locales/en_GB</id>
<updated>2006-06-13T18:14:18.601Z</updated>
<category scheme="http://base.google.com/categories/locales" term="en_GB"/>
<title type="text">en_GB</title>
<content type="text">en_GB</content>
<link rel="related" type="application/atom+xml"
href="http://www.google.com/base/feeds/itemtypes/en_GB" title="Item types in en_GB"/>
<link rel="self" type="application/atom+xml"
href="http://www.google.com/base/feeds/locales/en_GB"/>
</entry>
<entry>
<id>http://www.google.com/base/feeds/locales/de_DE</id>
<updated>2006-06-13T18:14:18.601Z</updated>
<category scheme="http://base.google.com/categories/locales" term="de_DE"/>
<title type="text">de_DE</title>
<content type="text">de_DE</content>
<link rel="related" type="application/atom+xml"
href="http://www.google.com/base/feeds/itemtypes/de_DE" title="Item types in de_DE"/>
<link rel="self" type="application/atom+xml"
href="http://www.google.com/base/feeds/locales/de_DE"/>
</entry>
</feed>"""
GBASE_STRING_ENCODING_ENTRY = """<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns='http://www.w3.org/2005/Atom' xmlns:gm='http://base.google.com/ns-metadata/1.0'
xmlns:g='http://base.google.com/ns/1.0' xmlns:batch='http://schemas.google.com/gdata/batch'>
<id>http://www.google.com/base/feeds/snippets/17495780256183230088</id>
<published>2007-12-09T03:13:07.000Z</published>
<updated>2008-01-07T03:26:46.000Z</updated>
<category scheme='http://base.google.com/categories/itemtypes' term='Products'/>
<title type='text'>Digital Camera Cord Fits SONY Cybershot DSC-R1 S40</title>
<content type='html'>SONY \xC2\xB7 Cybershot Digital Camera Usb Cable DESCRIPTION
This is a 2.5 USB 2.0 A to Mini B (5 Pin) high quality digital camera
cable used for connecting your Sony Digital Cameras and Camcoders. Backward
Compatible with USB 2.0, 1.0 and 1.1. Fully ...</content>
<link rel='alternate' type='text/html'
href='http://adfarm.mediaplex.com/ad/ck/711-5256-8196-2?loc=http%3A%2F%2Fcgi.ebay.com%2FDigital-Camera-Cord-Fits-SONY-Cybershot-DSC-R1-S40_W0QQitemZ270195049057QQcmdZViewItem'/>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/base/feeds/snippets/17495780256183230088'/>
<author>
<name>eBay</name>
</author>
<g:item_type type='text'>Products</g:item_type>
<g:item_language type='text'>EN</g:item_language>
<g:target_country type='text'>US</g:target_country>
<g:price type='floatUnit'>0.99 usd</g:price>
<g:image_link type='url'>http://thumbs.ebaystatic.com/pict/270195049057_1.jpg</g:image_link>
<g:category type='text'>Cameras & Photo>Digital Camera Accessories>Cables</g:category>
<g:category type='text'>Cords & Connectors>USB Cables>For Other Brands</g:category>
<g:customer_id type='int'>11729</g:customer_id>
<g:id type='text'>270195049057</g:id>
<g:expiration_date type='dateTime'>2008-02-06T03:26:46Z</g:expiration_date>
</entry>"""
RECURRENCE_EXCEPTION_ENTRY = """<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:gd='http://schemas.google.com/g/2005'
xmlns:gCal='http://schemas.google.com/gCal/2005'>
<id>
http://www.google.com/calendar/feeds/default/private/composite/i7lgfj69mjqjgnodklif3vbm7g</id>
<published>2007-04-05T21:51:49.000Z</published>
<updated>2007-04-05T21:51:49.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>testDavid</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=aTdsZ2ZqNjltanFqZ25vZGtsaWYzdmJtN2dfMjAwNzA0MDNUMTgwMDAwWiBnZGF0YS5vcHMudGVzdEBt'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/composite/i7lgfj69mjqjgnodklif3vbm7g'>
</link>
<author>
<name>gdata ops</name>
<email>gdata.ops.test@gmail.com</email>
</author>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gCal:sendEventNotifications value='true'>
</gCal:sendEventNotifications>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:recurrence>DTSTART;TZID=America/Anchorage:20070403T100000
DTEND;TZID=America/Anchorage:20070403T110000
RRULE:FREQ=DAILY;UNTIL=20070408T180000Z;WKST=SU
EXDATE;TZID=America/Anchorage:20070407T100000
EXDATE;TZID=America/Anchorage:20070405T100000
EXDATE;TZID=America/Anchorage:20070404T100000 BEGIN:VTIMEZONE
TZID:America/Anchorage X-LIC-LOCATION:America/Anchorage
BEGIN:STANDARD TZOFFSETFROM:-0800 TZOFFSETTO:-0900 TZNAME:AKST
DTSTART:19701025T020000 RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
END:STANDARD BEGIN:DAYLIGHT TZOFFSETFROM:-0900 TZOFFSETTO:-0800
TZNAME:AKDT DTSTART:19700405T020000
RRULE:FREQ=YEARLY;BYMONTH=4;BYDAY=1SU END:DAYLIGHT
END:VTIMEZONE</gd:recurrence>
<gd:where valueString=''></gd:where>
<gd:reminder minutes='10'></gd:reminder>
<gd:recurrenceException specialized='true'>
<gd:entryLink>
<entry>
<id>i7lgfj69mjqjgnodklif3vbm7g_20070407T180000Z</id>
<published>2007-04-05T21:51:49.000Z</published>
<updated>2007-04-05T21:52:58.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>testDavid</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=aTdsZ2ZqNjltanFqZ25vZGtsaWYzdmJtN2dfMjAwNzA0MDdUMTgwMDAwWiBnZGF0YS5vcHMudGVzdEBt'
title='alternate'></link>
<author>
<name>gdata ops</name>
<email>gdata.ops.test@gmail.com</email>
</author>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gd:originalEvent id='i7lgfj69mjqjgnodklif3vbm7g'
href='http://www.google.com/calendar/feeds/default/private/composite/i7lgfj69mjqjgnodklif3vbm7g'>
<gd:when startTime='2007-04-07T13:00:00.000-05:00'>
</gd:when>
</gd:originalEvent>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.canceled'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/i7lgfj69mjqjgnodklif3vbm7g_20070407T180000Z/comments'>
<feed>
<updated>2007-04-05T21:54:09.285Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#message'>
</category>
<title type='text'>Comments for: testDavid</title>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/feeds/default/private/full/i7lgfj69mjqjgnodklif3vbm7g_20070407T180000Z/comments'
title='alternate'></link>
</feed>
</gd:feedLink>
</gd:comments>
<gd:when startTime='2007-04-07T13:00:00.000-05:00'
endTime='2007-04-07T14:00:00.000-05:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where valueString=''></gd:where>
</entry>
</gd:entryLink>
</gd:recurrenceException>
</entry>"""
NICK_ENTRY = """<?xml version="1.0" encoding="UTF-8"?>
<atom:entry xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:apps="http://schemas.google.com/apps/2006"
xmlns:gd="http://schemas.google.com/g/2005">
<atom:id>https://www.google.com/a/feeds/example.com/nickname/2.0/Foo</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#nickname'/>
<atom:title type="text">Foo</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="https://www.google.com/a/feeds/example.com/nickname/2.0/Foo"/>
<atom:link rel="edit" type="application/atom+xml"
href="https://www.google.com/a/feeds/example.com/nickname/2.0/Foo"/>
<apps:nickname name="Foo"/>
<apps:login userName="TestUser"/>
</atom:entry>"""
NICK_FEED = """<?xml version="1.0" encoding="UTF-8"?>
<atom:feed xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:apps="http://schemas.google.com/apps/2006">
<atom:id>
http://www.google.com/a/feeds/example.com/nickname/2.0
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#nickname'/>
<atom:title type="text">Nicknames for user SusanJones</atom:title>
<atom:link rel='http://schemas.google.com/g/2005#feed'
type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/nickname/2.0"/>
<atom:link rel='http://schemas.google.com/g/2005#post'
type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/nickname/2.0"/>
<atom:link rel="self" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/nickname/2.0?username=TestUser"/>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>2</openSearch:itemsPerPage>
<atom:entry>
<atom:id>
http://www.google.com/a/feeds/example.com/nickname/2.0/Foo
</atom:id>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#nickname'/>
<atom:title type="text">Foo</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/nickname/2.0/Foo"/>
<atom:link rel="edit" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/nickname/2.0/Foo"/>
<apps:nickname name="Foo"/>
<apps:login userName="TestUser"/>
</atom:entry>
<atom:entry>
<atom:id>
http://www.google.com/a/feeds/example.com/nickname/2.0/suse
</atom:id>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#nickname'/>
<atom:title type="text">suse</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/nickname/2.0/Bar"/>
<atom:link rel="edit" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/nickname/2.0/Bar"/>
<apps:nickname name="Bar"/>
<apps:login userName="TestUser"/>
</atom:entry>
</atom:feed>"""
USER_ENTRY = """<?xml version="1.0" encoding="UTF-8"?>
<atom:entry xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:apps="http://schemas.google.com/apps/2006"
xmlns:gd="http://schemas.google.com/g/2005">
<atom:id>https://www.google.com/a/feeds/example.com/user/2.0/TestUser</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#user'/>
<atom:title type="text">TestUser</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="https://www.google.com/a/feeds/example.com/user/2.0/TestUser"/>
<atom:link rel="edit" type="application/atom+xml"
href="https://www.google.com/a/feeds/example.com/user/2.0/TestUser"/>
<apps:login userName="TestUser" password="password" suspended="false"
ipWhitelisted='false' hashFunctionName="SHA-1"/>
<apps:name familyName="Test" givenName="User"/>
<apps:quota limit="1024"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#user.nicknames'
href="https://www.google.com/a/feeds/example.com/nickname/2.0?username=Test-3121"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#user.emailLists'
href="https://www.google.com/a/feeds/example.com/emailList/2.0?recipient=testlist@example.com"/>
</atom:entry>"""
USER_FEED = """<?xml version="1.0" encoding="UTF-8"?>
<atom:feed xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:apps="http://schemas.google.com/apps/2006"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:gd="http://schemas.google.com/g/2005">
<atom:id>
http://www.google.com/a/feeds/example.com/user/2.0
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#user'/>
<atom:title type="text">Users</atom:title>
<atom:link rel="next" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/user/2.0?startUsername=john"/>
<atom:link rel='http://schemas.google.com/g/2005#feed'
type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/user/2.0"/>
<atom:link rel='http://schemas.google.com/g/2005#post'
type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/user/2.0"/>
<atom:link rel="self" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/user/2.0"/>
<openSearch:startIndex>1</openSearch:startIndex>
<atom:entry>
<atom:id>
http://www.google.com/a/feeds/example.com/user/2.0/TestUser
</atom:id>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#user'/>
<atom:title type="text">TestUser</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/user/2.0/TestUser"/>
<atom:link rel="edit" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/user/2.0/TestUser"/>
<gd:who rel='http://schemas.google.com/apps/2006#user.recipient'
email="TestUser@example.com"/>
<apps:login userName="TestUser" suspended="false"/>
<apps:quota limit="2048"/>
<apps:name familyName="Test" givenName="User"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#user.nicknames'
href="http://www.google.com/a/feeds/example.com/nickname/2.0?username=TestUser"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#user.emailLists'
href="http://www.google.com/a/feeds/example.com/emailList/2.0?recipient=TestUser@example.com"/>
</atom:entry>
<atom:entry>
<atom:id>
http://www.google.com/a/feeds/example.com/user/2.0/JohnSmith
</atom:id>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#user'/>
<atom:title type="text">JohnSmith</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/user/2.0/JohnSmith"/>
<atom:link rel="edit" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/user/2.0/JohnSmith"/>
<gd:who rel='http://schemas.google.com/apps/2006#user.recipient'
email="JohnSmith@example.com"/>
<apps:login userName="JohnSmith" suspended="false"/>
<apps:quota limit="2048"/>
<apps:name familyName="Smith" givenName="John"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#user.nicknames'
href="http://www.google.com/a/feeds/example.com/nickname/2.0?username=JohnSmith"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#user.emailLists'
href="http://www.google.com/a/feeds/example.com/emailList/2.0?recipient=JohnSmith@example.com"/>
</atom:entry>
</atom:feed>"""
EMAIL_LIST_ENTRY = """<?xml version="1.0" encoding="UTF-8"?>
<atom:entry xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:apps="http://schemas.google.com/apps/2006"
xmlns:gd="http://schemas.google.com/g/2005">
<atom:id>
https://www.google.com/a/feeds/example.com/emailList/2.0/testlist
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#emailList'/>
<atom:title type="text">testlist</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="https://www.google.com/a/feeds/example.com/emailList/2.0/testlist"/>
<atom:link rel="edit" type="application/atom+xml"
href="https://www.google.com/a/feeds/example.com/emailList/2.0/testlist"/>
<apps:emailList name="testlist"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#emailList.recipients'
href="http://www.google.com/a/feeds/example.com/emailList/2.0/testlist/recipient/"/>
</atom:entry>"""
EMAIL_LIST_FEED = """<?xml version="1.0" encoding="UTF-8"?>
<atom:feed xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:apps="http://schemas.google.com/apps/2006"
xmlns:gd="http://schemas.google.com/g/2005">
<atom:id>
http://www.google.com/a/feeds/example.com/emailList/2.0
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#emailList'/>
<atom:title type="text">EmailLists</atom:title>
<atom:link rel="next" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0?startEmailListName=john"/>
<atom:link rel='http://schemas.google.com/g/2005#feed'
type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0"/>
<atom:link rel='http://schemas.google.com/g/2005#post'
type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0"/>
<atom:link rel="self" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0"/>
<openSearch:startIndex>1</openSearch:startIndex>
<atom:entry>
<atom:id>
http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#emailList'/>
<atom:title type="text">us-sales</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales"/>
<atom:link rel="edit" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales"/>
<apps:emailList name="us-sales"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#emailList.recipients'
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/"/>
</atom:entry>
<atom:entry>
<atom:id>
http://www.google.com/a/feeds/example.com/emailList/2.0/us-eng
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#emailList'/>
<atom:title type="text">us-eng</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-eng"/>
<atom:link rel="edit" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-eng"/>
<apps:emailList name="us-eng"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#emailList.recipients'
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-eng/recipient/"/>
</atom:entry>
</atom:feed>"""
EMAIL_LIST_RECIPIENT_ENTRY = """<?xml version="1.0" encoding="UTF-8"?>
<atom:entry xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:apps="http://schemas.google.com/apps/2006"
xmlns:gd="http://schemas.google.com/g/2005">
<atom:id>https://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/TestUser%40example.com</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#emailList.recipient'/>
<atom:title type="text">TestUser</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="https://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/TestUser%40example.com"/>
<atom:link rel="edit" type="application/atom+xml"
href="https://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/TestUser%40example.com"/>
<gd:who email="TestUser@example.com"/>
</atom:entry>"""
EMAIL_LIST_RECIPIENT_FEED = """<?xml version="1.0" encoding="UTF-8"?>
<atom:feed xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:gd="http://schemas.google.com/g/2005">
<atom:id>
http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#emailList.recipient'/>
<atom:title type="text">Recipients for email list us-sales</atom:title>
<atom:link rel="next" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/?startRecipient=terry@example.com"/>
<atom:link rel='http://schemas.google.com/g/2005#feed'
type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient"/>
<atom:link rel='http://schemas.google.com/g/2005#post'
type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient"/>
<atom:link rel="self" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient"/>
<openSearch:startIndex>1</openSearch:startIndex>
<atom:entry>
<atom:id>
http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/joe%40example.com
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#emailList.recipient'/>
<atom:title type="text">joe@example.com</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/joe%40example.com"/>
<atom:link rel="edit" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/joe%40example.com"/>
<gd:who email="joe@example.com"/>
</atom:entry>
<atom:entry>
<atom:id>
http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/susan%40example.com
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#emailList.recipient'/>
<atom:title type="text">susan@example.com</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/susan%40example.com"/>
<atom:link rel="edit" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/susan%40example.com"/>
<gd:who email="susan@example.com"/>
</atom:entry>
</atom:feed>"""
ACL_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:gAcl='http://schemas.google.com/acl/2007'>
<id>http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full</id>
<updated>2007-04-21T00:52:04.000Z</updated>
<title type='text'>Elizabeth Bennet's access control list</title>
<link rel='http://schemas.google.com/acl/2007#controlledObject'
type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/private/full'>
</link>
<link rel='http://schemas.google.com/g/2005#feed'
type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full'>
</link>
<link rel='http://schemas.google.com/g/2005#post'
type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full'>
</link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full'>
</link>
<generator version='1.0'
uri='http://www.google.com/calendar'>Google Calendar</generator>
<openSearch:totalResults>2</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<entry>
<id>http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/user%3Aliz%40gmail.com</id>
<updated>2007-04-21T00:52:04.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/acl/2007#accessRule'>
</category>
<title type='text'>owner</title>
<content type='text'></content>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/user%3Aliz%40gmail.com'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/user%3Aliz%40gmail.com'>
</link>
<author>
<name>Elizabeth Bennet</name>
<email>liz@gmail.com</email>
</author>
<gAcl:scope type='user' value='liz@gmail.com'></gAcl:scope>
<gAcl:role value='http://schemas.google.com/gCal/2005#owner'>
</gAcl:role>
</entry>
<entry>
<id>http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/default</id>
<updated>2007-04-21T00:52:04.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/acl/2007#accessRule'>
</category>
<title type='text'>read</title>
<content type='text'></content>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/default'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/default'>
</link>
<author>
<name>Elizabeth Bennet</name>
<email>liz@gmail.com</email>
</author>
<gAcl:scope type='default'></gAcl:scope>
<gAcl:role value='http://schemas.google.com/gCal/2005#read'>
</gAcl:role>
</entry>
</feed>"""
ACL_ENTRY = """<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gd='http://schemas.google.com/g/2005' xmlns:gCal='http://schemas.google.com/gCal/2005' xmlns:gAcl='http://schemas.google.com/acl/2007'>
<id>http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/user%3Aliz%40gmail.com</id>
<updated>2007-04-21T00:52:04.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/acl/2007#accessRule'>
</category>
<title type='text'>owner</title>
<content type='text'></content>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/user%3Aliz%40gmail.com'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/user%3Aliz%40gmail.com'>
</link>
<author>
<name>Elizabeth Bennet</name>
<email>liz@gmail.com</email>
</author>
<gAcl:scope type='user' value='liz@gmail.com'></gAcl:scope>
<gAcl:role value='http://schemas.google.com/gCal/2005#owner'>
</gAcl:role>
</entry>"""
DOCUMENT_LIST_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<ns0:feed xmlns:ns0="http://www.w3.org/2005/Atom"><ns1:totalResults
xmlns:ns1="http://a9.com/-/spec/opensearchrss/1.0/">2</ns1:totalResults><ns1:startIndex
xmlns:ns1="http://a9.com/-/spec/opensearchrss/1.0/">1</ns1:startIndex><ns0:entry><ns0:content
src="http://foo.com/fm?fmcmd=102&key=supercalifragilisticexpeadocious"
type="text/html"
/><ns0:author><ns0:name>test.user</ns0:name><ns0:email>test.user@gmail.com</ns0:email></ns0:author><ns0:category
label="spreadsheet" scheme="http://schemas.google.com/g/2005#kind"
term="http://schemas.google.com/docs/2007#spreadsheet"
/><ns0:id>http://docs.google.com/feeds/documents/private/full/spreadsheet%3Asupercalifragilisticexpeadocious</ns0:id><ns0:link
href="http://foo.com/ccc?key=supercalifragilisticexpeadocious" rel="alternate"
type="text/html" /><ns0:link
href="http://foo.com/feeds/worksheets/supercalifragilisticexpeadocious/private/full"
rel="http://schemas.google.com/spreadsheets/2006#worksheetsfeed"
type="application/atom+xml" /><ns0:link
href="http://docs.google.com/feeds/documents/private/full/spreadsheet%3Asupercalifragilisticexpeadocious"
rel="self" type="application/atom+xml" /><ns0:title type="text">Test Spreadsheet</ns0:title><ns0:updated>2007-07-03T18:03:32.045Z</ns0:updated></ns0:entry><ns0:entry><ns0:content
src="http://docs.google.com/RawDocContents?action=fetch&docID=gr00vy"
type="text/html"
/><ns0:author><ns0:name>test.user</ns0:name><ns0:email>test.user@gmail.com</ns0:email></ns0:author><ns0:category
label="document" scheme="http://schemas.google.com/g/2005#kind"
term="http://schemas.google.com/docs/2007#document"
/><ns0:id>http://docs.google.com/feeds/documents/private/full/document%3Agr00vy</ns0:id><ns0:link
href="http://foobar.com/Doc?id=gr00vy" rel="alternate" type="text/html"
/><ns0:link
href="http://docs.google.com/feeds/documents/private/full/document%3Agr00vy"
rel="self" type="application/atom+xml" /><ns0:title type="text">Test Document</ns0:title><ns0:updated>2007-07-03T18:02:50.338Z</ns0:updated></ns0:entry><ns0:id>http://docs.google.com/feeds/documents/private/full</ns0:id><ns0:link
href="http://docs.google.com" rel="alternate" type="text/html" /><ns0:link
href="http://docs.google.com/feeds/documents/private/full"
rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"
/><ns0:link href="http://docs.google.com/feeds/documents/private/full"
rel="http://schemas.google.com/g/2005#post" type="application/atom+xml"
/><ns0:link href="http://docs.google.com/feeds/documents/private/full"
rel="self" type="application/atom+xml" /><ns0:title type="text">Available
Documents -
test.user@gmail.com</ns0:title><ns0:updated>2007-07-09T23:07:21.898Z</ns0:updated></ns0:feed>
"""
DOCUMENT_LIST_ENTRY = """<?xml version='1.0' encoding='UTF-8'?>
<ns0:entry xmlns:ns0="http://www.w3.org/2005/Atom"><ns0:content
src="http://foo.com/fm?fmcmd=102&key=supercalifragilisticexpealidocious"
type="text/html"
/><ns0:author><ns0:name>test.user</ns0:name><ns0:email>test.user@gmail.com</ns0:email></ns0:author><ns0:category
label="spreadsheet" scheme="http://schemas.google.com/g/2005#kind"
term="http://schemas.google.com/docs/2007#spreadsheet"
/><ns0:id>http://docs.google.com/feeds/documents/private/full/spreadsheet%3Asupercalifragilisticexpealidocious</ns0:id><ns0:link
href="http://foo.com/ccc?key=supercalifragilisticexpealidocious"
rel="alternate" type="text/html" /><ns0:link
href="http://foo.com/feeds/worksheets/supercalifragilisticexpealidocious/private/full"
rel="http://schemas.google.com/spreadsheets/2006#worksheetsfeed"
type="application/atom+xml" /><ns0:link
href="http://docs.google.com/feeds/documents/private/full/spreadsheet%3Asupercalifragilisticexpealidocious"
rel="self" type="application/atom+xml" /><ns0:title type="text">Test Spreadsheet</ns0:title><ns0:updated>2007-07-03T18:03:32.045Z</ns0:updated></ns0:entry>
"""
BATCH_ENTRY = """<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:batch="http://schemas.google.com/gdata/batch"
xmlns:g="http://base.google.com/ns/1.0">
<id>http://www.google.com/base/feeds/items/2173859253842813008</id>
<published>2006-07-11T14:51:43.560Z</published>
<updated>2006-07-11T14:51: 43.560Z</updated>
<title type="text">title</title>
<content type="html">content</content>
<link rel="self"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items/2173859253842813008"/>
<link rel="edit"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items/2173859253842813008"/>
<g:item_type>recipes</g:item_type>
<batch:operation type="insert"/>
<batch:id>itemB</batch:id>
<batch:status code="201" reason="Created"/>
</entry>"""
BATCH_FEED_REQUEST = """<?xml version="1.0" encoding="UTF-8"?>
<feed
xmlns="http://www.w3.org/2005/Atom"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:g="http://base.google.com/ns/1.0"
xmlns:batch="http://schemas.google.com/gdata/batch">
<title type="text">My Batch Feed</title>
<entry>
<id>http://www.google.com/base/feeds/items/13308004346459454600</id>
<batch:operation type="delete"/>
</entry>
<entry>
<id>http://www.google.com/base/feeds/items/17437536661927313949</id>
<batch:operation type="delete"/>
</entry>
<entry>
<title type="text">...</title>
<content type="html">...</content>
<batch:id>itemA</batch:id>
<batch:operation type="insert"/>
<g:item_type>recipes</g:item_type>
</entry>
<entry>
<title type="text">...</title>
<content type="html">...</content>
<batch:id>itemB</batch:id>
<batch:operation type="insert"/>
<g:item_type>recipes</g:item_type>
</entry>
</feed>"""
BATCH_FEED_RESULT = """<?xml version="1.0" encoding="UTF-8"?>
<feed
xmlns="http://www.w3.org/2005/Atom"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:g="http://base.google.com/ns/1.0"
xmlns:batch="http://schemas.google.com/gdata/batch">
<id>http://www.google.com/base/feeds/items</id>
<updated>2006-07-11T14:51:42.894Z</updated>
<title type="text">My Batch</title>
<link rel="http://schemas.google.com/g/2005#feed"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items"/>
<link rel="http://schemas.google.com/g/2005#post"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items"/>
<link rel=" http://schemas.google.com/g/2005#batch"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items/batch"/>
<entry>
<id>http://www.google.com/base/feeds/items/2173859253842813008</id>
<published>2006-07-11T14:51:43.560Z</published>
<updated>2006-07-11T14:51: 43.560Z</updated>
<title type="text">...</title>
<content type="html">...</content>
<link rel="self"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items/2173859253842813008"/>
<link rel="edit"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items/2173859253842813008"/>
<g:item_type>recipes</g:item_type>
<batch:operation type="insert"/>
<batch:id>itemB</batch:id>
<batch:status code="201" reason="Created"/>
</entry>
<entry>
<id>http://www.google.com/base/feeds/items/11974645606383737963</id>
<published>2006-07-11T14:51:43.247Z</published>
<updated>2006-07-11T14:51: 43.247Z</updated>
<title type="text">...</title>
<content type="html">...</content>
<link rel="self"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items/11974645606383737963"/>
<link rel="edit"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items/11974645606383737963"/>
<g:item_type>recipes</g:item_type>
<batch:operation type="insert"/>
<batch:id>itemA</batch:id>
<batch:status code="201" reason="Created"/>
</entry>
<entry>
<id>http://www.google.com/base/feeds/items/13308004346459454600</id>
<updated>2006-07-11T14:51:42.894Z</updated>
<title type="text">Error</title>
<content type="text">Bad request</content>
<batch:status code="404"
reason="Bad request"
content-type="application/xml">
<errors>
<error type="request" reason="Cannot find item"/>
</errors>
</batch:status>
</entry>
<entry>
<id>http://www.google.com/base/feeds/items/17437536661927313949</id>
<updated>2006-07-11T14:51:43.246Z</updated>
<content type="text">Deleted</content>
<batch:operation type="delete"/>
<batch:status code="200" reason="Success"/>
</entry>
</feed>"""
ALBUM_FEED = """<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:exif="http://schemas.google.com/photos/exif/2007" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:gml="http://www.opengis.net/gml" xmlns:georss="http://www.georss.org/georss" xmlns:photo="http://www.pheed.com/pheed/" xmlns:media="http://search.yahoo.com/mrss/" xmlns:batch="http://schemas.google.com/gdata/batch" xmlns:gphoto="http://schemas.google.com/photos/2007">
<id>http://picasaweb.google.com/data/feed/api/user/sample.user/albumid/1</id>
<updated>2007-09-21T18:23:05.000Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/photos/2007#album"/>
<title type="text">Test</title>
<subtitle type="text"/>
<rights type="text">public</rights>
<icon>http://lh6.google.com/sample.user/Rt8WNoDZEJE/AAAAAAAAABk/HQGlDhpIgWo/s160-c/Test.jpg</icon>
<link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://picasaweb.google.com/data/feed/api/user/sample.user/albumid/1"/>
<link rel="alternate" type="text/html" href="http://picasaweb.google.com/sample.user/Test"/>
<link rel="http://schemas.google.com/photos/2007#slideshow" type="application/x-shockwave-flash" href="http://picasaweb.google.com/s/c/bin/slideshow.swf?host=picasaweb.google.com&RGB=0x000000&feed=http%3A%2F%2Fpicasaweb.google.com%2Fdata%2Ffeed%2Fapi%2Fuser%2Fsample.user%2Falbumid%2F1%3Falt%3Drss"/>
<link rel="self" type="application/atom+xml" href="http://picasaweb.google.com/data/feed/api/user/sample.user/albumid/1?start-index=1&max-results=500&kind=photo%2Ctag"/>
<author>
<name>sample</name>
<uri>http://picasaweb.google.com/sample.user</uri>
</author>
<generator version="1.00" uri="http://picasaweb.google.com/">Picasaweb</generator> <openSearch:totalResults>4</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>500</openSearch:itemsPerPage>
<gphoto:id>1</gphoto:id>
<gphoto:name>Test</gphoto:name>
<gphoto:location/>
<gphoto:access>public</gphoto:access> <gphoto:timestamp>1188975600000</gphoto:timestamp>
<gphoto:numphotos>2</gphoto:numphotos>
<gphoto:user>sample.user</gphoto:user>
<gphoto:nickname>sample</gphoto:nickname>
<gphoto:commentingEnabled>true</gphoto:commentingEnabled>
<gphoto:commentCount>0</gphoto:commentCount>
<entry> <id>http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/photoid/2</id>
<published>2007-09-05T20:49:23.000Z</published>
<updated>2007-09-21T18:23:05.000Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/photos/2007#photo"/>
<title type="text">Aqua Blue.jpg</title>
<summary type="text">Blue</summary>
<content type="image/jpeg" src="http://lh4.google.com/sample.user/Rt8WU4DZEKI/AAAAAAAAABY/IVgLqmnzJII/Aqua%20Blue.jpg"/> <link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://picasaweb.google.com/data/feed/api/user/sample.user/albumid/1/photoid/2"/>
<link rel="alternate" type="text/html" href="http://picasaweb.google.com/sample.user/Test/photo#2"/>
<link rel="self" type="application/atom+xml" href="http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/photoid/2"/>
<gphoto:id>2</gphoto:id>
<gphoto:version>1190398985145172</gphoto:version>
<gphoto:position>0.0</gphoto:position>
<gphoto:albumid>1</gphoto:albumid> <gphoto:width>2560</gphoto:width>
<gphoto:height>1600</gphoto:height>
<gphoto:size>883405</gphoto:size>
<gphoto:client/>
<gphoto:checksum/>
<gphoto:timestamp>1189025362000</gphoto:timestamp>
<exif:tags> <exif:flash>true</exif:flash>
<exif:imageUniqueID>c041ce17aaa637eb656c81d9cf526c24</exif:imageUniqueID>
</exif:tags>
<gphoto:commentingEnabled>true</gphoto:commentingEnabled>
<gphoto:commentCount>1</gphoto:commentCount>
<media:group>
<media:title type="plain">Aqua Blue.jpg</media:title> <media:description type="plain">Blue</media:description>
<media:keywords>tag, test</media:keywords>
<media:content url="http://lh4.google.com/sample.user/Rt8WU4DZEKI/AAAAAAAAABY/IVgLqmnzJII/Aqua%20Blue.jpg" height="1600" width="2560" type="image/jpeg" medium="image"/>
<media:thumbnail url="http://lh4.google.com/sample.user/Rt8WU4DZEKI/AAAAAAAAABY/IVgLqmnzJII/s72/Aqua%20Blue.jpg" height="45" width="72"/>
<media:thumbnail url="http://lh4.google.com/sample.user/Rt8WU4DZEKI/AAAAAAAAABY/IVgLqmnzJII/s144/Aqua%20Blue.jpg" height="90" width="144"/>
<media:thumbnail url="http://lh4.google.com/sample.user/Rt8WU4DZEKI/AAAAAAAAABY/IVgLqmnzJII/s288/Aqua%20Blue.jpg" height="180" width="288"/>
<media:credit>sample</media:credit>
</media:group>
</entry>
<entry>
<id>http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/photoid/3</id>
<published>2007-09-05T20:49:24.000Z</published>
<updated>2007-09-21T18:19:38.000Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/photos/2007#photo"/>
<title type="text">Aqua Graphite.jpg</title>
<summary type="text">Gray</summary>
<content type="image/jpeg" src="http://lh5.google.com/sample.user/Rt8WVIDZELI/AAAAAAAAABg/d7e0i7gvhNU/Aqua%20Graphite.jpg"/>
<link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://picasaweb.google.com/data/feed/api/user/sample.user/albumid/1/photoid/3"/>
<link rel="alternate" type="text/html" href="http://picasaweb.google.com/sample.user/Test/photo#3"/>
<link rel="self" type="application/atom+xml" href="http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/photoid/3"/>
<gphoto:id>3</gphoto:id>
<gphoto:version>1190398778006402</gphoto:version>
<gphoto:position>1.0</gphoto:position>
<gphoto:albumid>1</gphoto:albumid>
<gphoto:width>2560</gphoto:width>
<gphoto:height>1600</gphoto:height>
<gphoto:size>798334</gphoto:size>
<gphoto:client/>
<gphoto:checksum/>
<gphoto:timestamp>1189025363000</gphoto:timestamp>
<exif:tags>
<exif:flash>true</exif:flash>
<exif:imageUniqueID>a5ce2e36b9df7d3cb081511c72e73926</exif:imageUniqueID>
</exif:tags>
<gphoto:commentingEnabled>true</gphoto:commentingEnabled>
<gphoto:commentCount>0</gphoto:commentCount>
<media:group>
<media:title type="plain">Aqua Graphite.jpg</media:title>
<media:description type="plain">Gray</media:description>
<media:keywords/>
<media:content url="http://lh5.google.com/sample.user/Rt8WVIDZELI/AAAAAAAAABg/d7e0i7gvhNU/Aqua%20Graphite.jpg" height="1600" width="2560" type="image/jpeg" medium="image"/>
<media:thumbnail url="http://lh5.google.com/sample.user/Rt8WVIDZELI/AAAAAAAAABg/d7e0i7gvhNU/s72/Aqua%20Graphite.jpg" height="45" width="72"/>
<media:thumbnail url="http://lh5.google.com/sample.user/Rt8WVIDZELI/AAAAAAAAABg/d7e0i7gvhNU/s144/Aqua%20Graphite.jpg" height="90" width="144"/>
<media:thumbnail url="http://lh5.google.com/sample.user/Rt8WVIDZELI/AAAAAAAAABg/d7e0i7gvhNU/s288/Aqua%20Graphite.jpg" height="180" width="288"/>
<media:credit>sample</media:credit>
</media:group>
</entry>
<entry>
<id>http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/tag/tag</id>
<updated>2007-09-05T20:49:24.000Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/photos/2007#tag"/>
<title type="text">tag</title>
<summary type="text">tag</summary>
<link rel="alternate" type="text/html" href="http://picasaweb.google.com/lh/searchbrowse?q=tag&psc=G&uname=sample.user&filter=0"/>
<link rel="self" type="application/atom+xml" href="http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/tag/tag"/>
<author>
<name>sample</name>
<uri>http://picasaweb.google.com/sample.user</uri>
</author>
</entry>
<entry>
<id>http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/tag/test</id>
<updated>2007-09-05T20:49:24.000Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/photos/2007#tag"/>
<title type="text">test</title>
<summary type="text">test</summary>
<link rel="alternate" type="text/html" href="http://picasaweb.google.com/lh/searchbrowse?q=test&psc=G&uname=sample.user&filter=0"/>
<link rel="self" type="application/atom+xml" href="http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/tag/test"/>
<author>
<name>sample</name>
<uri>http://picasaweb.google.com/sample.user</uri>
</author>
</entry>
</feed>"""
CODE_SEARCH_FEED = """<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:opensearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:gcs="http://schemas.google.com/codesearch/2006" xml:base="http://www.google.com">
<id>http://www.google.com/codesearch/feeds/search?q=malloc</id>
<updated>2007-12-19T16:08:04Z</updated>
<title type="text">Google Code Search</title>
<generator version="1.0" uri="http://www.google.com/codesearch">Google Code Search</generator>
<opensearch:totalResults>2530000</opensearch:totalResults>
<opensearch:startIndex>1</opensearch:startIndex>
<author>
<name>Google Code Search</name>
<uri>http://www.google.com/codesearch</uri>
</author>
<link rel="http://schemas.google.com/g/2006#feed" type="application/atom+xml" href="http://schemas.google.com/codesearch/2006"/>
<link rel="self" type="application/atom+xml" href="http://www.google.com/codesearch/feeds/search?q=malloc"/>
<link rel="next" type="application/atom+xml" href="http://www.google.com/codesearch/feeds/search?q=malloc&start-index=11"/>
<link rel="alternate" type="text/html" href="http://www.google.com/codesearch?q=malloc"/>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:LDjwp-Iqc7U:84hEYaYsZk8:xDGReDhvNi0&sa=N&ct=rx&cd=1&cs_p=http://www.gnu.org&cs_f=software/autoconf/manual/autoconf-2.60/autoconf.html-002&cs_p=http://www.gnu.org&cs_f=software/autoconf/manual/autoconf-2.60/autoconf.html-002#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">software/autoconf/manual/autoconf-2.60/autoconf.html</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:LDjwp-Iqc7U:84hEYaYsZk8:xDGReDhvNi0&sa=N&ct=rx&cd=1&cs_p=http://www.gnu.org&cs_f=software/autoconf/manual/autoconf-2.60/autoconf.html-002&cs_p=http://www.gnu.org&cs_f=software/autoconf/manual/autoconf-2.60/autoconf.html-002#first"/><gcs:package name="http://www.gnu.org" uri="http://www.gnu.org"></gcs:package><gcs:file name="software/autoconf/manual/autoconf-2.60/autoconf.html-002"></gcs:file><content type="text/html"><pre> 8: void *<b>malloc</b> ();
</pre></content><gcs:match lineNumber="4" type="text/html"><pre> #undef <b>malloc</b>
</pre></gcs:match><gcs:match lineNumber="8" type="text/html"><pre> void *<b>malloc</b> ();
</pre></gcs:match><gcs:match lineNumber="14" type="text/html"><pre> rpl_<b>malloc</b> (size_t n)
</pre></gcs:match><gcs:match lineNumber="18" type="text/html"><pre> return <b>malloc</b> (n);
</pre></gcs:match></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:h4hfh-fV-jI:niBq_bwWZNs:H0OhClf0HWQ&sa=N&ct=rx&cd=2&cs_p=ftp://ftp.gnu.org/gnu/guile/guile-1.6.8.tar.gz&cs_f=guile-1.6.8/libguile/mallocs.c&cs_p=ftp://ftp.gnu.org/gnu/guile/guile-1.6.8.tar.gz&cs_f=guile-1.6.8/libguile/mallocs.c#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">guile-1.6.8/libguile/mallocs.c</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:h4hfh-fV-jI:niBq_bwWZNs:H0OhClf0HWQ&sa=N&ct=rx&cd=2&cs_p=ftp://ftp.gnu.org/gnu/guile/guile-1.6.8.tar.gz&cs_f=guile-1.6.8/libguile/mallocs.c&cs_p=ftp://ftp.gnu.org/gnu/guile/guile-1.6.8.tar.gz&cs_f=guile-1.6.8/libguile/mallocs.c#first"/><gcs:package name="ftp://ftp.gnu.org/gnu/guile/guile-1.6.8.tar.gz" uri="ftp://ftp.gnu.org/gnu/guile/guile-1.6.8.tar.gz"></gcs:package><gcs:file name="guile-1.6.8/libguile/mallocs.c"></gcs:file><content type="text/html"><pre> 86: {
scm_t_bits mem = n ? (scm_t_bits) <b>malloc</b> (n) : 0;
if (n &amp;&amp; !mem)
</pre></content><gcs:match lineNumber="54" type="text/html"><pre>#include &lt;<b>malloc</b>.h&gt;
</pre></gcs:match><gcs:match lineNumber="62" type="text/html"><pre>scm_t_bits scm_tc16_<b>malloc</b>;
</pre></gcs:match><gcs:match lineNumber="66" type="text/html"><pre><b>malloc</b>_free (SCM ptr)
</pre></gcs:match><gcs:match lineNumber="75" type="text/html"><pre><b>malloc</b>_print (SCM exp, SCM port, scm_print_state *pstate SCM_UNUSED)
</pre></gcs:match><gcs:match lineNumber="77" type="text/html"><pre> scm_puts(&quot;#&lt;<b>malloc</b> &quot;, port);
</pre></gcs:match><gcs:match lineNumber="87" type="text/html"><pre> scm_t_bits mem = n ? (scm_t_bits) <b>malloc</b> (n) : 0;
</pre></gcs:match><gcs:match lineNumber="90" type="text/html"><pre> SCM_RETURN_NEWSMOB (scm_tc16_<b>malloc</b>, mem);
</pre></gcs:match><gcs:match lineNumber="98" type="text/html"><pre> scm_tc16_<b>malloc</b> = scm_make_smob_type (&quot;<b>malloc</b>&quot;, 0);
</pre></gcs:match><gcs:match lineNumber="99" type="text/html"><pre> scm_set_smob_free (scm_tc16_<b>malloc</b>, <b>malloc</b>_free);
</pre></gcs:match><rights>GPL</rights></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:9wyZUG-N_30:7_dFxoC1ZrY:C0_iYbFj90M&sa=N&ct=rx&cd=3&cs_p=http://ftp.gnu.org/gnu/bash/bash-3.0.tar.gz&cs_f=bash-3.0/lib/malloc/alloca.c&cs_p=http://ftp.gnu.org/gnu/bash/bash-3.0.tar.gz&cs_f=bash-3.0/lib/malloc/alloca.c#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">bash-3.0/lib/malloc/alloca.c</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:9wyZUG-N_30:7_dFxoC1ZrY:C0_iYbFj90M&sa=N&ct=rx&cd=3&cs_p=http://ftp.gnu.org/gnu/bash/bash-3.0.tar.gz&cs_f=bash-3.0/lib/malloc/alloca.c&cs_p=http://ftp.gnu.org/gnu/bash/bash-3.0.tar.gz&cs_f=bash-3.0/lib/malloc/alloca.c#first"/><gcs:package name="http://ftp.gnu.org/gnu/bash/bash-3.0.tar.gz" uri="http://ftp.gnu.org/gnu/bash/bash-3.0.tar.gz"></gcs:package><gcs:file name="bash-3.0/lib/malloc/alloca.c"></gcs:file><content type="text/html"><pre> 78: #ifndef emacs
#define <b>malloc</b> x<b>malloc</b>
extern pointer x<b>malloc</b> ();
</pre></content><gcs:match lineNumber="69" type="text/html"><pre> <b>malloc</b>. The Emacs executable needs alloca to call x<b>malloc</b>, because
</pre></gcs:match><gcs:match lineNumber="70" type="text/html"><pre> ordinary <b>malloc</b> isn&#39;t protected from input signals. On the other
</pre></gcs:match><gcs:match lineNumber="71" type="text/html"><pre> hand, the utilities in lib-src need alloca to call <b>malloc</b>; some of
</pre></gcs:match><gcs:match lineNumber="72" type="text/html"><pre> them are very simple, and don&#39;t have an x<b>malloc</b> routine.
</pre></gcs:match><gcs:match lineNumber="76" type="text/html"><pre> Callers below should use <b>malloc</b>. */
</pre></gcs:match><gcs:match lineNumber="79" type="text/html"><pre>#define <b>malloc</b> x<b>malloc</b>
</pre></gcs:match><gcs:match lineNumber="80" type="text/html"><pre>extern pointer x<b>malloc</b> ();
</pre></gcs:match><gcs:match lineNumber="132" type="text/html"><pre> It is very important that sizeof(header) agree with <b>malloc</b>
</pre></gcs:match><gcs:match lineNumber="198" type="text/html"><pre> register pointer new = <b>malloc</b> (sizeof (header) + size);
</pre></gcs:match><rights>GPL</rights></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:uhVCKyPcT6k:8juMxxzmUJw:H7_IDsTB2L4&sa=N&ct=rx&cd=4&cs_p=http://ftp.mozilla.org/pub/mozilla.org/mozilla/releases/mozilla1.7b/src/mozilla-source-1.7b-source.tar.bz2&cs_f=mozilla/xpcom/build/malloc.c&cs_p=http://ftp.mozilla.org/pub/mozilla.org/mozilla/releases/mozilla1.7b/src/mozilla-source-1.7b-source.tar.bz2&cs_f=mozilla/xpcom/build/malloc.c#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">mozilla/xpcom/build/malloc.c</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:uhVCKyPcT6k:8juMxxzmUJw:H7_IDsTB2L4&sa=N&ct=rx&cd=4&cs_p=http://ftp.mozilla.org/pub/mozilla.org/mozilla/releases/mozilla1.7b/src/mozilla-source-1.7b-source.tar.bz2&cs_f=mozilla/xpcom/build/malloc.c&cs_p=http://ftp.mozilla.org/pub/mozilla.org/mozilla/releases/mozilla1.7b/src/mozilla-source-1.7b-source.tar.bz2&cs_f=mozilla/xpcom/build/malloc.c#first"/><gcs:package name="http://ftp.mozilla.org/pub/mozilla.org/mozilla/releases/mozilla1.7b/src/mozilla-source-1.7b-source.tar.bz2" uri="http://ftp.mozilla.org/pub/mozilla.org/mozilla/releases/mozilla1.7b/src/mozilla-source-1.7b-source.tar.bz2"></gcs:package><gcs:file name="mozilla/xpcom/build/malloc.c"></gcs:file><content type="text/html"><pre> 54: http://gee.cs.oswego.edu/dl/html/<b>malloc</b>.html
You may already by default be using a c library containing a <b>malloc</b>
</pre></content><gcs:match lineNumber="4" type="text/html"><pre>/* ---------- To make a <b>malloc</b>.h, start cutting here ------------ */
</pre></gcs:match><gcs:match lineNumber="22" type="text/html"><pre> Note: There may be an updated version of this <b>malloc</b> obtainable at
</pre></gcs:match><gcs:match lineNumber="23" type="text/html"><pre> ftp://gee.cs.oswego.edu/pub/misc/<b>malloc</b>.c
</pre></gcs:match><gcs:match lineNumber="34" type="text/html"><pre>* Why use this <b>malloc</b>?
</pre></gcs:match><gcs:match lineNumber="37" type="text/html"><pre> most tunable <b>malloc</b> ever written. However it is among the fastest
</pre></gcs:match><gcs:match lineNumber="40" type="text/html"><pre> allocator for <b>malloc</b>-intensive programs.
</pre></gcs:match><gcs:match lineNumber="54" type="text/html"><pre> http://gee.cs.oswego.edu/dl/html/<b>malloc</b>.html
</pre></gcs:match><gcs:match lineNumber="56" type="text/html"><pre> You may already by default be using a c library containing a <b>malloc</b>
</pre></gcs:match><gcs:match lineNumber="57" type="text/html"><pre> that is somehow based on some version of this <b>malloc</b> (for example in
</pre></gcs:match><rights>Mozilla</rights></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:4n1P2HVOISs:Ybbpph0wR2M:OhIN_sDrG0U&sa=N&ct=rx&cd=5&cs_p=http://regexps.srparish.net/src/hackerlab/hackerlab-1.0pre2.tar.gz&cs_f=hackerlab-1.0pre2/src/hackerlab/tests/mem-tests/unit-must-malloc.sh&cs_p=http://regexps.srparish.net/src/hackerlab/hackerlab-1.0pre2.tar.gz&cs_f=hackerlab-1.0pre2/src/hackerlab/tests/mem-tests/unit-must-malloc.sh#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">hackerlab-1.0pre2/src/hackerlab/tests/mem-tests/unit-must-malloc.sh</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:4n1P2HVOISs:Ybbpph0wR2M:OhIN_sDrG0U&sa=N&ct=rx&cd=5&cs_p=http://regexps.srparish.net/src/hackerlab/hackerlab-1.0pre2.tar.gz&cs_f=hackerlab-1.0pre2/src/hackerlab/tests/mem-tests/unit-must-malloc.sh&cs_p=http://regexps.srparish.net/src/hackerlab/hackerlab-1.0pre2.tar.gz&cs_f=hackerlab-1.0pre2/src/hackerlab/tests/mem-tests/unit-must-malloc.sh#first"/><gcs:package name="http://regexps.srparish.net/src/hackerlab/hackerlab-1.0pre2.tar.gz" uri="http://regexps.srparish.net/src/hackerlab/hackerlab-1.0pre2.tar.gz"></gcs:package><gcs:file name="hackerlab-1.0pre2/src/hackerlab/tests/mem-tests/unit-must-malloc.sh"></gcs:file><content type="text/html"><pre> 11: echo ================ unit-must-<b>malloc</b> tests ================
./unit-must-<b>malloc</b>
echo ...passed
</pre></content><gcs:match lineNumber="2" type="text/html"><pre># tag: Tom Lord Tue Dec 4 14:54:29 2001 (mem-tests/unit-must-<b>malloc</b>.sh)
</pre></gcs:match><gcs:match lineNumber="11" type="text/html"><pre>echo ================ unit-must-<b>malloc</b> tests ================
</pre></gcs:match><gcs:match lineNumber="12" type="text/html"><pre>./unit-must-<b>malloc</b>
</pre></gcs:match><rights>GPL</rights></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:GzkwiWG266M:ykuz3bG00ws:2sTvVSif08g&sa=N&ct=rx&cd=6&cs_p=http://ftp.gnu.org/gnu/tar/tar-1.14.tar.bz2&cs_f=tar-1.14/lib/malloc.c&cs_p=http://ftp.gnu.org/gnu/tar/tar-1.14.tar.bz2&cs_f=tar-1.14/lib/malloc.c#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">tar-1.14/lib/malloc.c</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:GzkwiWG266M:ykuz3bG00ws:2sTvVSif08g&sa=N&ct=rx&cd=6&cs_p=http://ftp.gnu.org/gnu/tar/tar-1.14.tar.bz2&cs_f=tar-1.14/lib/malloc.c&cs_p=http://ftp.gnu.org/gnu/tar/tar-1.14.tar.bz2&cs_f=tar-1.14/lib/malloc.c#first"/><gcs:package name="http://ftp.gnu.org/gnu/tar/tar-1.14.tar.bz2" uri="http://ftp.gnu.org/gnu/tar/tar-1.14.tar.bz2"></gcs:package><gcs:file name="tar-1.14/lib/malloc.c"></gcs:file><content type="text/html"><pre> 22: #endif
#undef <b>malloc</b>
</pre></content><gcs:match lineNumber="1" type="text/html"><pre>/* Work around bug on some systems where <b>malloc</b> (0) fails.
</pre></gcs:match><gcs:match lineNumber="23" type="text/html"><pre>#undef <b>malloc</b>
</pre></gcs:match><gcs:match lineNumber="31" type="text/html"><pre>rpl_<b>malloc</b> (size_t n)
</pre></gcs:match><gcs:match lineNumber="35" type="text/html"><pre> return <b>malloc</b> (n);
</pre></gcs:match><rights>GPL</rights></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:o_TFIeBY6dY:ktI_dt8wPao:AI03BD1Dz0Y&sa=N&ct=rx&cd=7&cs_p=http://ftp.gnu.org/gnu/tar/tar-1.16.1.tar.gz&cs_f=tar-1.16.1/lib/malloc.c&cs_p=http://ftp.gnu.org/gnu/tar/tar-1.16.1.tar.gz&cs_f=tar-1.16.1/lib/malloc.c#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">tar-1.16.1/lib/malloc.c</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:o_TFIeBY6dY:ktI_dt8wPao:AI03BD1Dz0Y&sa=N&ct=rx&cd=7&cs_p=http://ftp.gnu.org/gnu/tar/tar-1.16.1.tar.gz&cs_f=tar-1.16.1/lib/malloc.c&cs_p=http://ftp.gnu.org/gnu/tar/tar-1.16.1.tar.gz&cs_f=tar-1.16.1/lib/malloc.c#first"/><gcs:package name="http://ftp.gnu.org/gnu/tar/tar-1.16.1.tar.gz" uri="http://ftp.gnu.org/gnu/tar/tar-1.16.1.tar.gz"></gcs:package><gcs:file name="tar-1.16.1/lib/malloc.c"></gcs:file><content type="text/html"><pre> 21: #include &lt;config.h&gt;
#undef <b>malloc</b>
</pre></content><gcs:match lineNumber="1" type="text/html"><pre>/* <b>malloc</b>() function that is glibc compatible.
</pre></gcs:match><gcs:match lineNumber="22" type="text/html"><pre>#undef <b>malloc</b>
</pre></gcs:match><gcs:match lineNumber="30" type="text/html"><pre>rpl_<b>malloc</b> (size_t n)
</pre></gcs:match><gcs:match lineNumber="34" type="text/html"><pre> return <b>malloc</b> (n);
</pre></gcs:match><rights>GPL</rights></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:_ibw-VLkMoI:jBOtIJSmFd4:-0NUEVeCwfY&sa=N&ct=rx&cd=8&cs_p=http://freshmeat.net/redir/uclibc/20616/url_bz2/uClibc-0.9.28.1.tar.bz2&cs_f=uClibc-0.9.29/include/malloc.h&cs_p=http://freshmeat.net/redir/uclibc/20616/url_bz2/uClibc-0.9.28.1.tar.bz2&cs_f=uClibc-0.9.29/include/malloc.h#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">uClibc-0.9.29/include/malloc.h</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:_ibw-VLkMoI:jBOtIJSmFd4:-0NUEVeCwfY&sa=N&ct=rx&cd=8&cs_p=http://freshmeat.net/redir/uclibc/20616/url_bz2/uClibc-0.9.28.1.tar.bz2&cs_f=uClibc-0.9.29/include/malloc.h&cs_p=http://freshmeat.net/redir/uclibc/20616/url_bz2/uClibc-0.9.28.1.tar.bz2&cs_f=uClibc-0.9.29/include/malloc.h#first"/><gcs:package name="http://freshmeat.net/redir/uclibc/20616/url_bz2/uClibc-0.9.28.1.tar.bz2" uri="http://freshmeat.net/redir/uclibc/20616/url_bz2/uClibc-0.9.28.1.tar.bz2"></gcs:package><gcs:file name="uClibc-0.9.29/include/malloc.h"></gcs:file><content type="text/html"><pre> 1: /* Prototypes and definition for <b>malloc</b> implementation.
Copyright (C) 1996, 1997, 1999, 2000 Free Software Foundation, Inc.
</pre></content><gcs:match lineNumber="1" type="text/html"><pre>/* Prototypes and definition for <b>malloc</b> implementation.
</pre></gcs:match><gcs:match lineNumber="26" type="text/html"><pre> `pt<b>malloc</b>&#39;, a <b>malloc</b> implementation for multiple threads without
</pre></gcs:match><gcs:match lineNumber="28" type="text/html"><pre> See the files `pt<b>malloc</b>.c&#39; or `COPYRIGHT&#39; for copying conditions.
</pre></gcs:match><gcs:match lineNumber="32" type="text/html"><pre> This work is mainly derived from <b>malloc</b>-2.6.4 by Doug Lea
</pre></gcs:match><gcs:match lineNumber="35" type="text/html"><pre> ftp://g.oswego.edu/pub/misc/<b>malloc</b>.c
</pre></gcs:match><gcs:match lineNumber="40" type="text/html"><pre> `pt<b>malloc</b>.c&#39;.
</pre></gcs:match><gcs:match lineNumber="45" type="text/html"><pre># define __<b>malloc</b>_ptr_t void *
</pre></gcs:match><gcs:match lineNumber="51" type="text/html"><pre># define __<b>malloc</b>_ptr_t char *
</pre></gcs:match><gcs:match lineNumber="56" type="text/html"><pre># define __<b>malloc</b>_size_t size_t
</pre></gcs:match><rights>LGPL</rights></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:F6qHcZ9vefo:bTX7o9gKfks:hECF4r_eKC0&sa=N&ct=rx&cd=9&cs_p=http://ftp.gnu.org/gnu/glibc/glibc-2.0.1.tar.gz&cs_f=glibc-2.0.1/hurd/hurdmalloc.h&cs_p=http://ftp.gnu.org/gnu/glibc/glibc-2.0.1.tar.gz&cs_f=glibc-2.0.1/hurd/hurdmalloc.h#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">glibc-2.0.1/hurd/hurdmalloc.h</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:F6qHcZ9vefo:bTX7o9gKfks:hECF4r_eKC0&sa=N&ct=rx&cd=9&cs_p=http://ftp.gnu.org/gnu/glibc/glibc-2.0.1.tar.gz&cs_f=glibc-2.0.1/hurd/hurdmalloc.h&cs_p=http://ftp.gnu.org/gnu/glibc/glibc-2.0.1.tar.gz&cs_f=glibc-2.0.1/hurd/hurdmalloc.h#first"/><gcs:package name="http://ftp.gnu.org/gnu/glibc/glibc-2.0.1.tar.gz" uri="http://ftp.gnu.org/gnu/glibc/glibc-2.0.1.tar.gz"></gcs:package><gcs:file name="glibc-2.0.1/hurd/hurdmalloc.h"></gcs:file><content type="text/html"><pre> 15: #define <b>malloc</b> _hurd_<b>malloc</b>
#define realloc _hurd_realloc
</pre></content><gcs:match lineNumber="3" type="text/html"><pre> All hurd-internal code which uses <b>malloc</b> et al includes this file so it
</pre></gcs:match><gcs:match lineNumber="4" type="text/html"><pre> will use the internal <b>malloc</b> routines _hurd_{<b>malloc</b>,realloc,free}
</pre></gcs:match><gcs:match lineNumber="7" type="text/html"><pre> of <b>malloc</b> et al is the unixoid one using sbrk.
</pre></gcs:match><gcs:match lineNumber="11" type="text/html"><pre>extern void *_hurd_<b>malloc</b> (size_t);
</pre></gcs:match><gcs:match lineNumber="15" type="text/html"><pre>#define <b>malloc</b> _hurd_<b>malloc</b>
</pre></gcs:match><rights>GPL</rights></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:CHUvHYzyLc8:pdcAfzDA6lY:wjofHuNLTHg&sa=N&ct=rx&cd=10&cs_p=ftp://apache.mirrors.pair.com/httpd/httpd-2.2.4.tar.bz2&cs_f=httpd-2.2.4/srclib/apr/include/arch/netware/apr_private.h&cs_p=ftp://apache.mirrors.pair.com/httpd/httpd-2.2.4.tar.bz2&cs_f=httpd-2.2.4/srclib/apr/include/arch/netware/apr_private.h#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">httpd-2.2.4/srclib/apr/include/arch/netware/apr_private.h</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:CHUvHYzyLc8:pdcAfzDA6lY:wjofHuNLTHg&sa=N&ct=rx&cd=10&cs_p=ftp://apache.mirrors.pair.com/httpd/httpd-2.2.4.tar.bz2&cs_f=httpd-2.2.4/srclib/apr/include/arch/netware/apr_private.h&cs_p=ftp://apache.mirrors.pair.com/httpd/httpd-2.2.4.tar.bz2&cs_f=httpd-2.2.4/srclib/apr/include/arch/netware/apr_private.h#first"/><gcs:package name="ftp://apache.mirrors.pair.com/httpd/httpd-2.2.4.tar.bz2" uri="ftp://apache.mirrors.pair.com/httpd/httpd-2.2.4.tar.bz2"></gcs:package><gcs:file name="httpd-2.2.4/srclib/apr/include/arch/netware/apr_private.h"></gcs:file><content type="text/html"><pre> 173: #undef <b>malloc</b>
#define <b>malloc</b>(x) library_<b>malloc</b>(gLibHandle,x)
</pre></content><gcs:match lineNumber="170" type="text/html"><pre>/* Redefine <b>malloc</b> to use the library <b>malloc</b> call so
</pre></gcs:match><gcs:match lineNumber="173" type="text/html"><pre>#undef <b>malloc</b>
</pre></gcs:match><gcs:match lineNumber="174" type="text/html"><pre>#define <b>malloc</b>(x) library_<b>malloc</b>(gLibHandle,x)
</pre></gcs:match><rights>Apache</rights></entry>
</feed>"""
YOUTUBE_VIDEO_FEED = """<?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gml='http://www.opengis.net/gml' xmlns:georss='http://www.georss.org/georss' xmlns:media='http://search.yahoo.com/mrss/' xmlns:yt='http://gdata.youtube.com/schemas/2007' xmlns:gd='http://schemas.google.com/g/2005'><id>http://gdata.youtube.com/feeds/api/standardfeeds/top_rated</id><updated>2008-05-14T02:24:07.000-07:00</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#video'/><title type='text'>Top Rated</title><logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo><link rel='alternate' type='text/html' href='http://www.youtube.com/browse?s=tr'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/standardfeeds/top_rated'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?start-index=1&max-results=25'/><link rel='next' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?start-index=26&max-results=25'/><author><name>YouTube</name><uri>http://www.youtube.com/</uri></author><generator version='beta' uri='http://gdata.youtube.com/'>YouTube data API</generator><openSearch:totalResults>100</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry><id>http://gdata.youtube.com/feeds/api/videos/C71ypXYGho8</id><published>2008-03-20T10:17:27.000-07:00</published><updated>2008-05-14T04:26:37.000-07:00</updated><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='karyn'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='garcia'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='me'/><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#video'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='boyfriend'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='por'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='te'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='odeio'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='amar'/><category scheme='http://gdata.youtube.com/schemas/2007/categories.cat' term='Music' label='Music'/><title type='text'>Me odeio por te amar - KARYN GARCIA</title><content type='text'>http://www.karyngarcia.com.br</content><link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=C71ypXYGho8'/><link rel='http://gdata.youtube.com/schemas/2007#video.related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/C71ypXYGho8/related'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/standardfeeds/top_rated/C71ypXYGho8'/><author><name>TvKarynGarcia</name><uri>http://gdata.youtube.com/feeds/api/users/tvkaryngarcia</uri></author><media:group><media:title type='plain'>Me odeio por te amar - KARYN GARCIA</media:title><media:description type='plain'>http://www.karyngarcia.com.br</media:description><media:keywords>amar, boyfriend, garcia, karyn, me, odeio, por, te</media:keywords><yt:duration seconds='203'/><media:category label='Music' scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>Music</media:category><media:category label='test111' scheme='http://gdata.youtube.com/schemas/2007/developertags.cat'>test111</media:category><media:category label='test222' scheme='http://gdata.youtube.com/schemas/2007/developertags.cat'>test222</media:category><media:content url='http://www.youtube.com/v/C71ypXYGho8' type='application/x-shockwave-flash' medium='video' isDefault='true' expression='full' duration='203' yt:format='5'/><media:content url='rtsp://rtsp2.youtube.com/ChoLENy73wIaEQmPhgZ2pXK9CxMYDSANFEgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='203' yt:format='1'/><media:content url='rtsp://rtsp2.youtube.com/ChoLENy73wIaEQmPhgZ2pXK9CxMYESARFEgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='203' yt:format='6'/><media:player url='http://www.youtube.com/watch?v=C71ypXYGho8'/><media:thumbnail url='http://img.youtube.com/vi/C71ypXYGho8/2.jpg' height='97' width='130' time='00:01:41.500'/><media:thumbnail url='http://img.youtube.com/vi/C71ypXYGho8/1.jpg' height='97' width='130' time='00:00:50.750'/><media:thumbnail url='http://img.youtube.com/vi/C71ypXYGho8/3.jpg' height='97' width='130' time='00:02:32.250'/><media:thumbnail url='http://img.youtube.com/vi/C71ypXYGho8/0.jpg' height='240' width='320' time='00:01:41.500'/></media:group><yt:statistics viewCount='138864' favoriteCount='2474'/><gd:rating min='1' max='5' numRaters='4626' average='4.95'/><gd:comments><gd:feedLink href='http://gdata.youtube.com/feeds/api/videos/C71ypXYGho8/comments' countHint='27'/></gd:comments></entry>
<entry><id>http://gdata.youtube.com/feeds/api/videos/gsVaTyb1tBw</id><published>2008-02-15T04:31:45.000-08:00</published><updated>2008-05-14T05:09:42.000-07:00</updated><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='extreme'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='cam'/><category scheme='http://gdata.youtube.com/schemas/2007/categories.cat' term='Sports' label='Sports'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='alcala'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='kani'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='helmet'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='campillo'/><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#video'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='pato'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='dirt'/><title type='text'>extreme helmet cam Kani, Keil and Pato</title><content type='text'>trimmed</content><link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=gsVaTyb1tBw'/><link rel='http://gdata.youtube.com/schemas/2007#video.responses' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/gsVaTyb1tBw/responses'/><link rel='http://gdata.youtube.com/schemas/2007#video.related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/gsVaTyb1tBw/related'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/standardfeeds/recently_featured/gsVaTyb1tBw'/><author><name>peraltamagic</name><uri>http://gdata.youtube.com/feeds/api/users/peraltamagic</uri></author><media:group><media:title type='plain'>extreme helmet cam Kani, Keil and Pato</media:title><media:description type='plain'>trimmed</media:description><media:keywords>alcala, cam, campillo, dirt, extreme, helmet, kani, pato</media:keywords><yt:duration seconds='31'/><media:category label='Sports' scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>Sports</media:category><media:content url='http://www.youtube.com/v/gsVaTyb1tBw' type='application/x-shockwave-flash' medium='video' isDefault='true' expression='full' duration='31' yt:format='5'/><media:content url='rtsp://rtsp2.youtube.com/ChoLENy73wIaEQkctPUmT1rFghMYDSANFEgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='31' yt:format='1'/><media:content url='rtsp://rtsp2.youtube.com/ChoLENy73wIaEQkctPUmT1rFghMYESARFEgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='31' yt:format='6'/><media:player url='http://www.youtube.com/watch?v=gsVaTyb1tBw'/><media:thumbnail url='http://img.youtube.com/vi/gsVaTyb1tBw/2.jpg' height='97' width='130' time='00:00:15.500'/><media:thumbnail url='http://img.youtube.com/vi/gsVaTyb1tBw/1.jpg' height='97' width='130' time='00:00:07.750'/><media:thumbnail url='http://img.youtube.com/vi/gsVaTyb1tBw/3.jpg' height='97' width='130' time='00:00:23.250'/><media:thumbnail url='http://img.youtube.com/vi/gsVaTyb1tBw/0.jpg' height='240' width='320' time='00:00:15.500'/></media:group><yt:statistics viewCount='489941' favoriteCount='561'/><gd:rating min='1' max='5' numRaters='1255' average='4.11'/><gd:comments><gd:feedLink href='http://gdata.youtube.com/feeds/api/videos/gsVaTyb1tBw/comments' countHint='1116'/></gd:comments></entry>
</feed>"""
YOUTUBE_ENTRY_PRIVATE = """<?xml version='1.0' encoding='utf-8'?>
<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:media='http://search.yahoo.com/mrss/'
xmlns:gd='http://schemas.google.com/g/2005'
xmlns:yt='http://gdata.youtube.com/schemas/2007'
xmlns:gml='http://www.opengis.net/gml'
xmlns:georss='http://www.georss.org/georss'
xmlns:app='http://purl.org/atom/app#'>
<id>http://gdata.youtube.com/feeds/videos/UMFI1hdm96E</id>
<published>2007-01-07T01:50:15.000Z</published>
<updated>2007-01-07T01:50:15.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://gdata.youtube.com/schemas/2007#video' />
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat'
term='barkley' />
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat'
term='singing' />
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat'
term='acoustic' />
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat'
term='cover' />
<category scheme='http://gdata.youtube.com/schemas/2007/categories.cat'
term='Music' label='Music' />
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat'
term='gnarls' />
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat'
term='music' />
<title type='text'>"Crazy (Gnarles Barkley)" - Acoustic Cover</title>
<content type='html'><div style="color: #000000;font-family:
Arial, Helvetica, sans-serif; font-size:12px; font-size: 12px;
width: 555px;"><table cellspacing="0" cellpadding="0"
border="0"><tbody><tr><td width="140"
valign="top" rowspan="2"><div style="border: 1px solid
#999999; margin: 0px 10px 5px 0px;"><a
href="http://www.youtube.com/watch?v=UMFI1hdm96E"><img
alt=""
src="http://img.youtube.com/vi/UMFI1hdm96E/2.jpg"></a></div></td>
<td width="256" valign="top"><div style="font-size:
12px; font-weight: bold;"><a style="font-size: 15px;
font-weight: bold; font-decoration: none;"
href="http://www.youtube.com/watch?v=UMFI1hdm96E">&quot;Crazy
(Gnarles Barkley)&quot; - Acoustic Cover</a>
<br></div> <div style="font-size: 12px; margin:
3px 0px;"><span>Gnarles Barkley acoustic cover
http://www.myspace.com/davidchoimusic</span></div></td>
<td style="font-size: 11px; line-height: 1.4em; padding-left:
20px; padding-top: 1px;" width="146"
valign="top"><div><span style="color: #666666;
font-size: 11px;">From:</span> <a
href="http://www.youtube.com/profile?user=davidchoimusic">davidchoimusic</a></div>
<div><span style="color: #666666; font-size:
11px;">Views:</span> 113321</div> <div
style="white-space: nowrap;text-align: left"><img
style="border: 0px none; margin: 0px; padding: 0px;
vertical-align: middle; font-size: 11px;" align="top" alt=""
src="http://gdata.youtube.com/static/images/icn_star_full_11x11.gif">
<img style="border: 0px none; margin: 0px; padding: 0px;
vertical-align: middle; font-size: 11px;" align="top" alt=""
src="http://gdata.youtube.com/static/images/icn_star_full_11x11.gif">
<img style="border: 0px none; margin: 0px; padding: 0px;
vertical-align: middle; font-size: 11px;" align="top" alt=""
src="http://gdata.youtube.com/static/images/icn_star_full_11x11.gif">
<img style="border: 0px none; margin: 0px; padding: 0px;
vertical-align: middle; font-size: 11px;" align="top" alt=""
src="http://gdata.youtube.com/static/images/icn_star_full_11x11.gif">
<img style="border: 0px none; margin: 0px; padding: 0px;
vertical-align: middle; font-size: 11px;" align="top" alt=""
src="http://gdata.youtube.com/static/images/icn_star_half_11x11.gif"></div>
<div style="font-size: 11px;">1005 <span style="color:
#666666; font-size:
11px;">ratings</span></div></td></tr>
<tr><td><span style="color: #666666; font-size:
11px;">Time:</span> <span style="color: #000000;
font-size: 11px; font-weight:
bold;">04:15</span></td> <td style="font-size:
11px; padding-left: 20px;"><span style="color: #666666;
font-size: 11px;">More in</span> <a
href="http://www.youtube.com/categories_portal?c=10">Music</a></td></tr></tbody></table></div></content>
<link rel='self' type='application/atom+xml'
href='http://gdata.youtube.com/feeds/videos/UMFI1hdm96E' />
<link rel='alternate' type='text/html'
href='http://www.youtube.com/watch?v=UMFI1hdm96E' />
<link rel='http://gdata.youtube.com/schemas/2007#video.responses'
type='application/atom+xml'
href='http://gdata.youtube.com/feeds/videos/UMFI1hdm96E/responses' />
<link rel='http://gdata.youtube.com/schemas/2007#video.related'
type='application/atom+xml'
href='http://gdata.youtube.com/feeds/videos/UMFI1hdm96E/related' />
<author>
<name>davidchoimusic</name>
<uri>http://gdata.youtube.com/feeds/users/davidchoimusic</uri>
</author>
<media:group>
<media:title type='plain'>"Crazy (Gnarles Barkley)" - Acoustic Cover</media:title>
<media:description type='plain'>Gnarles Barkley acoustic cover http://www.myspace.com/davidchoimusic</media:description>
<media:keywords>music, singing, gnarls, barkley, acoustic, cover</media:keywords>
<yt:duration seconds='255' />
<media:category label='Music'
scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>
Music</media:category>
<media:category
scheme='http://gdata.youtube.com/schemas/2007/developertags.cat'>
DeveloperTag1</media:category>
<media:content url='http://www.youtube.com/v/UMFI1hdm96E'
type='application/x-shockwave-flash' medium='video'
isDefault='true' expression='full' duration='255'
yt:format='5' />
<media:player url='http://www.youtube.com/watch?v=UMFI1hdm96E' />
<media:thumbnail url='http://img.youtube.com/vi/UMFI1hdm96E/2.jpg'
height='97' width='130' time='00:02:07.500' />
<media:thumbnail url='http://img.youtube.com/vi/UMFI1hdm96E/1.jpg'
height='97' width='130' time='00:01:03.750' />
<media:thumbnail url='http://img.youtube.com/vi/UMFI1hdm96E/3.jpg'
height='97' width='130' time='00:03:11.250' />
<media:thumbnail url='http://img.youtube.com/vi/UMFI1hdm96E/0.jpg'
height='240' width='320' time='00:02:07.500' />
<yt:private />
</media:group>
<yt:statistics viewCount='113321' />
<gd:rating min='1' max='5' numRaters='1005' average='4.77' />
<georss:where>
<gml:Point>
<gml:pos>37.398529052734375 -122.0635986328125</gml:pos>
</gml:Point>
</georss:where>
<gd:comments>
<gd:feedLink href='http://gdata.youtube.com/feeds/videos/UMFI1hdm96E/comments' />
</gd:comments>
<yt:noembed />
<app:control>
<app:draft>yes</app:draft>
<yt:state
name="rejected"
reasonCode="inappropriate"
helpUrl="http://www.youtube.com/t/community_guidelines">
The content of this video may violate the terms of use.</yt:state>
</app:control>
</entry>"""
YOUTUBE_COMMENT_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'><id>http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments</id><updated>2008-05-19T21:45:45.261Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#comment'/><title type='text'>Comments</title><logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo><link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU'/><link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=2Idhz9ef5oU'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments?start-index=1&max-results=25'/><author><name>YouTube</name><uri>http://www.youtube.com/</uri></author><generator version='beta' uri='http://gdata.youtube.com/'>YouTube data API</generator><openSearch:totalResults>0</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments/91F809A3DE2EB81B</id>
<published>2008-02-22T15:27:15.000-08:00</published><updated>2008-02-22T15:27:15.000-08:00</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#comment'/>
<title type='text'>test66</title>
<content type='text'>test66</content>
<link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU'/>
<link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=2Idhz9ef5oU'/>
<link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments/91F809A3DE2EB81B'/>
<author><name>apitestjhartmann</name><uri>http://gdata.youtube.com/feeds/users/apitestjhartmann</uri></author>
</entry>
<entry>
<id>http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments/A261AEEFD23674AA</id>
<published>2008-02-22T15:27:01.000-08:00</published><updated>2008-02-22T15:27:01.000-08:00</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#comment'/>
<title type='text'>test333</title>
<content type='text'>test333</content>
<link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU'/>
<link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=2Idhz9ef5oU'/>
<link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments/A261AEEFD23674AA'/>
<author><name>apitestjhartmann</name><uri>http://gdata.youtube.com/feeds/users/apitestjhartmann</uri></author>
</entry>
<entry>
<id>http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments/0DCF1E3531B3FF85</id>
<published>2008-02-22T15:11:06.000-08:00</published><updated>2008-02-22T15:11:06.000-08:00</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#comment'/>
<title type='text'>test2</title>
<content type='text'>test2</content>
<link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU'/>
<link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=2Idhz9ef5oU'/>
<link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments/0DCF1E3531B3FF85'/>
<author><name>apitestjhartmann</name><uri>http://gdata.youtube.com/feeds/users/apitestjhartmann</uri></author>
</entry>
</feed>"""
YOUTUBE_PLAYLIST_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:media='http://search.yahoo.com/mrss/'
xmlns:yt='http://gdata.youtube.com/schemas/2007'
xmlns:gd='http://schemas.google.com/g/2005'>
<id>http://gdata.youtube.com/feeds/users/andyland74/playlists?start-index=1&max-results=25</id>
<updated>2008-02-26T00:26:15.635Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#playlistLink'/>
<title type='text'>andyland74's Playlists</title>
<logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo>
<link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/andyland74'/>
<link rel='alternate' type='text/html' href='http://www.youtube.com/profile_play_list?user=andyland74'/>
<link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/andyland74/playlists'/>
<link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/andyland74/playlists?start-index=1&max-results=25'/>
<author>
<name>andyland74</name>
<uri>http://gdata.youtube.com/feeds/users/andyland74</uri>
</author>
<generator version='beta' uri='http://gdata.youtube.com/'>YouTube data API</generator>
<openSearch:totalResults>1</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<yt:description>My new playlist Description</yt:description>
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#playlist' href='http://gdata.youtube.com/feeds/playlists/8BCDD04DE8F771B2'/>
<id>http://gdata.youtube.com/feeds/users/andyland74/playlists/8BCDD04DE8F771B2</id>
<published>2007-11-04T17:30:27.000-08:00</published>
<updated>2008-02-22T09:55:14.000-08:00</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#playlistLink'/>
<title type='text'>My New Playlist Title</title>
<content type='text'>My new playlist Description</content>
<link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/andyland74'/>
<link rel='alternate' type='text/html' href='http://www.youtube.com/view_play_list?p=8BCDD04DE8F771B2'/>
<link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/andyland74/playlists/8BCDD04DE8F771B2'/>
<author>
<name>andyland74</name>
<uri>http://gdata.youtube.com/feeds/users/andyland74</uri>
</author>
</entry>
</feed>"""
YOUTUBE_PLAYLIST_VIDEO_FEED = """<?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gml='http://www.opengis.net/gml' xmlns:georss='http://www.georss.org/georss' xmlns:media='http://search.yahoo.com/mrss/' xmlns:yt='http://gdata.youtube.com/schemas/2007' xmlns:gd='http://schemas.google.com/g/2005'><id>http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505</id><updated>2008-05-16T12:03:17.000-07:00</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#playlist'/><category scheme='http://gdata.youtube.com/schemas/2007/tags.cat' term='videos'/><category scheme='http://gdata.youtube.com/schemas/2007/tags.cat' term='python'/><title type='text'>Test Playlist</title><subtitle type='text'>Test playlist 1</subtitle><logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo><link rel='alternate' type='text/html' href='http://www.youtube.com/view_play_list?p=BCB3BB96DF51B505'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505?start-index=1&max-results=25'/><author><name>gdpython</name><uri>http://gdata.youtube.com/feeds/api/users/gdpython</uri></author><generator version='beta' uri='http://gdata.youtube.com/'>YouTube data API</generator><openSearch:totalResults>1</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><media:group><media:title type='plain'>Test Playlist</media:title><media:description type='plain'>Test playlist 1</media:description><media:content url='http://www.youtube.com/ep.swf?id=BCB3BB96DF51B505' type='application/x-shockwave-flash' yt:format='5'/></media:group><entry><id>http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505/B0F29389E537F888</id><updated>2008-05-16T20:54:08.520Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#playlist'/><title type='text'>Uploading YouTube Videos with the PHP Client Library</title><content type='text'>Jochen Hartmann demonstrates the basics of how to use the PHP Client Library with the YouTube Data API.
PHP Developer's Guide:
http://code.google.com/apis/youtube/developers_guide_php.html
Other documentation:
http://code.google.com/apis/youtube/</content><link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=iIp7OnHXBlo'/><link rel='http://gdata.youtube.com/schemas/2007#video.responses' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/iIp7OnHXBlo/responses'/><link rel='http://gdata.youtube.com/schemas/2007#video.related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/iIp7OnHXBlo/related'/><link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/iIp7OnHXBlo'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505/B0F29389E537F888'/><author><name>GoogleDevelopers</name><uri>http://gdata.youtube.com/feeds/api/users/googledevelopers</uri></author><media:group><media:title type='plain'>Uploading YouTube Videos with the PHP Client Library</media:title><media:description type='plain'>Jochen Hartmann demonstrates the basics of how to use the PHP Client Library with the YouTube Data API.
PHP Developer's Guide:
http://code.google.com/apis/youtube/developers_guide_php.html
Other documentation:
http://code.google.com/apis/youtube/</media:description><media:keywords>api, data, demo, php, screencast, tutorial, uploading, walkthrough, youtube</media:keywords><yt:duration seconds='466'/><media:category label='Education' scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>Education</media:category><media:content url='http://www.youtube.com/v/iIp7OnHXBlo' type='application/x-shockwave-flash' medium='video' isDefault='true' expression='full' duration='466' yt:format='5'/><media:content url='rtsp://rtsp2.youtube.com/ChoLENy73wIaEQlaBtdxOnuKiBMYDSANFEgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='466' yt:format='1'/><media:content url='rtsp://rtsp2.youtube.com/ChoLENy73wIaEQlaBtdxOnuKiBMYESARFEgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='466' yt:format='6'/><media:player url='http://www.youtube.com/watch?v=iIp7OnHXBlo'/><media:thumbnail url='http://img.youtube.com/vi/iIp7OnHXBlo/2.jpg' height='97' width='130' time='00:03:53'/><media:thumbnail url='http://img.youtube.com/vi/iIp7OnHXBlo/1.jpg' height='97' width='130' time='00:01:56.500'/><media:thumbnail url='http://img.youtube.com/vi/iIp7OnHXBlo/3.jpg' height='97' width='130' time='00:05:49.500'/><media:thumbnail url='http://img.youtube.com/vi/iIp7OnHXBlo/0.jpg' height='240' width='320' time='00:03:53'/></media:group><yt:statistics viewCount='1550' favoriteCount='5'/><gd:rating min='1' max='5' numRaters='3' average='4.67'/><yt:location>undefined</yt:location><gd:comments><gd:feedLink href='http://gdata.youtube.com/feeds/api/videos/iIp7OnHXBlo/comments' countHint='2'/></gd:comments><yt:position>1</yt:position></entry></feed>"""
YOUTUBE_SUBSCRIPTION_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:media='http://search.yahoo.com/mrss/'
xmlns:yt='http://gdata.youtube.com/schemas/2007'
xmlns:gd='http://schemas.google.com/g/2005'>
<id>http://gdata.youtube.com/feeds/users/andyland74/subscriptions?start-index=1&max-results=25</id>
<updated>2008-02-26T00:26:15.635Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://gdata.youtube.com/schemas/2007#subscription'/>
<title type='text'>andyland74's Subscriptions</title>
<logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo>
<link rel='related' type='application/atom+xml'
href='http://gdata.youtube.com/feeds/users/andyland74'/>
<link rel='alternate' type='text/html'
href='http://www.youtube.com/profile_subscriptions?user=andyland74'/>
<link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml'
href='http://gdata.youtube.com/feeds/users/andyland74/subscriptions'/>
<link rel='self' type='application/atom+xml'
href='http://gdata.youtube.com/feeds/users/andyland74/subscriptions?start-index=1&max-results=25'/>
<author>
<name>andyland74</name>
<uri>http://gdata.youtube.com/feeds/users/andyland74</uri>
</author>
<generator version='beta' uri='http://gdata.youtube.com/'>YouTube data API</generator>
<openSearch:totalResults>1</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>http://gdata.youtube.com/feeds/users/andyland74/subscriptions/d411759045e2ad8c</id>
<published>2007-11-04T17:30:27.000-08:00</published>
<updated>2008-02-22T09:55:14.000-08:00</updated>
<category scheme='http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat'
term='channel'/>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://gdata.youtube.com/schemas/2007#subscription'/>
<title type='text'>Videos published by : NBC</title>
<link rel='related' type='application/atom+xml'
href='http://gdata.youtube.com/feeds/users/andyland74'/>
<link rel='alternate' type='text/html'
href='http://www.youtube.com/profile_videos?user=NBC'/>
<link rel='self' type='application/atom+xml'
href='http://gdata.youtube.com/feeds/users/andyland74/subscriptions/d411759045e2ad8c'/>
<author>
<name>andyland74</name>
<uri>http://gdata.youtube.com/feeds/users/andyland74</uri>
</author>
<yt:username>NBC</yt:username>
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#user.uploads'
href='http://gdata.youtube.com/feeds/api/users/nbc/uploads'/>
</entry>
</feed>"""
YOUTUBE_VIDEO_RESPONSE_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gml='http://www.opengis.net/gml' xmlns:georss='http://www.georss.org/georss' xmlns:media='http://search.yahoo.com/mrss/' xmlns:yt='http://gdata.youtube.com/schemas/2007' xmlns:gd='http://schemas.google.com/g/2005'>
<id>http://gdata.youtube.com/feeds/videos/2c3q9K4cHzY/responses</id><updated>2008-05-19T22:37:34.076Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#video'/><title type='text'>Videos responses to 'Giant NES controller coffee table'</title><logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo><link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2c3q9K4cHzY'/><link rel='alternate' type='text/html' href='http://www.youtube.com/video_response_view_all?v=2c3q9K4cHzY'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2c3q9K4cHzY/responses'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2c3q9K4cHzY/responses?start-index=1&max-results=25'/><author><name>YouTube</name><uri>http://www.youtube.com/</uri></author><generator version='beta' uri='http://gdata.youtube.com/'>YouTube data API</generator><openSearch:totalResults>8</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>http://gdata.youtube.com/feeds/videos/7b9EnRI9VbY</id><published>2008-03-11T19:08:53.000-07:00</published><updated>2008-05-18T21:33:10.000-07:00</updated>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='OD'/><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#video'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='chat'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='Uncle'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='sex'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='catmint'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='kato'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='kissa'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='katt'/>
<category scheme='http://gdata.youtube.com/schemas/2007/categories.cat' term='Animals' label='Pets & Animals'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='kat'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='cat'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='cats'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='kedi'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='gato'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='Brattman'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='drug'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='overdose'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='catnip'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='party'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='Katze'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='gatto'/>
<title type='text'>Catnip Party</title><content type='html'>snipped</content>
<link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=7b9EnRI9VbY'/>
<link rel='http://gdata.youtube.com/schemas/2007#video.responses' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/7b9EnRI9VbY/responses'/>
<link rel='http://gdata.youtube.com/schemas/2007#video.related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/7b9EnRI9VbY/related'/>
<link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2c3q9K4cHzY/responses/7b9EnRI9VbY'/>
<author><name>PismoBeach</name><uri>http://gdata.youtube.com/feeds/users/pismobeach</uri></author>
<media:group>
<media:title type='plain'>Catnip Party</media:title>
<media:description type='plain'>Uncle, Hillary, Hankette, and B4 all but overdose on the patio</media:description><media:keywords>Brattman, cat, catmint, catnip, cats, chat, drug, gato, gatto, kat, kato, katt, Katze, kedi, kissa, OD, overdose, party, sex, Uncle</media:keywords>
<yt:duration seconds='139'/>
<media:category label='Pets & Animals' scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>Animals</media:category>
<media:content url='http://www.youtube.com/v/7b9EnRI9VbY' type='application/x-shockwave-flash' medium='video' isDefault='true' expression='full' duration='139' yt:format='5'/>
<media:content url='rtsp://rtsp2.youtube.com/ChoLENy73wIaEQm2VT0SnUS_7RMYDSANFEgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='139' yt:format='1'/>
<media:content url='rtsp://rtsp2.youtube.com/ChoLENy73wIaEQm2VT0SnUS_7RMYESARFEgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='139' yt:format='6'/>
<media:player url='http://www.youtube.com/watch?v=7b9EnRI9VbY'/>
<media:thumbnail url='http://img.youtube.com/vi/7b9EnRI9VbY/2.jpg' height='97' width='130' time='00:01:09.500'/>
<media:thumbnail url='http://img.youtube.com/vi/7b9EnRI9VbY/1.jpg' height='97' width='130' time='00:00:34.750'/>
<media:thumbnail url='http://img.youtube.com/vi/7b9EnRI9VbY/3.jpg' height='97' width='130' time='00:01:44.250'/>
<media:thumbnail url='http://img.youtube.com/vi/7b9EnRI9VbY/0.jpg' height='240' width='320' time='00:01:09.500'/>
</media:group>
<yt:statistics viewCount='4235' favoriteCount='3'/>
<gd:rating min='1' max='5' numRaters='24' average='3.54'/>
<gd:comments>
<gd:feedLink href='http://gdata.youtube.com/feeds/videos/7b9EnRI9VbY/comments' countHint='14'/>
</gd:comments>
</entry>
</feed>
"""
YOUTUBE_PROFILE = """<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:media='http://search.yahoo.com/mrss/'
xmlns:yt='http://gdata.youtube.com/schemas/2007'
xmlns:gd='http://schemas.google.com/g/2005'>
<id>http://gdata.youtube.com/feeds/users/andyland74</id>
<published>2006-10-16T00:09:45.000-07:00</published>
<updated>2008-02-26T11:48:21.000-08:00</updated>
<category scheme='http://gdata.youtube.com/schemas/2007/channeltypes.cat'
term='Standard'/>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://gdata.youtube.com/schemas/2007#userProfile'/>
<title type='text'>andyland74 Channel</title>
<link rel='alternate' type='text/html'
href='http://www.youtube.com/profile?user=andyland74'/>
<link rel='self' type='application/atom+xml'
href='http://gdata.youtube.com/feeds/users/andyland74'/>
<author>
<name>andyland74</name>
<uri>http://gdata.youtube.com/feeds/users/andyland74</uri>
</author>
<yt:age>33</yt:age>
<yt:username>andyland74</yt:username>
<yt:firstName>andy</yt:firstName>
<yt:lastName>example</yt:lastName>
<yt:books>Catch-22</yt:books>
<yt:gender>m</yt:gender>
<yt:company>Google</yt:company>
<yt:hobbies>Testing YouTube APIs</yt:hobbies>
<yt:hometown>Somewhere</yt:hometown>
<yt:location>US</yt:location>
<yt:movies>Aqua Teen Hungerforce</yt:movies>
<yt:music>Elliott Smith</yt:music>
<yt:occupation>Technical Writer</yt:occupation>
<yt:school>University of North Carolina</yt:school>
<media:thumbnail url='http://i.ytimg.com/vi/YFbSxcdOL-w/default.jpg'/>
<yt:statistics viewCount='9' videoWatchCount='21' subscriberCount='1'
lastWebAccess='2008-02-25T16:03:38.000-08:00'/>
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#user.favorites'
href='http://gdata.youtube.com/feeds/users/andyland74/favorites' countHint='4'/>
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#user.contacts'
href='http://gdata.youtube.com/feeds/users/andyland74/contacts' countHint='1'/>
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#user.inbox'
href='http://gdata.youtube.com/feeds/users/andyland74/inbox' countHint='0'/>
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#user.playlists'
href='http://gdata.youtube.com/feeds/users/andyland74/playlists'/>
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#user.subscriptions'
href='http://gdata.youtube.com/feeds/users/andyland74/subscriptions' countHint='4'/>
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#user.uploads'
href='http://gdata.youtube.com/feeds/users/andyland74/uploads' countHint='1'/>
</entry>"""
YOUTUBE_CONTACTS_FEED = """<?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:yt='http://gdata.youtube.com/schemas/2007' xmlns:gd='http://schemas.google.com/g/2005'>
<id>http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts</id><updated>2008-05-16T19:24:34.916Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#friend'/><title type='text'>apitestjhartmann's Contacts</title><logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo><link rel='alternate' type='text/html' href='http://www.youtube.com/profile_friends?user=apitestjhartmann'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts'/><link rel='http://schemas.google.com/g/2005#post' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts?start-index=1&max-results=25'/><author><name>apitestjhartmann</name><uri>http://gdata.youtube.com/feeds/users/apitestjhartmann</uri></author><generator version='beta' uri='http://gdata.youtube.com/'>YouTube data API</generator><openSearch:totalResults>2</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts/test89899090</id><published>2008-02-04T11:27:54.000-08:00</published><updated>2008-05-16T19:24:34.916Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#friend'/><title type='text'>test89899090</title><link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/test89899090'/><link rel='alternate' type='text/html' href='http://www.youtube.com/profile?user=test89899090'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts/test89899090'/><link rel='edit' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts/test89899090'/><author><name>apitestjhartmann</name><uri>http://gdata.youtube.com/feeds/users/apitestjhartmann</uri></author><yt:username>test89899090</yt:username><yt:status>requested</yt:status></entry>
<entry>
<id>http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts/testjfisher</id><published>2008-02-26T14:13:03.000-08:00</published><updated>2008-05-16T19:24:34.916Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#friend'/><title type='text'>testjfisher</title><link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/testjfisher'/><link rel='alternate' type='text/html' href='http://www.youtube.com/profile?user=testjfisher'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts/testjfisher'/><link rel='edit' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts/testjfisher'/><author><name>apitestjhartmann</name><uri>http://gdata.youtube.com/feeds/users/apitestjhartmann</uri></author><yt:username>testjfisher</yt:username><yt:status>pending</yt:status></entry>
</feed>"""
NEW_CONTACT = """<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:gd='http://schemas.google.com/g/2005'
xmlns:gContact='http://schemas.google.com/contact/2008'>
<id>http://www.google.com/m8/feeds/contacts/liz%40gmail.com/base/8411573</id>
<updated>2008-02-28T18:47:02.303Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/contact/2008#contact' />
<title type='text'>Fitzgerald</title>
<content type='text'>Notes</content>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full/8411573' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full/8411573/1204224422303000' />
<gd:email rel='http://schemas.google.com/g/2005#work'
address='liz@gmail.com' />
<gd:email rel='http://schemas.google.com/g/2005#home'
address='liz@example.org' />
<gd:phoneNumber rel='http://schemas.google.com/g/2005#work'
primary='true'>(206)555-1212</gd:phoneNumber>
<gd:phoneNumber rel='http://schemas.google.com/g/2005#other'
primary='true'>456-123-2133</gd:phoneNumber>
<gd:phoneNumber rel='http://schemas.google.com/g/2005#home'>(206)555-1213</gd:phoneNumber>
<gd:extendedProperty name="pet" value="hamster" />
<gd:extendedProperty name="cousine">
<italian />
</gd:extendedProperty>
<gContact:groupMembershipInfo deleted="false" href="http://google.com/m8/feeds/groups/liz%40gmail.com/base/270f" />
<gd:im address='liz@gmail.com'
protocol='http://schemas.google.com/g/2005#GOOGLE_TALK'
rel='http://schemas.google.com/g/2005#home' />
<gd:postalAddress rel='http://schemas.google.com/g/2005#work'
primary='true'>1600 Amphitheatre Pkwy Mountain View</gd:postalAddress>
</entry>"""
CONTACTS_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:gd='http://schemas.google.com/g/2005'
xmlns:gContact='http://schemas.google.com/contact/2008'
xmlns:batch='http://schemas.google.com/gdata/batch'>
<id>http://www.google.com/m8/feeds/contacts/liz%40gmail.com/base</id>
<updated>2008-03-05T12:36:38.836Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/contact/2008#contact' />
<title type='text'>Contacts</title>
<link rel='http://schemas.google.com/g/2005#feed'
type='application/atom+xml'
href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full' />
<link rel='http://schemas.google.com/g/2005#post'
type='application/atom+xml'
href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full' />
<link rel='http://schemas.google.com/g/2005#batch'
type='application/atom+xml'
href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full/batch' />
<link rel='self' type='application/atom+xml'
href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full?max-results=25' />
<author>
<name>Elizabeth Bennet</name>
<email>liz@gmail.com</email>
</author>
<generator version='1.0' uri='http://www.google.com/m8/feeds/contacts'>
Contacts
</generator>
<openSearch:totalResults>1</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>
http://www.google.com/m8/feeds/contacts/liz%40gmail.com/base/c9012de
</id>
<updated>2008-03-05T12:36:38.835Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/contact/2008#contact' />
<title type='text'>Fitzgerald</title>
<link rel="http://schemas.google.com/contacts/2008/rel#photo" type="image/*"
href="http://google.com/m8/feeds/photos/media/liz%40gmail.com/c9012de"/>
<link rel="http://schemas.google.com/contacts/2008/rel#edit-photo" type="image/*"
href="http://www.google.com/m8/feeds/photos/media/liz%40gmail.com/c9012de/photo4524"/>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full/c9012de' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full/c9012de/1204720598835000' />
<gd:phoneNumber rel='http://schemas.google.com/g/2005#home'
primary='true'>
456
</gd:phoneNumber>
<gd:extendedProperty name="pet" value="hamster" />
<gContact:groupMembershipInfo deleted="false" href="http://google.com/m8/feeds/groups/liz%40gmail.com/base/270f" />
</entry>
</feed>"""
CONTACT_GROUPS_FEED = """<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:gContact="http://schemas.google.com/contact/2008"
xmlns:batch="http://schemas.google.com/gdata/batch"
xmlns:gd="http://schemas.google.com/g/2005">
<id>jo@gmail.com</id>
<updated>2008-05-21T21:11:25.237Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/contact/2008#group"/>
<title type="text">Jo's Contact Groups</title>
<link rel="alternate" type="text/html" href="http://www.google.com/"/>
<link rel="http://schemas.google.com/g/2005#feed"
type="application/atom+xml"
href="http://google.m/m8/feeds/groups/jo%40gmail.com/thin"/>
<link rel="http://schemas.google.com/g/2005#post"
type="application/atom+xml"
href="http://google.m/m8/feeds/groups/jo%40gmail.com/thin"/>
<link rel="http://schemas.google.com/g/2005#batch"
type="application/atom+xml"
href="http://googleom/m8/feeds/groups/jo%40gmail.com/thin/batch"/>
<link rel="self"
type="application/atom+xml"
href="http://google.com/m8/feeds/groups/jo%40gmail.com/thin?max-results=25"/>
<author>
<name>Jo Brown</name>
<email>jo@gmail.com</email>
</author>
<generator version="1.0" uri="http://google.com/m8/feeds">Contacts</generator>
<openSearch:totalResults>3</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>http://google.com/m8/feeds/groups/jo%40gmail.com/base/270f</id>
<updated>2008-05-14T13:10:19.070Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/contact/2008#group"/>
<title type="text">joggers</title>
<content type="text">joggers</content>
<link rel="self" type="application/atom+xml"
href="http://google.com/m8/feeds/groups/jo%40gmail.com/thin/270f"/>
<link rel="edit" type="application/atom+xml"
href="http://google.com/m8/feeds/groups/jo%40gmail.com/thin/270f/1210770619070000"/>
</entry>
</feed>"""
CONTACT_GROUP_ENTRY = """<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:gd="http://schemas.google.com/g/2005">
<category scheme="http://schemas.google.com/g/2005#kind"
term="http://schemas.google.com/g/2005#group"/>
<id>http://www.google.com/feeds/groups/jo%40gmail.com/base/1234</id>
<published>2005-01-18T21:00:00Z</published>
<updated>2006-01-01T00:00:00Z</updated>
<title type="text">Salsa group</title>
<content type="text">Salsa group</content>
<link rel='self' type='application/atom+xml'
href= 'http://www.google.com/m8/feeds/groups/jo%40gmail.com/full/2' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/m8/feeds/groups/jo%40gmail.com/full/2/0'/>
<gd:extendedProperty name="more info about the group">
<info>Very nice people.</info>
</gd:extendedProperty>
</entry>"""
BLOG_ENTRY = """<entry xmlns='http://www.w3.org/2005/Atom'>
<id>tag:blogger.com,1999:blog-blogID.post-postID</id>
<published>2006-08-02T18:44:43.089-07:00</published>
<updated>2006-11-08T18:10:23.020-08:00</updated>
<title type='text'>Lizzy's Diary</title>
<summary type='html'>Being the journal of Elizabeth Bennet</summary>
<link rel='alternate' type='text/html'
href='http://blogName.blogspot.com/'>
</link>
<link rel='http://schemas.google.com/g/2005#feed'
type='application/atom+xml'
href='http://blogName.blogspot.com/feeds/posts/default'>
</link>
<link rel='http://schemas.google.com/g/2005#post'
type='application/atom+xml'
href='http://www.blogger.com/feeds/blogID/posts/default'>
</link>
<link rel='self' type='application/atom+xml'
href='http://www.blogger.com/feeds/userID/blogs/blogID'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.blogger.com/feeds/userID/blogs/blogID'>
</link>
<author>
<name>Elizabeth Bennet</name>
<email>liz@gmail.com</email>
</author>
</entry>"""
BLOG_POST = """<entry xmlns='http://www.w3.org/2005/Atom'>
<title type='text'>Marriage!</title>
<content type='xhtml'>
<div xmlns="http://www.w3.org/1999/xhtml">
<p>Mr. Darcy has <em>proposed marriage</em> to me!</p>
<p>He is the last man on earth I would ever desire to marry.</p>
<p>Whatever shall I do?</p>
</div>
</content>
<author>
<name>Elizabeth Bennet</name>
<email>liz@gmail.com</email>
</author>
</entry>"""
BLOG_POSTS_FEED = """<feed xmlns='http://www.w3.org/2005/Atom'>
<id>tag:blogger.com,1999:blog-blogID</id>
<updated>2006-11-08T18:10:23.020-08:00</updated>
<title type='text'>Lizzy's Diary</title>
<link rel='alternate' type='text/html'
href='http://blogName.blogspot.com/index.html'>
</link>
<link rel='http://schemas.google.com/g/2005#feed'
type='application/atom+xml'
href='http://blogName.blogspot.com/feeds/posts/default'>
</link>
<link rel='self' type='application/atom+xml'
href='http://blogName.blogspot.com/feeds/posts/default'>
</link>
<author>
<name>Elizabeth Bennet</name>
<email>liz@gmail.com</email>
</author>
<generator version='7.00' uri='http://www2.blogger.com'>Blogger</generator>
<entry>
<id>tag:blogger.com,1999:blog-blogID.post-postID</id>
<published>2006-11-08T18:10:00.000-08:00</published>
<updated>2006-11-08T18:10:14.954-08:00</updated>
<title type='text'>Quite disagreeable</title>
<content type='html'><p>I met Mr. Bingley's friend Mr. Darcy
this evening. I found him quite disagreeable.</p></content>
<link rel='alternate' type='text/html'
href='http://blogName.blogspot.com/2006/11/quite-disagreeable.html'>
</link>
<link rel='self' type='application/atom+xml'
href='http://blogName.blogspot.com/feeds/posts/default/postID'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.blogger.com/feeds/blogID/posts/default/postID'>
</link>
<author>
<name>Elizabeth Bennet</name>
<email>liz@gmail.com</email>
</author>
</entry>
</feed>"""
BLOG_COMMENTS_FEED = """<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/">
<id>tag:blogger.com,1999:blog-blogID.postpostID..comments</id>
<updated>2007-04-04T21:56:29.803-07:00</updated>
<title type="text">My Blog : Time to relax</title>
<link rel="alternate" type="text/html" href="http://blogName.blogspot.com/2007/04/first-post.html"/>
<link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://blogName.blogspot.com/feeds/postID/comments/default"/>
<link rel="self" type="application/atom+xml" href="http://blogName.blogspot.com/feeds/postID/comments/default"/>
<author>
<name>Blog Author name</name>
</author>
<generator version="7.00" uri="http://www2.blogger.com">Blogger</generator>
<openSearch:totalResults>1</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<entry>
<id>tag:blogger.com,1999:blog-blogID.post-commentID</id>
<published>2007-04-04T21:56:00.000-07:00</published>
<updated>2007-04-04T21:56:29.803-07:00</updated>
<title type="text">This is my first comment</title>
<content type="html">This is my first comment</content>
<link rel="alternate" type="text/html" href="http://blogName.blogspot.com/2007/04/first-post.html#commentID"/>
<link rel="self" type="application/atom+xml" href="http://blogName.blogspot.com/feeds/postID/comments/default/commentID"/>
<link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/blogID/postID/comments/default/commentID"/>
<author>
<name>Blog Author name</name>
</author>
<thr:in-reply-to xmlns:thr='http://purl.org/syndication/thread/1.0'
href='http://blogName.blogspot.com/2007/04/first-post.html'
ref='tag:blogger.com,1999:blog-blogID.post-postID'
source='http://blogName.blogspot.com/feeds/posts/default/postID'
type='text/html' />
</entry>
</feed>"""
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains classes representing Google Data elements.
Extends Atom classes to add Google Data specific elements.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
import os
import atom
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
# XML namespaces which are often used in GData entities.
GDATA_NAMESPACE = 'http://schemas.google.com/g/2005'
GDATA_TEMPLATE = '{http://schemas.google.com/g/2005}%s'
OPENSEARCH_NAMESPACE = 'http://a9.com/-/spec/opensearchrss/1.0/'
OPENSEARCH_TEMPLATE = '{http://a9.com/-/spec/opensearchrss/1.0/}%s'
BATCH_NAMESPACE = 'http://schemas.google.com/gdata/batch'
GACL_NAMESPACE = 'http://schemas.google.com/acl/2007'
GACL_TEMPLATE = '{http://schemas.google.com/acl/2007}%s'
# Labels used in batch request entries to specify the desired CRUD operation.
BATCH_INSERT = 'insert'
BATCH_UPDATE = 'update'
BATCH_DELETE = 'delete'
BATCH_QUERY = 'query'
class Error(Exception):
pass
class MissingRequiredParameters(Error):
pass
class MediaSource(object):
"""GData Entries can refer to media sources, so this class provides a
place to store references to these objects along with some metadata.
"""
def __init__(self, file_handle=None, content_type=None, content_length=None,
file_path=None, file_name=None):
"""Creates an object of type MediaSource.
Args:
file_handle: A file handle pointing to the file to be encapsulated in the
MediaSource
content_type: string The MIME type of the file. Required if a file_handle
is given.
content_length: int The size of the file. Required if a file_handle is
given.
file_path: string (optional) A full path name to the file. Used in
place of a file_handle.
file_name: string The name of the file without any path information.
Required if a file_handle is given.
"""
self.file_handle = file_handle
self.content_type = content_type
self.content_length = content_length
self.file_name = file_name
if (file_handle is None and content_type is not None and
file_path is not None):
self.setFile(file_path, content_type)
def setFile(self, file_name, content_type):
"""A helper function which can create a file handle from a given filename
and set the content type and length all at once.
Args:
file_name: string The path and file name to the file containing the media
content_type: string A MIME type representing the type of the media
"""
self.file_handle = open(file_name, 'rb')
self.content_type = content_type
self.content_length = os.path.getsize(file_name)
self.file_name = os.path.basename(file_name)
class LinkFinder(atom.LinkFinder):
"""An "interface" providing methods to find link elements
GData Entry elements often contain multiple links which differ in the rel
attribute or content type. Often, developers are interested in a specific
type of link so this class provides methods to find specific classes of
links.
This class is used as a mixin in GData entries.
"""
def GetSelfLink(self):
"""Find the first link with rel set to 'self'
Returns:
An atom.Link or none if none of the links had rel equal to 'self'
"""
for a_link in self.link:
if a_link.rel == 'self':
return a_link
return None
def GetEditLink(self):
for a_link in self.link:
if a_link.rel == 'edit':
return a_link
return None
def GetEditMediaLink(self):
"""The Picasa API mistakenly returns media-edit rather than edit-media, but
this may change soon.
"""
for a_link in self.link:
if a_link.rel == 'edit-media':
return a_link
if a_link.rel == 'media-edit':
return a_link
return None
def GetHtmlLink(self):
"""Find the first link with rel of alternate and type of text/html
Returns:
An atom.Link or None if no links matched
"""
for a_link in self.link:
if a_link.rel == 'alternate' and a_link.type == 'text/html':
return a_link
return None
def GetPostLink(self):
"""Get a link containing the POST target URL.
The POST target URL is used to insert new entries.
Returns:
A link object with a rel matching the POST type.
"""
for a_link in self.link:
if a_link.rel == 'http://schemas.google.com/g/2005#post':
return a_link
return None
def GetAclLink(self):
for a_link in self.link:
if a_link.rel == 'http://schemas.google.com/acl/2007#accessControlList':
return a_link
return None
def GetFeedLink(self):
for a_link in self.link:
if a_link.rel == 'http://schemas.google.com/g/2005#feed':
return a_link
return None
def GetNextLink(self):
for a_link in self.link:
if a_link.rel == 'next':
return a_link
return None
class TotalResults(atom.AtomBase):
"""opensearch:TotalResults for a GData feed"""
_tag = 'totalResults'
_namespace = OPENSEARCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def TotalResultsFromString(xml_string):
return atom.CreateClassFromXMLString(TotalResults, xml_string)
class StartIndex(atom.AtomBase):
"""The opensearch:startIndex element in GData feed"""
_tag = 'startIndex'
_namespace = OPENSEARCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def StartIndexFromString(xml_string):
return atom.CreateClassFromXMLString(StartIndex, xml_string)
class ItemsPerPage(atom.AtomBase):
"""The opensearch:itemsPerPage element in GData feed"""
_tag = 'itemsPerPage'
_namespace = OPENSEARCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ItemsPerPageFromString(xml_string):
return atom.CreateClassFromXMLString(ItemsPerPage, xml_string)
class ExtendedProperty(atom.AtomBase):
"""The Google Data extendedProperty element.
Used to store arbitrary key-value information specific to your
application. The value can either be a text string stored as an XML
attribute (.value), or an XML node (XmlBlob) as a child element.
This element is used in the Google Calendar data API and the Google
Contacts data API.
"""
_tag = 'extendedProperty'
_namespace = GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['name'] = 'name'
_attributes['value'] = 'value'
def __init__(self, name=None, value=None, extension_elements=None,
extension_attributes=None, text=None):
self.name = name
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GetXmlBlobExtensionElement(self):
"""Returns the XML blob as an atom.ExtensionElement.
Returns:
An atom.ExtensionElement representing the blob's XML, or None if no
blob was set.
"""
if len(self.extension_elements) < 1:
return None
else:
return self.extension_elements[0]
def GetXmlBlobString(self):
"""Returns the XML blob as a string.
Returns:
A string containing the blob's XML, or None if no blob was set.
"""
blob = self.GetXmlBlobExtensionElement()
if blob:
return blob.ToString()
return None
def SetXmlBlob(self, blob):
"""Sets the contents of the extendedProperty to XML as a child node.
Since the extendedProperty is only allowed one child element as an XML
blob, setting the XML blob will erase any preexisting extension elements
in this object.
Args:
blob: str, ElementTree Element or atom.ExtensionElement representing
the XML blob stored in the extendedProperty.
"""
# Erase any existing extension_elements, clears the child nodes from the
# extendedProperty.
self.extension_elements = []
if isinstance(blob, atom.ExtensionElement):
self.extension_elements.append(blob)
elif ElementTree.iselement(blob):
self.extension_elements.append(atom._ExtensionElementFromElementTree(
blob))
else:
self.extension_elements.append(atom.ExtensionElementFromString(blob))
def ExtendedPropertyFromString(xml_string):
return atom.CreateClassFromXMLString(ExtendedProperty, xml_string)
class GDataEntry(atom.Entry, LinkFinder):
"""Extends Atom Entry to provide data processing"""
_tag = atom.Entry._tag
_namespace = atom.Entry._namespace
_children = atom.Entry._children.copy()
_attributes = atom.Entry._attributes.copy()
def __GetId(self):
return self.__id
# This method was created to strip the unwanted whitespace from the id's
# text node.
def __SetId(self, id):
self.__id = id
if id is not None and id.text is not None:
self.__id.text = id.text.strip()
id = property(__GetId, __SetId)
def IsMedia(self):
"""Determines whether or not an entry is a GData Media entry.
"""
if (self.GetEditMediaLink()):
return True
else:
return False
def GetMediaURL(self):
"""Returns the URL to the media content, if the entry is a media entry.
Otherwise returns None.
"""
if not self.IsMedia():
return None
else:
return self.content.src
def GDataEntryFromString(xml_string):
"""Creates a new GDataEntry instance given a string of XML."""
return atom.CreateClassFromXMLString(GDataEntry, xml_string)
class GDataFeed(atom.Feed, LinkFinder):
"""A Feed from a GData service"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = atom.Feed._children.copy()
_attributes = atom.Feed._attributes.copy()
_children['{%s}totalResults' % OPENSEARCH_NAMESPACE] = ('total_results',
TotalResults)
_children['{%s}startIndex' % OPENSEARCH_NAMESPACE] = ('start_index',
StartIndex)
_children['{%s}itemsPerPage' % OPENSEARCH_NAMESPACE] = ('items_per_page',
ItemsPerPage)
# Add a conversion rule for atom:entry to make it into a GData
# Entry.
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GDataEntry])
def __GetId(self):
return self.__id
def __SetId(self, id):
self.__id = id
if id is not None and id.text is not None:
self.__id.text = id.text.strip()
id = property(__GetId, __SetId)
def __GetGenerator(self):
return self.__generator
def __SetGenerator(self, generator):
self.__generator = generator
if generator is not None:
self.__generator.text = generator.text.strip()
generator = property(__GetGenerator, __SetGenerator)
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None, entry=None,
total_results=None, start_index=None, items_per_page=None,
extension_elements=None, extension_attributes=None, text=None):
"""Constructor for Source
Args:
author: list (optional) A list of Author instances which belong to this
class.
category: list (optional) A list of Category instances
contributor: list (optional) A list on Contributor instances
generator: Generator (optional)
icon: Icon (optional)
id: Id (optional) The entry's Id element
link: list (optional) A list of Link instances
logo: Logo (optional)
rights: Rights (optional) The entry's Rights element
subtitle: Subtitle (optional) The entry's subtitle element
title: Title (optional) the entry's title element
updated: Updated (optional) the entry's updated element
entry: list (optional) A list of the Entry instances contained in the
feed.
text: String (optional) The text contents of the element. This is the
contents of the Entry's XML text node.
(Example: <foo>This is the text</foo>)
extension_elements: list (optional) A list of ExtensionElement instances
which are children of this element.
extension_attributes: dict (optional) A dictionary of strings which are
the values for additional XML attributes of this element.
"""
self.author = author or []
self.category = category or []
self.contributor = contributor or []
self.generator = generator
self.icon = icon
self.id = atom_id
self.link = link or []
self.logo = logo
self.rights = rights
self.subtitle = subtitle
self.title = title
self.updated = updated
self.entry = entry or []
self.total_results = total_results
self.start_index = start_index
self.items_per_page = items_per_page
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GDataFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GDataFeed, xml_string)
class BatchId(atom.AtomBase):
_tag = 'id'
_namespace = BATCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def BatchIdFromString(xml_string):
return atom.CreateClassFromXMLString(BatchId, xml_string)
class BatchOperation(atom.AtomBase):
_tag = 'operation'
_namespace = BATCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['type'] = 'type'
def __init__(self, op_type=None, extension_elements=None,
extension_attributes=None,
text=None):
self.type = op_type
atom.AtomBase.__init__(self,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def BatchOperationFromString(xml_string):
return atom.CreateClassFromXMLString(BatchOperation, xml_string)
class BatchStatus(atom.AtomBase):
"""The batch:status element present in a batch response entry.
A status element contains the code (HTTP response code) and
reason as elements. In a single request these fields would
be part of the HTTP response, but in a batch request each
Entry operation has a corresponding Entry in the response
feed which includes status information.
See http://code.google.com/apis/gdata/batch.html#Handling_Errors
"""
_tag = 'status'
_namespace = BATCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['code'] = 'code'
_attributes['reason'] = 'reason'
_attributes['content-type'] = 'content_type'
def __init__(self, code=None, reason=None, content_type=None,
extension_elements=None, extension_attributes=None, text=None):
self.code = code
self.reason = reason
self.content_type = content_type
atom.AtomBase.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def BatchStatusFromString(xml_string):
return atom.CreateClassFromXMLString(BatchStatus, xml_string)
class BatchEntry(GDataEntry):
"""An atom:entry for use in batch requests.
The BatchEntry contains additional members to specify the operation to be
performed on this entry and a batch ID so that the server can reference
individual operations in the response feed. For more information, see:
http://code.google.com/apis/gdata/batch.html
"""
_tag = GDataEntry._tag
_namespace = GDataEntry._namespace
_children = GDataEntry._children.copy()
_children['{%s}operation' % BATCH_NAMESPACE] = ('batch_operation', BatchOperation)
_children['{%s}id' % BATCH_NAMESPACE] = ('batch_id', BatchId)
_children['{%s}status' % BATCH_NAMESPACE] = ('batch_status', BatchStatus)
_attributes = GDataEntry._attributes.copy()
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, control=None, title=None, updated=None,
batch_operation=None, batch_id=None, batch_status=None,
extension_elements=None, extension_attributes=None, text=None):
self.batch_operation = batch_operation
self.batch_id = batch_id
self.batch_status = batch_status
GDataEntry.__init__(self, author=author, category=category,
content=content, contributor=contributor, atom_id=atom_id, link=link,
published=published, rights=rights, source=source, summary=summary,
control=control, title=title, updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes, text=text)
def BatchEntryFromString(xml_string):
return atom.CreateClassFromXMLString(BatchEntry, xml_string)
class BatchInterrupted(atom.AtomBase):
"""The batch:interrupted element sent if batch request was interrupted.
Only appears in a feed if some of the batch entries could not be processed.
See: http://code.google.com/apis/gdata/batch.html#Handling_Errors
"""
_tag = 'interrupted'
_namespace = BATCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['reason'] = 'reason'
_attributes['success'] = 'success'
_attributes['failures'] = 'failures'
_attributes['parsed'] = 'parsed'
def __init__(self, reason=None, success=None, failures=None, parsed=None,
extension_elements=None, extension_attributes=None, text=None):
self.reason = reason
self.success = success
self.failures = failures
self.parsed = parsed
atom.AtomBase.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def BatchInterruptedFromString(xml_string):
return atom.CreateClassFromXMLString(BatchInterrupted, xml_string)
class BatchFeed(GDataFeed):
"""A feed containing a list of batch request entries."""
_tag = GDataFeed._tag
_namespace = GDataFeed._namespace
_children = GDataFeed._children.copy()
_attributes = GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [BatchEntry])
_children['{%s}interrupted' % BATCH_NAMESPACE] = ('interrupted', BatchInterrupted)
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None, entry=None,
total_results=None, start_index=None, items_per_page=None,
interrupted=None,
extension_elements=None, extension_attributes=None, text=None):
self.interrupted = interrupted
GDataFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results, start_index=start_index,
items_per_page=items_per_page,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def AddBatchEntry(self, entry=None, id_url_string=None,
batch_id_string=None, operation_string=None):
"""Logic for populating members of a BatchEntry and adding to the feed.
If the entry is not a BatchEntry, it is converted to a BatchEntry so
that the batch specific members will be present.
The id_url_string can be used in place of an entry if the batch operation
applies to a URL. For example query and delete operations require just
the URL of an entry, no body is sent in the HTTP request. If an
id_url_string is sent instead of an entry, a BatchEntry is created and
added to the feed.
This method also assigns the desired batch id to the entry so that it
can be referenced in the server's response. If the batch_id_string is
None, this method will assign a batch_id to be the index at which this
entry will be in the feed's entry list.
Args:
entry: BatchEntry, atom.Entry, or another Entry flavor (optional) The
entry which will be sent to the server as part of the batch request.
The item must have a valid atom id so that the server knows which
entry this request references.
id_url_string: str (optional) The URL of the entry to be acted on. You
can find this URL in the text member of the atom id for an entry.
If an entry is not sent, this id will be used to construct a new
BatchEntry which will be added to the request feed.
batch_id_string: str (optional) The batch ID to be used to reference
this batch operation in the results feed. If this parameter is None,
the current length of the feed's entry array will be used as a
count. Note that batch_ids should either always be specified or
never, mixing could potentially result in duplicate batch ids.
operation_string: str (optional) The desired batch operation which will
set the batch_operation.type member of the entry. Options are
'insert', 'update', 'delete', and 'query'
Raises:
MissingRequiredParameters: Raised if neither an id_ url_string nor an
entry are provided in the request.
Returns:
The added entry.
"""
if entry is None and id_url_string is None:
raise MissingRequiredParameters('supply either an entry or URL string')
if entry is None and id_url_string is not None:
entry = BatchEntry(atom_id=atom.Id(text=id_url_string))
# TODO: handle cases in which the entry lacks batch_... members.
#if not isinstance(entry, BatchEntry):
# Convert the entry to a batch entry.
if batch_id_string is not None:
entry.batch_id = BatchId(text=batch_id_string)
elif entry.batch_id is None or entry.batch_id.text is None:
entry.batch_id = BatchId(text=str(len(self.entry)))
if operation_string is not None:
entry.batch_operation = BatchOperation(op_type=operation_string)
self.entry.append(entry)
return entry
def AddInsert(self, entry, batch_id_string=None):
"""Add an insert request to the operations in this batch request feed.
If the entry doesn't yet have an operation or a batch id, these will
be set to the insert operation and a batch_id specified as a parameter.
Args:
entry: BatchEntry The entry which will be sent in the batch feed as an
insert request.
batch_id_string: str (optional) The batch ID to be used to reference
this batch operation in the results feed. If this parameter is None,
the current length of the feed's entry array will be used as a
count. Note that batch_ids should either always be specified or
never, mixing could potentially result in duplicate batch ids.
"""
entry = self.AddBatchEntry(entry=entry, batch_id_string=batch_id_string,
operation_string=BATCH_INSERT)
def AddUpdate(self, entry, batch_id_string=None):
"""Add an update request to the list of batch operations in this feed.
Sets the operation type of the entry to insert if it is not already set
and assigns the desired batch id to the entry so that it can be
referenced in the server's response.
Args:
entry: BatchEntry The entry which will be sent to the server as an
update (HTTP PUT) request. The item must have a valid atom id
so that the server knows which entry to replace.
batch_id_string: str (optional) The batch ID to be used to reference
this batch operation in the results feed. If this parameter is None,
the current length of the feed's entry array will be used as a
count. See also comments for AddInsert.
"""
entry = self.AddBatchEntry(entry=entry, batch_id_string=batch_id_string,
operation_string=BATCH_UPDATE)
def AddDelete(self, url_string=None, entry=None, batch_id_string=None):
"""Adds a delete request to the batch request feed.
This method takes either the url_string which is the atom id of the item
to be deleted, or the entry itself. The atom id of the entry must be
present so that the server knows which entry should be deleted.
Args:
url_string: str (optional) The URL of the entry to be deleted. You can
find this URL in the text member of the atom id for an entry.
entry: BatchEntry (optional) The entry to be deleted.
batch_id_string: str (optional)
Raises:
MissingRequiredParameters: Raised if neither a url_string nor an entry
are provided in the request.
"""
entry = self.AddBatchEntry(entry=entry, id_url_string=url_string,
batch_id_string=batch_id_string,
operation_string=BATCH_DELETE)
def AddQuery(self, url_string=None, entry=None, batch_id_string=None):
"""Adds a query request to the batch request feed.
This method takes either the url_string which is the query URL
whose results will be added to the result feed. The query URL will
be encapsulated in a BatchEntry, and you may pass in the BatchEntry
with a query URL instead of sending a url_string.
Args:
url_string: str (optional)
entry: BatchEntry (optional)
batch_id_string: str (optional)
Raises:
MissingRequiredParameters
"""
entry = self.AddBatchEntry(entry=entry, id_url_string=url_string,
batch_id_string=batch_id_string,
operation_string=BATCH_QUERY)
def GetBatchLink(self):
for link in self.link:
if link.rel == 'http://schemas.google.com/g/2005#batch':
return link
return None
def BatchFeedFromString(xml_string):
return atom.CreateClassFromXMLString(BatchFeed, xml_string)
class EntryLink(atom.AtomBase):
"""The gd:entryLink element"""
_tag = 'entryLink'
_namespace = GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
# The entry used to be an atom.Entry, now it is a GDataEntry.
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', GDataEntry)
_attributes['rel'] = 'rel',
_attributes['readOnly'] = 'read_only'
_attributes['href'] = 'href'
def __init__(self, href=None, read_only=None, rel=None,
entry=None, extension_elements=None,
extension_attributes=None, text=None):
self.href = href
self.read_only = read_only
self.rel = rel
self.entry = entry
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def EntryLinkFromString(xml_string):
return atom.CreateClassFromXMLString(EntryLink, xml_string)
class FeedLink(atom.AtomBase):
"""The gd:feedLink element"""
_tag = 'feedLink'
_namespace = GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}feed' % atom.ATOM_NAMESPACE] = ('feed', GDataFeed)
_attributes['rel'] = 'rel'
_attributes['readOnly'] = 'read_only'
_attributes['countHint'] = 'count_hint'
_attributes['href'] = 'href'
def __init__(self, count_hint=None, href=None, read_only=None, rel=None,
feed=None, extension_elements=None, extension_attributes=None,
text=None):
self.count_hint = count_hint
self.href = href
self.read_only = read_only
self.rel = rel
self.feed = feed
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def FeedLinkFromString(xml_string):
return atom.CreateClassFromXMLString(EntryLink, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""GDataService provides CRUD ops. and programmatic login for GData services.
Error: A base exception class for all exceptions in the gdata_client
module.
CaptchaRequired: This exception is thrown when a login attempt results in a
captcha challenge from the ClientLogin service. When this
exception is thrown, the captcha_token and captcha_url are
set to the values provided in the server's response.
BadAuthentication: Raised when a login attempt is made with an incorrect
username or password.
NotAuthenticated: Raised if an operation requiring authentication is called
before a user has authenticated.
NonAuthSubToken: Raised if a method to modify an AuthSub token is used when
the user is either not authenticated or is authenticated
through programmatic login.
RequestError: Raised if a CRUD request returned a non-success code.
UnexpectedReturnType: Raised if the response from the server was not of the
desired type. For example, this would be raised if the
server sent a feed when the client requested an entry.
GDataService: Encapsulates user credentials needed to perform insert, update
and delete operations with the GData API. An instance can
perform user authentication, query, insertion, deletion, and
update.
Query: Eases query URI creation by allowing URI parameters to be set as
dictionary attributes. For example a query with a feed of
'/base/feeds/snippets' and ['bq'] set to 'digital camera' will
produce '/base/feeds/snippets?bq=digital+camera' when .ToUri() is
called on it.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
import re
import httplib
import urllib
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import atom.service
import gdata
import atom
import gdata.auth
PROGRAMMATIC_AUTH_LABEL = 'GoogleLogin auth'
AUTHSUB_AUTH_LABEL = 'AuthSub token'
AUTH_SERVER_HOST = 'https://www.google.com'
# Module level variable specifies which module should be used by GDataService
# objects to make HttpRequests. This setting can be overridden on each
# instance of GDataService.
http_request_handler = atom.service
class Error(Exception):
pass
class CaptchaRequired(Error):
pass
class BadAuthentication(Error):
pass
class NotAuthenticated(Error):
pass
class NonAuthSubToken(Error):
pass
class RequestError(Error):
pass
class UnexpectedReturnType(Error):
pass
class BadAuthenticationServiceURL(Error):
pass
class GDataService(atom.service.AtomService):
"""Contains elements needed for GData login and CRUD request headers.
Maintains additional headers (tokens for example) needed for the GData
services to allow a user to perform inserts, updates, and deletes.
"""
def __init__(self, email=None, password=None, account_type='HOSTED_OR_GOOGLE',
service=None, auth_service_url=None, source=None, server=None,
additional_headers=None, handler=None):
"""Creates an object of type GDataService.
Args:
email: string (optional) The user's email address, used for
authentication.
password: string (optional) The user's password.
account_type: string (optional) The type of account to use. Use
'GOOGLE' for regular Google accounts or 'HOSTED' for Google
Apps accounts, or 'HOSTED_OR_GOOGLE' to try finding a HOSTED
account first and, if it doesn't exist, try finding a regular
GOOGLE account. Default value: 'HOSTED_OR_GOOGLE'.
service: string (optional) The desired service for which credentials
will be obtained.
auth_service_url: string (optional) User-defined auth token request URL
allows users to explicitly specify where to send auth token requests.
source: string (optional) The name of the user's application.
server: string (optional) The name of the server to which a connection
will be opened. Default value: 'base.google.com'.
additional_headers: dictionary (optional) Any additional headers which
should be included with CRUD operations.
handler: module (optional) The module whose HttpRequest function
should be used when making requests to the server. The default
value is atom.service.
"""
self.email = email
self.password = password
self.account_type = account_type
self.service = service
self.auth_service_url = auth_service_url
self.server = server
self.additional_headers = additional_headers or {}
self.handler = handler or http_request_handler
self.__SetSource(source)
self.__auth_token = None
self.__captcha_token = None
self.__captcha_url = None
self.__gsessionid = None
# Define properties for GDataService
def _SetAuthSubToken(self, auth_token):
"""Sets the token sent in requests to an AuthSub token.
Only use this method if you have received a token from the AuthSub
service. The auth_token is set automatically when ProgrammaticLogin()
is used. See documentation for Google AuthSub here:
http://code.google.com/apis/accounts/AuthForWebApps.html .
Args:
auth_token: string The token returned by the AuthSub service.
"""
self.__auth_token = '%s=%s' % (AUTHSUB_AUTH_LABEL, auth_token)
# The auth token is only set externally when using AuthSub authentication,
# so set the auth_type to indicate AuthSub.
def __SetAuthSubToken(self, auth_token):
self._SetAuthSubToken(auth_token)
def _GetAuthToken(self):
"""Returns the auth token used for authenticating requests.
Returns:
string
"""
return self.__auth_token
def __GetAuthToken(self):
return self._GetAuthToken()
auth_token = property(__GetAuthToken, __SetAuthSubToken,
doc="""Get or set the token used for authentication.""")
def _GetCaptchaToken(self):
"""Returns a captcha token if the most recent login attempt generated one.
The captcha token is only set if the Programmatic Login attempt failed
because the Google service issued a captcha challenge.
Returns:
string
"""
return self.__captcha_token
def __GetCaptchaToken(self):
return self._GetCaptchaToken()
captcha_token = property(__GetCaptchaToken,
doc="""Get the captcha token for a login request.""")
def _GetCaptchaURL(self):
"""Returns the URL of the captcha image if a login attempt generated one.
The captcha URL is only set if the Programmatic Login attempt failed
because the Google service issued a captcha challenge.
Returns:
string
"""
return self.__captcha_url
def __GetCaptchaURL(self):
return self._GetCaptchaURL()
captcha_url = property(__GetCaptchaURL,
doc="""Get the captcha URL for a login request.""")
def GetAuthSubToken(self):
"""Returns the AuthSub Token after removing the AuthSub Authorization
Label.
The AuthSub Authorization Label reads: "AuthSub token"
Returns:
If the AuthSub Token is set AND it begins with the AuthSub
Authorization Label, the AuthSub Token is returned minus the AuthSub
Label. If the AuthSub Token does not start with the AuthSub
Authorization Label or it is not set, None is returned.
"""
if self.__auth_token.startswith(AUTHSUB_AUTH_LABEL):
# Strip off the leading 'AUTHSUB_AUTH_LABEL=' and just return the
# token value.
return self.__auth_token[len(AUTHSUB_AUTH_LABEL)+1:]
else:
return None
def SetAuthSubToken(self, token):
self.__auth_token = '%s=%s' % (AUTHSUB_AUTH_LABEL, token)
def GetClientLoginToken(self):
if self.__auth_token.startswith(PROGRAMMATIC_AUTH_LABEL):
# Strip off the leading 'PROGRAMMATIC_AUTH_LABEL=' and just return the
# token value.
return self.__auth_token[len(PROGRAMMATIC_AUTH_LABEL)+1:]
else:
return None
def SetClientLoginToken(self, token):
self.__auth_token = '%s=%s' % (PROGRAMMATIC_AUTH_LABEL, token)
# Private methods to create the source property.
def __GetSource(self):
return self.__source
def __SetSource(self, new_source):
self.__source = new_source
# Update the UserAgent header to include the new application name.
self.additional_headers['User-Agent'] = '%s GData-Python/1.1.1' % (
self.__source)
source = property(__GetSource, __SetSource,
doc="""The source is the name of the application making the request.
It should be in the form company_id-app_name-app_version""")
# Authentication operations
def 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
"""
request_body = gdata.auth.GenerateClientLoginRequestBody(self.email,
self.password, self.service, self.source, self.account_type,
captcha_token, captcha_response)
# If the user has defined their own authentication service URL,
# send the ClientLogin requests to this URL:
if not self.auth_service_url:
auth_request_url = AUTH_SERVER_HOST + '/accounts/ClientLogin'
else:
auth_request_url = self.auth_service_url
auth_response = self.handler.HttpRequest(self, 'POST', request_body,
auth_request_url,
extra_headers={'Content-Length':str(len(request_body))},
content_type='application/x-www-form-urlencoded')
response_body = auth_response.read()
if auth_response.status == 200:
self.__auth_token = gdata.auth.GenerateClientLoginAuthToken(
response_body)
self.__captcha_token = None
self.__captcha_url = None
elif auth_response.status == 403:
# Examine each line to find the error type and the captcha token and
# captch URL if they are present.
captcha_parameters = gdata.auth.GetCaptchChallenge(response_body,
captcha_base_url='%s/accounts/' % AUTH_SERVER_HOST)
if captcha_parameters:
self.__captcha_token = captcha_parameters['token']
self.__captcha_url = captcha_parameters['url']
raise CaptchaRequired, 'Captcha Required'
elif response_body.splitlines()[0] == 'Error=BadAuthentication':
self.__captcha_token = None
self.__captcha_url = None
raise BadAuthentication, 'Incorrect username or password'
else:
self.__captcha_token = None
self.__captcha_url = None
raise Error, 'Server responded with a 403 code'
elif auth_response.status == 302:
self.__captcha_token = None
self.__captcha_url = None
# Google tries to redirect all bad URLs back to
# http://www.google.<locale>. If a redirect
# attempt is made, assume the user has supplied an incorrect authentication URL
raise BadAuthenticationServiceURL, 'Server responded with a 302 code.'
def ClientLogin(self, username, password, account_type=None, service=None,
auth_service_url=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)
auth_service_url: string (optional)
captcha_token: string (optional)
captcha_response: string (optional)
"""
self.email = username
self.password = password
if account_type:
self.account_type = account_type
if service:
self.service = service
if source:
self.source = source
if auth_service_url:
self.auth_service_url = auth_service_url
self.ProgrammaticLogin(captcha_token, captcha_response)
def 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.
"""
# Translate True/False values for parameters into numeric values acceoted
# by the AuthSub service.
if secure:
secure = 1
else:
secure = 0
if session:
session = 1
else:
session = 0
request_params = urllib.urlencode({'next': next, 'scope': scope,
'secure': secure, 'session': session})
return '%s/accounts/AuthSubRequest?%s' % (AUTH_SERVER_HOST, request_params)
def 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
"""
if not self.__auth_token.startswith(AUTHSUB_AUTH_LABEL):
raise NonAuthSubToken
response = self.handler.HttpRequest(self, 'GET', None,
AUTH_SERVER_HOST + '/accounts/AuthSubSessionToken',
extra_headers={'Authorization':self.__auth_token},
content_type='application/x-www-form-urlencoded')
response_body = response.read()
if response.status == 200:
for response_line in response_body.splitlines():
if response_line.startswith('Token='):
self.SetAuthSubToken(response_line.lstrip('Token='))
def RevokeAuthSubToken(self):
"""Revokes an existing AuthSub token.
Raises:
NonAuthSubToken if the user's auth token is not an AuthSub token
"""
if not self.__auth_token.startswith(AUTHSUB_AUTH_LABEL):
raise NonAuthSubToken
response = self.handler.HttpRequest(self, 'GET', None,
AUTH_SERVER_HOST + '/accounts/AuthSubRevokeToken',
extra_headers={'Authorization':self.__auth_token},
content_type='application/x-www-form-urlencoded')
if response.status == 200:
self.__auth_token = None
# CRUD operations
def 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.
"""
if extra_headers is None:
extra_headers = {}
# Add the authentication header to the Get request
if self.__auth_token:
extra_headers['Authorization'] = self.__auth_token
if self.__gsessionid is not None:
if uri.find('gsessionid=') < 0:
if uri.find('?') > -1:
uri += '&gsessionid=%s' % (self.__gsessionid,)
else:
uri += '?gsessionid=%s' % (self.__gsessionid,)
server_response = self.handler.HttpRequest(self, 'GET', None, uri,
extra_headers=extra_headers)
result_body = server_response.read()
if server_response.status == 200:
if converter:
return converter(result_body)
# There was no ResultsTransformer specified, so try to convert the
# server's response into a GDataFeed.
feed = gdata.GDataFeedFromString(result_body)
if not feed:
# If conversion to a GDataFeed failed, try to convert the server's
# response to a GDataEntry.
entry = gdata.GDataEntryFromString(result_body)
if not entry:
# The server's response wasn't a feed, or an entry, so return the
# response body as a string.
return result_body
return entry
return feed
elif server_response.status == 302:
if redirects_remaining > 0:
location = server_response.getheader('Location')
if location is not None:
m = re.compile('[\?\&]gsessionid=(\w*)').search(location)
if m is not None:
self.__gsessionid = m.group(1)
return self.Get(location, extra_headers, redirects_remaining - 1,
encoding=encoding, converter=converter)
else:
raise RequestError, {'status': server_response.status,
'reason': '302 received without Location header',
'body': result_body}
else:
raise RequestError, {'status': server_response.status,
'reason': 'Redirect received, but redirects_remaining <= 0',
'body': result_body}
else:
raise RequestError, {'status': server_response.status,
'reason': server_response.reason, 'body': result_body}
def GetMedia(self, uri, extra_headers=None):
"""Returns a MediaSource containing media and its metadata from the given
URI string.
"""
response_handle = self.handler.HttpRequest(self, 'GET', None, uri,
extra_headers=extra_headers)
return gdata.MediaSource(response_handle, response_handle.getheader(
'Content-Type'),
response_handle.getheader('Content-Length'))
def GetEntry(self, uri, extra_headers=None):
"""Query the GData API with the given URI and receive an Entry.
See also documentation for gdata.service.Get
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.
Returns:
A GDataEntry built from the XML in the server's response.
"""
result = self.Get(uri, extra_headers, converter=atom.EntryFromString)
if isinstance(result, atom.Entry):
return result
else:
raise UnexpectedReturnType, 'Server did not send an entry'
def GetFeed(self, uri, extra_headers=None,
converter=gdata.GDataFeedFromString):
"""Query the GData API with the given URI and receive a Feed.
See also documentation for gdata.service.Get
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.
Returns:
A GDataFeed built from the XML in the server's response.
"""
result = self.Get(uri, extra_headers, converter=converter)
if isinstance(result, atom.Feed):
return result
else:
raise UnexpectedReturnType, 'Server did not send a feed'
def 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.
"""
next_link = feed.GetNextLink()
# Create a closure which will convert an XML string to the class of
# the feed object passed in.
def ConvertToFeedClass(xml_string):
return atom.CreateClassFromXMLString(feed.__class__, xml_string)
# Make a GET request on the next link and use the above closure for the
# converted which processes the XML string from the server.
if next_link and next_link.href:
return self.Get(next_link.href, converter=ConvertToFeedClass)
else:
return None
def Post(self, data, uri, extra_headers=None, url_params=None,
escape_params=True, redirects_remaining=4, media_source=None,
converter=None):
"""Insert or update 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).
"""
return self.PostOrPut('POST', data, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params,
redirects_remaining=redirects_remaining,
media_source=media_source, converter=converter)
def PostOrPut(self, verb, 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:
verb: string, either 'POST' or 'PUT'
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).
"""
if extra_headers is None:
extra_headers = {}
# Add the authentication header to the Get request
if self.__auth_token:
extra_headers['Authorization'] = self.__auth_token
if self.__gsessionid is not None:
if uri.find('gsessionid=') < 0:
if uri.find('?') > -1:
uri += '&gsessionid=%s' % (self.__gsessionid,)
else:
uri += '?gsessionid=%s' % (self.__gsessionid,)
if data and media_source:
if ElementTree.iselement(data):
data_str = ElementTree.tostring(data)
else:
data_str = str(data)
multipart = []
multipart.append('Media multipart posting\r\n--END_OF_PART\r\n' + \
'Content-Type: application/atom+xml\r\n\r\n')
multipart.append('\r\n--END_OF_PART\r\nContent-Type: ' + \
media_source.content_type+'\r\n\r\n')
multipart.append('\r\n--END_OF_PART--\r\n')
extra_headers['MIME-version'] = '1.0'
extra_headers['Content-Length'] = str(len(multipart[0]) +
len(multipart[1]) + len(multipart[2]) +
len(data_str) + media_source.content_length)
server_response = self.handler.HttpRequest(self, verb,
[multipart[0], data_str, multipart[1], media_source.file_handle,
multipart[2]], uri,
extra_headers=extra_headers, url_params=url_params,
escape_params=escape_params,
content_type='multipart/related; boundary=END_OF_PART')
result_body = server_response.read()
elif media_source or isinstance(data, gdata.MediaSource):
if isinstance(data, gdata.MediaSource):
media_source = data
extra_headers['Content-Length'] = str(media_source.content_length)
server_response = self.handler.HttpRequest(self, verb,
media_source.file_handle, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params,
content_type=media_source.content_type)
result_body = server_response.read()
else:
http_data = data
content_type = 'application/atom+xml'
server_response = self.handler.HttpRequest(self, verb,
http_data, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params,
content_type=content_type)
result_body = server_response.read()
# Server returns 201 for most post requests, but when performing a batch
# request the server responds with a 200 on success.
if server_response.status == 201 or server_response.status == 200:
if converter:
return converter(result_body)
feed = gdata.GDataFeedFromString(result_body)
if not feed:
entry = gdata.GDataEntryFromString(result_body)
if not entry:
return result_body
return entry
return feed
elif server_response.status == 302:
if redirects_remaining > 0:
location = server_response.getheader('Location')
if location is not None:
m = re.compile('[\?\&]gsessionid=(\w*)').search(location)
if m is not None:
self.__gsessionid = m.group(1)
return self.Post(data, location, extra_headers, url_params,
escape_params, redirects_remaining - 1, media_source,
converter=converter)
else:
raise RequestError, {'status': server_response.status,
'reason': '302 received without Location header',
'body': result_body}
else:
raise RequestError, {'status': server_response.status,
'reason': 'Redirect received, but redirects_remaining <= 0',
'body': result_body}
else:
raise RequestError, {'status': server_response.status,
'reason': server_response.reason, 'body': result_body}
def 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).
"""
return self.PostOrPut('PUT', data, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params,
redirects_remaining=redirects_remaining,
media_source=media_source, converter=converter)
def Delete(self, uri, extra_headers=None, url_params=None,
escape_params=True, redirects_remaining=4):
"""Deletes the entry at the given URI.
Args:
uri: string The URI of the entry to be deleted. Example:
'/base/feeds/items/ITEM-ID'
extra_headers: dict (optional) HTTP headers which are to be included.
The client automatically sets the Content-Type and
Authorization 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.
Returns:
True if the entry was deleted.
"""
if extra_headers is None:
extra_headers = {}
# Add the authentication header to the Get request
if self.__auth_token:
extra_headers['Authorization'] = self.__auth_token
if self.__gsessionid is not None:
if uri.find('gsessionid=') < 0:
if uri.find('?') > -1:
uri += '&gsessionid=%s' % (self.__gsessionid,)
else:
uri += '?gsessionid=%s' % (self.__gsessionid,)
server_response = self.handler.HttpRequest(self, 'DELETE', None, uri,
extra_headers=extra_headers, url_params=url_params,
escape_params=escape_params)
result_body = server_response.read()
if server_response.status == 200:
return True
elif server_response.status == 302:
if redirects_remaining > 0:
location = server_response.getheader('Location')
if location is not None:
m = re.compile('[\?\&]gsessionid=(\w*)').search(location)
if m is not None:
self.__gsessionid = m.group(1)
return self.Delete(location, extra_headers, url_params,
escape_params, redirects_remaining - 1)
else:
raise RequestError, {'status': server_response.status,
'reason': '302 received without Location header',
'body': result_body}
else:
raise RequestError, {'status': server_response.status,
'reason': 'Redirect received, but redirects_remaining <= 0',
'body': result_body}
else:
raise RequestError, {'status': server_response.status,
'reason': server_response.reason, 'body': result_body}
class Query(dict):
"""Constructs a query URL to be used in GET requests
Url parameters are created by adding key-value pairs to this object as a
dict. For example, to add &max-results=25 to the URL do
my_query['max-results'] = 25
Category queries are created by adding category strings to the categories
member. All items in the categories list will be concatenated with the /
symbol (symbolizing a category x AND y restriction). If you would like to OR
2 categories, append them as one string with a | between the categories.
For example, do query.categories.append('Fritz|Laurie') to create a query
like this feed/-/Fritz%7CLaurie . This query will look for results in both
categories.
"""
def __init__(self, feed=None, text_query=None, params=None,
categories=None):
"""Constructor for Query
Args:
feed: str (optional) The path for the feed (Examples:
'/base/feeds/snippets' or 'calendar/feeds/jo@gmail.com/private/full'
text_query: str (optional) The contents of the q query parameter. The
contents of the text_query are URL escaped upon conversion to a URI.
params: dict (optional) Parameter value string pairs which become URL
params when translated to a URI. These parameters are added to the
query's items (key-value pairs).
categories: list (optional) List of category strings which should be
included as query categories. See
http://code.google.com/apis/gdata/reference.html#Queries for
details. If you want to get results from category A or B (both
categories), specify a single list item 'A|B'.
"""
self.feed = feed
self.categories = []
if text_query:
self.text_query = text_query
if isinstance(params, dict):
for param in params:
self[param] = params[param]
if isinstance(categories, list):
for category in categories:
self.categories.append(category)
def _GetTextQuery(self):
if 'q' in self.keys():
return self['q']
else:
return None
def _SetTextQuery(self, query):
self['q'] = query
text_query = property(_GetTextQuery, _SetTextQuery,
doc="""The feed query's q parameter""")
def _GetAuthor(self):
if 'author' in self.keys():
return self['author']
else:
return None
def _SetAuthor(self, query):
self['author'] = query
author = property(_GetAuthor, _SetAuthor,
doc="""The feed query's author parameter""")
def _GetAlt(self):
if 'alt' in self.keys():
return self['alt']
else:
return None
def _SetAlt(self, query):
self['alt'] = query
alt = property(_GetAlt, _SetAlt,
doc="""The feed query's alt parameter""")
def _GetUpdatedMin(self):
if 'updated-min' in self.keys():
return self['updated-min']
else:
return None
def _SetUpdatedMin(self, query):
self['updated-min'] = query
updated_min = property(_GetUpdatedMin, _SetUpdatedMin,
doc="""The feed query's updated-min parameter""")
def _GetUpdatedMax(self):
if 'updated-max' in self.keys():
return self['updated-max']
else:
return None
def _SetUpdatedMax(self, query):
self['updated-max'] = query
updated_max = property(_GetUpdatedMax, _SetUpdatedMax,
doc="""The feed query's updated-max parameter""")
def _GetPublishedMin(self):
if 'published-min' in self.keys():
return self['published-min']
else:
return None
def _SetPublishedMin(self, query):
self['published-min'] = query
published_min = property(_GetPublishedMin, _SetPublishedMin,
doc="""The feed query's published-min parameter""")
def _GetPublishedMax(self):
if 'published-max' in self.keys():
return self['published-max']
else:
return None
def _SetPublishedMax(self, query):
self['published-max'] = query
published_max = property(_GetPublishedMax, _SetPublishedMax,
doc="""The feed query's published-max parameter""")
def _GetStartIndex(self):
if 'start-index' in self.keys():
return self['start-index']
else:
return None
def _SetStartIndex(self, query):
if not isinstance(query, str):
query = str(query)
self['start-index'] = query
start_index = property(_GetStartIndex, _SetStartIndex,
doc="""The feed query's start-index parameter""")
def _GetMaxResults(self):
if 'max-results' in self.keys():
return self['max-results']
else:
return None
def _SetMaxResults(self, query):
if not isinstance(query, str):
query = str(query)
self['max-results'] = query
max_results = property(_GetMaxResults, _SetMaxResults,
doc="""The feed query's max-results parameter""")
def _GetOrderBy(self):
if 'orderby' in self.keys():
return self['orderby']
else:
return None
def _SetOrderBy(self, query):
self['orderby'] = query
orderby = property(_GetOrderBy, _SetOrderBy,
doc="""The feed query's orderby parameter""")
def ToUri(self):
q_feed = self.feed or ''
category_string = '/'.join(
[urllib.quote_plus(c) for c in self.categories])
# Add categories to the feed if there are any.
if len(self.categories) > 0:
q_feed = q_feed + '/-/' + category_string
return atom.service.BuildUri(q_feed, self)
def __str__(self):
return self.ToUri()
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""GDataService provides CRUD ops. and programmatic login for GData services.
Error: A base exception class for all exceptions in the gdata_client
module.
CaptchaRequired: This exception is thrown when a login attempt results in a
captcha challenge from the ClientLogin service. When this
exception is thrown, the captcha_token and captcha_url are
set to the values provided in the server's response.
BadAuthentication: Raised when a login attempt is made with an incorrect
username or password.
NotAuthenticated: Raised if an operation requiring authentication is called
before a user has authenticated.
NonAuthSubToken: Raised if a method to modify an AuthSub token is used when
the user is either not authenticated or is authenticated
through programmatic login.
RequestError: Raised if a CRUD request returned a non-success code.
UnexpectedReturnType: Raised if the response from the server was not of the
desired type. For example, this would be raised if the
server sent a feed when the client requested an entry.
GDataService: Encapsulates user credentials needed to perform insert, update
and delete operations with the GData API. An instance can
perform user authentication, query, insertion, deletion, and
update.
Query: Eases query URI creation by allowing URI parameters to be set as
dictionary attributes. For example a query with a feed of
'/base/feeds/snippets' and ['bq'] set to 'digital camera' will
produce '/base/feeds/snippets?bq=digital+camera' when .ToUri() is
called on it.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
import re
import httplib
import urllib
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import atom.service
import gdata
import atom
import gdata.auth
PROGRAMMATIC_AUTH_LABEL = 'GoogleLogin auth'
AUTHSUB_AUTH_LABEL = 'AuthSub token'
AUTH_SERVER_HOST = 'https://www.google.com'
# Module level variable specifies which module should be used by GDataService
# objects to make HttpRequests. This setting can be overridden on each
# instance of GDataService.
http_request_handler = atom.service
class Error(Exception):
pass
class CaptchaRequired(Error):
pass
class BadAuthentication(Error):
pass
class NotAuthenticated(Error):
pass
class NonAuthSubToken(Error):
pass
class RequestError(Error):
pass
class UnexpectedReturnType(Error):
pass
class BadAuthenticationServiceURL(Error):
pass
class GDataService(atom.service.AtomService):
"""Contains elements needed for GData login and CRUD request headers.
Maintains additional headers (tokens for example) needed for the GData
services to allow a user to perform inserts, updates, and deletes.
"""
def __init__(self, email=None, password=None, account_type='HOSTED_OR_GOOGLE',
service=None, auth_service_url=None, source=None, server=None,
additional_headers=None, handler=None):
"""Creates an object of type GDataService.
Args:
email: string (optional) The user's email address, used for
authentication.
password: string (optional) The user's password.
account_type: string (optional) The type of account to use. Use
'GOOGLE' for regular Google accounts or 'HOSTED' for Google
Apps accounts, or 'HOSTED_OR_GOOGLE' to try finding a HOSTED
account first and, if it doesn't exist, try finding a regular
GOOGLE account. Default value: 'HOSTED_OR_GOOGLE'.
service: string (optional) The desired service for which credentials
will be obtained.
auth_service_url: string (optional) User-defined auth token request URL
allows users to explicitly specify where to send auth token requests.
source: string (optional) The name of the user's application.
server: string (optional) The name of the server to which a connection
will be opened. Default value: 'base.google.com'.
additional_headers: dictionary (optional) Any additional headers which
should be included with CRUD operations.
handler: module (optional) The module whose HttpRequest function
should be used when making requests to the server. The default
value is atom.service.
"""
self.email = email
self.password = password
self.account_type = account_type
self.service = service
self.auth_service_url = auth_service_url
self.server = server
self.additional_headers = additional_headers or {}
self.handler = handler or http_request_handler
self.__SetSource(source)
self.__auth_token = None
self.__captcha_token = None
self.__captcha_url = None
self.__gsessionid = None
# Define properties for GDataService
def _SetAuthSubToken(self, auth_token):
"""Sets the token sent in requests to an AuthSub token.
Only use this method if you have received a token from the AuthSub
service. The auth_token is set automatically when ProgrammaticLogin()
is used. See documentation for Google AuthSub here:
http://code.google.com/apis/accounts/AuthForWebApps.html .
Args:
auth_token: string The token returned by the AuthSub service.
"""
self.__auth_token = '%s=%s' % (AUTHSUB_AUTH_LABEL, auth_token)
# The auth token is only set externally when using AuthSub authentication,
# so set the auth_type to indicate AuthSub.
def __SetAuthSubToken(self, auth_token):
self._SetAuthSubToken(auth_token)
def _GetAuthToken(self):
"""Returns the auth token used for authenticating requests.
Returns:
string
"""
return self.__auth_token
def __GetAuthToken(self):
return self._GetAuthToken()
auth_token = property(__GetAuthToken, __SetAuthSubToken,
doc="""Get or set the token used for authentication.""")
def _GetCaptchaToken(self):
"""Returns a captcha token if the most recent login attempt generated one.
The captcha token is only set if the Programmatic Login attempt failed
because the Google service issued a captcha challenge.
Returns:
string
"""
return self.__captcha_token
def __GetCaptchaToken(self):
return self._GetCaptchaToken()
captcha_token = property(__GetCaptchaToken,
doc="""Get the captcha token for a login request.""")
def _GetCaptchaURL(self):
"""Returns the URL of the captcha image if a login attempt generated one.
The captcha URL is only set if the Programmatic Login attempt failed
because the Google service issued a captcha challenge.
Returns:
string
"""
return self.__captcha_url
def __GetCaptchaURL(self):
return self._GetCaptchaURL()
captcha_url = property(__GetCaptchaURL,
doc="""Get the captcha URL for a login request.""")
def GetAuthSubToken(self):
"""Returns the AuthSub Token after removing the AuthSub Authorization
Label.
The AuthSub Authorization Label reads: "AuthSub token"
Returns:
If the AuthSub Token is set AND it begins with the AuthSub
Authorization Label, the AuthSub Token is returned minus the AuthSub
Label. If the AuthSub Token does not start with the AuthSub
Authorization Label or it is not set, None is returned.
"""
if self.__auth_token.startswith(AUTHSUB_AUTH_LABEL):
# Strip off the leading 'AUTHSUB_AUTH_LABEL=' and just return the
# token value.
return self.__auth_token[len(AUTHSUB_AUTH_LABEL)+1:]
else:
return None
def SetAuthSubToken(self, token):
self.__auth_token = '%s=%s' % (AUTHSUB_AUTH_LABEL, token)
def GetClientLoginToken(self):
if self.__auth_token.startswith(PROGRAMMATIC_AUTH_LABEL):
# Strip off the leading 'PROGRAMMATIC_AUTH_LABEL=' and just return the
# token value.
return self.__auth_token[len(PROGRAMMATIC_AUTH_LABEL)+1:]
else:
return None
def SetClientLoginToken(self, token):
self.__auth_token = '%s=%s' % (PROGRAMMATIC_AUTH_LABEL, token)
# Private methods to create the source property.
def __GetSource(self):
return self.__source
def __SetSource(self, new_source):
self.__source = new_source
# Update the UserAgent header to include the new application name.
self.additional_headers['User-Agent'] = '%s GData-Python/1.1.1' % (
self.__source)
source = property(__GetSource, __SetSource,
doc="""The source is the name of the application making the request.
It should be in the form company_id-app_name-app_version""")
# Authentication operations
def 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
"""
request_body = gdata.auth.GenerateClientLoginRequestBody(self.email,
self.password, self.service, self.source, self.account_type,
captcha_token, captcha_response)
# If the user has defined their own authentication service URL,
# send the ClientLogin requests to this URL:
if not self.auth_service_url:
auth_request_url = AUTH_SERVER_HOST + '/accounts/ClientLogin'
else:
auth_request_url = self.auth_service_url
auth_response = self.handler.HttpRequest(self, 'POST', request_body,
auth_request_url,
extra_headers={'Content-Length':str(len(request_body))},
content_type='application/x-www-form-urlencoded')
response_body = auth_response.read()
if auth_response.status == 200:
self.__auth_token = gdata.auth.GenerateClientLoginAuthToken(
response_body)
self.__captcha_token = None
self.__captcha_url = None
elif auth_response.status == 403:
# Examine each line to find the error type and the captcha token and
# captch URL if they are present.
captcha_parameters = gdata.auth.GetCaptchChallenge(response_body,
captcha_base_url='%s/accounts/' % AUTH_SERVER_HOST)
if captcha_parameters:
self.__captcha_token = captcha_parameters['token']
self.__captcha_url = captcha_parameters['url']
raise CaptchaRequired, 'Captcha Required'
elif response_body.splitlines()[0] == 'Error=BadAuthentication':
self.__captcha_token = None
self.__captcha_url = None
raise BadAuthentication, 'Incorrect username or password'
else:
self.__captcha_token = None
self.__captcha_url = None
raise Error, 'Server responded with a 403 code'
elif auth_response.status == 302:
self.__captcha_token = None
self.__captcha_url = None
# Google tries to redirect all bad URLs back to
# http://www.google.<locale>. If a redirect
# attempt is made, assume the user has supplied an incorrect authentication URL
raise BadAuthenticationServiceURL, 'Server responded with a 302 code.'
def ClientLogin(self, username, password, account_type=None, service=None,
auth_service_url=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)
auth_service_url: string (optional)
captcha_token: string (optional)
captcha_response: string (optional)
"""
self.email = username
self.password = password
if account_type:
self.account_type = account_type
if service:
self.service = service
if source:
self.source = source
if auth_service_url:
self.auth_service_url = auth_service_url
self.ProgrammaticLogin(captcha_token, captcha_response)
def 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.
"""
# Translate True/False values for parameters into numeric values acceoted
# by the AuthSub service.
if secure:
secure = 1
else:
secure = 0
if session:
session = 1
else:
session = 0
request_params = urllib.urlencode({'next': next, 'scope': scope,
'secure': secure, 'session': session})
return '%s/accounts/AuthSubRequest?%s' % (AUTH_SERVER_HOST, request_params)
def 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
"""
if not self.__auth_token.startswith(AUTHSUB_AUTH_LABEL):
raise NonAuthSubToken
response = self.handler.HttpRequest(self, 'GET', None,
AUTH_SERVER_HOST + '/accounts/AuthSubSessionToken',
extra_headers={'Authorization':self.__auth_token},
content_type='application/x-www-form-urlencoded')
response_body = response.read()
if response.status == 200:
for response_line in response_body.splitlines():
if response_line.startswith('Token='):
self.SetAuthSubToken(response_line.lstrip('Token='))
def RevokeAuthSubToken(self):
"""Revokes an existing AuthSub token.
Raises:
NonAuthSubToken if the user's auth token is not an AuthSub token
"""
if not self.__auth_token.startswith(AUTHSUB_AUTH_LABEL):
raise NonAuthSubToken
response = self.handler.HttpRequest(self, 'GET', None,
AUTH_SERVER_HOST + '/accounts/AuthSubRevokeToken',
extra_headers={'Authorization':self.__auth_token},
content_type='application/x-www-form-urlencoded')
if response.status == 200:
self.__auth_token = None
# CRUD operations
def 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.
"""
if extra_headers is None:
extra_headers = {}
# Add the authentication header to the Get request
if self.__auth_token:
extra_headers['Authorization'] = self.__auth_token
if self.__gsessionid is not None:
if uri.find('gsessionid=') < 0:
if uri.find('?') > -1:
uri += '&gsessionid=%s' % (self.__gsessionid,)
else:
uri += '?gsessionid=%s' % (self.__gsessionid,)
server_response = self.handler.HttpRequest(self, 'GET', None, uri,
extra_headers=extra_headers)
result_body = server_response.read()
if server_response.status == 200:
if converter:
return converter(result_body)
# There was no ResultsTransformer specified, so try to convert the
# server's response into a GDataFeed.
feed = gdata.GDataFeedFromString(result_body)
if not feed:
# If conversion to a GDataFeed failed, try to convert the server's
# response to a GDataEntry.
entry = gdata.GDataEntryFromString(result_body)
if not entry:
# The server's response wasn't a feed, or an entry, so return the
# response body as a string.
return result_body
return entry
return feed
elif server_response.status == 302:
if redirects_remaining > 0:
location = server_response.getheader('Location')
if location is not None:
m = re.compile('[\?\&]gsessionid=(\w*)').search(location)
if m is not None:
self.__gsessionid = m.group(1)
return self.Get(location, extra_headers, redirects_remaining - 1,
encoding=encoding, converter=converter)
else:
raise RequestError, {'status': server_response.status,
'reason': '302 received without Location header',
'body': result_body}
else:
raise RequestError, {'status': server_response.status,
'reason': 'Redirect received, but redirects_remaining <= 0',
'body': result_body}
else:
raise RequestError, {'status': server_response.status,
'reason': server_response.reason, 'body': result_body}
def GetMedia(self, uri, extra_headers=None):
"""Returns a MediaSource containing media and its metadata from the given
URI string.
"""
response_handle = self.handler.HttpRequest(self, 'GET', None, uri,
extra_headers=extra_headers)
return gdata.MediaSource(response_handle, response_handle.getheader(
'Content-Type'),
response_handle.getheader('Content-Length'))
def GetEntry(self, uri, extra_headers=None):
"""Query the GData API with the given URI and receive an Entry.
See also documentation for gdata.service.Get
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.
Returns:
A GDataEntry built from the XML in the server's response.
"""
result = self.Get(uri, extra_headers, converter=atom.EntryFromString)
if isinstance(result, atom.Entry):
return result
else:
raise UnexpectedReturnType, 'Server did not send an entry'
def GetFeed(self, uri, extra_headers=None,
converter=gdata.GDataFeedFromString):
"""Query the GData API with the given URI and receive a Feed.
See also documentation for gdata.service.Get
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.
Returns:
A GDataFeed built from the XML in the server's response.
"""
result = self.Get(uri, extra_headers, converter=converter)
if isinstance(result, atom.Feed):
return result
else:
raise UnexpectedReturnType, 'Server did not send a feed'
def 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.
"""
next_link = feed.GetNextLink()
# Create a closure which will convert an XML string to the class of
# the feed object passed in.
def ConvertToFeedClass(xml_string):
return atom.CreateClassFromXMLString(feed.__class__, xml_string)
# Make a GET request on the next link and use the above closure for the
# converted which processes the XML string from the server.
if next_link and next_link.href:
return self.Get(next_link.href, converter=ConvertToFeedClass)
else:
return None
def Post(self, data, uri, extra_headers=None, url_params=None,
escape_params=True, redirects_remaining=4, media_source=None,
converter=None):
"""Insert or update 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).
"""
return self.PostOrPut('POST', data, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params,
redirects_remaining=redirects_remaining,
media_source=media_source, converter=converter)
def PostOrPut(self, verb, 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:
verb: string, either 'POST' or 'PUT'
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).
"""
if extra_headers is None:
extra_headers = {}
# Add the authentication header to the Get request
if self.__auth_token:
extra_headers['Authorization'] = self.__auth_token
if self.__gsessionid is not None:
if uri.find('gsessionid=') < 0:
if uri.find('?') > -1:
uri += '&gsessionid=%s' % (self.__gsessionid,)
else:
uri += '?gsessionid=%s' % (self.__gsessionid,)
if data and media_source:
if ElementTree.iselement(data):
data_str = ElementTree.tostring(data)
else:
data_str = str(data)
multipart = []
multipart.append('Media multipart posting\r\n--END_OF_PART\r\n' + \
'Content-Type: application/atom+xml\r\n\r\n')
multipart.append('\r\n--END_OF_PART\r\nContent-Type: ' + \
media_source.content_type+'\r\n\r\n')
multipart.append('\r\n--END_OF_PART--\r\n')
extra_headers['MIME-version'] = '1.0'
extra_headers['Content-Length'] = str(len(multipart[0]) +
len(multipart[1]) + len(multipart[2]) +
len(data_str) + media_source.content_length)
server_response = self.handler.HttpRequest(self, verb,
[multipart[0], data_str, multipart[1], media_source.file_handle,
multipart[2]], uri,
extra_headers=extra_headers, url_params=url_params,
escape_params=escape_params,
content_type='multipart/related; boundary=END_OF_PART')
result_body = server_response.read()
elif media_source or isinstance(data, gdata.MediaSource):
if isinstance(data, gdata.MediaSource):
media_source = data
extra_headers['Content-Length'] = str(media_source.content_length)
server_response = self.handler.HttpRequest(self, verb,
media_source.file_handle, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params,
content_type=media_source.content_type)
result_body = server_response.read()
else:
http_data = data
content_type = 'application/atom+xml'
server_response = self.handler.HttpRequest(self, verb,
http_data, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params,
content_type=content_type)
result_body = server_response.read()
# Server returns 201 for most post requests, but when performing a batch
# request the server responds with a 200 on success.
if server_response.status == 201 or server_response.status == 200:
if converter:
return converter(result_body)
feed = gdata.GDataFeedFromString(result_body)
if not feed:
entry = gdata.GDataEntryFromString(result_body)
if not entry:
return result_body
return entry
return feed
elif server_response.status == 302:
if redirects_remaining > 0:
location = server_response.getheader('Location')
if location is not None:
m = re.compile('[\?\&]gsessionid=(\w*)').search(location)
if m is not None:
self.__gsessionid = m.group(1)
return self.Post(data, location, extra_headers, url_params,
escape_params, redirects_remaining - 1, media_source,
converter=converter)
else:
raise RequestError, {'status': server_response.status,
'reason': '302 received without Location header',
'body': result_body}
else:
raise RequestError, {'status': server_response.status,
'reason': 'Redirect received, but redirects_remaining <= 0',
'body': result_body}
else:
raise RequestError, {'status': server_response.status,
'reason': server_response.reason, 'body': result_body}
def 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).
"""
return self.PostOrPut('PUT', data, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params,
redirects_remaining=redirects_remaining,
media_source=media_source, converter=converter)
def Delete(self, uri, extra_headers=None, url_params=None,
escape_params=True, redirects_remaining=4):
"""Deletes the entry at the given URI.
Args:
uri: string The URI of the entry to be deleted. Example:
'/base/feeds/items/ITEM-ID'
extra_headers: dict (optional) HTTP headers which are to be included.
The client automatically sets the Content-Type and
Authorization 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.
Returns:
True if the entry was deleted.
"""
if extra_headers is None:
extra_headers = {}
# Add the authentication header to the Get request
if self.__auth_token:
extra_headers['Authorization'] = self.__auth_token
if self.__gsessionid is not None:
if uri.find('gsessionid=') < 0:
if uri.find('?') > -1:
uri += '&gsessionid=%s' % (self.__gsessionid,)
else:
uri += '?gsessionid=%s' % (self.__gsessionid,)
server_response = self.handler.HttpRequest(self, 'DELETE', None, uri,
extra_headers=extra_headers, url_params=url_params,
escape_params=escape_params)
result_body = server_response.read()
if server_response.status == 200:
return True
elif server_response.status == 302:
if redirects_remaining > 0:
location = server_response.getheader('Location')
if location is not None:
m = re.compile('[\?\&]gsessionid=(\w*)').search(location)
if m is not None:
self.__gsessionid = m.group(1)
return self.Delete(location, extra_headers, url_params,
escape_params, redirects_remaining - 1)
else:
raise RequestError, {'status': server_response.status,
'reason': '302 received without Location header',
'body': result_body}
else:
raise RequestError, {'status': server_response.status,
'reason': 'Redirect received, but redirects_remaining <= 0',
'body': result_body}
else:
raise RequestError, {'status': server_response.status,
'reason': server_response.reason, 'body': result_body}
class Query(dict):
"""Constructs a query URL to be used in GET requests
Url parameters are created by adding key-value pairs to this object as a
dict. For example, to add &max-results=25 to the URL do
my_query['max-results'] = 25
Category queries are created by adding category strings to the categories
member. All items in the categories list will be concatenated with the /
symbol (symbolizing a category x AND y restriction). If you would like to OR
2 categories, append them as one string with a | between the categories.
For example, do query.categories.append('Fritz|Laurie') to create a query
like this feed/-/Fritz%7CLaurie . This query will look for results in both
categories.
"""
def __init__(self, feed=None, text_query=None, params=None,
categories=None):
"""Constructor for Query
Args:
feed: str (optional) The path for the feed (Examples:
'/base/feeds/snippets' or 'calendar/feeds/jo@gmail.com/private/full'
text_query: str (optional) The contents of the q query parameter. The
contents of the text_query are URL escaped upon conversion to a URI.
params: dict (optional) Parameter value string pairs which become URL
params when translated to a URI. These parameters are added to the
query's items (key-value pairs).
categories: list (optional) List of category strings which should be
included as query categories. See
http://code.google.com/apis/gdata/reference.html#Queries for
details. If you want to get results from category A or B (both
categories), specify a single list item 'A|B'.
"""
self.feed = feed
self.categories = []
if text_query:
self.text_query = text_query
if isinstance(params, dict):
for param in params:
self[param] = params[param]
if isinstance(categories, list):
for category in categories:
self.categories.append(category)
def _GetTextQuery(self):
if 'q' in self.keys():
return self['q']
else:
return None
def _SetTextQuery(self, query):
self['q'] = query
text_query = property(_GetTextQuery, _SetTextQuery,
doc="""The feed query's q parameter""")
def _GetAuthor(self):
if 'author' in self.keys():
return self['author']
else:
return None
def _SetAuthor(self, query):
self['author'] = query
author = property(_GetAuthor, _SetAuthor,
doc="""The feed query's author parameter""")
def _GetAlt(self):
if 'alt' in self.keys():
return self['alt']
else:
return None
def _SetAlt(self, query):
self['alt'] = query
alt = property(_GetAlt, _SetAlt,
doc="""The feed query's alt parameter""")
def _GetUpdatedMin(self):
if 'updated-min' in self.keys():
return self['updated-min']
else:
return None
def _SetUpdatedMin(self, query):
self['updated-min'] = query
updated_min = property(_GetUpdatedMin, _SetUpdatedMin,
doc="""The feed query's updated-min parameter""")
def _GetUpdatedMax(self):
if 'updated-max' in self.keys():
return self['updated-max']
else:
return None
def _SetUpdatedMax(self, query):
self['updated-max'] = query
updated_max = property(_GetUpdatedMax, _SetUpdatedMax,
doc="""The feed query's updated-max parameter""")
def _GetPublishedMin(self):
if 'published-min' in self.keys():
return self['published-min']
else:
return None
def _SetPublishedMin(self, query):
self['published-min'] = query
published_min = property(_GetPublishedMin, _SetPublishedMin,
doc="""The feed query's published-min parameter""")
def _GetPublishedMax(self):
if 'published-max' in self.keys():
return self['published-max']
else:
return None
def _SetPublishedMax(self, query):
self['published-max'] = query
published_max = property(_GetPublishedMax, _SetPublishedMax,
doc="""The feed query's published-max parameter""")
def _GetStartIndex(self):
if 'start-index' in self.keys():
return self['start-index']
else:
return None
def _SetStartIndex(self, query):
if not isinstance(query, str):
query = str(query)
self['start-index'] = query
start_index = property(_GetStartIndex, _SetStartIndex,
doc="""The feed query's start-index parameter""")
def _GetMaxResults(self):
if 'max-results' in self.keys():
return self['max-results']
else:
return None
def _SetMaxResults(self, query):
if not isinstance(query, str):
query = str(query)
self['max-results'] = query
max_results = property(_GetMaxResults, _SetMaxResults,
doc="""The feed query's max-results parameter""")
def _GetOrderBy(self):
if 'orderby' in self.keys():
return self['orderby']
else:
return None
def _SetOrderBy(self, query):
self['orderby'] = query
orderby = property(_GetOrderBy, _SetOrderBy,
doc="""The feed query's orderby parameter""")
def ToUri(self):
q_feed = self.feed or ''
category_string = '/'.join(
[urllib.quote_plus(c) for c in self.categories])
# Add categories to the feed if there are any.
if len(self.categories) > 0:
q_feed = q_feed + '/-/' + category_string
return atom.service.BuildUri(q_feed, self)
def __str__(self):
return self.ToUri()
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to Atom objects used with Google Documents."""
__author__ = 'api.jfisher (Jeff Fisher)'
import atom
import gdata
class DocumentListEntry(gdata.GDataEntry):
"""The Google Documents version of an Atom Entry"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
def DocumentListEntryFromString(xml_string):
"""Converts an XML string into a DocumentListEntry object.
Args:
xml_string: string The XML describing a Document List feed entry.
Returns:
A DocumentListEntry object corresponding to the given XML.
"""
return atom.CreateClassFromXMLString(DocumentListEntry, xml_string)
class DocumentListFeed(gdata.GDataFeed):
"""A feed containing a list of Google Documents Items"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[DocumentListEntry])
def DocumentListFeedFromString(xml_string):
"""Converts an XML string into a DocumentListFeed object.
Args:
xml_string: string The XML describing a DocumentList feed.
Returns:
A DocumentListFeed object corresponding to the given XML.
"""
return atom.CreateClassFromXMLString(DocumentListFeed, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""DocsService extends the GDataService to streamline Google Documents
operations.
DocsService: Provides methods to query feeds and manipulate items.
Extends GDataService.
DocumentQuery: Queries a Google Document list feed.
"""
__author__ = 'api.jfisher (Jeff Fisher)'
import urllib
import atom
import gdata.service
import gdata.docs
# XML Namespaces used in Google Documents entities.
DATA_KIND_SCHEME = 'http://schemas.google.com/g/2005#kind'
DOCUMENT_KIND_TERM = 'http://schemas.google.com/docs/2007#document'
SPREADSHEET_KIND_TERM = 'http://schemas.google.com/docs/2007#spreadsheet'
PRESENTATION_KIND_TERM = 'http://schemas.google.com/docs/2007#presentation'
# File extensions of documents that are permitted to be uploaded.
SUPPORTED_FILETYPES = {
'CSV': 'text/csv',
'TSV': 'text/tab-separated-values',
'TAB': 'text/tab-separated-values',
'DOC': 'application/msword',
'ODS': 'application/x-vnd.oasis.opendocument.spreadsheet',
'ODT': 'application/vnd.oasis.opendocument.text',
'RTF': 'application/rtf',
'SXW': 'application/vnd.sun.xml.writer',
'TXT': 'text/plain',
'XLS': 'application/vnd.ms-excel',
'PPT': 'application/vnd.ms-powerpoint',
'PPS': 'application/vnd.ms-powerpoint',
'HTM': 'text/html',
'HTML' : 'text/html'}
class DocsService(gdata.service.GDataService):
"""Client extension for the Google Documents service Document List feed."""
def __init__(self, email=None, password=None, source=None,
server='docs.google.com', additional_headers=None):
"""Constructor for the DocsService.
Args:
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.
Yields:
A DocsService object used to communicate with the Google Documents
service.
"""
gdata.service.GDataService.__init__(self, email=email, password=password,
service='writely', source=source,
server=server,
additional_headers=additional_headers)
def Query(self, uri, converter=gdata.docs.DocumentListFeedFromString):
"""Queries the Document List feed and returns the resulting feed of
entries.
Args:
uri: string The full URI to be queried. This can contain query
parameters, a hostname, or simply the relative path to a Document
List feed. The DocumentQuery object is useful when constructing
query parameters.
converter: func (optional) A function which will be executed on the
retrieved item, generally to render it into a Python object.
By default the DocumentListFeedFromString function is used to
return a DocumentListFeed object. This is because most feed
queries will result in a feed and not a single entry.
"""
return self.Get(uri, converter=converter)
def QueryDocumentListFeed(self, uri):
"""Retrieves a DocumentListFeed by retrieving a URI based off the Document
List feed, including any query parameters. A DocumentQuery object can
be used to construct these parameters.
Args:
uri: string The URI of the feed being retrieved possibly with query
parameters.
Returns:
A DocumentListFeed object representing the feed returned by the server.
"""
return self.Get(uri, converter=gdata.docs.DocumentListFeedFromString)
def GetDocumentListEntry(self, uri):
"""Retrieves a particular DocumentListEntry by its unique URI.
Args:
uri: string The unique URI of an entry in a Document List feed.
Returns:
A DocumentListEntry object representing the retrieved entry.
"""
return self.Get(uri, converter=gdata.docs.DocumentListEntryFromString)
def GetDocumentListFeed(self):
"""Retrieves a feed containing all of a user's documents."""
q = gdata.docs.service.DocumentQuery();
return self.QueryDocumentListFeed(q.ToUri())
def UploadPresentation(self, media_source, title):
"""Uploads a presentation inside of a MediaSource object to the Document
List feed with the given title.
Args:
media_source: MediaSource The MediaSource object containing a
presentation file to be uploaded.
title: string The title of the presentation on the server after being
uploaded.
Returns:
A GDataEntry containing information about the presentation created on the
Google Documents service.
"""
category = atom.Category(scheme=DATA_KIND_SCHEME,
term=PRESENTATION_KIND_TERM)
return self._UploadFile(media_source, title, category)
def UploadSpreadsheet(self, media_source, title):
"""Uploads a spreadsheet inside of a MediaSource object to the Document
List feed with the given title.
Args:
media_source: MediaSource The MediaSource object containing a spreadsheet
file to be uploaded.
title: string The title of the spreadsheet on the server after being
uploaded.
Returns:
A GDataEntry containing information about the spreadsheet created on the
Google Documents service.
"""
category = atom.Category(scheme=DATA_KIND_SCHEME,
term=SPREADSHEET_KIND_TERM)
return self._UploadFile(media_source, title, category)
def UploadDocument(self, media_source, title):
"""Uploads a document inside of a MediaSource object to the Document List
feed with the given title.
Args:
media_source: MediaSource The gdata.MediaSource object containing a
document file to be uploaded.
title: string The title of the document on the server after being
uploaded.
Returns:
A GDataEntry containing information about the document created on the
Google Documents service.
"""
category = atom.Category(scheme=DATA_KIND_SCHEME,
term=DOCUMENT_KIND_TERM)
return self._UploadFile(media_source, title, category)
def _UploadFile(self, media_source, title, category):
"""Uploads a file to the Document List feed.
Args:
media_source: A gdata.MediaSource object containing the file to be
uploaded.
title: string The title of the document on the server after being
uploaded.
category: An atom.Category object specifying the appropriate document
type
Returns:
A GDataEntry containing information about the document created on
the Google Documents service.
"""
media_entry = gdata.GDataEntry()
media_entry.title = atom.Title(text=title)
media_entry.category.append(category)
media_entry = self.Post(media_entry, '/feeds/documents/private/full',
media_source = media_source,
extra_headers = {'Slug' : media_source.file_name })
return media_entry
class DocumentQuery(gdata.service.Query):
"""Object used to construct a URI to query the Google Document List feed"""
def __init__(self, feed='/feeds/documents', visibility='private',
projection='full', text_query=None, params=None,
categories=None):
"""Constructor for Document List Query
Args:
feed: string (optional) The path for the feed. (e.g. '/feeds/documents')
visibility: string (optional) The visibility chosen for the current feed.
projection: string (optional) The projection chosen for the current feed.
text_query: string (optional) The contents of the q query parameter. This
string is URL escaped upon conversion to a URI.
params: dict (optional) Parameter value string pairs which become URL
params when translated to a URI. These parameters are added to
the query's items.
categories: list (optional) List of category strings which should be
included as query categories. See gdata.service.Query for
additional documentation.
Yields:
A DocumentQuery object used to construct a URI based on the Document
List feed.
"""
self.visibility = visibility
self.projection = projection
gdata.service.Query.__init__(self, feed, text_query, params, categories)
def ToUri(self):
"""Generates a URI from the query parameters set in the object.
Returns:
A string containing the URI used to retrieve entries from the Document
List feed.
"""
old_feed = self.feed
self.feed = '/'.join([old_feed, self.visibility, self.projection])
new_feed = gdata.service.Query.ToUri(self)
self.feed = old_feed
return new_feed
def AddNamedFolder(self, email, folder_name):
"""Adds a named folder category, qualified by a schema.
This function lets you query for documents that are contained inside a
named folder without fear of collision with other categories.
Args:
email: string The email of the user who owns the folder.
folder_name: string The name of the folder.
Returns:
The string of the category that was added to the object.
"""
category = '{http://schemas.google.com/docs/2007/folders/'
category += email + '}' + folder_name
self.categories.append(category)
return category
def RemoveNamedFolder(self, email, folder_name):
"""Removes a named folder category, qualified by a schema.
Args:
email: string The email of the user who owns the folder.
folder_name: string The name of the folder.
Returns:
The string of the category that was removed to the object.
"""
category = '{http://schemas.google.com/docs/2007/folders/'
category += email + '}' + folder_name
self.categories.remove(category)
return category
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""DocsService extends the GDataService to streamline Google Documents
operations.
DocsService: Provides methods to query feeds and manipulate items.
Extends GDataService.
DocumentQuery: Queries a Google Document list feed.
"""
__author__ = 'api.jfisher (Jeff Fisher)'
import urllib
import atom
import gdata.service
import gdata.docs
# XML Namespaces used in Google Documents entities.
DATA_KIND_SCHEME = 'http://schemas.google.com/g/2005#kind'
DOCUMENT_KIND_TERM = 'http://schemas.google.com/docs/2007#document'
SPREADSHEET_KIND_TERM = 'http://schemas.google.com/docs/2007#spreadsheet'
PRESENTATION_KIND_TERM = 'http://schemas.google.com/docs/2007#presentation'
# File extensions of documents that are permitted to be uploaded.
SUPPORTED_FILETYPES = {
'CSV': 'text/csv',
'TSV': 'text/tab-separated-values',
'TAB': 'text/tab-separated-values',
'DOC': 'application/msword',
'ODS': 'application/x-vnd.oasis.opendocument.spreadsheet',
'ODT': 'application/vnd.oasis.opendocument.text',
'RTF': 'application/rtf',
'SXW': 'application/vnd.sun.xml.writer',
'TXT': 'text/plain',
'XLS': 'application/vnd.ms-excel',
'PPT': 'application/vnd.ms-powerpoint',
'PPS': 'application/vnd.ms-powerpoint',
'HTM': 'text/html',
'HTML' : 'text/html'}
class DocsService(gdata.service.GDataService):
"""Client extension for the Google Documents service Document List feed."""
def __init__(self, email=None, password=None, source=None,
server='docs.google.com', additional_headers=None):
"""Constructor for the DocsService.
Args:
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.
Yields:
A DocsService object used to communicate with the Google Documents
service.
"""
gdata.service.GDataService.__init__(self, email=email, password=password,
service='writely', source=source,
server=server,
additional_headers=additional_headers)
def Query(self, uri, converter=gdata.docs.DocumentListFeedFromString):
"""Queries the Document List feed and returns the resulting feed of
entries.
Args:
uri: string The full URI to be queried. This can contain query
parameters, a hostname, or simply the relative path to a Document
List feed. The DocumentQuery object is useful when constructing
query parameters.
converter: func (optional) A function which will be executed on the
retrieved item, generally to render it into a Python object.
By default the DocumentListFeedFromString function is used to
return a DocumentListFeed object. This is because most feed
queries will result in a feed and not a single entry.
"""
return self.Get(uri, converter=converter)
def QueryDocumentListFeed(self, uri):
"""Retrieves a DocumentListFeed by retrieving a URI based off the Document
List feed, including any query parameters. A DocumentQuery object can
be used to construct these parameters.
Args:
uri: string The URI of the feed being retrieved possibly with query
parameters.
Returns:
A DocumentListFeed object representing the feed returned by the server.
"""
return self.Get(uri, converter=gdata.docs.DocumentListFeedFromString)
def GetDocumentListEntry(self, uri):
"""Retrieves a particular DocumentListEntry by its unique URI.
Args:
uri: string The unique URI of an entry in a Document List feed.
Returns:
A DocumentListEntry object representing the retrieved entry.
"""
return self.Get(uri, converter=gdata.docs.DocumentListEntryFromString)
def GetDocumentListFeed(self):
"""Retrieves a feed containing all of a user's documents."""
q = gdata.docs.service.DocumentQuery();
return self.QueryDocumentListFeed(q.ToUri())
def UploadPresentation(self, media_source, title):
"""Uploads a presentation inside of a MediaSource object to the Document
List feed with the given title.
Args:
media_source: MediaSource The MediaSource object containing a
presentation file to be uploaded.
title: string The title of the presentation on the server after being
uploaded.
Returns:
A GDataEntry containing information about the presentation created on the
Google Documents service.
"""
category = atom.Category(scheme=DATA_KIND_SCHEME,
term=PRESENTATION_KIND_TERM)
return self._UploadFile(media_source, title, category)
def UploadSpreadsheet(self, media_source, title):
"""Uploads a spreadsheet inside of a MediaSource object to the Document
List feed with the given title.
Args:
media_source: MediaSource The MediaSource object containing a spreadsheet
file to be uploaded.
title: string The title of the spreadsheet on the server after being
uploaded.
Returns:
A GDataEntry containing information about the spreadsheet created on the
Google Documents service.
"""
category = atom.Category(scheme=DATA_KIND_SCHEME,
term=SPREADSHEET_KIND_TERM)
return self._UploadFile(media_source, title, category)
def UploadDocument(self, media_source, title):
"""Uploads a document inside of a MediaSource object to the Document List
feed with the given title.
Args:
media_source: MediaSource The gdata.MediaSource object containing a
document file to be uploaded.
title: string The title of the document on the server after being
uploaded.
Returns:
A GDataEntry containing information about the document created on the
Google Documents service.
"""
category = atom.Category(scheme=DATA_KIND_SCHEME,
term=DOCUMENT_KIND_TERM)
return self._UploadFile(media_source, title, category)
def _UploadFile(self, media_source, title, category):
"""Uploads a file to the Document List feed.
Args:
media_source: A gdata.MediaSource object containing the file to be
uploaded.
title: string The title of the document on the server after being
uploaded.
category: An atom.Category object specifying the appropriate document
type
Returns:
A GDataEntry containing information about the document created on
the Google Documents service.
"""
media_entry = gdata.GDataEntry()
media_entry.title = atom.Title(text=title)
media_entry.category.append(category)
media_entry = self.Post(media_entry, '/feeds/documents/private/full',
media_source = media_source,
extra_headers = {'Slug' : media_source.file_name })
return media_entry
class DocumentQuery(gdata.service.Query):
"""Object used to construct a URI to query the Google Document List feed"""
def __init__(self, feed='/feeds/documents', visibility='private',
projection='full', text_query=None, params=None,
categories=None):
"""Constructor for Document List Query
Args:
feed: string (optional) The path for the feed. (e.g. '/feeds/documents')
visibility: string (optional) The visibility chosen for the current feed.
projection: string (optional) The projection chosen for the current feed.
text_query: string (optional) The contents of the q query parameter. This
string is URL escaped upon conversion to a URI.
params: dict (optional) Parameter value string pairs which become URL
params when translated to a URI. These parameters are added to
the query's items.
categories: list (optional) List of category strings which should be
included as query categories. See gdata.service.Query for
additional documentation.
Yields:
A DocumentQuery object used to construct a URI based on the Document
List feed.
"""
self.visibility = visibility
self.projection = projection
gdata.service.Query.__init__(self, feed, text_query, params, categories)
def ToUri(self):
"""Generates a URI from the query parameters set in the object.
Returns:
A string containing the URI used to retrieve entries from the Document
List feed.
"""
old_feed = self.feed
self.feed = '/'.join([old_feed, self.visibility, self.projection])
new_feed = gdata.service.Query.ToUri(self)
self.feed = old_feed
return new_feed
def AddNamedFolder(self, email, folder_name):
"""Adds a named folder category, qualified by a schema.
This function lets you query for documents that are contained inside a
named folder without fear of collision with other categories.
Args:
email: string The email of the user who owns the folder.
folder_name: string The name of the folder.
Returns:
The string of the category that was added to the object.
"""
category = '{http://schemas.google.com/docs/2007/folders/'
category += email + '}' + folder_name
self.categories.append(category)
return category
def RemoveNamedFolder(self, email, folder_name):
"""Removes a named folder category, qualified by a schema.
Args:
email: string The email of the user who owns the folder.
folder_name: string The name of the folder.
Returns:
The string of the category that was removed to the object.
"""
category = '{http://schemas.google.com/docs/2007/folders/'
category += email + '}' + folder_name
self.categories.remove(category)
return category
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to Atom objects used with Google Documents."""
__author__ = 'api.jfisher (Jeff Fisher)'
import atom
import gdata
class DocumentListEntry(gdata.GDataEntry):
"""The Google Documents version of an Atom Entry"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
def DocumentListEntryFromString(xml_string):
"""Converts an XML string into a DocumentListEntry object.
Args:
xml_string: string The XML describing a Document List feed entry.
Returns:
A DocumentListEntry object corresponding to the given XML.
"""
return atom.CreateClassFromXMLString(DocumentListEntry, xml_string)
class DocumentListFeed(gdata.GDataFeed):
"""A feed containing a list of Google Documents Items"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[DocumentListEntry])
def DocumentListFeedFromString(xml_string):
"""Converts an XML string into a DocumentListFeed object.
Args:
xml_string: string The XML describing a DocumentList feed.
Returns:
A DocumentListFeed object corresponding to the given XML.
"""
return atom.CreateClassFromXMLString(DocumentListFeed, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to ElementWrapper objects used with Google Contacts."""
__author__ = 'dbrattli (Dag Brattli)'
import atom
import gdata
## Constants from http://code.google.com/apis/gdata/elements.html ##
REL_HOME = 'http://schemas.google.com/g/2005#home'
REL_WORK = 'http://schemas.google.com/g/2005#work'
REL_OTHER = 'http://schemas.google.com/g/2005#other'
IM_AIM = 'http://schemas.google.com/g/2005#AIM' # AOL Instant Messenger protocol
IM_MSN = 'http://schemas.google.com/g/2005#MSN' # MSN Messenger protocol
IM_YAHOO = 'http://schemas.google.com/g/2005#YAHOO' # Yahoo Messenger protocol
IM_SKYPE = 'http://schemas.google.com/g/2005#SKYPE' # Skype protocol
IM_QQ = 'http://schemas.google.com/g/2005#QQ' # QQ protocol
IM_GOOGLE_TALK = 'http://schemas.google.com/g/2005#GOOGLE_TALK' # Google Talk protocol
IM_ICQ = 'http://schemas.google.com/g/2005#ICQ' # ICQ protocol
IM_JABBER = 'http://schemas.google.com/g/2005#JABBER' # Jabber protocol
PHOTO_LINK_REL = 'http://schemas.google.com/contacts/2008/rel#photo'
PHOTO_EDIT_LINK_REL = 'http://schemas.google.com/contacts/2008/rel#edit-photo'
CONTACTS_NAMESPACE = 'http://schemas.google.com/contact/2008'
class OrgName(atom.AtomBase):
_tag = 'orgName'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, text=None,
extension_elements=None, extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class OrgTitle(atom.AtomBase):
_tag = 'orgTitle'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, text=None,
extension_elements=None, extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Organization(atom.AtomBase):
_tag = 'organization'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['rel'] = 'rel'
_attributes['label'] = 'label'
_attributes['primary'] = 'primary'
_children['{%s}orgName' % gdata.GDATA_NAMESPACE] = ('org_name', OrgName)
_children['{%s}orgTitle' % gdata.GDATA_NAMESPACE] = ('org_title', OrgTitle)
def __init__(self, rel=None, primary='false', org_name=None, org_title=None,
label=None, text=None, extension_elements=None,
extension_attributes=None):
self.rel = rel or REL_OTHER
self.primary = primary
self.org_name = org_name
self.org_title = org_title
self.label = label
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class PostalAddress(atom.AtomBase):
_tag = 'postalAddress'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['primary'] = 'primary'
_attributes['rel'] = 'rel'
def __init__(self, primary=None, rel=None, text=None,
extension_elements=None, extension_attributes=None):
self.primary = primary
self.rel = rel or REL_OTHER
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class IM(atom.AtomBase):
_tag = 'im'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['address'] = 'address'
_attributes['primary'] = 'primary'
_attributes['protocol'] = 'protocol'
_attributes['label'] = 'label'
_attributes['rel'] = 'rel'
def __init__(self, primary=None, rel=None, address=None, protocol=None,
label=None, text=None, extension_elements=None,
extension_attributes=None):
self.protocol = protocol
self.address = address
self.primary = primary
self.rel = rel or REL_OTHER
self.label = label
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Email(atom.AtomBase):
_tag = 'email'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['address'] = 'address'
_attributes['primary'] = 'primary'
_attributes['rel'] = 'rel'
_attributes['label'] = 'label'
def __init__(self, primary=None, rel=None, address=None, text=None,
label=None, extension_elements=None, extension_attributes=None):
self.address = address
self.primary = primary
self.rel = rel or REL_OTHER
self.label = label
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class PhoneNumber(atom.AtomBase):
_tag = 'phoneNumber'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['primary'] = 'primary'
_attributes['rel'] = 'rel'
def __init__(self, primary=None, rel=None, text=None,
extension_elements=None, extension_attributes=None):
self.primary = primary
self.rel = rel or REL_OTHER
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Deleted(atom.AtomBase):
_tag = 'deleted'
_namespace = gdata.GDATA_NAMESPACE
def __init__(self, text=None,
extension_elements=None, extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class GroupMembershipInfo(atom.AtomBase):
_tag = 'groupMembershipInfo'
_namespace = CONTACTS_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['deleted'] = 'deleted'
_attributes['href'] = 'href'
def __init__(self, deleted=None, href=None, text=None,
extension_elements=None, extension_attributes=None):
self.deleted = deleted
self.href = href
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class ContactEntry(gdata.BatchEntry):
"""A Google Contact flavor of an Atom Entry """
_children = gdata.BatchEntry._children.copy()
_children['{%s}postalAddress' % gdata.GDATA_NAMESPACE] = ('postal_address',
[PostalAddress])
_children['{%s}phoneNumber' % gdata.GDATA_NAMESPACE] = ('phone_number',
[PhoneNumber])
_children['{%s}organization' % gdata.GDATA_NAMESPACE] = ('organization',
Organization)
_children['{%s}email' % gdata.GDATA_NAMESPACE] = ('email', [Email])
_children['{%s}im' % gdata.GDATA_NAMESPACE] = ('im', [IM])
_children['{%s}deleted' % gdata.GDATA_NAMESPACE] = ('deleted', Deleted)
_children['{%s}groupMembershipInfo' % CONTACTS_NAMESPACE] = (
'group_membership_info', [GroupMembershipInfo])
_children['{%s}extendedProperty' % gdata.GDATA_NAMESPACE] = (
'extended_property', [gdata.ExtendedProperty])
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None, email=None, postal_address=None,
deleted=None, organization=None, phone_number=None, im=None,
extended_property=None, group_membership_info=None,
batch_operation=None, batch_id=None, batch_status=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.BatchEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link, published=published,
batch_operation=batch_operation, batch_id=batch_id,
batch_status=batch_status, title=title, updated=updated)
self.organization = organization
self.deleted = deleted
self.phone_number = phone_number or []
self.postal_address = postal_address or []
self.im = im or []
self.extended_property = extended_property or []
self.email = email or []
self.group_membership_info = group_membership_info or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GetPhotoLink(self):
for a_link in self.link:
if a_link.rel == PHOTO_LINK_REL:
return a_link
return None
def GetPhotoEditLink(self):
for a_link in self.link:
if a_link.rel == PHOTO_EDIT_LINK_REL:
return a_link
return None
def ContactEntryFromString(xml_string):
return atom.CreateClassFromXMLString(ContactEntry, xml_string)
class ContactsFeed(gdata.BatchFeed, gdata.LinkFinder):
"""A Google Contacts feed flavor of an Atom Feed"""
_children = gdata.BatchFeed._children.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [ContactEntry])
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None,
entry=None, total_results=None, start_index=None,
items_per_page=None, extension_elements=None,
extension_attributes=None, text=None):
gdata.BatchFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def ContactsFeedFromString(xml_string):
return atom.CreateClassFromXMLString(ContactsFeed, xml_string)
class GroupEntry(gdata.BatchEntry):
"""Represents a contact group."""
_children = gdata.BatchEntry._children.copy()
_children['{%s}extendedProperty' % gdata.GDATA_NAMESPACE] = (
'extended_property', [gdata.ExtendedProperty])
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, control=None, title=None, updated=None,
extended_property=None, batch_operation=None, batch_id=None,
batch_status=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.BatchEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
batch_operation=batch_operation, batch_id=batch_id,
batch_status=batch_status,
title=title, updated=updated)
self.extended_property = extended_property or []
def GroupEntryFromString(xml_string):
return atom.CreateClassFromXMLString(GroupEntry, xml_string)
class GroupsFeed(gdata.BatchFeed):
"""A Google contact groups feed flavor of an Atom Feed"""
_children = gdata.BatchFeed._children.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GroupEntry])
def GroupsFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GroupsFeed, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""ContactsService extends the GDataService to streamline Google Contacts operations.
ContactsService: Provides methods to query feeds and manipulate items. Extends
GDataService.
DictionaryToParamList: Function which converts a dictionary into a list of
URL arguments (represented as strings). This is a
utility function used in CRUD operations.
"""
__author__ = 'dbrattli (Dag Brattli)'
import gdata
import atom.service
import gdata.service
import gdata.calendar
import atom
class Error(Exception):
pass
class RequestError(Error):
pass
class ContactsService(gdata.service.GDataService):
"""Client for the Google Contats service."""
def __init__(self, email=None, password=None, source=None,
server='www.google.com',
additional_headers=None):
gdata.service.GDataService.__init__(self, email=email, password=password,
service='cp', source=source,
server=server,
additional_headers=additional_headers)
def GetContactsFeed(self,
uri='http://www.google.com/m8/feeds/contacts/default/full'):
return self.Get(uri, converter=gdata.contacts.ContactsFeedFromString)
def GetContact(self, uri):
return self.Get(uri, converter=gdata.contacts.ContactEntryFromString)
def CreateContact(self, new_contact,
insert_uri='/m8/feeds/contacts/default/full', url_params=None,
escape_params=True):
"""Adds an event to Google Contacts.
Args:
new_contact: atom.Entry or subclass A new event which is to be added to
Google Contacts.
insert_uri: the URL to post new contacts to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the contact created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Post(new_contact, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.contacts.ContactEntryFromString)
def UpdateContact(self, edit_uri, updated_contact, url_params=None,
escape_params=True):
"""Updates an existing contact.
Args:
edit_uri: string The edit link URI for the element being updated
updated_contact: string, atom.Entry or subclass containing
the Atom Entry which will replace the event which is
stored at the edit_url
url_params: dict (optional) Additional URL parameters to be included
in the update request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful update, a httplib.HTTPResponse containing the server's
response to the PUT request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Put(updated_contact, '/%s' % edit_uri,
url_params=url_params,
escape_params=escape_params,
converter=gdata.contacts.ContactEntryFromString)
def DeleteContact(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
"""Removes an event with the specified ID from Google Contacts.
Args:
edit_uri: string The edit URL of the entry to be deleted. Example:
'http://www.google.com/m8/feeds/contacts/default/full/xxx/yyy'
url_params: dict (optional) Additional URL parameters to be included
in the deletion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful delete, a httplib.HTTPResponse containing the server's
response to the DELETE request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Delete('/%s' % edit_uri,
url_params=url_params, escape_params=escape_params)
def GetGroupsFeed(self,
uri='http://www.google.com/m8/feeds/groups/default/full'):
return self.Get(uri, converter=gdata.contacts.GroupsFeedFromString)
def CreateGroup(self, new_group,
insert_uri='/m8/feeds/groups/default/full', url_params=None,
escape_params=True):
return self.Post(new_group, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.contacts.GroupEntryFromString)
def UpdateGroup(self, edit_uri, updated_group, url_params=None,
escape_params=True):
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Put(updated_group, '/%s' % edit_uri,
url_params=url_params,
escape_params=escape_params,
converter=gdata.contacts.GroupEntryFromString)
def DeleteGroup(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Delete('/%s' % edit_uri,
url_params=url_params, escape_params=escape_params)
def ChangePhoto(self, media, contact_entry_or_url, content_type=None,
content_length=None):
"""Change the photo for the contact by uploading a new photo.
Performs a PUT against the photo edit URL to send the binary data for the
photo.
Args:
media: filename, file-like-object, or a gdata.MediaSource object to send.
contact_entry_or_url: ContactEntry or str If it is a ContactEntry, this
method will search for an edit photo link URL and
perform a PUT to the URL.
content_type: str (optional) the mime type for the photo data. This is
necessary if media is a file or file name, but if media
is a MediaSource object then the media object can contain
the mime type. If media_type is set, it will override the
mime type in the media object.
content_length: int or str (optional) Specifying the content length is
only required if media is a file-like object. If media
is a filename, the length is determined using
os.path.getsize. If media is a MediaSource object, it is
assumed that it already contains the content length.
"""
if isinstance(contact_entry_or_url, gdata.contacts.ContactEntry):
url = contact_entry_or_url.GetPhotoEditLink().href
else:
url = contact_entry_or_url
if isinstance(media, gdata.MediaSource):
payload = media
# If the media object is a file-like object, then use it as the file
# handle in the in the MediaSource.
elif hasattr(media, 'read'):
payload = gdata.MediaSource(file_handle=media,
content_type=content_type, content_length=content_length)
# Assume that the media object is a file name.
else:
payload = gdata.MediaSource(content_type=content_type,
content_length=content_length, file_path=media)
return self.Put(payload, url)
def GetPhoto(self, contact_entry_or_url):
"""Retrives the binary data for the contact's profile photo as a string.
Args:
contact_entry_or_url: a gdata.contacts.ContactEntry objecr or a string
containing the photo link's URL. If the contact entry does not
contain a photo link, the image will not be fetched and this method
will return None.
"""
# TODO: add the ability to write out the binary image data to a file,
# reading and writing a chunk at a time to avoid potentially using up
# large amounts of memory.
url = None
if isinstance(contact_entry_or_url, gdata.contacts.ContactEntry):
photo_link = contact_entry_or_url.GetPhotoLink()
if photo_link:
url = photo_link.href
else:
url = contact_entry_or_url
if url:
return self.Get(url, converter=str)
else:
return None
def DeletePhoto(self, contact_entry_or_url):
url = None
if isinstance(contact_entry_or_url, gdata.contacts.ContactEntry):
url = contact_entry_or_url.GetPhotoEditLink().href
else:
url = contact_entry_or_url
if url:
self.Delete(url)
class ContactsQuery(gdata.service.Query):
def __init__(self, feed=None, text_query=None, params=None,
categories=None):
self.feed = feed or '/m8/feeds/contacts/default/full'
gdata.service.Query.__init__(self, feed=self.feed, text_query=text_query,
params=params, categories=categories)
def _GetGroup(self):
if 'group' in self:
return self['group']
else:
return None
def _SetGroup(self, group_id):
self['group'] = group_id
group = property(_GetGroup, _SetGroup,
doc='The group query parameter to find only contacts in this group')
| Python |
#!/usr/bin/python
#
# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""ContactsService extends the GDataService to streamline Google Contacts operations.
ContactsService: Provides methods to query feeds and manipulate items. Extends
GDataService.
DictionaryToParamList: Function which converts a dictionary into a list of
URL arguments (represented as strings). This is a
utility function used in CRUD operations.
"""
__author__ = 'dbrattli (Dag Brattli)'
import gdata
import atom.service
import gdata.service
import gdata.calendar
import atom
class Error(Exception):
pass
class RequestError(Error):
pass
class ContactsService(gdata.service.GDataService):
"""Client for the Google Contats service."""
def __init__(self, email=None, password=None, source=None,
server='www.google.com',
additional_headers=None):
gdata.service.GDataService.__init__(self, email=email, password=password,
service='cp', source=source,
server=server,
additional_headers=additional_headers)
def GetContactsFeed(self,
uri='http://www.google.com/m8/feeds/contacts/default/full'):
return self.Get(uri, converter=gdata.contacts.ContactsFeedFromString)
def GetContact(self, uri):
return self.Get(uri, converter=gdata.contacts.ContactEntryFromString)
def CreateContact(self, new_contact,
insert_uri='/m8/feeds/contacts/default/full', url_params=None,
escape_params=True):
"""Adds an event to Google Contacts.
Args:
new_contact: atom.Entry or subclass A new event which is to be added to
Google Contacts.
insert_uri: the URL to post new contacts to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the contact created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Post(new_contact, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.contacts.ContactEntryFromString)
def UpdateContact(self, edit_uri, updated_contact, url_params=None,
escape_params=True):
"""Updates an existing contact.
Args:
edit_uri: string The edit link URI for the element being updated
updated_contact: string, atom.Entry or subclass containing
the Atom Entry which will replace the event which is
stored at the edit_url
url_params: dict (optional) Additional URL parameters to be included
in the update request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful update, a httplib.HTTPResponse containing the server's
response to the PUT request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Put(updated_contact, '/%s' % edit_uri,
url_params=url_params,
escape_params=escape_params,
converter=gdata.contacts.ContactEntryFromString)
def DeleteContact(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
"""Removes an event with the specified ID from Google Contacts.
Args:
edit_uri: string The edit URL of the entry to be deleted. Example:
'http://www.google.com/m8/feeds/contacts/default/full/xxx/yyy'
url_params: dict (optional) Additional URL parameters to be included
in the deletion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful delete, a httplib.HTTPResponse containing the server's
response to the DELETE request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Delete('/%s' % edit_uri,
url_params=url_params, escape_params=escape_params)
def GetGroupsFeed(self,
uri='http://www.google.com/m8/feeds/groups/default/full'):
return self.Get(uri, converter=gdata.contacts.GroupsFeedFromString)
def CreateGroup(self, new_group,
insert_uri='/m8/feeds/groups/default/full', url_params=None,
escape_params=True):
return self.Post(new_group, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.contacts.GroupEntryFromString)
def UpdateGroup(self, edit_uri, updated_group, url_params=None,
escape_params=True):
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Put(updated_group, '/%s' % edit_uri,
url_params=url_params,
escape_params=escape_params,
converter=gdata.contacts.GroupEntryFromString)
def DeleteGroup(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Delete('/%s' % edit_uri,
url_params=url_params, escape_params=escape_params)
def ChangePhoto(self, media, contact_entry_or_url, content_type=None,
content_length=None):
"""Change the photo for the contact by uploading a new photo.
Performs a PUT against the photo edit URL to send the binary data for the
photo.
Args:
media: filename, file-like-object, or a gdata.MediaSource object to send.
contact_entry_or_url: ContactEntry or str If it is a ContactEntry, this
method will search for an edit photo link URL and
perform a PUT to the URL.
content_type: str (optional) the mime type for the photo data. This is
necessary if media is a file or file name, but if media
is a MediaSource object then the media object can contain
the mime type. If media_type is set, it will override the
mime type in the media object.
content_length: int or str (optional) Specifying the content length is
only required if media is a file-like object. If media
is a filename, the length is determined using
os.path.getsize. If media is a MediaSource object, it is
assumed that it already contains the content length.
"""
if isinstance(contact_entry_or_url, gdata.contacts.ContactEntry):
url = contact_entry_or_url.GetPhotoEditLink().href
else:
url = contact_entry_or_url
if isinstance(media, gdata.MediaSource):
payload = media
# If the media object is a file-like object, then use it as the file
# handle in the in the MediaSource.
elif hasattr(media, 'read'):
payload = gdata.MediaSource(file_handle=media,
content_type=content_type, content_length=content_length)
# Assume that the media object is a file name.
else:
payload = gdata.MediaSource(content_type=content_type,
content_length=content_length, file_path=media)
return self.Put(payload, url)
def GetPhoto(self, contact_entry_or_url):
"""Retrives the binary data for the contact's profile photo as a string.
Args:
contact_entry_or_url: a gdata.contacts.ContactEntry objecr or a string
containing the photo link's URL. If the contact entry does not
contain a photo link, the image will not be fetched and this method
will return None.
"""
# TODO: add the ability to write out the binary image data to a file,
# reading and writing a chunk at a time to avoid potentially using up
# large amounts of memory.
url = None
if isinstance(contact_entry_or_url, gdata.contacts.ContactEntry):
photo_link = contact_entry_or_url.GetPhotoLink()
if photo_link:
url = photo_link.href
else:
url = contact_entry_or_url
if url:
return self.Get(url, converter=str)
else:
return None
def DeletePhoto(self, contact_entry_or_url):
url = None
if isinstance(contact_entry_or_url, gdata.contacts.ContactEntry):
url = contact_entry_or_url.GetPhotoEditLink().href
else:
url = contact_entry_or_url
if url:
self.Delete(url)
class ContactsQuery(gdata.service.Query):
def __init__(self, feed=None, text_query=None, params=None,
categories=None):
self.feed = feed or '/m8/feeds/contacts/default/full'
gdata.service.Query.__init__(self, feed=self.feed, text_query=text_query,
params=params, categories=categories)
def _GetGroup(self):
if 'group' in self:
return self['group']
else:
return None
def _SetGroup(self, group_id):
self['group'] = group_id
group = property(_GetGroup, _SetGroup,
doc='The group query parameter to find only contacts in this group')
| Python |
#!/usr/bin/python
#
# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to ElementWrapper objects used with Google Contacts."""
__author__ = 'dbrattli (Dag Brattli)'
import atom
import gdata
## Constants from http://code.google.com/apis/gdata/elements.html ##
REL_HOME = 'http://schemas.google.com/g/2005#home'
REL_WORK = 'http://schemas.google.com/g/2005#work'
REL_OTHER = 'http://schemas.google.com/g/2005#other'
IM_AIM = 'http://schemas.google.com/g/2005#AIM' # AOL Instant Messenger protocol
IM_MSN = 'http://schemas.google.com/g/2005#MSN' # MSN Messenger protocol
IM_YAHOO = 'http://schemas.google.com/g/2005#YAHOO' # Yahoo Messenger protocol
IM_SKYPE = 'http://schemas.google.com/g/2005#SKYPE' # Skype protocol
IM_QQ = 'http://schemas.google.com/g/2005#QQ' # QQ protocol
IM_GOOGLE_TALK = 'http://schemas.google.com/g/2005#GOOGLE_TALK' # Google Talk protocol
IM_ICQ = 'http://schemas.google.com/g/2005#ICQ' # ICQ protocol
IM_JABBER = 'http://schemas.google.com/g/2005#JABBER' # Jabber protocol
PHOTO_LINK_REL = 'http://schemas.google.com/contacts/2008/rel#photo'
PHOTO_EDIT_LINK_REL = 'http://schemas.google.com/contacts/2008/rel#edit-photo'
CONTACTS_NAMESPACE = 'http://schemas.google.com/contact/2008'
class OrgName(atom.AtomBase):
_tag = 'orgName'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, text=None,
extension_elements=None, extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class OrgTitle(atom.AtomBase):
_tag = 'orgTitle'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, text=None,
extension_elements=None, extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Organization(atom.AtomBase):
_tag = 'organization'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['rel'] = 'rel'
_attributes['label'] = 'label'
_attributes['primary'] = 'primary'
_children['{%s}orgName' % gdata.GDATA_NAMESPACE] = ('org_name', OrgName)
_children['{%s}orgTitle' % gdata.GDATA_NAMESPACE] = ('org_title', OrgTitle)
def __init__(self, rel=None, primary='false', org_name=None, org_title=None,
label=None, text=None, extension_elements=None,
extension_attributes=None):
self.rel = rel or REL_OTHER
self.primary = primary
self.org_name = org_name
self.org_title = org_title
self.label = label
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class PostalAddress(atom.AtomBase):
_tag = 'postalAddress'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['primary'] = 'primary'
_attributes['rel'] = 'rel'
def __init__(self, primary=None, rel=None, text=None,
extension_elements=None, extension_attributes=None):
self.primary = primary
self.rel = rel or REL_OTHER
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class IM(atom.AtomBase):
_tag = 'im'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['address'] = 'address'
_attributes['primary'] = 'primary'
_attributes['protocol'] = 'protocol'
_attributes['label'] = 'label'
_attributes['rel'] = 'rel'
def __init__(self, primary=None, rel=None, address=None, protocol=None,
label=None, text=None, extension_elements=None,
extension_attributes=None):
self.protocol = protocol
self.address = address
self.primary = primary
self.rel = rel or REL_OTHER
self.label = label
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Email(atom.AtomBase):
_tag = 'email'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['address'] = 'address'
_attributes['primary'] = 'primary'
_attributes['rel'] = 'rel'
_attributes['label'] = 'label'
def __init__(self, primary=None, rel=None, address=None, text=None,
label=None, extension_elements=None, extension_attributes=None):
self.address = address
self.primary = primary
self.rel = rel or REL_OTHER
self.label = label
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class PhoneNumber(atom.AtomBase):
_tag = 'phoneNumber'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['primary'] = 'primary'
_attributes['rel'] = 'rel'
def __init__(self, primary=None, rel=None, text=None,
extension_elements=None, extension_attributes=None):
self.primary = primary
self.rel = rel or REL_OTHER
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Deleted(atom.AtomBase):
_tag = 'deleted'
_namespace = gdata.GDATA_NAMESPACE
def __init__(self, text=None,
extension_elements=None, extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class GroupMembershipInfo(atom.AtomBase):
_tag = 'groupMembershipInfo'
_namespace = CONTACTS_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['deleted'] = 'deleted'
_attributes['href'] = 'href'
def __init__(self, deleted=None, href=None, text=None,
extension_elements=None, extension_attributes=None):
self.deleted = deleted
self.href = href
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class ContactEntry(gdata.BatchEntry):
"""A Google Contact flavor of an Atom Entry """
_children = gdata.BatchEntry._children.copy()
_children['{%s}postalAddress' % gdata.GDATA_NAMESPACE] = ('postal_address',
[PostalAddress])
_children['{%s}phoneNumber' % gdata.GDATA_NAMESPACE] = ('phone_number',
[PhoneNumber])
_children['{%s}organization' % gdata.GDATA_NAMESPACE] = ('organization',
Organization)
_children['{%s}email' % gdata.GDATA_NAMESPACE] = ('email', [Email])
_children['{%s}im' % gdata.GDATA_NAMESPACE] = ('im', [IM])
_children['{%s}deleted' % gdata.GDATA_NAMESPACE] = ('deleted', Deleted)
_children['{%s}groupMembershipInfo' % CONTACTS_NAMESPACE] = (
'group_membership_info', [GroupMembershipInfo])
_children['{%s}extendedProperty' % gdata.GDATA_NAMESPACE] = (
'extended_property', [gdata.ExtendedProperty])
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None, email=None, postal_address=None,
deleted=None, organization=None, phone_number=None, im=None,
extended_property=None, group_membership_info=None,
batch_operation=None, batch_id=None, batch_status=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.BatchEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link, published=published,
batch_operation=batch_operation, batch_id=batch_id,
batch_status=batch_status, title=title, updated=updated)
self.organization = organization
self.deleted = deleted
self.phone_number = phone_number or []
self.postal_address = postal_address or []
self.im = im or []
self.extended_property = extended_property or []
self.email = email or []
self.group_membership_info = group_membership_info or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GetPhotoLink(self):
for a_link in self.link:
if a_link.rel == PHOTO_LINK_REL:
return a_link
return None
def GetPhotoEditLink(self):
for a_link in self.link:
if a_link.rel == PHOTO_EDIT_LINK_REL:
return a_link
return None
def ContactEntryFromString(xml_string):
return atom.CreateClassFromXMLString(ContactEntry, xml_string)
class ContactsFeed(gdata.BatchFeed, gdata.LinkFinder):
"""A Google Contacts feed flavor of an Atom Feed"""
_children = gdata.BatchFeed._children.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [ContactEntry])
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None,
entry=None, total_results=None, start_index=None,
items_per_page=None, extension_elements=None,
extension_attributes=None, text=None):
gdata.BatchFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def ContactsFeedFromString(xml_string):
return atom.CreateClassFromXMLString(ContactsFeed, xml_string)
class GroupEntry(gdata.BatchEntry):
"""Represents a contact group."""
_children = gdata.BatchEntry._children.copy()
_children['{%s}extendedProperty' % gdata.GDATA_NAMESPACE] = (
'extended_property', [gdata.ExtendedProperty])
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, control=None, title=None, updated=None,
extended_property=None, batch_operation=None, batch_id=None,
batch_status=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.BatchEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
batch_operation=batch_operation, batch_id=batch_id,
batch_status=batch_status,
title=title, updated=updated)
self.extended_property = extended_property or []
def GroupEntryFromString(xml_string):
return atom.CreateClassFromXMLString(GroupEntry, xml_string)
class GroupsFeed(gdata.BatchFeed):
"""A Google contact groups feed flavor of an Atom Feed"""
_children = gdata.BatchFeed._children.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GroupEntry])
def GroupsFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GroupsFeed, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to ElementWrapper objects used with Google Calendar."""
__author__ = 'api.vli (Vivian Li), api.rboyd (Ryan Boyd)'
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import atom
import gdata
# XML namespaces which are often used in Google Calendar entities.
GCAL_NAMESPACE = 'http://schemas.google.com/gCal/2005'
GCAL_TEMPLATE = '{http://schemas.google.com/gCal/2005}%s'
WEB_CONTENT_LINK_REL = '%s/%s' % (GCAL_NAMESPACE, 'webContent')
GACL_NAMESPACE = gdata.GACL_NAMESPACE
GACL_TEMPLATE = gdata.GACL_TEMPLATE
class ValueAttributeContainer(atom.AtomBase):
"""A parent class for all Calendar classes which have a value attribute.
Children include Color, AccessLevel, Hidden
"""
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, value=None, extension_elements=None,
extension_attributes=None, text=None):
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Color(ValueAttributeContainer):
"""The Google Calendar color element"""
_tag = 'color'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class AccessLevel(ValueAttributeContainer):
"""The Google Calendar accesslevel element"""
_tag = 'accesslevel'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class Hidden(ValueAttributeContainer):
"""The Google Calendar hidden element"""
_tag = 'hidden'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class Selected(ValueAttributeContainer):
"""The Google Calendar selected element"""
_tag = 'selected'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class Timezone(ValueAttributeContainer):
"""The Google Calendar timezone element"""
_tag = 'timezone'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class Where(atom.AtomBase):
"""The Google Calendar Where element"""
_tag = 'where'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['valueString'] = 'value_string'
def __init__(self, value_string=None, extension_elements=None,
extension_attributes=None, text=None):
self.value_string = value_string
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class CalendarListEntry(gdata.GDataEntry, gdata.LinkFinder):
"""A Google Calendar meta Entry flavor of an Atom Entry """
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}color' % GCAL_NAMESPACE] = ('color', Color)
_children['{%s}accesslevel' % GCAL_NAMESPACE] = ('access_level',
AccessLevel)
_children['{%s}hidden' % GCAL_NAMESPACE] = ('hidden', Hidden)
_children['{%s}selected' % GCAL_NAMESPACE] = ('selected', Selected)
_children['{%s}timezone' % GCAL_NAMESPACE] = ('timezone', Timezone)
_children['{%s}where' % gdata.GDATA_NAMESPACE] = ('where', Where)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
color=None, access_level=None, hidden=None, timezone=None,
selected=None,
where=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title,
updated=updated, text=None)
self.color = color
self.access_level = access_level
self.hidden = hidden
self.selected = selected
self.timezone = timezone
self.where = where
class CalendarListFeed(gdata.GDataFeed, gdata.LinkFinder):
"""A Google Calendar meta feed flavor of an Atom Feed"""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CalendarListEntry])
class Scope(atom.AtomBase):
"""The Google ACL scope element"""
_tag = 'scope'
_namespace = GACL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
_attributes['type'] = 'type'
def __init__(self, extension_elements=None, value=None, scope_type=None,
extension_attributes=None, text=None):
self.value = value
self.type = scope_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Role(ValueAttributeContainer):
"""The Google Calendar timezone element"""
_tag = 'role'
_namespace = GACL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class CalendarAclEntry(gdata.GDataEntry, gdata.LinkFinder):
"""A Google Calendar ACL Entry flavor of an Atom Entry """
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}scope' % GACL_NAMESPACE] = ('scope', Scope)
_children['{%s}role' % GACL_NAMESPACE] = ('role', Role)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
scope=None, role=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title,
updated=updated, text=None)
self.scope = scope
self.role = role
class CalendarAclFeed(gdata.GDataFeed, gdata.LinkFinder):
"""A Google Calendar ACL feed flavor of an Atom Feed"""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CalendarAclEntry])
class CalendarEventCommentEntry(gdata.GDataEntry, gdata.LinkFinder):
"""A Google Calendar event comments entry flavor of an Atom Entry"""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
class CalendarEventCommentFeed(gdata.GDataFeed, gdata.LinkFinder):
"""A Google Calendar event comments feed flavor of an Atom Feed"""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[CalendarEventCommentEntry])
class ExtendedProperty(gdata.ExtendedProperty):
"""A transparent subclass of gdata.ExtendedProperty added to this module
for backwards compatibility."""
class Reminder(atom.AtomBase):
"""The Google Calendar reminder element"""
_tag = 'reminder'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['absoluteTime'] = 'absolute_time'
_attributes['days'] = 'days'
_attributes['hours'] = 'hours'
_attributes['minutes'] = 'minutes'
def __init__(self, absolute_time=None,
days=None, hours=None, minutes=None,
extension_elements=None,
extension_attributes=None, text=None):
self.absolute_time = absolute_time
if days is not None:
self.days = str(days)
else:
self.days = None
if hours is not None:
self.hours = str(hours)
else:
self.hours = None
if minutes is not None:
self.minutes = str(minutes)
else:
self.minutes = None
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class When(atom.AtomBase):
"""The Google Calendar When element"""
_tag = 'when'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}reminder' % gdata.GDATA_NAMESPACE] = ('reminder', [Reminder])
_attributes['startTime'] = 'start_time'
_attributes['endTime'] = 'end_time'
def __init__(self, start_time=None, end_time=None, reminder=None,
extension_elements=None, extension_attributes=None, text=None):
self.start_time = start_time
self.end_time = end_time
self.reminder = reminder or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Recurrence(atom.AtomBase):
"""The Google Calendar Recurrence element"""
_tag = 'recurrence'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
class UriEnumElement(atom.AtomBase):
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, tag, enum_map, attrib_name='value',
extension_elements=None, extension_attributes=None, text=None):
self.tag=tag
self.enum_map=enum_map
self.attrib_name=attrib_name
self.value=None
self.text=text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def findKey(self, value):
res=[item[0] for item in self.enum_map.items() if item[1] == value]
if res is None or len(res) == 0:
return None
return res[0]
def _ConvertElementAttributeToMember(self, attribute, value):
# Special logic to use the enum_map to set the value of the object's value member.
if attribute == self.attrib_name and value != '':
self.value = self.enum_map[value]
return
# Find the attribute in this class's list of attributes.
if self.__class__._attributes.has_key(attribute):
# Find the member of this class which corresponds to the XML attribute
# (lookup in current_class._attributes) and set this member to the
# desired value (using self.__dict__).
setattr(self, self.__class__._attributes[attribute], value)
else:
# The current class doesn't map this attribute, so try to parent class.
atom.ExtensionContainer._ConvertElementAttributeToMember(self,
attribute,
value)
def _AddMembersToElementTree(self, tree):
# Convert the members of this class which are XML child nodes.
# This uses the class's _children dictionary to find the members which
# should become XML child nodes.
member_node_names = [values[0] for tag, values in
self.__class__._children.iteritems()]
for member_name in member_node_names:
member = getattr(self, member_name)
if member is None:
pass
elif isinstance(member, list):
for instance in member:
instance._BecomeChildElement(tree)
else:
member._BecomeChildElement(tree)
# Special logic to set the desired XML attribute.
key = self.findKey(self.value)
if key is not None:
tree.attrib[self.attrib_name]=key
# Convert the members of this class which are XML attributes.
for xml_attribute, member_name in self.__class__._attributes.iteritems():
member = getattr(self, member_name)
if member is not None:
tree.attrib[xml_attribute] = member
# Lastly, call the parent's _AddMembersToElementTree to get any
# extension elements.
atom.ExtensionContainer._AddMembersToElementTree(self, tree)
class AttendeeStatus(UriEnumElement):
"""The Google Calendar attendeeStatus element"""
_tag = 'attendeeStatus'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
attendee_enum = {
'http://schemas.google.com/g/2005#event.accepted' : 'ACCEPTED',
'http://schemas.google.com/g/2005#event.declined' : 'DECLINED',
'http://schemas.google.com/g/2005#event.invited' : 'INVITED',
'http://schemas.google.com/g/2005#event.tentative' : 'TENTATIVE'}
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, 'attendeeStatus', AttendeeStatus.attendee_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
class AttendeeType(UriEnumElement):
"""The Google Calendar attendeeType element"""
_tag = 'attendeeType'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
attendee_type_enum = {
'http://schemas.google.com/g/2005#event.optional' : 'OPTIONAL',
'http://schemas.google.com/g/2005#event.required' : 'REQUIRED' }
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, 'attendeeType',
AttendeeType.attendee_type_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,text=text)
class Visibility(UriEnumElement):
"""The Google Calendar Visibility element"""
_tag = 'visibility'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
visibility_enum = {
'http://schemas.google.com/g/2005#event.confidential' : 'CONFIDENTIAL',
'http://schemas.google.com/g/2005#event.default' : 'DEFAULT',
'http://schemas.google.com/g/2005#event.private' : 'PRIVATE',
'http://schemas.google.com/g/2005#event.public' : 'PUBLIC' }
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, 'visibility', Visibility.visibility_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
class Transparency(UriEnumElement):
"""The Google Calendar Transparency element"""
_tag = 'transparency'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
transparency_enum = {
'http://schemas.google.com/g/2005#event.opaque' : 'OPAQUE',
'http://schemas.google.com/g/2005#event.transparent' : 'TRANSPARENT' }
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, tag='transparency',
enum_map=Transparency.transparency_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
class Comments(atom.AtomBase):
"""The Google Calendar comments element"""
_tag = 'comments'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
gdata.FeedLink)
_attributes['rel'] = 'rel'
def __init__(self, rel=None, feed_link=None, extension_elements=None,
extension_attributes=None, text=None):
self.rel = rel
self.feed_link = feed_link
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class EventStatus(UriEnumElement):
"""The Google Calendar eventStatus element"""
_tag = 'eventStatus'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
status_enum = { 'http://schemas.google.com/g/2005#event.canceled' : 'CANCELED',
'http://schemas.google.com/g/2005#event.confirmed' : 'CONFIRMED',
'http://schemas.google.com/g/2005#event.tentative' : 'TENTATIVE'}
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, tag='eventStatus',
enum_map=EventStatus.status_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
class Who(UriEnumElement):
"""The Google Calendar Who element"""
_tag = 'who'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
_children['{%s}attendeeStatus' % gdata.GDATA_NAMESPACE] = (
'attendee_status', AttendeeStatus)
_children['{%s}attendeeType' % gdata.GDATA_NAMESPACE] = ('attendee_type',
AttendeeType)
_attributes['valueString'] = 'name'
_attributes['email'] = 'email'
relEnum = { 'http://schemas.google.com/g/2005#event.attendee' : 'ATTENDEE',
'http://schemas.google.com/g/2005#event.organizer' : 'ORGANIZER',
'http://schemas.google.com/g/2005#event.performer' : 'PERFORMER',
'http://schemas.google.com/g/2005#event.speaker' : 'SPEAKER',
'http://schemas.google.com/g/2005#message.bcc' : 'BCC',
'http://schemas.google.com/g/2005#message.cc' : 'CC',
'http://schemas.google.com/g/2005#message.from' : 'FROM',
'http://schemas.google.com/g/2005#message.reply-to' : 'REPLY_TO',
'http://schemas.google.com/g/2005#message.to' : 'TO' }
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, 'who', Who.relEnum, attrib_name='rel',
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.name=None
self.email=None
self.attendee_status=None
self.attendee_type=None
self.rel=None
class OriginalEvent(atom.AtomBase):
"""The Google Calendar OriginalEvent element"""
_tag = 'originalEvent'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
# TODO: The when tag used to map to a EntryLink, make sure it should really be a When.
_children['{%s}when' % gdata.GDATA_NAMESPACE] = ('when', When)
_attributes['id'] = 'id'
_attributes['href'] = 'href'
def __init__(self, id=None, href=None, when=None,
extension_elements=None, extension_attributes=None, text=None):
self.id = id
self.href = href
self.when = when
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GetCalendarEventEntryClass():
return CalendarEventEntry
# This class is not completely defined here, because of a circular reference
# in which CalendarEventEntryLink and CalendarEventEntry refer to one another.
class CalendarEventEntryLink(gdata.EntryLink):
"""An entryLink which contains a calendar event entry
Within an event's recurranceExceptions, an entry link
points to a calendar event entry. This class exists
to capture the calendar specific extensions in the entry.
"""
_tag = 'entryLink'
_namespace = gdata.GDATA_NAMESPACE
_children = gdata.EntryLink._children.copy()
_attributes = gdata.EntryLink._attributes.copy()
# The CalendarEventEntryLink should like CalendarEventEntry as a child but
# that class hasn't been defined yet, so we will wait until after defining
# CalendarEventEntry to list it in _children.
class RecurrenceException(atom.AtomBase):
"""The Google Calendar RecurrenceException element"""
_tag = 'recurrenceException'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}entryLink' % gdata.GDATA_NAMESPACE] = ('entry_link',
CalendarEventEntryLink)
_children['{%s}originalEvent' % gdata.GDATA_NAMESPACE] = ('original_event',
OriginalEvent)
_attributes['specialized'] = 'specialized'
def __init__(self, specialized=None, entry_link=None,
original_event=None, extension_elements=None,
extension_attributes=None, text=None):
self.specialized = specialized
self.entry_link = entry_link
self.original_event = original_event
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class SendEventNotifications(atom.AtomBase):
"""The Google Calendar sendEventNotifications element"""
_tag = 'sendEventNotifications'
_namespace = GCAL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, extension_elements=None,
value=None, extension_attributes=None, text=None):
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class QuickAdd(atom.AtomBase):
"""The Google Calendar quickadd element"""
_tag = 'quickadd'
_namespace = GCAL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, extension_elements=None,
value=None, extension_attributes=None, text=None):
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def _TransferToElementTree(self, element_tree):
if self.value:
element_tree.attrib['value'] = self.value
element_tree.tag = GCAL_TEMPLATE % 'quickadd'
atom.AtomBase._TransferToElementTree(self, element_tree)
return element_tree
def _TakeAttributeFromElementTree(self, attribute, element_tree):
if attribute == 'value':
self.value = element_tree.attrib[attribute]
del element_tree.attrib[attribute]
else:
atom.AtomBase._TakeAttributeFromElementTree(self, attribute,
element_tree)
class WebContentGadgetPref(atom.AtomBase):
_tag = 'webContentGadgetPref'
_namespace = GCAL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['name'] = 'name'
_attributes['value'] = 'value'
"""The Google Calendar Web Content Gadget Preferences element"""
def __init__(self, name=None, value=None, extension_elements=None,
extension_attributes=None, text=None):
self.name = name
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class WebContent(atom.AtomBase):
_tag = 'webContent'
_namespace = GCAL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}webContentGadgetPref' % GCAL_NAMESPACE] = ('gadget_pref',
[WebContentGadgetPref])
_attributes['url'] = 'url'
_attributes['width'] = 'width'
_attributes['height'] = 'height'
def __init__(self, url=None, width=None, height=None, text=None,
gadget_pref=None, extension_elements=None, extension_attributes=None):
self.url = url
self.width = width
self.height = height
self.text = text
self.gadget_pref = gadget_pref or []
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class WebContentLink(atom.Link):
_tag = 'link'
_namespace = atom.ATOM_NAMESPACE
_children = atom.Link._children.copy()
_attributes = atom.Link._attributes.copy()
_children['{%s}webContent' % GCAL_NAMESPACE] = ('web_content', WebContent)
def __init__(self, title=None, href=None, link_type=None,
web_content=None):
atom.Link.__init__(self, rel=WEB_CONTENT_LINK_REL, title=title, href=href,
link_type=link_type)
self.web_content = web_content
class CalendarEventEntry(gdata.BatchEntry):
"""A Google Calendar flavor of an Atom Entry """
_tag = gdata.BatchEntry._tag
_namespace = gdata.BatchEntry._namespace
_children = gdata.BatchEntry._children.copy()
_attributes = gdata.BatchEntry._attributes.copy()
# This class also contains WebContentLinks but converting those members
# is handled in a special version of _ConvertElementTreeToMember.
_children['{%s}where' % gdata.GDATA_NAMESPACE] = ('where', [Where])
_children['{%s}when' % gdata.GDATA_NAMESPACE] = ('when', [When])
_children['{%s}who' % gdata.GDATA_NAMESPACE] = ('who', [Who])
_children['{%s}extendedProperty' % gdata.GDATA_NAMESPACE] = (
'extended_property', [ExtendedProperty])
_children['{%s}visibility' % gdata.GDATA_NAMESPACE] = ('visibility',
Visibility)
_children['{%s}transparency' % gdata.GDATA_NAMESPACE] = ('transparency',
Transparency)
_children['{%s}eventStatus' % gdata.GDATA_NAMESPACE] = ('event_status',
EventStatus)
_children['{%s}recurrence' % gdata.GDATA_NAMESPACE] = ('recurrence',
Recurrence)
_children['{%s}recurrenceException' % gdata.GDATA_NAMESPACE] = (
'recurrence_exception', [RecurrenceException])
_children['{%s}sendEventNotifications' % GCAL_NAMESPACE] = (
'send_event_notifications', SendEventNotifications)
_children['{%s}quickadd' % GCAL_NAMESPACE] = ('quick_add', QuickAdd)
_children['{%s}comments' % gdata.GDATA_NAMESPACE] = ('comments', Comments)
_children['{%s}originalEvent' % gdata.GDATA_NAMESPACE] = ('original_event',
OriginalEvent)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
transparency=None, comments=None, event_status=None,
send_event_notifications=None, visibility=None,
recurrence=None, recurrence_exception=None,
where=None, when=None, who=None, quick_add=None,
extended_property=None, original_event=None,
batch_operation=None, batch_id=None, batch_status=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.BatchEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
batch_operation=batch_operation, batch_id=batch_id,
batch_status=batch_status,
title=title, updated=updated)
self.transparency = transparency
self.comments = comments
self.event_status = event_status
self.send_event_notifications = send_event_notifications
self.visibility = visibility
self.recurrence = recurrence
self.recurrence_exception = recurrence_exception or []
self.where = where or []
self.when = when or []
self.who = who or []
self.quick_add = quick_add
self.extended_property = extended_property or []
self.original_event = original_event
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
# We needed to add special logic to _ConvertElementTreeToMember because we
# want to make links with a rel of WEB_CONTENT_LINK_REL into a
# WebContentLink
def _ConvertElementTreeToMember(self, child_tree):
# Special logic to handle Web Content links
if (child_tree.tag == '{%s}link' % atom.ATOM_NAMESPACE and
child_tree.attrib['rel'] == WEB_CONTENT_LINK_REL):
if self.link is None:
self.link = []
self.link.append(atom._CreateClassFromElementTree(WebContentLink,
child_tree))
return
# Find the element's tag in this class's list of child members
if self.__class__._children.has_key(child_tree.tag):
member_name = self.__class__._children[child_tree.tag][0]
member_class = self.__class__._children[child_tree.tag][1]
# If the class member is supposed to contain a list, make sure the
# matching member is set to a list, then append the new member
# instance to the list.
if isinstance(member_class, list):
if getattr(self, member_name) is None:
setattr(self, member_name, [])
getattr(self, member_name).append(atom._CreateClassFromElementTree(
member_class[0], child_tree))
else:
setattr(self, member_name,
atom._CreateClassFromElementTree(member_class, child_tree))
else:
atom.ExtensionContainer._ConvertElementTreeToMember(self, child_tree)
def GetWebContentLink(self):
"""Finds the first link with rel set to WEB_CONTENT_REL
Returns:
A gdata.calendar.WebContentLink or none if none of the links had rel
equal to WEB_CONTENT_REL
"""
for a_link in self.link:
if a_link.rel == WEB_CONTENT_LINK_REL:
return a_link
return None
def CalendarEventEntryFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventEntry, xml_string)
def CalendarEventCommentEntryFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventCommentEntry, xml_string)
CalendarEventEntryLink._children = {'{%s}entry' % atom.ATOM_NAMESPACE:
('entry', CalendarEventEntry)}
def CalendarEventEntryLinkFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventEntryLink, xml_string)
class CalendarEventFeed(gdata.BatchFeed, gdata.LinkFinder):
"""A Google Calendar event feed flavor of an Atom Feed"""
_tag = gdata.BatchFeed._tag
_namespace = gdata.BatchFeed._namespace
_children = gdata.BatchFeed._children.copy()
_attributes = gdata.BatchFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[CalendarEventEntry])
_children['{%s}timezone' % GCAL_NAMESPACE] = ('timezone', Timezone)
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None, entry=None,
total_results=None, start_index=None, items_per_page=None,
interrupted=None, timezone=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.BatchFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
interrupted=interrupted,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.timezone = timezone
def CalendarListEntryFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarListEntry, xml_string)
def CalendarAclEntryFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarAclEntry, xml_string)
def CalendarListFeedFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarListFeed, xml_string)
def CalendarAclFeedFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarAclFeed, xml_string)
def CalendarEventFeedFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventFeed, xml_string)
def CalendarEventCommentFeedFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventCommentFeed, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""CalendarService extends the GDataService to streamline Google Calendar operations.
CalendarService: Provides methods to query feeds and manipulate items. Extends
GDataService.
DictionaryToParamList: Function which converts a dictionary into a list of
URL arguments (represented as strings). This is a
utility function used in CRUD operations.
"""
__author__ = 'api.vli (Vivian Li)'
import urllib
import gdata
import atom.service
import gdata.service
import gdata.calendar
import atom
DEFAULT_BATCH_URL = ('http://www.google.com/calendar/feeds/default/private'
'/full/batch')
class Error(Exception):
pass
class RequestError(Error):
pass
class CalendarService(gdata.service.GDataService):
"""Client for the Google Calendar service."""
def __init__(self, email=None, password=None, source=None,
server='www.google.com',
additional_headers=None):
gdata.service.GDataService.__init__(self, email=email, password=password,
service='cl', source=source,
server=server,
additional_headers=additional_headers)
def GetCalendarEventFeed(self, uri='/calendar/feeds/default/private/full'):
return self.Get(uri, converter=gdata.calendar.CalendarEventFeedFromString)
def GetCalendarEventEntry(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarEventEntryFromString)
def GetCalendarListFeed(self, uri='/calendar/feeds/default/allcalendars/full'):
return self.Get(uri, converter=gdata.calendar.CalendarListFeedFromString)
def GetAllCalendarsFeed(self, uri='/calendar/feeds/default/allcalendars/full'):
return self.Get(uri, converter=gdata.calendar.CalendarListFeedFromString)
def GetOwnCalendarsFeed(self, uri='/calendar/feeds/default/owncalendars/full'):
return self.Get(uri, converter=gdata.calendar.CalendarListFeedFromString)
def GetCalendarListEntry(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarListEntryFromString)
def GetCalendarAclFeed(self, uri='/calendar/feeds/default/acl/full'):
return self.Get(uri, converter=gdata.calendar.CalendarAclFeedFromString)
def GetCalendarAclEntry(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarAclEntryFromString)
def GetCalendarEventCommentFeed(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarEventCommentFeedFromString)
def GetCalendarEventCommentEntry(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarEventCommentEntryFromString)
def Query(self, uri, converter=None):
"""Performs a query and returns a resulting feed or entry.
Args:
feed: string The feed which is to be queried
Returns:
On success, a GDataFeed or Entry depending on which is sent from the
server.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
if converter:
result = self.Get(uri, converter=converter)
else:
result = self.Get(uri)
return result
def CalendarQuery(self, query):
if isinstance(query, CalendarEventQuery):
return self.Query(query.ToUri(),
converter=gdata.calendar.CalendarEventFeedFromString)
elif isinstance(query, CalendarListQuery):
return self.Query(query.ToUri(),
converter=gdata.calendar.CalendarListFeedFromString)
elif isinstance(query, CalendarEventCommentQuery):
return self.Query(query.ToUri(),
converter=gdata.calendar.CalendarEventCommentFeedFromString)
else:
return self.Query(query.ToUri())
def InsertEvent(self, new_event, insert_uri, url_params=None,
escape_params=True):
"""Adds an event to Google Calendar.
Args:
new_event: atom.Entry or subclass A new event which is to be added to
Google Calendar.
insert_uri: the URL to post new events to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the event created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Post(new_event, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarEventEntryFromString)
def InsertCalendarSubscription(self, calendar, url_params=None,
escape_params=True):
"""Subscribes the authenticated user to the provided calendar.
Args:
calendar: The calendar to which the user should be subscribed.
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the subscription created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
insert_uri = '/calendar/feeds/default/allcalendars/full'
return self.Post(calendar, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarListEntryFromString)
def InsertCalendar(self, new_calendar, url_params=None,
escape_params=True):
"""Creates a new calendar.
Args:
new_calendar: The calendar to be created
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the calendar created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
insert_uri = '/calendar/feeds/default/owncalendars/full'
response = self.Post(new_calendar, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarListEntryFromString)
return response
def UpdateCalendar(self, calendar, url_params=None,
escape_params=True):
"""Updates a calendar.
Args:
calendar: The calendar which should be updated
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the calendar created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
update_uri = calendar.GetEditLink().href
response = self.Put(data=calendar, uri=update_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarListEntryFromString)
return response
def InsertAclEntry(self, new_entry, insert_uri, url_params=None,
escape_params=True):
"""Adds an ACL entry (rule) to Google Calendar.
Args:
new_entry: atom.Entry or subclass A new ACL entry which is to be added to
Google Calendar.
insert_uri: the URL to post new entries to the ACL feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the ACL entry created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Post(new_entry, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarAclEntryFromString)
def InsertEventComment(self, new_entry, insert_uri, url_params=None,
escape_params=True):
"""Adds an entry to Google Calendar.
Args:
new_entry: atom.Entry or subclass A new entry which is to be added to
Google Calendar.
insert_uri: the URL to post new entrys to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the comment created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Post(new_entry, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarEventCommentEntryFromString)
def DeleteEvent(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
"""Removes an event with the specified ID from Google Calendar.
Args:
edit_uri: string The edit URL of the entry to be deleted. Example:
'http://www.google.com/calendar/feeds/default/private/full/abx'
url_params: dict (optional) Additional URL parameters to be included
in the deletion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful delete, a httplib.HTTPResponse containing the server's
response to the DELETE request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Delete('/%s' % edit_uri,
url_params=url_params, escape_params=escape_params)
def DeleteAclEntry(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
"""Removes an ACL entry at the given edit_uri from Google Calendar.
Args:
edit_uri: string The edit URL of the entry to be deleted. Example:
'http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/default'
url_params: dict (optional) Additional URL parameters to be included
in the deletion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful delete, a httplib.HTTPResponse containing the server's
response to the DELETE request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Delete('/%s' % edit_uri,
url_params=url_params, escape_params=escape_params)
def DeleteCalendarEntry(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
"""Removes a calendar entry at the given edit_uri from Google Calendar.
Args:
edit_uri: string The edit URL of the entry to be deleted. Example:
'http://www.google.com/calendar/feeds/default/allcalendars/abcdef@group.calendar.google.com'
url_params: dict (optional) Additional URL parameters to be included
in the deletion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful delete, True is returned
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Delete(edit_uri, url_params=url_params,
escape_params=escape_params)
def UpdateEvent(self, edit_uri, updated_event, url_params=None,
escape_params=True):
"""Updates an existing event.
Args:
edit_uri: string The edit link URI for the element being updated
updated_event: string, atom.Entry, or subclass containing
the Atom Entry which will replace the event which is
stored at the edit_url
url_params: dict (optional) Additional URL parameters to be included
in the update request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful update, a httplib.HTTPResponse containing the server's
response to the PUT request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Put(updated_event, '/%s' % edit_uri,
url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarEventEntryFromString)
def UpdateAclEntry(self, edit_uri, updated_rule, url_params=None,
escape_params=True):
"""Updates an existing ACL rule.
Args:
edit_uri: string The edit link URI for the element being updated
updated_rule: string, atom.Entry, or subclass containing
the Atom Entry which will replace the event which is
stored at the edit_url
url_params: dict (optional) Additional URL parameters to be included
in the update request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful update, a httplib.HTTPResponse containing the server's
response to the PUT request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Put(updated_rule, '/%s' % edit_uri,
url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarAclEntryFromString)
def ExecuteBatch(self, batch_feed, url,
converter=gdata.calendar.CalendarEventFeedFromString):
"""Sends a batch request feed to the server.
The batch request needs to be sent to the batch URL for a particular
calendar. You can find the URL by calling GetBatchLink().href on the
CalendarEventFeed.
Args:
batch_feed: gdata.calendar.CalendarEventFeed A feed containing batch
request entries. Each entry contains the operation to be performed
on the data contained in the entry. For example an entry with an
operation type of insert will be used as if the individual entry
had been inserted.
url: str The batch URL for the Calendar to which these operations should
be applied.
converter: Function (optional) The function used to convert the server's
response to an object. The default value is
CalendarEventFeedFromString.
Returns:
The results of the batch request's execution on the server. If the
default converter is used, this is stored in a CalendarEventFeed.
"""
return self.Post(batch_feed, url, converter=converter)
class CalendarEventQuery(gdata.service.Query):
def __init__(self, user='default', visibility='private', projection='full',
text_query=None, params=None, categories=None):
gdata.service.Query.__init__(self,
feed='http://www.google.com/calendar/feeds/%s/%s/%s' % (
urllib.quote(user),
urllib.quote(visibility),
urllib.quote(projection)),
text_query=text_query, params=params, categories=categories)
def _GetStartMin(self):
if 'start-min' in self.keys():
return self['start-min']
else:
return None
def _SetStartMin(self, val):
self['start-min'] = val
start_min = property(_GetStartMin, _SetStartMin,
doc="""The start-min query parameter""")
def _GetStartMax(self):
if 'start-max' in self.keys():
return self['start-max']
else:
return None
def _SetStartMax(self, val):
self['start-max'] = val
start_max = property(_GetStartMax, _SetStartMax,
doc="""The start-max query parameter""")
def _GetOrderBy(self):
if 'orderby' in self.keys():
return self['orderby']
else:
return None
def _SetOrderBy(self, val):
if val is not 'lastmodified' and val is not 'starttime':
raise Error, "Order By must be either 'lastmodified' or 'starttime'"
self['orderby'] = val
orderby = property(_GetOrderBy, _SetOrderBy,
doc="""The orderby query parameter""")
def _GetSortOrder(self):
if 'sortorder' in self.keys():
return self['sortorder']
else:
return None
def _SetSortOrder(self, val):
if (val is not 'ascending' and val is not 'descending'
and val is not 'a' and val is not 'd' and val is not 'ascend'
and val is not 'descend'):
raise Error, "Sort order must be either ascending, ascend, " + (
"a or descending, descend, or d")
self['sortorder'] = val
sortorder = property(_GetSortOrder, _SetSortOrder,
doc="""The sortorder query parameter""")
def _GetSingleEvents(self):
if 'singleevents' in self.keys():
return self['singleevents']
else:
return None
def _SetSingleEvents(self, val):
self['singleevents'] = val
singleevents = property(_GetSingleEvents, _SetSingleEvents,
doc="""The singleevents query parameter""")
def _GetFutureEvents(self):
if 'futureevents' in self.keys():
return self['futureevents']
else:
return None
def _SetFutureEvents(self, val):
self['futureevents'] = val
futureevents = property(_GetFutureEvents, _SetFutureEvents,
doc="""The futureevents query parameter""")
def _GetRecurrenceExpansionStart(self):
if 'recurrence-expansion-start' in self.keys():
return self['recurrence-expansion-start']
else:
return None
def _SetRecurrenceExpansionStart(self, val):
self['recurrence-expansion-start'] = val
recurrence_expansion_start = property(_GetRecurrenceExpansionStart,
_SetRecurrenceExpansionStart,
doc="""The recurrence-expansion-start query parameter""")
def _GetRecurrenceExpansionEnd(self):
if 'recurrence-expansion-end' in self.keys():
return self['recurrence-expansion-end']
else:
return None
def _SetRecurrenceExpansionEnd(self, val):
self['recurrence-expansion-end'] = val
recurrence_expansion_end = property(_GetRecurrenceExpansionEnd,
_SetRecurrenceExpansionEnd,
doc="""The recurrence-expansion-end query parameter""")
def _SetTimezone(self, val):
self['ctz'] = val
def _GetTimezone(self):
if 'ctz' in self.keys():
return self['ctz']
else:
return None
ctz = property(_GetTimezone, _SetTimezone,
doc="""The ctz query parameter which sets report time on the server.""")
class CalendarListQuery(gdata.service.Query):
"""Queries the Google Calendar meta feed"""
def __init__(self, userId=None, text_query=None,
params=None, categories=None):
if userId is None:
userId = 'default'
gdata.service.Query.__init__(self, feed='http://www.google.com/calendar/feeds/'
+userId,
text_query=text_query, params=params,
categories=categories)
class CalendarEventCommentQuery(gdata.service.Query):
"""Queries the Google Calendar event comments feed"""
def __init__(self, feed=None):
gdata.service.Query.__init__(self, feed=feed)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""CalendarService extends the GDataService to streamline Google Calendar operations.
CalendarService: Provides methods to query feeds and manipulate items. Extends
GDataService.
DictionaryToParamList: Function which converts a dictionary into a list of
URL arguments (represented as strings). This is a
utility function used in CRUD operations.
"""
__author__ = 'api.vli (Vivian Li)'
import urllib
import gdata
import atom.service
import gdata.service
import gdata.calendar
import atom
DEFAULT_BATCH_URL = ('http://www.google.com/calendar/feeds/default/private'
'/full/batch')
class Error(Exception):
pass
class RequestError(Error):
pass
class CalendarService(gdata.service.GDataService):
"""Client for the Google Calendar service."""
def __init__(self, email=None, password=None, source=None,
server='www.google.com',
additional_headers=None):
gdata.service.GDataService.__init__(self, email=email, password=password,
service='cl', source=source,
server=server,
additional_headers=additional_headers)
def GetCalendarEventFeed(self, uri='/calendar/feeds/default/private/full'):
return self.Get(uri, converter=gdata.calendar.CalendarEventFeedFromString)
def GetCalendarEventEntry(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarEventEntryFromString)
def GetCalendarListFeed(self, uri='/calendar/feeds/default/allcalendars/full'):
return self.Get(uri, converter=gdata.calendar.CalendarListFeedFromString)
def GetAllCalendarsFeed(self, uri='/calendar/feeds/default/allcalendars/full'):
return self.Get(uri, converter=gdata.calendar.CalendarListFeedFromString)
def GetOwnCalendarsFeed(self, uri='/calendar/feeds/default/owncalendars/full'):
return self.Get(uri, converter=gdata.calendar.CalendarListFeedFromString)
def GetCalendarListEntry(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarListEntryFromString)
def GetCalendarAclFeed(self, uri='/calendar/feeds/default/acl/full'):
return self.Get(uri, converter=gdata.calendar.CalendarAclFeedFromString)
def GetCalendarAclEntry(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarAclEntryFromString)
def GetCalendarEventCommentFeed(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarEventCommentFeedFromString)
def GetCalendarEventCommentEntry(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarEventCommentEntryFromString)
def Query(self, uri, converter=None):
"""Performs a query and returns a resulting feed or entry.
Args:
feed: string The feed which is to be queried
Returns:
On success, a GDataFeed or Entry depending on which is sent from the
server.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
if converter:
result = self.Get(uri, converter=converter)
else:
result = self.Get(uri)
return result
def CalendarQuery(self, query):
if isinstance(query, CalendarEventQuery):
return self.Query(query.ToUri(),
converter=gdata.calendar.CalendarEventFeedFromString)
elif isinstance(query, CalendarListQuery):
return self.Query(query.ToUri(),
converter=gdata.calendar.CalendarListFeedFromString)
elif isinstance(query, CalendarEventCommentQuery):
return self.Query(query.ToUri(),
converter=gdata.calendar.CalendarEventCommentFeedFromString)
else:
return self.Query(query.ToUri())
def InsertEvent(self, new_event, insert_uri, url_params=None,
escape_params=True):
"""Adds an event to Google Calendar.
Args:
new_event: atom.Entry or subclass A new event which is to be added to
Google Calendar.
insert_uri: the URL to post new events to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the event created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Post(new_event, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarEventEntryFromString)
def InsertCalendarSubscription(self, calendar, url_params=None,
escape_params=True):
"""Subscribes the authenticated user to the provided calendar.
Args:
calendar: The calendar to which the user should be subscribed.
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the subscription created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
insert_uri = '/calendar/feeds/default/allcalendars/full'
return self.Post(calendar, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarListEntryFromString)
def InsertCalendar(self, new_calendar, url_params=None,
escape_params=True):
"""Creates a new calendar.
Args:
new_calendar: The calendar to be created
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the calendar created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
insert_uri = '/calendar/feeds/default/owncalendars/full'
response = self.Post(new_calendar, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarListEntryFromString)
return response
def UpdateCalendar(self, calendar, url_params=None,
escape_params=True):
"""Updates a calendar.
Args:
calendar: The calendar which should be updated
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the calendar created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
update_uri = calendar.GetEditLink().href
response = self.Put(data=calendar, uri=update_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarListEntryFromString)
return response
def InsertAclEntry(self, new_entry, insert_uri, url_params=None,
escape_params=True):
"""Adds an ACL entry (rule) to Google Calendar.
Args:
new_entry: atom.Entry or subclass A new ACL entry which is to be added to
Google Calendar.
insert_uri: the URL to post new entries to the ACL feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the ACL entry created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Post(new_entry, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarAclEntryFromString)
def InsertEventComment(self, new_entry, insert_uri, url_params=None,
escape_params=True):
"""Adds an entry to Google Calendar.
Args:
new_entry: atom.Entry or subclass A new entry which is to be added to
Google Calendar.
insert_uri: the URL to post new entrys to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the comment created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Post(new_entry, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarEventCommentEntryFromString)
def DeleteEvent(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
"""Removes an event with the specified ID from Google Calendar.
Args:
edit_uri: string The edit URL of the entry to be deleted. Example:
'http://www.google.com/calendar/feeds/default/private/full/abx'
url_params: dict (optional) Additional URL parameters to be included
in the deletion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful delete, a httplib.HTTPResponse containing the server's
response to the DELETE request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Delete('/%s' % edit_uri,
url_params=url_params, escape_params=escape_params)
def DeleteAclEntry(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
"""Removes an ACL entry at the given edit_uri from Google Calendar.
Args:
edit_uri: string The edit URL of the entry to be deleted. Example:
'http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/default'
url_params: dict (optional) Additional URL parameters to be included
in the deletion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful delete, a httplib.HTTPResponse containing the server's
response to the DELETE request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Delete('/%s' % edit_uri,
url_params=url_params, escape_params=escape_params)
def DeleteCalendarEntry(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
"""Removes a calendar entry at the given edit_uri from Google Calendar.
Args:
edit_uri: string The edit URL of the entry to be deleted. Example:
'http://www.google.com/calendar/feeds/default/allcalendars/abcdef@group.calendar.google.com'
url_params: dict (optional) Additional URL parameters to be included
in the deletion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful delete, True is returned
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Delete(edit_uri, url_params=url_params,
escape_params=escape_params)
def UpdateEvent(self, edit_uri, updated_event, url_params=None,
escape_params=True):
"""Updates an existing event.
Args:
edit_uri: string The edit link URI for the element being updated
updated_event: string, atom.Entry, or subclass containing
the Atom Entry which will replace the event which is
stored at the edit_url
url_params: dict (optional) Additional URL parameters to be included
in the update request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful update, a httplib.HTTPResponse containing the server's
response to the PUT request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Put(updated_event, '/%s' % edit_uri,
url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarEventEntryFromString)
def UpdateAclEntry(self, edit_uri, updated_rule, url_params=None,
escape_params=True):
"""Updates an existing ACL rule.
Args:
edit_uri: string The edit link URI for the element being updated
updated_rule: string, atom.Entry, or subclass containing
the Atom Entry which will replace the event which is
stored at the edit_url
url_params: dict (optional) Additional URL parameters to be included
in the update request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful update, a httplib.HTTPResponse containing the server's
response to the PUT request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Put(updated_rule, '/%s' % edit_uri,
url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarAclEntryFromString)
def ExecuteBatch(self, batch_feed, url,
converter=gdata.calendar.CalendarEventFeedFromString):
"""Sends a batch request feed to the server.
The batch request needs to be sent to the batch URL for a particular
calendar. You can find the URL by calling GetBatchLink().href on the
CalendarEventFeed.
Args:
batch_feed: gdata.calendar.CalendarEventFeed A feed containing batch
request entries. Each entry contains the operation to be performed
on the data contained in the entry. For example an entry with an
operation type of insert will be used as if the individual entry
had been inserted.
url: str The batch URL for the Calendar to which these operations should
be applied.
converter: Function (optional) The function used to convert the server's
response to an object. The default value is
CalendarEventFeedFromString.
Returns:
The results of the batch request's execution on the server. If the
default converter is used, this is stored in a CalendarEventFeed.
"""
return self.Post(batch_feed, url, converter=converter)
class CalendarEventQuery(gdata.service.Query):
def __init__(self, user='default', visibility='private', projection='full',
text_query=None, params=None, categories=None):
gdata.service.Query.__init__(self,
feed='http://www.google.com/calendar/feeds/%s/%s/%s' % (
urllib.quote(user),
urllib.quote(visibility),
urllib.quote(projection)),
text_query=text_query, params=params, categories=categories)
def _GetStartMin(self):
if 'start-min' in self.keys():
return self['start-min']
else:
return None
def _SetStartMin(self, val):
self['start-min'] = val
start_min = property(_GetStartMin, _SetStartMin,
doc="""The start-min query parameter""")
def _GetStartMax(self):
if 'start-max' in self.keys():
return self['start-max']
else:
return None
def _SetStartMax(self, val):
self['start-max'] = val
start_max = property(_GetStartMax, _SetStartMax,
doc="""The start-max query parameter""")
def _GetOrderBy(self):
if 'orderby' in self.keys():
return self['orderby']
else:
return None
def _SetOrderBy(self, val):
if val is not 'lastmodified' and val is not 'starttime':
raise Error, "Order By must be either 'lastmodified' or 'starttime'"
self['orderby'] = val
orderby = property(_GetOrderBy, _SetOrderBy,
doc="""The orderby query parameter""")
def _GetSortOrder(self):
if 'sortorder' in self.keys():
return self['sortorder']
else:
return None
def _SetSortOrder(self, val):
if (val is not 'ascending' and val is not 'descending'
and val is not 'a' and val is not 'd' and val is not 'ascend'
and val is not 'descend'):
raise Error, "Sort order must be either ascending, ascend, " + (
"a or descending, descend, or d")
self['sortorder'] = val
sortorder = property(_GetSortOrder, _SetSortOrder,
doc="""The sortorder query parameter""")
def _GetSingleEvents(self):
if 'singleevents' in self.keys():
return self['singleevents']
else:
return None
def _SetSingleEvents(self, val):
self['singleevents'] = val
singleevents = property(_GetSingleEvents, _SetSingleEvents,
doc="""The singleevents query parameter""")
def _GetFutureEvents(self):
if 'futureevents' in self.keys():
return self['futureevents']
else:
return None
def _SetFutureEvents(self, val):
self['futureevents'] = val
futureevents = property(_GetFutureEvents, _SetFutureEvents,
doc="""The futureevents query parameter""")
def _GetRecurrenceExpansionStart(self):
if 'recurrence-expansion-start' in self.keys():
return self['recurrence-expansion-start']
else:
return None
def _SetRecurrenceExpansionStart(self, val):
self['recurrence-expansion-start'] = val
recurrence_expansion_start = property(_GetRecurrenceExpansionStart,
_SetRecurrenceExpansionStart,
doc="""The recurrence-expansion-start query parameter""")
def _GetRecurrenceExpansionEnd(self):
if 'recurrence-expansion-end' in self.keys():
return self['recurrence-expansion-end']
else:
return None
def _SetRecurrenceExpansionEnd(self, val):
self['recurrence-expansion-end'] = val
recurrence_expansion_end = property(_GetRecurrenceExpansionEnd,
_SetRecurrenceExpansionEnd,
doc="""The recurrence-expansion-end query parameter""")
def _SetTimezone(self, val):
self['ctz'] = val
def _GetTimezone(self):
if 'ctz' in self.keys():
return self['ctz']
else:
return None
ctz = property(_GetTimezone, _SetTimezone,
doc="""The ctz query parameter which sets report time on the server.""")
class CalendarListQuery(gdata.service.Query):
"""Queries the Google Calendar meta feed"""
def __init__(self, userId=None, text_query=None,
params=None, categories=None):
if userId is None:
userId = 'default'
gdata.service.Query.__init__(self, feed='http://www.google.com/calendar/feeds/'
+userId,
text_query=text_query, params=params,
categories=categories)
class CalendarEventCommentQuery(gdata.service.Query):
"""Queries the Google Calendar event comments feed"""
def __init__(self, feed=None):
gdata.service.Query.__init__(self, feed=feed)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to ElementWrapper objects used with Google Calendar."""
__author__ = 'api.vli (Vivian Li), api.rboyd (Ryan Boyd)'
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import atom
import gdata
# XML namespaces which are often used in Google Calendar entities.
GCAL_NAMESPACE = 'http://schemas.google.com/gCal/2005'
GCAL_TEMPLATE = '{http://schemas.google.com/gCal/2005}%s'
WEB_CONTENT_LINK_REL = '%s/%s' % (GCAL_NAMESPACE, 'webContent')
GACL_NAMESPACE = gdata.GACL_NAMESPACE
GACL_TEMPLATE = gdata.GACL_TEMPLATE
class ValueAttributeContainer(atom.AtomBase):
"""A parent class for all Calendar classes which have a value attribute.
Children include Color, AccessLevel, Hidden
"""
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, value=None, extension_elements=None,
extension_attributes=None, text=None):
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Color(ValueAttributeContainer):
"""The Google Calendar color element"""
_tag = 'color'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class AccessLevel(ValueAttributeContainer):
"""The Google Calendar accesslevel element"""
_tag = 'accesslevel'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class Hidden(ValueAttributeContainer):
"""The Google Calendar hidden element"""
_tag = 'hidden'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class Selected(ValueAttributeContainer):
"""The Google Calendar selected element"""
_tag = 'selected'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class Timezone(ValueAttributeContainer):
"""The Google Calendar timezone element"""
_tag = 'timezone'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class Where(atom.AtomBase):
"""The Google Calendar Where element"""
_tag = 'where'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['valueString'] = 'value_string'
def __init__(self, value_string=None, extension_elements=None,
extension_attributes=None, text=None):
self.value_string = value_string
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class CalendarListEntry(gdata.GDataEntry, gdata.LinkFinder):
"""A Google Calendar meta Entry flavor of an Atom Entry """
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}color' % GCAL_NAMESPACE] = ('color', Color)
_children['{%s}accesslevel' % GCAL_NAMESPACE] = ('access_level',
AccessLevel)
_children['{%s}hidden' % GCAL_NAMESPACE] = ('hidden', Hidden)
_children['{%s}selected' % GCAL_NAMESPACE] = ('selected', Selected)
_children['{%s}timezone' % GCAL_NAMESPACE] = ('timezone', Timezone)
_children['{%s}where' % gdata.GDATA_NAMESPACE] = ('where', Where)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
color=None, access_level=None, hidden=None, timezone=None,
selected=None,
where=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title,
updated=updated, text=None)
self.color = color
self.access_level = access_level
self.hidden = hidden
self.selected = selected
self.timezone = timezone
self.where = where
class CalendarListFeed(gdata.GDataFeed, gdata.LinkFinder):
"""A Google Calendar meta feed flavor of an Atom Feed"""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CalendarListEntry])
class Scope(atom.AtomBase):
"""The Google ACL scope element"""
_tag = 'scope'
_namespace = GACL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
_attributes['type'] = 'type'
def __init__(self, extension_elements=None, value=None, scope_type=None,
extension_attributes=None, text=None):
self.value = value
self.type = scope_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Role(ValueAttributeContainer):
"""The Google Calendar timezone element"""
_tag = 'role'
_namespace = GACL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class CalendarAclEntry(gdata.GDataEntry, gdata.LinkFinder):
"""A Google Calendar ACL Entry flavor of an Atom Entry """
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}scope' % GACL_NAMESPACE] = ('scope', Scope)
_children['{%s}role' % GACL_NAMESPACE] = ('role', Role)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
scope=None, role=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title,
updated=updated, text=None)
self.scope = scope
self.role = role
class CalendarAclFeed(gdata.GDataFeed, gdata.LinkFinder):
"""A Google Calendar ACL feed flavor of an Atom Feed"""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CalendarAclEntry])
class CalendarEventCommentEntry(gdata.GDataEntry, gdata.LinkFinder):
"""A Google Calendar event comments entry flavor of an Atom Entry"""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
class CalendarEventCommentFeed(gdata.GDataFeed, gdata.LinkFinder):
"""A Google Calendar event comments feed flavor of an Atom Feed"""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[CalendarEventCommentEntry])
class ExtendedProperty(gdata.ExtendedProperty):
"""A transparent subclass of gdata.ExtendedProperty added to this module
for backwards compatibility."""
class Reminder(atom.AtomBase):
"""The Google Calendar reminder element"""
_tag = 'reminder'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['absoluteTime'] = 'absolute_time'
_attributes['days'] = 'days'
_attributes['hours'] = 'hours'
_attributes['minutes'] = 'minutes'
def __init__(self, absolute_time=None,
days=None, hours=None, minutes=None,
extension_elements=None,
extension_attributes=None, text=None):
self.absolute_time = absolute_time
if days is not None:
self.days = str(days)
else:
self.days = None
if hours is not None:
self.hours = str(hours)
else:
self.hours = None
if minutes is not None:
self.minutes = str(minutes)
else:
self.minutes = None
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class When(atom.AtomBase):
"""The Google Calendar When element"""
_tag = 'when'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}reminder' % gdata.GDATA_NAMESPACE] = ('reminder', [Reminder])
_attributes['startTime'] = 'start_time'
_attributes['endTime'] = 'end_time'
def __init__(self, start_time=None, end_time=None, reminder=None,
extension_elements=None, extension_attributes=None, text=None):
self.start_time = start_time
self.end_time = end_time
self.reminder = reminder or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Recurrence(atom.AtomBase):
"""The Google Calendar Recurrence element"""
_tag = 'recurrence'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
class UriEnumElement(atom.AtomBase):
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, tag, enum_map, attrib_name='value',
extension_elements=None, extension_attributes=None, text=None):
self.tag=tag
self.enum_map=enum_map
self.attrib_name=attrib_name
self.value=None
self.text=text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def findKey(self, value):
res=[item[0] for item in self.enum_map.items() if item[1] == value]
if res is None or len(res) == 0:
return None
return res[0]
def _ConvertElementAttributeToMember(self, attribute, value):
# Special logic to use the enum_map to set the value of the object's value member.
if attribute == self.attrib_name and value != '':
self.value = self.enum_map[value]
return
# Find the attribute in this class's list of attributes.
if self.__class__._attributes.has_key(attribute):
# Find the member of this class which corresponds to the XML attribute
# (lookup in current_class._attributes) and set this member to the
# desired value (using self.__dict__).
setattr(self, self.__class__._attributes[attribute], value)
else:
# The current class doesn't map this attribute, so try to parent class.
atom.ExtensionContainer._ConvertElementAttributeToMember(self,
attribute,
value)
def _AddMembersToElementTree(self, tree):
# Convert the members of this class which are XML child nodes.
# This uses the class's _children dictionary to find the members which
# should become XML child nodes.
member_node_names = [values[0] for tag, values in
self.__class__._children.iteritems()]
for member_name in member_node_names:
member = getattr(self, member_name)
if member is None:
pass
elif isinstance(member, list):
for instance in member:
instance._BecomeChildElement(tree)
else:
member._BecomeChildElement(tree)
# Special logic to set the desired XML attribute.
key = self.findKey(self.value)
if key is not None:
tree.attrib[self.attrib_name]=key
# Convert the members of this class which are XML attributes.
for xml_attribute, member_name in self.__class__._attributes.iteritems():
member = getattr(self, member_name)
if member is not None:
tree.attrib[xml_attribute] = member
# Lastly, call the parent's _AddMembersToElementTree to get any
# extension elements.
atom.ExtensionContainer._AddMembersToElementTree(self, tree)
class AttendeeStatus(UriEnumElement):
"""The Google Calendar attendeeStatus element"""
_tag = 'attendeeStatus'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
attendee_enum = {
'http://schemas.google.com/g/2005#event.accepted' : 'ACCEPTED',
'http://schemas.google.com/g/2005#event.declined' : 'DECLINED',
'http://schemas.google.com/g/2005#event.invited' : 'INVITED',
'http://schemas.google.com/g/2005#event.tentative' : 'TENTATIVE'}
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, 'attendeeStatus', AttendeeStatus.attendee_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
class AttendeeType(UriEnumElement):
"""The Google Calendar attendeeType element"""
_tag = 'attendeeType'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
attendee_type_enum = {
'http://schemas.google.com/g/2005#event.optional' : 'OPTIONAL',
'http://schemas.google.com/g/2005#event.required' : 'REQUIRED' }
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, 'attendeeType',
AttendeeType.attendee_type_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,text=text)
class Visibility(UriEnumElement):
"""The Google Calendar Visibility element"""
_tag = 'visibility'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
visibility_enum = {
'http://schemas.google.com/g/2005#event.confidential' : 'CONFIDENTIAL',
'http://schemas.google.com/g/2005#event.default' : 'DEFAULT',
'http://schemas.google.com/g/2005#event.private' : 'PRIVATE',
'http://schemas.google.com/g/2005#event.public' : 'PUBLIC' }
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, 'visibility', Visibility.visibility_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
class Transparency(UriEnumElement):
"""The Google Calendar Transparency element"""
_tag = 'transparency'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
transparency_enum = {
'http://schemas.google.com/g/2005#event.opaque' : 'OPAQUE',
'http://schemas.google.com/g/2005#event.transparent' : 'TRANSPARENT' }
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, tag='transparency',
enum_map=Transparency.transparency_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
class Comments(atom.AtomBase):
"""The Google Calendar comments element"""
_tag = 'comments'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
gdata.FeedLink)
_attributes['rel'] = 'rel'
def __init__(self, rel=None, feed_link=None, extension_elements=None,
extension_attributes=None, text=None):
self.rel = rel
self.feed_link = feed_link
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class EventStatus(UriEnumElement):
"""The Google Calendar eventStatus element"""
_tag = 'eventStatus'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
status_enum = { 'http://schemas.google.com/g/2005#event.canceled' : 'CANCELED',
'http://schemas.google.com/g/2005#event.confirmed' : 'CONFIRMED',
'http://schemas.google.com/g/2005#event.tentative' : 'TENTATIVE'}
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, tag='eventStatus',
enum_map=EventStatus.status_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
class Who(UriEnumElement):
"""The Google Calendar Who element"""
_tag = 'who'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
_children['{%s}attendeeStatus' % gdata.GDATA_NAMESPACE] = (
'attendee_status', AttendeeStatus)
_children['{%s}attendeeType' % gdata.GDATA_NAMESPACE] = ('attendee_type',
AttendeeType)
_attributes['valueString'] = 'name'
_attributes['email'] = 'email'
relEnum = { 'http://schemas.google.com/g/2005#event.attendee' : 'ATTENDEE',
'http://schemas.google.com/g/2005#event.organizer' : 'ORGANIZER',
'http://schemas.google.com/g/2005#event.performer' : 'PERFORMER',
'http://schemas.google.com/g/2005#event.speaker' : 'SPEAKER',
'http://schemas.google.com/g/2005#message.bcc' : 'BCC',
'http://schemas.google.com/g/2005#message.cc' : 'CC',
'http://schemas.google.com/g/2005#message.from' : 'FROM',
'http://schemas.google.com/g/2005#message.reply-to' : 'REPLY_TO',
'http://schemas.google.com/g/2005#message.to' : 'TO' }
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, 'who', Who.relEnum, attrib_name='rel',
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.name=None
self.email=None
self.attendee_status=None
self.attendee_type=None
self.rel=None
class OriginalEvent(atom.AtomBase):
"""The Google Calendar OriginalEvent element"""
_tag = 'originalEvent'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
# TODO: The when tag used to map to a EntryLink, make sure it should really be a When.
_children['{%s}when' % gdata.GDATA_NAMESPACE] = ('when', When)
_attributes['id'] = 'id'
_attributes['href'] = 'href'
def __init__(self, id=None, href=None, when=None,
extension_elements=None, extension_attributes=None, text=None):
self.id = id
self.href = href
self.when = when
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GetCalendarEventEntryClass():
return CalendarEventEntry
# This class is not completely defined here, because of a circular reference
# in which CalendarEventEntryLink and CalendarEventEntry refer to one another.
class CalendarEventEntryLink(gdata.EntryLink):
"""An entryLink which contains a calendar event entry
Within an event's recurranceExceptions, an entry link
points to a calendar event entry. This class exists
to capture the calendar specific extensions in the entry.
"""
_tag = 'entryLink'
_namespace = gdata.GDATA_NAMESPACE
_children = gdata.EntryLink._children.copy()
_attributes = gdata.EntryLink._attributes.copy()
# The CalendarEventEntryLink should like CalendarEventEntry as a child but
# that class hasn't been defined yet, so we will wait until after defining
# CalendarEventEntry to list it in _children.
class RecurrenceException(atom.AtomBase):
"""The Google Calendar RecurrenceException element"""
_tag = 'recurrenceException'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}entryLink' % gdata.GDATA_NAMESPACE] = ('entry_link',
CalendarEventEntryLink)
_children['{%s}originalEvent' % gdata.GDATA_NAMESPACE] = ('original_event',
OriginalEvent)
_attributes['specialized'] = 'specialized'
def __init__(self, specialized=None, entry_link=None,
original_event=None, extension_elements=None,
extension_attributes=None, text=None):
self.specialized = specialized
self.entry_link = entry_link
self.original_event = original_event
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class SendEventNotifications(atom.AtomBase):
"""The Google Calendar sendEventNotifications element"""
_tag = 'sendEventNotifications'
_namespace = GCAL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, extension_elements=None,
value=None, extension_attributes=None, text=None):
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class QuickAdd(atom.AtomBase):
"""The Google Calendar quickadd element"""
_tag = 'quickadd'
_namespace = GCAL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, extension_elements=None,
value=None, extension_attributes=None, text=None):
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def _TransferToElementTree(self, element_tree):
if self.value:
element_tree.attrib['value'] = self.value
element_tree.tag = GCAL_TEMPLATE % 'quickadd'
atom.AtomBase._TransferToElementTree(self, element_tree)
return element_tree
def _TakeAttributeFromElementTree(self, attribute, element_tree):
if attribute == 'value':
self.value = element_tree.attrib[attribute]
del element_tree.attrib[attribute]
else:
atom.AtomBase._TakeAttributeFromElementTree(self, attribute,
element_tree)
class WebContentGadgetPref(atom.AtomBase):
_tag = 'webContentGadgetPref'
_namespace = GCAL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['name'] = 'name'
_attributes['value'] = 'value'
"""The Google Calendar Web Content Gadget Preferences element"""
def __init__(self, name=None, value=None, extension_elements=None,
extension_attributes=None, text=None):
self.name = name
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class WebContent(atom.AtomBase):
_tag = 'webContent'
_namespace = GCAL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}webContentGadgetPref' % GCAL_NAMESPACE] = ('gadget_pref',
[WebContentGadgetPref])
_attributes['url'] = 'url'
_attributes['width'] = 'width'
_attributes['height'] = 'height'
def __init__(self, url=None, width=None, height=None, text=None,
gadget_pref=None, extension_elements=None, extension_attributes=None):
self.url = url
self.width = width
self.height = height
self.text = text
self.gadget_pref = gadget_pref or []
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class WebContentLink(atom.Link):
_tag = 'link'
_namespace = atom.ATOM_NAMESPACE
_children = atom.Link._children.copy()
_attributes = atom.Link._attributes.copy()
_children['{%s}webContent' % GCAL_NAMESPACE] = ('web_content', WebContent)
def __init__(self, title=None, href=None, link_type=None,
web_content=None):
atom.Link.__init__(self, rel=WEB_CONTENT_LINK_REL, title=title, href=href,
link_type=link_type)
self.web_content = web_content
class CalendarEventEntry(gdata.BatchEntry):
"""A Google Calendar flavor of an Atom Entry """
_tag = gdata.BatchEntry._tag
_namespace = gdata.BatchEntry._namespace
_children = gdata.BatchEntry._children.copy()
_attributes = gdata.BatchEntry._attributes.copy()
# This class also contains WebContentLinks but converting those members
# is handled in a special version of _ConvertElementTreeToMember.
_children['{%s}where' % gdata.GDATA_NAMESPACE] = ('where', [Where])
_children['{%s}when' % gdata.GDATA_NAMESPACE] = ('when', [When])
_children['{%s}who' % gdata.GDATA_NAMESPACE] = ('who', [Who])
_children['{%s}extendedProperty' % gdata.GDATA_NAMESPACE] = (
'extended_property', [ExtendedProperty])
_children['{%s}visibility' % gdata.GDATA_NAMESPACE] = ('visibility',
Visibility)
_children['{%s}transparency' % gdata.GDATA_NAMESPACE] = ('transparency',
Transparency)
_children['{%s}eventStatus' % gdata.GDATA_NAMESPACE] = ('event_status',
EventStatus)
_children['{%s}recurrence' % gdata.GDATA_NAMESPACE] = ('recurrence',
Recurrence)
_children['{%s}recurrenceException' % gdata.GDATA_NAMESPACE] = (
'recurrence_exception', [RecurrenceException])
_children['{%s}sendEventNotifications' % GCAL_NAMESPACE] = (
'send_event_notifications', SendEventNotifications)
_children['{%s}quickadd' % GCAL_NAMESPACE] = ('quick_add', QuickAdd)
_children['{%s}comments' % gdata.GDATA_NAMESPACE] = ('comments', Comments)
_children['{%s}originalEvent' % gdata.GDATA_NAMESPACE] = ('original_event',
OriginalEvent)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
transparency=None, comments=None, event_status=None,
send_event_notifications=None, visibility=None,
recurrence=None, recurrence_exception=None,
where=None, when=None, who=None, quick_add=None,
extended_property=None, original_event=None,
batch_operation=None, batch_id=None, batch_status=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.BatchEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
batch_operation=batch_operation, batch_id=batch_id,
batch_status=batch_status,
title=title, updated=updated)
self.transparency = transparency
self.comments = comments
self.event_status = event_status
self.send_event_notifications = send_event_notifications
self.visibility = visibility
self.recurrence = recurrence
self.recurrence_exception = recurrence_exception or []
self.where = where or []
self.when = when or []
self.who = who or []
self.quick_add = quick_add
self.extended_property = extended_property or []
self.original_event = original_event
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
# We needed to add special logic to _ConvertElementTreeToMember because we
# want to make links with a rel of WEB_CONTENT_LINK_REL into a
# WebContentLink
def _ConvertElementTreeToMember(self, child_tree):
# Special logic to handle Web Content links
if (child_tree.tag == '{%s}link' % atom.ATOM_NAMESPACE and
child_tree.attrib['rel'] == WEB_CONTENT_LINK_REL):
if self.link is None:
self.link = []
self.link.append(atom._CreateClassFromElementTree(WebContentLink,
child_tree))
return
# Find the element's tag in this class's list of child members
if self.__class__._children.has_key(child_tree.tag):
member_name = self.__class__._children[child_tree.tag][0]
member_class = self.__class__._children[child_tree.tag][1]
# If the class member is supposed to contain a list, make sure the
# matching member is set to a list, then append the new member
# instance to the list.
if isinstance(member_class, list):
if getattr(self, member_name) is None:
setattr(self, member_name, [])
getattr(self, member_name).append(atom._CreateClassFromElementTree(
member_class[0], child_tree))
else:
setattr(self, member_name,
atom._CreateClassFromElementTree(member_class, child_tree))
else:
atom.ExtensionContainer._ConvertElementTreeToMember(self, child_tree)
def GetWebContentLink(self):
"""Finds the first link with rel set to WEB_CONTENT_REL
Returns:
A gdata.calendar.WebContentLink or none if none of the links had rel
equal to WEB_CONTENT_REL
"""
for a_link in self.link:
if a_link.rel == WEB_CONTENT_LINK_REL:
return a_link
return None
def CalendarEventEntryFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventEntry, xml_string)
def CalendarEventCommentEntryFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventCommentEntry, xml_string)
CalendarEventEntryLink._children = {'{%s}entry' % atom.ATOM_NAMESPACE:
('entry', CalendarEventEntry)}
def CalendarEventEntryLinkFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventEntryLink, xml_string)
class CalendarEventFeed(gdata.BatchFeed, gdata.LinkFinder):
"""A Google Calendar event feed flavor of an Atom Feed"""
_tag = gdata.BatchFeed._tag
_namespace = gdata.BatchFeed._namespace
_children = gdata.BatchFeed._children.copy()
_attributes = gdata.BatchFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[CalendarEventEntry])
_children['{%s}timezone' % GCAL_NAMESPACE] = ('timezone', Timezone)
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None, entry=None,
total_results=None, start_index=None, items_per_page=None,
interrupted=None, timezone=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.BatchFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
interrupted=interrupted,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.timezone = timezone
def CalendarListEntryFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarListEntry, xml_string)
def CalendarAclEntryFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarAclEntry, xml_string)
def CalendarListFeedFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarListFeed, xml_string)
def CalendarAclFeedFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarAclFeed, xml_string)
def CalendarEventFeedFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventFeed, xml_string)
def CalendarEventCommentFeedFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventCommentFeed, xml_string)
| Python |
# -*-*- encoding: utf-8 -*-*-
#
# This is gdata.photos.media, implementing parts of the MediaRSS spec in gdata structures
#
# $Id: __init__.py 81 2007-10-03 14:41:42Z havard.gulldahl $
#
# Copyright 2007 Håvard Gulldahl
# Portions copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Essential attributes of photos in Google Photos/Picasa Web Albums are
expressed using elements from the `media' namespace, defined in the
MediaRSS specification[1].
Due to copyright issues, the elements herein are documented sparingly, please
consult with the Google Photos API Reference Guide[2], alternatively the
official MediaRSS specification[1] for details.
(If there is a version conflict between the two sources, stick to the
Google Photos API).
[1]: http://search.yahoo.com/mrss (version 1.1.1)
[2]: http://code.google.com/apis/picasaweb/reference.html#media_reference
Keep in mind that Google Photos only uses a subset of the MediaRSS elements
(and some of the attributes are trimmed down, too):
media:content
media:credit
media:description
media:group
media:keywords
media:thumbnail
media:title
"""
__author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: api chokes on non-ascii chars in __author__
__license__ = 'Apache License v2'
import atom
import gdata
MEDIA_NAMESPACE = 'http://search.yahoo.com/mrss/'
YOUTUBE_NAMESPACE = 'http://gdata.youtube.com/schemas/2007'
class MediaBaseElement(atom.AtomBase):
"""Base class for elements in the MEDIA_NAMESPACE.
To add new elements, you only need to add the element tag name to self._tag
"""
_tag = ''
_namespace = MEDIA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, name=None, extension_elements=None,
extension_attributes=None, text=None):
self.name = name
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Content(MediaBaseElement):
"""(attribute container) This element describes the original content,
e.g. an image or a video. There may be multiple Content elements
in a media:Group.
For example, a video may have a
<media:content medium="image"> element that specifies a JPEG
representation of the video, and a <media:content medium="video">
element that specifies the URL of the video itself.
Attributes:
url: non-ambigous reference to online object
width: width of the object frame, in pixels
height: width of the object frame, in pixels
medium: one of `image' or `video', allowing the api user to quickly
determine the object's type
type: Internet media Type[1] (a.k.a. mime type) of the object -- a more
verbose way of determining the media type
(optional) fileSize: the size of the object, in bytes
[1]: http://en.wikipedia.org/wiki/Internet_media_type
"""
_tag = 'content'
_attributes = atom.AtomBase._attributes.copy()
_attributes['url'] = 'url'
_attributes['width'] = 'width'
_attributes['height'] = 'height'
_attributes['medium'] = 'medium'
_attributes['type'] = 'type'
_attributes['fileSize'] = 'fileSize'
def __init__(self, url=None, width=None, height=None,
medium=None, content_type=None, fileSize=None, format=None,
extension_elements=None, extension_attributes=None, text=None):
MediaBaseElement.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.url = url
self.width = width
self.height = height
self.medium = medium
self.type = content_type
self.fileSize = fileSize
def ContentFromString(xml_string):
return atom.CreateClassFromXMLString(Content, xml_string)
class Credit(MediaBaseElement):
"""(string) Contains the nickname of the user who created the content,
e.g. `Liz Bennet'.
This is a user-specified value that should be used when referring to
the user by name.
Note that none of the attributes from the MediaRSS spec are supported.
"""
_tag = 'credit'
def CreditFromString(xml_string):
return atom.CreateClassFromXMLString(Credit, xml_string)
class Description(MediaBaseElement):
"""(string) A description of the media object.
Either plain unicode text, or entity-encoded html (look at the `type'
attribute).
E.g `A set of photographs I took while vacationing in Italy.'
For `api' projections, the description is in plain text;
for `base' projections, the description is in HTML.
Attributes:
type: either `text' or `html'.
"""
_tag = 'description'
_attributes = atom.AtomBase._attributes.copy()
_attributes['type'] = 'type'
def __init__(self, description_type=None,
extension_elements=None, extension_attributes=None, text=None):
MediaBaseElement.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.type = description_type
def DescriptionFromString(xml_string):
return atom.CreateClassFromXMLString(Description, xml_string)
class Keywords(MediaBaseElement):
"""(string) Lists the tags associated with the entry,
e.g `italy, vacation, sunset'.
Contains a comma-separated list of tags that have been added to the photo, or
all tags that have been added to photos in the album.
"""
_tag = 'keywords'
def KeywordsFromString(xml_string):
return atom.CreateClassFromXMLString(Keywords, xml_string)
class Thumbnail(MediaBaseElement):
"""(attributes) Contains the URL of a thumbnail of a photo or album cover.
There can be multiple <media:thumbnail> elements for a given <media:group>;
for example, a given item may have multiple thumbnails at different sizes.
Photos generally have two thumbnails at different sizes;
albums generally have one cropped thumbnail.
If the thumbsize parameter is set to the initial query, this element points
to thumbnails of the requested sizes; otherwise the thumbnails are the
default thumbnail size.
This element must not be confused with the <gphoto:thumbnail> element.
Attributes:
url: The URL of the thumbnail image.
height: The height of the thumbnail image, in pixels.
width: The width of the thumbnail image, in pixels.
"""
_tag = 'thumbnail'
_attributes = atom.AtomBase._attributes.copy()
_attributes['url'] = 'url'
_attributes['width'] = 'width'
_attributes['height'] = 'height'
def __init__(self, url=None, width=None, height=None,
extension_attributes=None, text=None, extension_elements=None):
MediaBaseElement.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.url = url
self.width = width
self.height = height
def ThumbnailFromString(xml_string):
return atom.CreateClassFromXMLString(Thumbnail, xml_string)
class Title(MediaBaseElement):
"""(string) Contains the title of the entry's media content, in plain text.
Attributes:
type: Always set to plain
"""
_tag = 'title'
_attributes = atom.AtomBase._attributes.copy()
_attributes['type'] = 'type'
def __init__(self, title_type=None,
extension_attributes=None, text=None, extension_elements=None):
MediaBaseElement.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.type = title_type
def TitleFromString(xml_string):
return atom.CreateClassFromXMLString(Title, xml_string)
class Player(MediaBaseElement):
"""(string) Contains the embeddable player URL for the entry's media content
if the media is a video.
Attributes:
url: Always set to plain
"""
_tag = 'player'
_attributes = atom.AtomBase._attributes.copy()
_attributes['url'] = 'url'
def __init__(self, player_url=None,
extension_attributes=None, extension_elements=None):
MediaBaseElement.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes)
self.url= player_url
class Private(atom.AtomBase):
"""The YouTube Private element"""
_tag = 'private'
_namespace = YOUTUBE_NAMESPACE
class Duration(atom.AtomBase):
"""The YouTube Duration element"""
_tag = 'duration'
_namespace = YOUTUBE_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['seconds'] = 'seconds'
class Category(MediaBaseElement):
"""The mediagroup:category element"""
_tag = 'category'
_attributes = atom.AtomBase._attributes.copy()
_attributes['term'] = 'term'
_attributes['scheme'] = 'scheme'
_attributes['label'] = 'label'
def __init__(self, term=None, scheme=None, label=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for Category
Args:
term: str
scheme: str
label: str
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.term = term
self.scheme = scheme
self.label = label
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Group(MediaBaseElement):
"""Container element for all media elements.
The <media:group> element can appear as a child of an album, photo or
video entry."""
_tag = 'group'
_children = atom.AtomBase._children.copy()
_children['{%s}content' % MEDIA_NAMESPACE] = ('content', [Content,])
_children['{%s}credit' % MEDIA_NAMESPACE] = ('credit', Credit)
_children['{%s}description' % MEDIA_NAMESPACE] = ('description', Description)
_children['{%s}keywords' % MEDIA_NAMESPACE] = ('keywords', Keywords)
_children['{%s}thumbnail' % MEDIA_NAMESPACE] = ('thumbnail', [Thumbnail,])
_children['{%s}title' % MEDIA_NAMESPACE] = ('title', Title)
_children['{%s}category' % MEDIA_NAMESPACE] = ('category', [Category,])
_children['{%s}duration' % YOUTUBE_NAMESPACE] = ('duration', Duration)
_children['{%s}private' % YOUTUBE_NAMESPACE] = ('private', Private)
_children['{%s}player' % MEDIA_NAMESPACE] = ('player', Player)
def __init__(self, content=None, credit=None, description=None, keywords=None,
thumbnail=None, title=None, duration=None, private=None,
category=None, player=None, extension_elements=None,
extension_attributes=None, text=None):
MediaBaseElement.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.content=content
self.credit=credit
self.description=description
self.keywords=keywords
self.thumbnail=thumbnail or []
self.title=title
self.duration=duration
self.private=private
self.category=category or []
self.player=player
def GroupFromString(xml_string):
return atom.CreateClassFromXMLString(Group, xml_string)
| Python |
# -*-*- encoding: utf-8 -*-*-
#
# This is gdata.photos.geo, implementing geological positioning in gdata structures
#
# $Id: __init__.py 81 2007-10-03 14:41:42Z havard.gulldahl $
#
# Copyright 2007 Håvard Gulldahl
# Portions copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Picasa Web Albums uses the georss and gml namespaces for
elements defined in the GeoRSS and Geography Markup Language specifications.
Specifically, Picasa Web Albums uses the following elements:
georss:where
gml:Point
gml:pos
http://code.google.com/apis/picasaweb/reference.html#georss_reference
Picasa Web Albums also accepts geographic-location data in two other formats:
W3C format and plain-GeoRSS (without GML) format.
"""
#
#Over the wire, the Picasa Web Albums only accepts and sends the
#elements mentioned above, but this module will let you seamlessly convert
#between the different formats (TODO 2007-10-18 hg)
__author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: api chokes on non-ascii chars in __author__
__license__ = 'Apache License v2'
import atom
import gdata
GEO_NAMESPACE = 'http://www.w3.org/2003/01/geo/wgs84_pos#'
GML_NAMESPACE = 'http://www.opengis.net/gml'
GEORSS_NAMESPACE = 'http://www.georss.org/georss'
class GeoBaseElement(atom.AtomBase):
"""Base class for elements.
To add new elements, you only need to add the element tag name to self._tag
and the namespace to self._namespace
"""
_tag = ''
_namespace = GML_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, name=None, extension_elements=None,
extension_attributes=None, text=None):
self.name = name
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Pos(GeoBaseElement):
"""(string) Specifies a latitude and longitude, separated by a space,
e.g. `35.669998 139.770004'"""
_tag = 'pos'
def PosFromString(xml_string):
return atom.CreateClassFromXMLString(Pos, xml_string)
class Point(GeoBaseElement):
"""(container) Specifies a particular geographical point, by means of
a <gml:pos> element."""
_tag = 'Point'
_children = atom.AtomBase._children.copy()
_children['{%s}pos' % GML_NAMESPACE] = ('pos', Pos)
def __init__(self, pos=None, extension_elements=None, extension_attributes=None, text=None):
GeoBaseElement.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
if pos is None:
pos = Pos()
self.pos=pos
def PointFromString(xml_string):
return atom.CreateClassFromXMLString(Point, xml_string)
class Where(GeoBaseElement):
"""(container) Specifies a geographical location or region.
A container element, containing a single <gml:Point> element.
(Not to be confused with <gd:where>.)
Note that the (only) child attribute, .Point, is title-cased.
This reflects the names of elements in the xml stream
(principle of least surprise).
As a convenience, you can get a tuple of (lat, lon) with Where.location(),
and set the same data with Where.setLocation( (lat, lon) ).
Similarly, there are methods to set and get only latitude and longtitude.
"""
_tag = 'where'
_namespace = GEORSS_NAMESPACE
_children = atom.AtomBase._children.copy()
_children['{%s}Point' % GML_NAMESPACE] = ('Point', Point)
def __init__(self, point=None, extension_elements=None, extension_attributes=None, text=None):
GeoBaseElement.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
if point is None:
point = Point()
self.Point=point
def location(self):
"(float, float) Return Where.Point.pos.text as a (lat,lon) tuple"
try:
return tuple([float(z) for z in self.Point.pos.text.split(' ')])
except AttributeError:
return tuple()
def set_location(self, latlon):
"""(bool) Set Where.Point.pos.text from a (lat,lon) tuple.
Arguments:
lat (float): The latitude in degrees, from -90.0 to 90.0
lon (float): The longitude in degrees, from -180.0 to 180.0
Returns True on success.
"""
assert(isinstance(latlon[0], float))
assert(isinstance(latlon[1], float))
try:
self.Point.pos.text = "%s %s" % (latlon[0], latlon[1])
return True
except AttributeError:
return False
def latitude(self):
"(float) Get the latitude value of the geo-tag. See also .location()"
lat, lon = self.location()
return lat
def longtitude(self):
"(float) Get the longtitude value of the geo-tag. See also .location()"
lat, lon = self.location()
return lon
def set_latitude(self, lat):
"""(bool) Set the latitude value of the geo-tag.
Args:
lat (float): The new latitude value
See also .set_location()
"""
_lat, lon = self.location()
return self.set_location(lat, lon)
def set_longtitude(self, lon):
"""(bool) Set the longtitude value of the geo-tag.
Args:
lat (float): The new latitude value
See also .set_location()
"""
lat, _lon = self.location()
return self.set_location(lat, lon)
def WhereFromString(xml_string):
return atom.CreateClassFromXMLString(Where, xml_string)
| Python |
#!/usr/bin/env python
# -*-*- encoding: utf-8 -*-*-
#
# This is the service file for the Google Photo python client.
# It is used for higher level operations.
#
# $Id: service.py 144 2007-10-25 21:03:34Z havard.gulldahl $
#
# Copyright 2007 Håvard Gulldahl
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""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)
"""
__author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: pydoc chokes on non-ascii chars in __author__
__license__ = 'Apache License v2'
__version__ = '$Revision: 176 $'[11:-2]
import sys, os.path, StringIO
import time
import gdata.service
import gdata
import atom.service
import atom
import gdata.photos
SUPPORTED_UPLOAD_TYPES = ('bmp', 'jpeg', 'jpg', 'gif', 'png')
UNKOWN_ERROR=1000
GPHOTOS_BAD_REQUEST=400
GPHOTOS_CONFLICT=409
GPHOTOS_INTERNAL_SERVER_ERROR=500
GPHOTOS_INVALID_ARGUMENT=601
GPHOTOS_INVALID_CONTENT_TYPE=602
GPHOTOS_NOT_AN_IMAGE=603
GPHOTOS_INVALID_KIND=604
class GooglePhotosException(Exception):
def __init__(self, response):
self.error_code = response['status']
self.reason = response['reason'].strip()
if '<html>' in str(response['body']): #general html message, discard it
response['body'] = ""
self.body = response['body'].strip()
self.message = "(%(status)s) %(body)s -- %(reason)s" % response
#return explicit error codes
error_map = { '(12) Not an image':GPHOTOS_NOT_AN_IMAGE,
'kind: That is not one of the acceptable values':
GPHOTOS_INVALID_KIND,
}
for msg, code in error_map.iteritems():
if self.body == msg:
self.error_code = code
break
self.args = [self.error_code, self.reason, self.body]
class PhotosService(gdata.service.GDataService):
userUri = '/data/feed/api/user/%s'
def __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:
A PhotosService object used to communicate with the Google Photos
service.
"""
self.email = email
self.client = source
gdata.service.GDataService.__init__(self, email=self.email, password=password,
service='lh2', source=source,
server=server,
additional_headers=additional_headers)
def 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
"""
if limit is not None:
uri += '&max-results=%s' % limit
if start_index is not None:
uri += '&start-index=%s' % start_index
try:
return self.Get(uri, converter=gdata.photos.AnyFeedFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def 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
"""
if limit is not None:
uri += '&max-results=%s' % limit
if start_index is not None:
uri += '&start-index=%s' % start_index
try:
return self.Get(uri, converter=gdata.photos.AnyEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def 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
"""
if isinstance(kind, (list, tuple) ):
kind = ",".join(kind)
uri = '/data/feed/api/user/%s?kind=%s' % (user, kind)
return self.GetFeed(uri, limit=limit)
def 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
"""
# Lower-casing because of
# http://code.google.com/p/gdata-issues/issues/detail?id=194
uri = '/data/feed/api/user/%s?kind=photo&tag=%s' % (user, tag.lower())
return self.GetFeed(uri, limit)
def 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
"""
uri = '/data/feed/api/user/%s?kind=photo&q=%s' % (user, query)
return self.GetFeed(uri, limit=limit)
def 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
"""
uri='/data/feed/api/all?q=%s' % query
return self.GetFeed(uri, limit=limit)
def 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
"""
uri = '/data/feed/api/user/%s/contacts?kind=user' % user
return self.GetFeed(uri, limit=limit)
def 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
"""
uri = '/data/feed/api/user/%s/contacts?kind=photo&q=%s' % (user, search)
return self.GetFeed(uri, limit=limit)
def InsertAlbum(self, title, summary, location=None, access='public',
commenting_enabled='true', timestamp=None):
"""Add an album.
Needs authentication, see self.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
"""
album = gdata.photos.AlbumEntry()
album.title = atom.Title(text=title, title_type='text')
album.summary = atom.Summary(text=summary, summary_type='text')
if location is not None:
album.location = gdata.photos.Location(text=location)
album.access = gdata.photos.Access(text=access)
if commenting_enabled in ('true', 'false'):
album.commentingEnabled = gdata.photos.CommentingEnabled(text=commenting_enabled)
if timestamp is None:
timestamp = '%i' % int(time.time() * 1000)
album.timestamp = gdata.photos.Timestamp(text=timestamp)
try:
return self.Post(album, uri=self.userUri % self.email,
converter=gdata.photos.AlbumEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def InsertPhoto(self, album_or_uri, photo, filename_or_handle,
content_type='image/jpeg'):
"""Add a PhotoEntry
Needs authentication, see self.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'
"""
try:
assert(isinstance(photo, gdata.photos.PhotoEntry))
except AssertionError:
raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUMENT,
'body':'`photo` must be a gdata.photos.PhotoEntry instance',
'reason':'Found %s, not PhotoEntry' % type(photo)
})
try:
majtype, mintype = content_type.split('/')
assert(mintype in SUPPORTED_UPLOAD_TYPES)
except (ValueError, AssertionError):
raise GooglePhotosException({'status':GPHOTOS_INVALID_CONTENT_TYPE,
'body':'This is not a valid content type: %s' % content_type,
'reason':'Accepted content types: %s' % \
['image/'+t for t in SUPPORTED_UPLOAD_TYPES]
})
if isinstance(filename_or_handle, (str, unicode)) and \
os.path.exists(filename_or_handle): # it's a file name
mediasource = gdata.MediaSource()
mediasource.setFile(filename_or_handle, content_type)
elif hasattr(filename_or_handle, 'read'):# it's a file-like resource
if hasattr(filename_or_handle, 'seek'):
filename_or_handle.seek(0) # rewind pointer to the start of the file
# gdata.MediaSource needs the content length, so read the whole image
file_handle = StringIO.StringIO(filename_or_handle.read())
name = 'image'
if hasattr(filename_or_handle, 'name'):
name = filename_or_handle.name
mediasource = gdata.MediaSource(file_handle, content_type,
content_length=file_handle.len, file_name=name)
else: #filename_or_handle is not valid
raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUMENT,
'body':'`filename_or_handle` must be a path name or a file-like object',
'reason':'Found %s, not path name or object with a .read() method' % \
type(filename_or_handle)
})
if isinstance(album_or_uri, (str, unicode)): # it's a uri
feed_uri = album_or_uri
elif hasattr(album_or_uri, 'GetFeedLink'): # it's a AlbumFeed object
feed_uri = album_or_uri.GetFeedLink().href
try:
return self.Post(photo, uri=feed_uri, media_source=mediasource,
converter=gdata.photos.PhotoEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def 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 self.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
"""
metadata = gdata.photos.PhotoEntry()
metadata.title=atom.Title(text=title)
metadata.summary = atom.Summary(text=summary, summary_type='text')
if keywords is not None:
if isinstance(keywords, list):
keywords = ','.join(keywords)
metadata.media.keywords = gdata.media.Keywords(text=keywords)
return self.InsertPhoto(album_or_uri, metadata, filename_or_handle,
content_type)
def UpdatePhotoMetadata(self, photo):
"""Update a photo's metadata.
Needs authentication, see self.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
"""
try:
return self.Put(data=photo, uri=photo.GetEditLink().href,
converter=gdata.photos.PhotoEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def UpdatePhotoBlob(self, photo_or_uri, filename_or_handle,
content_type = 'image/jpeg'):
"""Update a photo's binary data.
Needs authentication, see self.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
"""
try:
majtype, mintype = content_type.split('/')
assert(mintype in SUPPORTED_UPLOAD_TYPES)
except (ValueError, AssertionError):
raise GooglePhotosException({'status':GPHOTOS_INVALID_CONTENT_TYPE,
'body':'This is not a valid content type: %s' % content_type,
'reason':'Accepted content types: %s' % \
['image/'+t for t in SUPPORTED_UPLOAD_TYPES]
})
if isinstance(filename_or_handle, (str, unicode)) and \
os.path.exists(filename_or_handle): # it's a file name
photoblob = gdata.MediaSource()
photoblob.setFile(filename_or_handle, content_type)
elif hasattr(filename_or_handle, 'read'):# it's a file-like resource
if hasattr(filename_or_handle, 'seek'):
filename_or_handle.seek(0) # rewind pointer to the start of the file
# gdata.MediaSource needs the content length, so read the whole image
file_handle = StringIO.StringIO(filename_or_handle.read())
name = 'image'
if hasattr(filename_or_handle, 'name'):
name = filename_or_handle.name
mediasource = gdata.MediaSource(file_handle, content_type,
content_length=file_handle.len, file_name=name)
else: #filename_or_handle is not valid
raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUMENT,
'body':'`filename_or_handle` must be a path name or a file-like object',
'reason':'Found %s, not path name or an object with .read() method' % \
type(filename_or_handle)
})
if isinstance(photo_or_uri, (str, unicode)):
entry_uri = photo_or_uri # it's a uri
elif hasattr(photo_or_uri, 'GetEditMediaLink'):
entry_uri = photo_or_uri.GetEditMediaLink().href
try:
return self.Put(photoblob, entry_uri,
converter=gdata.photos.PhotoEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def InsertTag(self, photo_or_uri, tag):
"""Add a tag (a.k.a. keyword) to a photo.
Needs authentication, see self.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')
"""
tag = gdata.photos.TagEntry(title=atom.Title(text=tag))
if isinstance(photo_or_uri, (str, unicode)):
post_uri = photo_or_uri # it's a uri
elif hasattr(photo_or_uri, 'GetEditMediaLink'):
post_uri = photo_or_uri.GetPostLink().href
try:
return self.Post(data=tag, uri=post_uri,
converter=gdata.photos.TagEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def InsertComment(self, photo_or_uri, comment):
"""Add a comment to a photo.
Needs authentication, see self.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?')
"""
comment = gdata.photos.CommentEntry(content=atom.Content(text=comment))
if isinstance(photo_or_uri, (str, unicode)):
post_uri = photo_or_uri # it's a uri
elif hasattr(photo_or_uri, 'GetEditMediaLink'):
post_uri = photo_or_uri.GetPostLink().href
try:
return self.Post(data=comment, uri=post_uri,
converter=gdata.photos.CommentEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def 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
"""
try:
uri = object_or_uri.GetEditLink().href
except AttributeError:
uri = object_or_uri
try:
return gdata.service.GDataService.Delete(self, uri, *args, **kwargs)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def GetSmallestThumbnail(media_thumbnail_list):
"""Helper function to get the smallest thumbnail of a list of
gdata.media.Thumbnail.
Returns gdata.media.Thumbnail """
r = {}
for thumb in media_thumbnail_list:
r[int(thumb.width)*int(thumb.height)] = thumb
keys = r.keys()
keys.sort()
return r[keys[0]]
def 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' -> """
return time.mktime(time.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.000Z'))
## TODO: Timezone aware
| Python |
#!/usr/bin/env python
# -*-*- encoding: utf-8 -*-*-
#
# This is the service file for the Google Photo python client.
# It is used for higher level operations.
#
# $Id: service.py 144 2007-10-25 21:03:34Z havard.gulldahl $
#
# Copyright 2007 Håvard Gulldahl
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""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)
"""
__author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: pydoc chokes on non-ascii chars in __author__
__license__ = 'Apache License v2'
__version__ = '$Revision: 176 $'[11:-2]
import sys, os.path, StringIO
import time
import gdata.service
import gdata
import atom.service
import atom
import gdata.photos
SUPPORTED_UPLOAD_TYPES = ('bmp', 'jpeg', 'jpg', 'gif', 'png')
UNKOWN_ERROR=1000
GPHOTOS_BAD_REQUEST=400
GPHOTOS_CONFLICT=409
GPHOTOS_INTERNAL_SERVER_ERROR=500
GPHOTOS_INVALID_ARGUMENT=601
GPHOTOS_INVALID_CONTENT_TYPE=602
GPHOTOS_NOT_AN_IMAGE=603
GPHOTOS_INVALID_KIND=604
class GooglePhotosException(Exception):
def __init__(self, response):
self.error_code = response['status']
self.reason = response['reason'].strip()
if '<html>' in str(response['body']): #general html message, discard it
response['body'] = ""
self.body = response['body'].strip()
self.message = "(%(status)s) %(body)s -- %(reason)s" % response
#return explicit error codes
error_map = { '(12) Not an image':GPHOTOS_NOT_AN_IMAGE,
'kind: That is not one of the acceptable values':
GPHOTOS_INVALID_KIND,
}
for msg, code in error_map.iteritems():
if self.body == msg:
self.error_code = code
break
self.args = [self.error_code, self.reason, self.body]
class PhotosService(gdata.service.GDataService):
userUri = '/data/feed/api/user/%s'
def __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:
A PhotosService object used to communicate with the Google Photos
service.
"""
self.email = email
self.client = source
gdata.service.GDataService.__init__(self, email=self.email, password=password,
service='lh2', source=source,
server=server,
additional_headers=additional_headers)
def 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
"""
if limit is not None:
uri += '&max-results=%s' % limit
if start_index is not None:
uri += '&start-index=%s' % start_index
try:
return self.Get(uri, converter=gdata.photos.AnyFeedFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def 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
"""
if limit is not None:
uri += '&max-results=%s' % limit
if start_index is not None:
uri += '&start-index=%s' % start_index
try:
return self.Get(uri, converter=gdata.photos.AnyEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def 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
"""
if isinstance(kind, (list, tuple) ):
kind = ",".join(kind)
uri = '/data/feed/api/user/%s?kind=%s' % (user, kind)
return self.GetFeed(uri, limit=limit)
def 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
"""
# Lower-casing because of
# http://code.google.com/p/gdata-issues/issues/detail?id=194
uri = '/data/feed/api/user/%s?kind=photo&tag=%s' % (user, tag.lower())
return self.GetFeed(uri, limit)
def 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
"""
uri = '/data/feed/api/user/%s?kind=photo&q=%s' % (user, query)
return self.GetFeed(uri, limit=limit)
def 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
"""
uri='/data/feed/api/all?q=%s' % query
return self.GetFeed(uri, limit=limit)
def 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
"""
uri = '/data/feed/api/user/%s/contacts?kind=user' % user
return self.GetFeed(uri, limit=limit)
def 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
"""
uri = '/data/feed/api/user/%s/contacts?kind=photo&q=%s' % (user, search)
return self.GetFeed(uri, limit=limit)
def InsertAlbum(self, title, summary, location=None, access='public',
commenting_enabled='true', timestamp=None):
"""Add an album.
Needs authentication, see self.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
"""
album = gdata.photos.AlbumEntry()
album.title = atom.Title(text=title, title_type='text')
album.summary = atom.Summary(text=summary, summary_type='text')
if location is not None:
album.location = gdata.photos.Location(text=location)
album.access = gdata.photos.Access(text=access)
if commenting_enabled in ('true', 'false'):
album.commentingEnabled = gdata.photos.CommentingEnabled(text=commenting_enabled)
if timestamp is None:
timestamp = '%i' % int(time.time() * 1000)
album.timestamp = gdata.photos.Timestamp(text=timestamp)
try:
return self.Post(album, uri=self.userUri % self.email,
converter=gdata.photos.AlbumEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def InsertPhoto(self, album_or_uri, photo, filename_or_handle,
content_type='image/jpeg'):
"""Add a PhotoEntry
Needs authentication, see self.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'
"""
try:
assert(isinstance(photo, gdata.photos.PhotoEntry))
except AssertionError:
raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUMENT,
'body':'`photo` must be a gdata.photos.PhotoEntry instance',
'reason':'Found %s, not PhotoEntry' % type(photo)
})
try:
majtype, mintype = content_type.split('/')
assert(mintype in SUPPORTED_UPLOAD_TYPES)
except (ValueError, AssertionError):
raise GooglePhotosException({'status':GPHOTOS_INVALID_CONTENT_TYPE,
'body':'This is not a valid content type: %s' % content_type,
'reason':'Accepted content types: %s' % \
['image/'+t for t in SUPPORTED_UPLOAD_TYPES]
})
if isinstance(filename_or_handle, (str, unicode)) and \
os.path.exists(filename_or_handle): # it's a file name
mediasource = gdata.MediaSource()
mediasource.setFile(filename_or_handle, content_type)
elif hasattr(filename_or_handle, 'read'):# it's a file-like resource
if hasattr(filename_or_handle, 'seek'):
filename_or_handle.seek(0) # rewind pointer to the start of the file
# gdata.MediaSource needs the content length, so read the whole image
file_handle = StringIO.StringIO(filename_or_handle.read())
name = 'image'
if hasattr(filename_or_handle, 'name'):
name = filename_or_handle.name
mediasource = gdata.MediaSource(file_handle, content_type,
content_length=file_handle.len, file_name=name)
else: #filename_or_handle is not valid
raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUMENT,
'body':'`filename_or_handle` must be a path name or a file-like object',
'reason':'Found %s, not path name or object with a .read() method' % \
type(filename_or_handle)
})
if isinstance(album_or_uri, (str, unicode)): # it's a uri
feed_uri = album_or_uri
elif hasattr(album_or_uri, 'GetFeedLink'): # it's a AlbumFeed object
feed_uri = album_or_uri.GetFeedLink().href
try:
return self.Post(photo, uri=feed_uri, media_source=mediasource,
converter=gdata.photos.PhotoEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def 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 self.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
"""
metadata = gdata.photos.PhotoEntry()
metadata.title=atom.Title(text=title)
metadata.summary = atom.Summary(text=summary, summary_type='text')
if keywords is not None:
if isinstance(keywords, list):
keywords = ','.join(keywords)
metadata.media.keywords = gdata.media.Keywords(text=keywords)
return self.InsertPhoto(album_or_uri, metadata, filename_or_handle,
content_type)
def UpdatePhotoMetadata(self, photo):
"""Update a photo's metadata.
Needs authentication, see self.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
"""
try:
return self.Put(data=photo, uri=photo.GetEditLink().href,
converter=gdata.photos.PhotoEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def UpdatePhotoBlob(self, photo_or_uri, filename_or_handle,
content_type = 'image/jpeg'):
"""Update a photo's binary data.
Needs authentication, see self.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
"""
try:
majtype, mintype = content_type.split('/')
assert(mintype in SUPPORTED_UPLOAD_TYPES)
except (ValueError, AssertionError):
raise GooglePhotosException({'status':GPHOTOS_INVALID_CONTENT_TYPE,
'body':'This is not a valid content type: %s' % content_type,
'reason':'Accepted content types: %s' % \
['image/'+t for t in SUPPORTED_UPLOAD_TYPES]
})
if isinstance(filename_or_handle, (str, unicode)) and \
os.path.exists(filename_or_handle): # it's a file name
photoblob = gdata.MediaSource()
photoblob.setFile(filename_or_handle, content_type)
elif hasattr(filename_or_handle, 'read'):# it's a file-like resource
if hasattr(filename_or_handle, 'seek'):
filename_or_handle.seek(0) # rewind pointer to the start of the file
# gdata.MediaSource needs the content length, so read the whole image
file_handle = StringIO.StringIO(filename_or_handle.read())
name = 'image'
if hasattr(filename_or_handle, 'name'):
name = filename_or_handle.name
mediasource = gdata.MediaSource(file_handle, content_type,
content_length=file_handle.len, file_name=name)
else: #filename_or_handle is not valid
raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUMENT,
'body':'`filename_or_handle` must be a path name or a file-like object',
'reason':'Found %s, not path name or an object with .read() method' % \
type(filename_or_handle)
})
if isinstance(photo_or_uri, (str, unicode)):
entry_uri = photo_or_uri # it's a uri
elif hasattr(photo_or_uri, 'GetEditMediaLink'):
entry_uri = photo_or_uri.GetEditMediaLink().href
try:
return self.Put(photoblob, entry_uri,
converter=gdata.photos.PhotoEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def InsertTag(self, photo_or_uri, tag):
"""Add a tag (a.k.a. keyword) to a photo.
Needs authentication, see self.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')
"""
tag = gdata.photos.TagEntry(title=atom.Title(text=tag))
if isinstance(photo_or_uri, (str, unicode)):
post_uri = photo_or_uri # it's a uri
elif hasattr(photo_or_uri, 'GetEditMediaLink'):
post_uri = photo_or_uri.GetPostLink().href
try:
return self.Post(data=tag, uri=post_uri,
converter=gdata.photos.TagEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def InsertComment(self, photo_or_uri, comment):
"""Add a comment to a photo.
Needs authentication, see self.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?')
"""
comment = gdata.photos.CommentEntry(content=atom.Content(text=comment))
if isinstance(photo_or_uri, (str, unicode)):
post_uri = photo_or_uri # it's a uri
elif hasattr(photo_or_uri, 'GetEditMediaLink'):
post_uri = photo_or_uri.GetPostLink().href
try:
return self.Post(data=comment, uri=post_uri,
converter=gdata.photos.CommentEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def 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
"""
try:
uri = object_or_uri.GetEditLink().href
except AttributeError:
uri = object_or_uri
try:
return gdata.service.GDataService.Delete(self, uri, *args, **kwargs)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def GetSmallestThumbnail(media_thumbnail_list):
"""Helper function to get the smallest thumbnail of a list of
gdata.media.Thumbnail.
Returns gdata.media.Thumbnail """
r = {}
for thumb in media_thumbnail_list:
r[int(thumb.width)*int(thumb.height)] = thumb
keys = r.keys()
keys.sort()
return r[keys[0]]
def 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' -> """
return time.mktime(time.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.000Z'))
## TODO: Timezone aware
| Python |
# -*-*- encoding: utf-8 -*-*-
#
# This is the base file for the PicasaWeb python client.
# It is used for lower level operations.
#
# $Id: __init__.py 148 2007-10-28 15:09:19Z havard.gulldahl $
#
# Copyright 2007 Håvard Gulldahl
# Portions (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This module provides a pythonic, gdata-centric interface to Google Photos
(a.k.a. Picasa Web Services.
It is modelled after the gdata/* interfaces from the gdata-python-client
project[1] by Google.
You'll find the user-friendly api in photos.service. Please see the
documentation or live help() system for available methods.
[1]: http://gdata-python-client.googlecode.com/
"""
__author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: pydoc chokes on non-ascii chars in __author__
__license__ = 'Apache License v2'
__version__ = '$Revision: 164 $'[11:-2]
import re
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import atom
import gdata
# importing google photo submodules
import gdata.media as Media, gdata.exif as Exif, gdata.geo as Geo
# XML namespaces which are often used in Google Photo elements
PHOTOS_NAMESPACE = 'http://schemas.google.com/photos/2007'
MEDIA_NAMESPACE = 'http://search.yahoo.com/mrss/'
EXIF_NAMESPACE = 'http://schemas.google.com/photos/exif/2007'
OPENSEARCH_NAMESPACE = 'http://a9.com/-/spec/opensearchrss/1.0/'
GEO_NAMESPACE = 'http://www.w3.org/2003/01/geo/wgs84_pos#'
GML_NAMESPACE = 'http://www.opengis.net/gml'
GEORSS_NAMESPACE = 'http://www.georss.org/georss'
PHEED_NAMESPACE = 'http://www.pheed.com/pheed/'
BATCH_NAMESPACE = 'http://schemas.google.com/gdata/batch'
class PhotosBaseElement(atom.AtomBase):
"""Base class for elements in the PHOTO_NAMESPACE. To add new elements,
you only need to add the element tag name to self._tag
"""
_tag = ''
_namespace = PHOTOS_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, name=None, extension_elements=None,
extension_attributes=None, text=None):
self.name = name
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
#def __str__(self):
#return str(self.text)
#def __unicode__(self):
#return unicode(self.text)
def __int__(self):
return int(self.text)
def bool(self):
return self.text == 'true'
class GPhotosBaseFeed(gdata.GDataFeed, gdata.LinkFinder):
"Base class for all Feeds in gdata.photos"
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_attributes = gdata.GDataFeed._attributes.copy()
_children = gdata.GDataFeed._children.copy()
# We deal with Entry elements ourselves
del _children['{%s}entry' % atom.ATOM_NAMESPACE]
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None,
entry=None, total_results=None, start_index=None,
items_per_page=None, extension_elements=None,
extension_attributes=None, text=None):
gdata.GDataFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def kind(self):
"(string) Returns the kind"
try:
return self.category[0].term.split('#')[1]
except IndexError:
return None
def _feedUri(self, kind):
"Convenience method to return a uri to a feed of a special kind"
assert(kind in ('album', 'tag', 'photo', 'comment', 'user'))
here_href = self.GetSelfLink().href
if 'kind=%s' % kind in here_href:
return here_href
if not 'kind=' in here_href:
sep = '?'
if '?' in here_href: sep = '&'
return here_href + "%skind=%s" % (sep, kind)
rx = re.match('.*(kind=)(album|tag|photo|comment)', here_href)
return here_href[:rx.end(1)] + kind + here_href[rx.end(2):]
def _ConvertElementTreeToMember(self, child_tree):
"""Re-implementing the method from AtomBase, since we deal with
Entry elements specially"""
category = child_tree.find('{%s}category' % atom.ATOM_NAMESPACE)
if category is None:
return atom.AtomBase._ConvertElementTreeToMember(self, child_tree)
namespace, kind = category.get('term').split('#')
if namespace != PHOTOS_NAMESPACE:
return atom.AtomBase._ConvertElementTreeToMember(self, child_tree)
## TODO: is it safe to use getattr on gdata.photos?
entry_class = getattr(gdata.photos, '%sEntry' % kind.title())
if not hasattr(self, 'entry') or self.entry is None:
self.entry = []
self.entry.append(atom._CreateClassFromElementTree(
entry_class, child_tree))
class GPhotosBaseEntry(gdata.GDataEntry, gdata.LinkFinder):
"Base class for all Entry elements in gdata.photos"
_tag = 'entry'
_kind = ''
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
extended_property=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title,
updated=updated, text=text,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
self.category.append(
atom.Category(scheme='http://schemas.google.com/g/2005#kind',
term = 'http://schemas.google.com/photos/2007#%s' % self._kind))
def kind(self):
"(string) Returns the kind"
try:
return self.category[0].term.split('#')[1]
except IndexError:
return None
def _feedUri(self, kind):
"Convenience method to get the uri to this entry's feed of the some kind"
try:
href = self.GetFeedLink().href
except AttributeError:
return None
sep = '?'
if '?' in href: sep = '&'
return '%s%skind=%s' % (href, sep, kind)
class PhotosBaseEntry(GPhotosBaseEntry):
pass
class PhotosBaseFeed(GPhotosBaseFeed):
pass
class GPhotosBaseData(object):
pass
class Access(PhotosBaseElement):
"""The Google Photo `Access' element.
The album's access level. Valid values are `public' or `private'.
In documentation, access level is also referred to as `visibility.'"""
_tag = 'access'
def AccessFromString(xml_string):
return atom.CreateClassFromXMLString(Access, xml_string)
class Albumid(PhotosBaseElement):
"The Google Photo `Albumid' element"
_tag = 'albumid'
def AlbumidFromString(xml_string):
return atom.CreateClassFromXMLString(Albumid, xml_string)
class BytesUsed(PhotosBaseElement):
"The Google Photo `BytesUsed' element"
_tag = 'bytesUsed'
def BytesUsedFromString(xml_string):
return atom.CreateClassFromXMLString(BytesUsed, xml_string)
class Client(PhotosBaseElement):
"The Google Photo `Client' element"
_tag = 'client'
def ClientFromString(xml_string):
return atom.CreateClassFromXMLString(Client, xml_string)
class Checksum(PhotosBaseElement):
"The Google Photo `Checksum' element"
_tag = 'checksum'
def ChecksumFromString(xml_string):
return atom.CreateClassFromXMLString(Checksum, xml_string)
class CommentCount(PhotosBaseElement):
"The Google Photo `CommentCount' element"
_tag = 'commentCount'
def CommentCountFromString(xml_string):
return atom.CreateClassFromXMLString(CommentCount, xml_string)
class CommentingEnabled(PhotosBaseElement):
"The Google Photo `CommentingEnabled' element"
_tag = 'commentingEnabled'
def CommentingEnabledFromString(xml_string):
return atom.CreateClassFromXMLString(CommentingEnabled, xml_string)
class Height(PhotosBaseElement):
"The Google Photo `Height' element"
_tag = 'height'
def HeightFromString(xml_string):
return atom.CreateClassFromXMLString(Height, xml_string)
class Id(PhotosBaseElement):
"The Google Photo `Id' element"
_tag = 'id'
def IdFromString(xml_string):
return atom.CreateClassFromXMLString(Id, xml_string)
class Location(PhotosBaseElement):
"The Google Photo `Location' element"
_tag = 'location'
def LocationFromString(xml_string):
return atom.CreateClassFromXMLString(Location, xml_string)
class MaxPhotosPerAlbum(PhotosBaseElement):
"The Google Photo `MaxPhotosPerAlbum' element"
_tag = 'maxPhotosPerAlbum'
def MaxPhotosPerAlbumFromString(xml_string):
return atom.CreateClassFromXMLString(MaxPhotosPerAlbum, xml_string)
class Name(PhotosBaseElement):
"The Google Photo `Name' element"
_tag = 'name'
def NameFromString(xml_string):
return atom.CreateClassFromXMLString(Name, xml_string)
class Nickname(PhotosBaseElement):
"The Google Photo `Nickname' element"
_tag = 'nickname'
def NicknameFromString(xml_string):
return atom.CreateClassFromXMLString(Nickname, xml_string)
class Numphotos(PhotosBaseElement):
"The Google Photo `Numphotos' element"
_tag = 'numphotos'
def NumphotosFromString(xml_string):
return atom.CreateClassFromXMLString(Numphotos, xml_string)
class Numphotosremaining(PhotosBaseElement):
"The Google Photo `Numphotosremaining' element"
_tag = 'numphotosremaining'
def NumphotosremainingFromString(xml_string):
return atom.CreateClassFromXMLString(Numphotosremaining, xml_string)
class Position(PhotosBaseElement):
"The Google Photo `Position' element"
_tag = 'position'
def PositionFromString(xml_string):
return atom.CreateClassFromXMLString(Position, xml_string)
class Photoid(PhotosBaseElement):
"The Google Photo `Photoid' element"
_tag = 'photoid'
def PhotoidFromString(xml_string):
return atom.CreateClassFromXMLString(Photoid, xml_string)
class Quotacurrent(PhotosBaseElement):
"The Google Photo `Quotacurrent' element"
_tag = 'quotacurrent'
def QuotacurrentFromString(xml_string):
return atom.CreateClassFromXMLString(Quotacurrent, xml_string)
class Quotalimit(PhotosBaseElement):
"The Google Photo `Quotalimit' element"
_tag = 'quotalimit'
def QuotalimitFromString(xml_string):
return atom.CreateClassFromXMLString(Quotalimit, xml_string)
class Rotation(PhotosBaseElement):
"The Google Photo `Rotation' element"
_tag = 'rotation'
def RotationFromString(xml_string):
return atom.CreateClassFromXMLString(Rotation, xml_string)
class Size(PhotosBaseElement):
"The Google Photo `Size' element"
_tag = 'size'
def SizeFromString(xml_string):
return atom.CreateClassFromXMLString(Size, xml_string)
class Snippet(PhotosBaseElement):
"""The Google Photo `snippet' element.
When searching, the snippet element will contain a
string with the word you're looking for, highlighted in html markup
E.g. when your query is `hafjell', this element may contain:
`... here at <b>Hafjell</b>.'
You'll find this element in searches -- that is, feeds that combine the
`kind=photo' and `q=yoursearch' parameters in the request.
See also gphoto:truncated and gphoto:snippettype.
"""
_tag = 'snippet'
def SnippetFromString(xml_string):
return atom.CreateClassFromXMLString(Snippet, xml_string)
class Snippettype(PhotosBaseElement):
"""The Google Photo `Snippettype' element
When searching, this element will tell you the type of element that matches.
You'll find this element in searches -- that is, feeds that combine the
`kind=photo' and `q=yoursearch' parameters in the request.
See also gphoto:snippet and gphoto:truncated.
Possible values and their interpretation:
o ALBUM_TITLE - The album title matches
o PHOTO_TAGS - The match is a tag/keyword
o PHOTO_DESCRIPTION - The match is in the photo's description
If you discover a value not listed here, please submit a patch to update this docstring.
"""
_tag = 'snippettype'
def SnippettypeFromString(xml_string):
return atom.CreateClassFromXMLString(Snippettype, xml_string)
class Thumbnail(PhotosBaseElement):
"""The Google Photo `Thumbnail' element
Used to display user's photo thumbnail (hackergotchi).
(Not to be confused with the <media:thumbnail> element, which gives you
small versions of the photo object.)"""
_tag = 'thumbnail'
def ThumbnailFromString(xml_string):
return atom.CreateClassFromXMLString(Thumbnail, xml_string)
class Timestamp(PhotosBaseElement):
"""The Google Photo `Timestamp' element
Represented as the number of milliseconds since January 1st, 1970.
Take a look at the convenience methods .isoformat() and .datetime():
photo_epoch = Time.text # 1180294337000
photo_isostring = Time.isoformat() # '2007-05-27T19:32:17.000Z'
Alternatively:
photo_datetime = Time.datetime() # (requires python >= 2.3)
"""
_tag = 'timestamp'
def isoformat(self):
"""(string) Return the timestamp as a ISO 8601 formatted string,
e.g. '2007-05-27T19:32:17.000Z'
"""
import time
epoch = float(self.text)/1000
return time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(epoch))
def datetime(self):
"""(datetime.datetime) Return the timestamp as a datetime.datetime object
Requires python 2.3
"""
import datetime
epoch = float(self.text)/1000
return datetime.datetime.fromtimestamp(epoch)
def TimestampFromString(xml_string):
return atom.CreateClassFromXMLString(Timestamp, xml_string)
class Truncated(PhotosBaseElement):
"""The Google Photo `Truncated' element
You'll find this element in searches -- that is, feeds that combine the
`kind=photo' and `q=yoursearch' parameters in the request.
See also gphoto:snippet and gphoto:snippettype.
Possible values and their interpretation:
0 -- unknown
"""
_tag = 'Truncated'
def TruncatedFromString(xml_string):
return atom.CreateClassFromXMLString(Truncated, xml_string)
class User(PhotosBaseElement):
"The Google Photo `User' element"
_tag = 'user'
def UserFromString(xml_string):
return atom.CreateClassFromXMLString(User, xml_string)
class Version(PhotosBaseElement):
"The Google Photo `Version' element"
_tag = 'version'
def VersionFromString(xml_string):
return atom.CreateClassFromXMLString(Version, xml_string)
class Width(PhotosBaseElement):
"The Google Photo `Width' element"
_tag = 'width'
def WidthFromString(xml_string):
return atom.CreateClassFromXMLString(Width, xml_string)
class Weight(PhotosBaseElement):
"""The Google Photo `Weight' element.
The weight of the tag is the number of times the tag
appears in the collection of tags currently being viewed.
The default weight is 1, in which case this tags is omitted."""
_tag = 'weight'
def WeightFromString(xml_string):
return atom.CreateClassFromXMLString(Weight, xml_string)
class CommentAuthor(atom.Author):
"""The Atom `Author' element in CommentEntry entries is augmented to
contain elements from the PHOTOS_NAMESPACE
http://groups.google.com/group/Google-Picasa-Data-API/msg/819b0025b5ff5e38
"""
_children = atom.Author._children.copy()
_children['{%s}user' % PHOTOS_NAMESPACE] = ('user', User)
_children['{%s}nickname' % PHOTOS_NAMESPACE] = ('nickname', Nickname)
_children['{%s}thumbnail' % PHOTOS_NAMESPACE] = ('thumbnail', Thumbnail)
def CommentAuthorFromString(xml_string):
return atom.CreateClassFromXMLString(CommentAuthor, xml_string)
########################## ################################
class AlbumData(object):
_children = {}
_children['{%s}id' % PHOTOS_NAMESPACE] = ('gphoto_id', Id)
_children['{%s}name' % PHOTOS_NAMESPACE] = ('name', Name)
_children['{%s}location' % PHOTOS_NAMESPACE] = ('location', Location)
_children['{%s}access' % PHOTOS_NAMESPACE] = ('access', Access)
_children['{%s}bytesUsed' % PHOTOS_NAMESPACE] = ('bytesUsed', BytesUsed)
_children['{%s}timestamp' % PHOTOS_NAMESPACE] = ('timestamp', Timestamp)
_children['{%s}numphotos' % PHOTOS_NAMESPACE] = ('numphotos', Numphotos)
_children['{%s}numphotosremaining' % PHOTOS_NAMESPACE] = \
('numphotosremaining', Numphotosremaining)
_children['{%s}user' % PHOTOS_NAMESPACE] = ('user', User)
_children['{%s}nickname' % PHOTOS_NAMESPACE] = ('nickname', Nickname)
_children['{%s}commentingEnabled' % PHOTOS_NAMESPACE] = \
('commentingEnabled', CommentingEnabled)
_children['{%s}commentCount' % PHOTOS_NAMESPACE] = \
('commentCount', CommentCount)
## NOTE: storing media:group as self.media, to create a self-explaining api
gphoto_id = None
name = None
location = None
access = None
bytesUsed = None
timestamp = None
numphotos = None
numphotosremaining = None
user = None
nickname = None
commentingEnabled = None
commentCount = None
class AlbumEntry(GPhotosBaseEntry, AlbumData):
"""All metadata for a Google Photos Album
Take a look at AlbumData for metadata accessible as attributes to this object.
Notes:
To avoid name clashes, and to create a more sensible api, some
objects have names that differ from the original elements:
o media:group -> self.media,
o geo:where -> self.geo,
o photo:id -> self.gphoto_id
"""
_kind = 'album'
_children = GPhotosBaseEntry._children.copy()
_children.update(AlbumData._children.copy())
# child tags only for Album entries, not feeds
_children['{%s}where' % GEORSS_NAMESPACE] = ('geo', Geo.Where)
_children['{%s}group' % MEDIA_NAMESPACE] = ('media', Media.Group)
media = Media.Group()
geo = Geo.Where()
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
#GPHOTO NAMESPACE:
gphoto_id=None, name=None, location=None, access=None,
timestamp=None, numphotos=None, user=None, nickname=None,
commentingEnabled=None, commentCount=None, thumbnail=None,
# MEDIA NAMESPACE:
media=None,
# GEORSS NAMESPACE:
geo=None,
extended_property=None,
extension_elements=None, extension_attributes=None, text=None):
GPhotosBaseEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title,
updated=updated, text=text,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
## NOTE: storing photo:id as self.gphoto_id, to avoid name clash with atom:id
self.gphoto_id = gphoto_id
self.name = name
self.location = location
self.access = access
self.timestamp = timestamp
self.numphotos = numphotos
self.user = user
self.nickname = nickname
self.commentingEnabled = commentingEnabled
self.commentCount = commentCount
self.thumbnail = thumbnail
self.extended_property = extended_property or []
self.text = text
## NOTE: storing media:group as self.media, and geo:where as geo,
## to create a self-explaining api
self.media = media or Media.Group()
self.geo = geo or Geo.Where()
def GetAlbumId(self):
"Return the id of this album"
return self.GetFeedLink().href.split('/')[-1]
def GetPhotosUri(self):
"(string) Return the uri to this albums feed of the PhotoEntry kind"
return self._feedUri('photo')
def GetCommentsUri(self):
"(string) Return the uri to this albums feed of the CommentEntry kind"
return self._feedUri('comment')
def GetTagsUri(self):
"(string) Return the uri to this albums feed of the TagEntry kind"
return self._feedUri('tag')
def AlbumEntryFromString(xml_string):
return atom.CreateClassFromXMLString(AlbumEntry, xml_string)
class AlbumFeed(GPhotosBaseFeed, AlbumData):
"""All metadata for a Google Photos Album, including its sub-elements
This feed represents an album as the container for other objects.
A Album feed contains entries of
PhotoEntry, CommentEntry or TagEntry,
depending on the `kind' parameter in the original query.
Take a look at AlbumData for accessible attributes.
"""
_children = GPhotosBaseFeed._children.copy()
_children.update(AlbumData._children.copy())
def GetPhotosUri(self):
"(string) Return the uri to the same feed, but of the PhotoEntry kind"
return self._feedUri('photo')
def GetTagsUri(self):
"(string) Return the uri to the same feed, but of the TagEntry kind"
return self._feedUri('tag')
def GetCommentsUri(self):
"(string) Return the uri to the same feed, but of the CommentEntry kind"
return self._feedUri('comment')
def AlbumFeedFromString(xml_string):
return atom.CreateClassFromXMLString(AlbumFeed, xml_string)
class PhotoData(object):
_children = {}
## NOTE: storing photo:id as self.gphoto_id, to avoid name clash with atom:id
_children['{%s}id' % PHOTOS_NAMESPACE] = ('gphoto_id', Id)
_children['{%s}albumid' % PHOTOS_NAMESPACE] = ('albumid', Albumid)
_children['{%s}checksum' % PHOTOS_NAMESPACE] = ('checksum', Checksum)
_children['{%s}client' % PHOTOS_NAMESPACE] = ('client', Client)
_children['{%s}height' % PHOTOS_NAMESPACE] = ('height', Height)
_children['{%s}position' % PHOTOS_NAMESPACE] = ('position', Position)
_children['{%s}rotation' % PHOTOS_NAMESPACE] = ('rotation', Rotation)
_children['{%s}size' % PHOTOS_NAMESPACE] = ('size', Size)
_children['{%s}timestamp' % PHOTOS_NAMESPACE] = ('timestamp', Timestamp)
_children['{%s}version' % PHOTOS_NAMESPACE] = ('version', Version)
_children['{%s}width' % PHOTOS_NAMESPACE] = ('width', Width)
_children['{%s}commentingEnabled' % PHOTOS_NAMESPACE] = \
('commentingEnabled', CommentingEnabled)
_children['{%s}commentCount' % PHOTOS_NAMESPACE] = \
('commentCount', CommentCount)
## NOTE: storing media:group as self.media, exif:tags as self.exif, and
## geo:where as self.geo, to create a self-explaining api
_children['{%s}tags' % EXIF_NAMESPACE] = ('exif', Exif.Tags)
_children['{%s}where' % GEORSS_NAMESPACE] = ('geo', Geo.Where)
_children['{%s}group' % MEDIA_NAMESPACE] = ('media', Media.Group)
# These elements show up in search feeds
_children['{%s}snippet' % PHOTOS_NAMESPACE] = ('snippet', Snippet)
_children['{%s}snippettype' % PHOTOS_NAMESPACE] = ('snippettype', Snippettype)
_children['{%s}truncated' % PHOTOS_NAMESPACE] = ('truncated', Truncated)
gphoto_id = None
albumid = None
checksum = None
client = None
height = None
position = None
rotation = None
size = None
timestamp = None
version = None
width = None
commentingEnabled = None
commentCount = None
snippet=None
snippettype=None
truncated=None
media = Media.Group()
geo = Geo.Where()
tags = Exif.Tags()
class PhotoEntry(GPhotosBaseEntry, PhotoData):
"""All metadata for a Google Photos Photo
Take a look at PhotoData for metadata accessible as attributes to this object.
Notes:
To avoid name clashes, and to create a more sensible api, some
objects have names that differ from the original elements:
o media:group -> self.media,
o exif:tags -> self.exif,
o geo:where -> self.geo,
o photo:id -> self.gphoto_id
"""
_kind = 'photo'
_children = GPhotosBaseEntry._children.copy()
_children.update(PhotoData._children.copy())
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None, text=None,
# GPHOTO NAMESPACE:
gphoto_id=None, albumid=None, checksum=None, client=None, height=None,
position=None, rotation=None, size=None, timestamp=None, version=None,
width=None, commentCount=None, commentingEnabled=None,
# MEDIARSS NAMESPACE:
media=None,
# EXIF_NAMESPACE:
exif=None,
# GEORSS NAMESPACE:
geo=None,
extension_elements=None, extension_attributes=None):
GPhotosBaseEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
title=title, updated=updated, text=text,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
## NOTE: storing photo:id as self.gphoto_id, to avoid name clash with atom:id
self.gphoto_id = gphoto_id
self.albumid = albumid
self.checksum = checksum
self.client = client
self.height = height
self.position = position
self.rotation = rotation
self.size = size
self.timestamp = timestamp
self.version = version
self.width = width
self.commentingEnabled = commentingEnabled
self.commentCount = commentCount
## NOTE: storing media:group as self.media, to create a self-explaining api
self.media = media or Media.Group()
self.exif = exif or Exif.Tags()
self.geo = geo or Geo.Where()
def GetPostLink(self):
"Return the uri to this photo's `POST' link (use it for updates of the object)"
return self.GetFeedLink()
def GetCommentsUri(self):
"Return the uri to this photo's feed of CommentEntry comments"
return self._feedUri('comment')
def GetTagsUri(self):
"Return the uri to this photo's feed of TagEntry tags"
return self._feedUri('tag')
def GetAlbumUri(self):
"""Return the uri to the AlbumEntry containing this photo"""
href = self.GetSelfLink().href
return href[:href.find('/photoid')]
def PhotoEntryFromString(xml_string):
return atom.CreateClassFromXMLString(PhotoEntry, xml_string)
class PhotoFeed(GPhotosBaseFeed, PhotoData):
"""All metadata for a Google Photos Photo, including its sub-elements
This feed represents a photo as the container for other objects.
A Photo feed contains entries of
CommentEntry or TagEntry,
depending on the `kind' parameter in the original query.
Take a look at PhotoData for metadata accessible as attributes to this object.
"""
_children = GPhotosBaseFeed._children.copy()
_children.update(PhotoData._children.copy())
def GetTagsUri(self):
"(string) Return the uri to the same feed, but of the TagEntry kind"
return self._feedUri('tag')
def GetCommentsUri(self):
"(string) Return the uri to the same feed, but of the CommentEntry kind"
return self._feedUri('comment')
def PhotoFeedFromString(xml_string):
return atom.CreateClassFromXMLString(PhotoFeed, xml_string)
class TagData(GPhotosBaseData):
_children = {}
_children['{%s}weight' % PHOTOS_NAMESPACE] = ('weight', Weight)
weight=None
class TagEntry(GPhotosBaseEntry, TagData):
"""All metadata for a Google Photos Tag
The actual tag is stored in the .title.text attribute
"""
_kind = 'tag'
_children = GPhotosBaseEntry._children.copy()
_children.update(TagData._children.copy())
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
# GPHOTO NAMESPACE:
weight=None,
extended_property=None,
extension_elements=None, extension_attributes=None, text=None):
GPhotosBaseEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
title=title, updated=updated, text=text,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
self.weight = weight
def GetAlbumUri(self):
"""Return the uri to the AlbumEntry containing this tag"""
href = self.GetSelfLink().href
pos = href.find('/photoid')
if pos == -1:
return None
return href[:pos]
def GetPhotoUri(self):
"""Return the uri to the PhotoEntry containing this tag"""
href = self.GetSelfLink().href
pos = href.find('/tag')
if pos == -1:
return None
return href[:pos]
def TagEntryFromString(xml_string):
return atom.CreateClassFromXMLString(TagEntry, xml_string)
class TagFeed(GPhotosBaseFeed, TagData):
"""All metadata for a Google Photos Tag, including its sub-elements"""
_children = GPhotosBaseFeed._children.copy()
_children.update(TagData._children.copy())
def TagFeedFromString(xml_string):
return atom.CreateClassFromXMLString(TagFeed, xml_string)
class CommentData(GPhotosBaseData):
_children = {}
## NOTE: storing photo:id as self.gphoto_id, to avoid name clash with atom:id
_children['{%s}id' % PHOTOS_NAMESPACE] = ('gphoto_id', Id)
_children['{%s}albumid' % PHOTOS_NAMESPACE] = ('albumid', Albumid)
_children['{%s}photoid' % PHOTOS_NAMESPACE] = ('photoid', Photoid)
_children['{%s}author' % atom.ATOM_NAMESPACE] = ('author', [CommentAuthor,])
gphoto_id=None
albumid=None
photoid=None
author=None
class CommentEntry(GPhotosBaseEntry, CommentData):
"""All metadata for a Google Photos Comment
The comment is stored in the .content.text attribute,
with a content type in .content.type.
"""
_kind = 'comment'
_children = GPhotosBaseEntry._children.copy()
_children.update(CommentData._children.copy())
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
# GPHOTO NAMESPACE:
gphoto_id=None, albumid=None, photoid=None,
extended_property=None,
extension_elements=None, extension_attributes=None, text=None):
GPhotosBaseEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
title=title, updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.gphoto_id = gphoto_id
self.albumid = albumid
self.photoid = photoid
def GetCommentId(self):
"""Return the globally unique id of this comment"""
return self.GetSelfLink().href.split('/')[-1]
def GetAlbumUri(self):
"""Return the uri to the AlbumEntry containing this comment"""
href = self.GetSelfLink().href
return href[:href.find('/photoid')]
def GetPhotoUri(self):
"""Return the uri to the PhotoEntry containing this comment"""
href = self.GetSelfLink().href
return href[:href.find('/commentid')]
def CommentEntryFromString(xml_string):
return atom.CreateClassFromXMLString(CommentEntry, xml_string)
class CommentFeed(GPhotosBaseFeed, CommentData):
"""All metadata for a Google Photos Comment, including its sub-elements"""
_children = GPhotosBaseFeed._children.copy()
_children.update(CommentData._children.copy())
def CommentFeedFromString(xml_string):
return atom.CreateClassFromXMLString(CommentFeed, xml_string)
class UserData(GPhotosBaseData):
_children = {}
_children['{%s}maxPhotosPerAlbum' % PHOTOS_NAMESPACE] = ('maxPhotosPerAlbum', MaxPhotosPerAlbum)
_children['{%s}nickname' % PHOTOS_NAMESPACE] = ('nickname', Nickname)
_children['{%s}quotalimit' % PHOTOS_NAMESPACE] = ('quotalimit', Quotalimit)
_children['{%s}quotacurrent' % PHOTOS_NAMESPACE] = ('quotacurrent', Quotacurrent)
_children['{%s}thumbnail' % PHOTOS_NAMESPACE] = ('thumbnail', Thumbnail)
_children['{%s}user' % PHOTOS_NAMESPACE] = ('user', User)
_children['{%s}id' % PHOTOS_NAMESPACE] = ('gphoto_id', Id)
maxPhotosPerAlbum=None
nickname=None
quotalimit=None
quotacurrent=None
thumbnail=None
user=None
gphoto_id=None
class UserEntry(GPhotosBaseEntry, UserData):
"""All metadata for a Google Photos User
This entry represents an album owner and all appropriate metadata.
Take a look at at the attributes of the UserData for metadata available.
"""
_children = GPhotosBaseEntry._children.copy()
_children.update(UserData._children.copy())
_kind = 'user'
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
# GPHOTO NAMESPACE:
gphoto_id=None, maxPhotosPerAlbum=None, nickname=None, quotalimit=None,
quotacurrent=None, thumbnail=None, user=None,
extended_property=None,
extension_elements=None, extension_attributes=None, text=None):
GPhotosBaseEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
title=title, updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.gphoto_id=gphoto_id
self.maxPhotosPerAlbum=maxPhotosPerAlbum
self.nickname=nickname
self.quotalimit=quotalimit
self.quotacurrent=quotacurrent
self.thumbnail=thumbnail
self.user=user
def GetAlbumsUri(self):
"(string) Return the uri to this user's feed of the AlbumEntry kind"
return self._feedUri('album')
def GetPhotosUri(self):
"(string) Return the uri to this user's feed of the PhotoEntry kind"
return self._feedUri('photo')
def GetCommentsUri(self):
"(string) Return the uri to this user's feed of the CommentEntry kind"
return self._feedUri('comment')
def GetTagsUri(self):
"(string) Return the uri to this user's feed of the TagEntry kind"
return self._feedUri('tag')
def UserEntryFromString(xml_string):
return atom.CreateClassFromXMLString(UserEntry, xml_string)
class UserFeed(GPhotosBaseFeed, UserData):
"""Feed for a User in the google photos api.
This feed represents a user as the container for other objects.
A User feed contains entries of
AlbumEntry, PhotoEntry, CommentEntry, UserEntry or TagEntry,
depending on the `kind' parameter in the original query.
The user feed itself also contains all of the metadata available
as part of a UserData object."""
_children = GPhotosBaseFeed._children.copy()
_children.update(UserData._children.copy())
def GetAlbumsUri(self):
"""Get the uri to this feed, but with entries of the AlbumEntry kind."""
return self._feedUri('album')
def GetTagsUri(self):
"""Get the uri to this feed, but with entries of the TagEntry kind."""
return self._feedUri('tag')
def GetPhotosUri(self):
"""Get the uri to this feed, but with entries of the PhotosEntry kind."""
return self._feedUri('photo')
def GetCommentsUri(self):
"""Get the uri to this feed, but with entries of the CommentsEntry kind."""
return self._feedUri('comment')
def UserFeedFromString(xml_string):
return atom.CreateClassFromXMLString(UserFeed, xml_string)
def AnyFeedFromString(xml_string):
"""Creates an instance of the appropriate feed class from the
xml string contents.
Args:
xml_string: str A string which contains valid XML. The root element
of the XML string should match the tag and namespace of the desired
class.
Returns:
An instance of the target class with members assigned according to the
contents of the XML - or a basic gdata.GDataFeed instance if it is
impossible to determine the appropriate class (look for extra elements
in GDataFeed's .FindExtensions() and extension_elements[] ).
"""
tree = ElementTree.fromstring(xml_string)
category = tree.find('{%s}category' % atom.ATOM_NAMESPACE)
if category is None:
# TODO: is this the best way to handle this?
return atom._CreateClassFromElementTree(GPhotosBaseFeed, tree)
namespace, kind = category.get('term').split('#')
if namespace != PHOTOS_NAMESPACE:
# TODO: is this the best way to handle this?
return atom._CreateClassFromElementTree(GPhotosBaseFeed, tree)
## TODO: is getattr safe this way?
feed_class = getattr(gdata.photos, '%sFeed' % kind.title())
return atom._CreateClassFromElementTree(feed_class, tree)
def AnyEntryFromString(xml_string):
"""Creates an instance of the appropriate entry class from the
xml string contents.
Args:
xml_string: str A string which contains valid XML. The root element
of the XML string should match the tag and namespace of the desired
class.
Returns:
An instance of the target class with members assigned according to the
contents of the XML - or a basic gdata.GDataEndry instance if it is
impossible to determine the appropriate class (look for extra elements
in GDataEntry's .FindExtensions() and extension_elements[] ).
"""
tree = ElementTree.fromstring(xml_string)
category = tree.find('{%s}category' % atom.ATOM_NAMESPACE)
if category is None:
# TODO: is this the best way to handle this?
return atom._CreateClassFromElementTree(GPhotosBaseEntry, tree)
namespace, kind = category.get('term').split('#')
if namespace != PHOTOS_NAMESPACE:
# TODO: is this the best way to handle this?
return atom._CreateClassFromElementTree(GPhotosBaseEntry, tree)
## TODO: is getattr safe this way?
feed_class = getattr(gdata.photos, '%sEntry' % kind.title())
return atom._CreateClassFromElementTree(feed_class, tree)
| Python |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2007 Benoit Chesneau <benoitc@metavers.net>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""CodesearchService extends GDataService to streamline Google Codesearch
operations"""
__author__ = 'Benoit Chesneau'
import atom
import gdata.service
import gdata.codesearch
class CodesearchService(gdata.service.GDataService):
"""Client extension for Google codesearch service"""
def __init__(self, email=None, password=None, source=None,
server='www.google.com', additional_headers=None):
"""Constructor for the CodesearchService.
Args:
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.
Yields:
A CodesearchService object used to communicate with the Google Codesearch
service.
"""
gdata.service.GDataService.__init__(self,
email=email, password=password, service='codesearch',
source=source,server=server,
additional_headers=additional_headers)
def Query(self, uri, converter=gdata.codesearch.CodesearchFeedFromString):
"""Queries the Codesearch feed and returns the resulting feed of
entries.
Args:
uri: string The full URI to be queried. This can contain query
parameters, a hostname, or simply the relative path to a Document
List feed. The DocumentQuery object is useful when constructing
query parameters.
converter: func (optional) A function which will be executed on the
retrieved item, generally to render it into a Python object.
By default the CodesearchFeedFromString function is used to
return a CodesearchFeed object. This is because most feed
queries will result in a feed and not a single entry.
Returns :
A CodesearchFeed objects representing the feed returned by the server
"""
return self.Get(uri, converter=converter)
def GetSnippetsFeed(self, text_query=None):
"""Retrieve Codesearch feed for a keyword
Args:
text_query : string (optional) The contents of the q query parameter. This
string is URL escaped upon conversion to a URI.
Returns:
A CodesearchFeed objects representing the feed returned by the server
"""
query=gdata.codesearch.service.CodesearchQuery(text_query=text_query)
feed = self.Query(query.ToUri())
return feed
class CodesearchQuery(gdata.service.Query):
"""Object used to construct the query to the Google Codesearch feed. here only as a shorcut"""
def __init__(self, feed='/codesearch/feeds/search', text_query=None,
params=None, categories=None):
"""Constructor for Codesearch Query.
Args:
feed: string (optional) The path for the feed. (e.g. '/codesearch/feeds/search')
text_query: string (optional) The contents of the q query parameter. This
string is URL escaped upon conversion to a URI.
params: dict (optional) Parameter value string pairs which become URL
params when translated to a URI. These parameters are added to
the query's items.
categories: list (optional) List of category strings which should be
included as query categories. See gdata.service.Query for
additional documentation.
Yelds:
A CodesearchQuery object to construct a URI based on Codesearch feed
"""
gdata.service.Query.__init__(self, feed, text_query, params, categories)
| Python |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2007 Benoit Chesneau <benoitc@metavers.net>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""Contains extensions to Atom objects used by Google Codesearch"""
__author__ = 'Benoit Chesneau'
import atom
import gdata
CODESEARCH_NAMESPACE='http://schemas.google.com/codesearch/2006'
CODESEARCH_TEMPLATE='{http://shema.google.com/codesearch/2006}%s'
class Match(atom.AtomBase):
""" The Google Codesearch match element """
_tag = 'match'
_namespace = CODESEARCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['lineNumber'] = 'line_number'
_attributes['type'] = 'type'
def __init__(self, line_number=None, type=None, extension_elements=None,
extension_attributes=None, text=None):
self.text = text
self.type = type
self.line_number = line_number
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class File(atom.AtomBase):
""" The Google Codesearch file element"""
_tag = 'file'
_namespace = CODESEARCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['name'] = 'name'
def __init__(self, name=None, extension_elements=None,
extension_attributes=None, text=None):
self.text = text
self.name = name
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Package(atom.AtomBase):
""" The Google Codesearch package element"""
_tag = 'package'
_namespace = CODESEARCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['name'] = 'name'
_attributes['uri'] = 'uri'
def __init__(self, name=None, uri=None, extension_elements=None,
extension_attributes=None, text=None):
self.text = text
self.name = name
self.uri = uri
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class CodesearchEntry(gdata.GDataEntry):
""" Google codesearch atom entry"""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}file' % CODESEARCH_NAMESPACE] = ('file', File)
_children['{%s}package' % CODESEARCH_NAMESPACE] = ('package', Package)
_children['{%s}match' % CODESEARCH_NAMESPACE] = ('match', [Match])
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
match=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title,
updated=updated, text=None)
self.match = match or []
def CodesearchEntryFromString(xml_string):
"""Converts an XML string into a CodesearchEntry object.
Args:
xml_string: string The XML describing a Codesearch feed entry.
Returns:
A CodesearchEntry object corresponding to the given XML.
"""
return atom.CreateClassFromXMLString(CodesearchEntry, xml_string)
class CodesearchFeed(gdata.GDataFeed):
"""feed containing list of Google codesearch Items"""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CodesearchEntry])
def CodesearchFeedFromString(xml_string):
"""Converts an XML string into a CodesearchFeed object.
Args:
xml_string: string The XML describing a Codesearch feed.
Returns:
A CodeseartchFeed object corresponding to the given XML.
"""
return atom.CreateClassFromXMLString(CodesearchFeed, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to Atom objects used with Google Base."""
__author__ = 'api.jscudder (Jeffrey Scudder)'
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import atom
import gdata
# XML namespaces which are often used in Google Base entities.
GBASE_NAMESPACE = 'http://base.google.com/ns/1.0'
GBASE_TEMPLATE = '{http://base.google.com/ns/1.0}%s'
GMETA_NAMESPACE = 'http://base.google.com/ns-metadata/1.0'
GMETA_TEMPLATE = '{http://base.google.com/ns-metadata/1.0}%s'
class ItemAttributeContainer(object):
"""Provides methods for finding Google Base Item attributes.
Google Base item attributes are child nodes in the gbase namespace. Google
Base allows you to define your own item attributes and this class provides
methods to interact with the custom attributes.
"""
def GetItemAttributes(self, name):
"""Returns a list of all item attributes which have the desired name.
Args:
name: str The tag of the desired base attributes. For example, calling
this method with 'rating' would return a list of ItemAttributes
represented by a 'g:rating' tag.
Returns:
A list of matching ItemAttribute objects.
"""
result = []
for attrib in self.item_attributes:
if attrib.name == name:
result.append(attrib)
return result
def FindItemAttribute(self, name):
"""Get the contents of the first Base item attribute which matches name.
This method is deprecated, please use GetItemAttributes instead.
Args:
name: str The tag of the desired base attribute. For example, calling
this method with name = 'rating' would search for a tag rating
in the GBase namespace in the item attributes.
Returns:
The text contents of the item attribute, or none if the attribute was
not found.
"""
for attrib in self.item_attributes:
if attrib.name == name:
return attrib.text
return None
def AddItemAttribute(self, name, value, value_type=None, access=None):
"""Adds a new item attribute tag containing the value.
Creates a new extension element in the GBase namespace to represent a
Google Base item attribute.
Args:
name: str The tag name for the new attribute. This must be a valid xml
tag name. The tag will be placed in the GBase namespace.
value: str Contents for the item attribute
value_type: str (optional) The type of data in the vlaue, Examples: text
float
access: str (optional) Used to hide attributes. The attribute is not
exposed in the snippets feed if access is set to 'private'.
"""
new_attribute = ItemAttribute(name, text=value,
text_type=value_type, access=access)
self.item_attributes.append(new_attribute)
def SetItemAttribute(self, name, value):
"""Changes an existing item attribute's value."""
for attrib in self.item_attributes:
if attrib.name == name:
attrib.text = value
return
def RemoveItemAttribute(self, name):
"""Deletes the first extension element which matches name.
Deletes the first extension element which matches name.
"""
for i in xrange(len(self.item_attributes)):
if self.item_attributes[i].name == name:
del self.item_attributes[i]
return
# We need to overwrite _ConvertElementTreeToMember to add special logic to
# convert custom attributes to members
def _ConvertElementTreeToMember(self, child_tree):
# Find the element's tag in this class's list of child members
if self.__class__._children.has_key(child_tree.tag):
member_name = self.__class__._children[child_tree.tag][0]
member_class = self.__class__._children[child_tree.tag][1]
# If the class member is supposed to contain a list, make sure the
# matching member is set to a list, then append the new member
# instance to the list.
if isinstance(member_class, list):
if getattr(self, member_name) is None:
setattr(self, member_name, [])
getattr(self, member_name).append(atom._CreateClassFromElementTree(
member_class[0], child_tree))
else:
setattr(self, member_name,
atom._CreateClassFromElementTree(member_class, child_tree))
elif child_tree.tag.find('{%s}' % GBASE_NAMESPACE) == 0:
# If this is in the gbase namespace, make it into an extension element.
name = child_tree.tag[child_tree.tag.index('}')+1:]
value = child_tree.text
if child_tree.attrib.has_key('type'):
value_type = child_tree.attrib['type']
else:
value_type = None
self.AddItemAttribute(name, value, value_type)
else:
atom.ExtensionContainer._ConvertElementTreeToMember(self, child_tree)
# We need to overwtite _AddMembersToElementTree to add special logic to
# convert custom members to XML nodes.
def _AddMembersToElementTree(self, tree):
# Convert the members of this class which are XML child nodes.
# This uses the class's _children dictionary to find the members which
# should become XML child nodes.
member_node_names = [values[0] for tag, values in
self.__class__._children.iteritems()]
for member_name in member_node_names:
member = getattr(self, member_name)
if member is None:
pass
elif isinstance(member, list):
for instance in member:
instance._BecomeChildElement(tree)
else:
member._BecomeChildElement(tree)
# Convert the members of this class which are XML attributes.
for xml_attribute, member_name in self.__class__._attributes.iteritems():
member = getattr(self, member_name)
if member is not None:
tree.attrib[xml_attribute] = member
# Convert all special custom item attributes to nodes
for attribute in self.item_attributes:
attribute._BecomeChildElement(tree)
# Lastly, call the ExtensionContainers's _AddMembersToElementTree to
# convert any extension attributes.
atom.ExtensionContainer._AddMembersToElementTree(self, tree)
class ItemAttribute(atom.Text):
"""An optional or user defined attribute for a GBase item.
Google Base allows items to have custom attribute child nodes. These nodes
have contents and a type attribute which tells Google Base whether the
contents are text, a float value with units, etc. The Atom text class has
the same structure, so this class inherits from Text.
"""
_namespace = GBASE_NAMESPACE
_children = atom.Text._children.copy()
_attributes = atom.Text._attributes.copy()
_attributes['access'] = 'access'
def __init__(self, name, text_type=None, access=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for a GBase item attribute
Args:
name: str The name of the attribute. Examples include
price, color, make, model, pages, salary, etc.
text_type: str (optional) The type associated with the text contents
access: str (optional) If the access attribute is set to 'private', the
attribute will not be included in the item's description in the
snippets feed
text: str (optional) The text data in the this element
extension_elements: list (optional) A list of ExtensionElement
instances
extension_attributes: dict (optional) A dictionary of attribute
value string pairs
"""
self.name = name
self.type = text_type
self.access = access
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def _BecomeChildElement(self, tree):
new_child = ElementTree.Element('')
tree.append(new_child)
new_child.tag = '{%s}%s' % (self.__class__._namespace,
self.name)
self._AddMembersToElementTree(new_child)
def _ToElementTree(self):
new_tree = ElementTree.Element('{%s}%s' % (self.__class__._namespace,
self.name))
self._AddMembersToElementTree(new_tree)
return new_tree
def ItemAttributeFromString(xml_string):
element_tree = ElementTree.fromstring(xml_string)
return _ItemAttributeFromElementTree(element_tree)
def _ItemAttributeFromElementTree(element_tree):
if element_tree.tag.find(GBASE_TEMPLATE % '') == 0:
to_return = ItemAttribute('')
to_return._HarvestElementTree(element_tree)
to_return.name = element_tree.tag[element_tree.tag.index('}')+1:]
if to_return.name and to_return.name != '':
return to_return
return None
class Label(atom.AtomBase):
"""The Google Base label element"""
_tag = 'label'
_namespace = GBASE_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def LabelFromString(xml_string):
return atom.CreateClassFromXMLString(Label, xml_string)
class Thumbnail(atom.AtomBase):
"""The Google Base thumbnail element"""
_tag = 'thumbnail'
_namespace = GMETA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['width'] = 'width'
_attributes['height'] = 'height'
def __init__(self, width=None, height=None, text=None, extension_elements=None,
extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.width = width
self.height = height
def ThumbnailFromString(xml_string):
return atom.CreateClassFromXMLString(Thumbnail, xml_string)
class ImageLink(atom.Text):
"""The Google Base image_link element"""
_tag = 'image_link'
_namespace = GBASE_NAMESPACE
_children = atom.Text._children.copy()
_attributes = atom.Text._attributes.copy()
_children['{%s}thumbnail' % GMETA_NAMESPACE] = ('thumbnail', [Thumbnail])
def __init__(self, thumbnail=None, text=None, extension_elements=None,
text_type=None, extension_attributes=None):
self.thumbnail = thumbnail or []
self.text = text
self.type = text_type
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ImageLinkFromString(xml_string):
return atom.CreateClassFromXMLString(ImageLink, xml_string)
class ItemType(atom.Text):
"""The Google Base item_type element"""
_tag = 'item_type'
_namespace = GBASE_NAMESPACE
_children = atom.Text._children.copy()
_attributes = atom.Text._attributes.copy()
def __init__(self, text=None, extension_elements=None,
text_type=None, extension_attributes=None):
self.text = text
self.type = text_type
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ItemTypeFromString(xml_string):
return atom.CreateClassFromXMLString(ItemType, xml_string)
class MetaItemType(ItemType):
"""The Google Base item_type element"""
_tag = 'item_type'
_namespace = GMETA_NAMESPACE
_children = ItemType._children.copy()
_attributes = ItemType._attributes.copy()
def MetaItemTypeFromString(xml_string):
return atom.CreateClassFromXMLString(MetaItemType, xml_string)
class Value(atom.AtomBase):
"""Metadata about common values for a given attribute
A value is a child of an attribute which comes from the attributes feed.
The value's text is a commonly used value paired with an attribute name
and the value's count tells how often this value appears for the given
attribute in the search results.
"""
_tag = 'value'
_namespace = GMETA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['count'] = 'count'
def __init__(self, count=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Attribute metadata element
Args:
count: str (optional) The number of times the value in text is given
for the parent attribute.
text: str (optional) The value which appears in the search results.
extension_elements: list (optional) A list of ExtensionElement
instances
extension_attributes: dict (optional) A dictionary of attribute value
string pairs
"""
self.count = count
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ValueFromString(xml_string):
return atom.CreateClassFromXMLString(Value, xml_string)
class Attribute(atom.Text):
"""Metadata about an attribute from the attributes feed
An entry from the attributes feed contains a list of attributes. Each
attribute describes the attribute's type and count of the items which
use the attribute.
"""
_tag = 'attribute'
_namespace = GMETA_NAMESPACE
_children = atom.Text._children.copy()
_attributes = atom.Text._attributes.copy()
_children['{%s}value' % GMETA_NAMESPACE] = ('value', [Value])
_attributes['count'] = 'count'
_attributes['name'] = 'name'
def __init__(self, name=None, attribute_type=None, count=None, value=None,
text=None, extension_elements=None, extension_attributes=None):
"""Constructor for Attribute metadata element
Args:
name: str (optional) The name of the attribute
attribute_type: str (optional) The type for the attribute. Examples:
test, float, etc.
count: str (optional) The number of times this attribute appears in
the query results.
value: list (optional) The values which are often used for this
attirbute.
text: str (optional) The text contents of the XML for this attribute.
extension_elements: list (optional) A list of ExtensionElement
instances
extension_attributes: dict (optional) A dictionary of attribute value
string pairs
"""
self.name = name
self.type = attribute_type
self.count = count
self.value = value or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def AttributeFromString(xml_string):
return atom.CreateClassFromXMLString(Attribute, xml_string)
class Attributes(atom.AtomBase):
"""A collection of Google Base metadata attributes"""
_tag = 'attributes'
_namespace = GMETA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}attribute' % GMETA_NAMESPACE] = ('attribute', [Attribute])
def __init__(self, attribute=None, extension_elements=None,
extension_attributes=None, text=None):
self.attribute = attribute or []
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
class GBaseItem(ItemAttributeContainer, gdata.BatchEntry):
"""An Google Base flavor of an Atom Entry.
Google Base items have required attributes, recommended attributes, and user
defined attributes. The required attributes are stored in this class as
members, and other attributes are stored as extension elements. You can
access the recommended and user defined attributes by using
AddItemAttribute, SetItemAttribute, FindItemAttribute, and
RemoveItemAttribute.
The Base Item
"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.BatchEntry._children.copy()
_attributes = gdata.BatchEntry._attributes.copy()
_children['{%s}label' % GBASE_NAMESPACE] = ('label', [Label])
_children['{%s}item_type' % GBASE_NAMESPACE] = ('item_type', ItemType)
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, updated=None, control=None,
label=None, item_type=None, item_attributes=None,
batch_operation=None, batch_id=None, batch_status=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.title = title
self.updated = updated
self.control = control
self.label = label or []
self.item_type = item_type
self.item_attributes = item_attributes or []
self.batch_operation = batch_operation
self.batch_id = batch_id
self.batch_status = batch_status
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GBaseItemFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseItem, xml_string)
class GBaseSnippet(GBaseItem):
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = GBaseItem._children.copy()
_attributes = GBaseItem._attributes.copy()
def GBaseSnippetFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseSnippet, xml_string)
class GBaseAttributeEntry(gdata.GDataEntry):
"""An Atom Entry from the attributes feed"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}attribute' % GMETA_NAMESPACE] = ('attribute', [Attribute])
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, updated=None, label=None,
attribute=None, control=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.control = control
self.title = title
self.updated = updated
self.label = label or []
self.attribute = attribute or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GBaseAttributeEntryFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseAttributeEntry, xml_string)
class GBaseItemTypeEntry(gdata.GDataEntry):
"""An Atom entry from the item types feed
These entries contain a list of attributes which are stored in one
XML node called attributes. This class simplifies the data structure
by treating attributes as a list of attribute instances.
Note that the item_type for an item type entry is in the Google Base meta
namespace as opposed to item_types encountered in other feeds.
"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}attributes' % GMETA_NAMESPACE] = ('attributes', Attributes)
_children['{%s}attribute' % GMETA_NAMESPACE] = ('attribute', [Attribute])
_children['{%s}item_type' % GMETA_NAMESPACE] = ('item_type', MetaItemType)
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, updated=None, label=None,
item_type=None, control=None, attribute=None, attributes=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.title = title
self.updated = updated
self.control = control
self.label = label or []
self.item_type = item_type
self.attributes = attributes
self.attribute = attribute or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GBaseItemTypeEntryFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseItemTypeEntry, xml_string)
class GBaseItemFeed(gdata.BatchFeed):
"""A feed containing Google Base Items"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.BatchFeed._children.copy()
_attributes = gdata.BatchFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GBaseItem])
def GBaseItemFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseItemFeed, xml_string)
class GBaseSnippetFeed(gdata.GDataFeed):
"""A feed containing Google Base Snippets"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GBaseSnippet])
def GBaseSnippetFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseSnippetFeed, xml_string)
class GBaseAttributesFeed(gdata.GDataFeed):
"""A feed containing Google Base Attributes
A query sent to the attributes feed will return a feed of
attributes which are present in the items that match the
query.
"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[GBaseAttributeEntry])
def GBaseAttributesFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseAttributesFeed, xml_string)
class GBaseLocalesFeed(gdata.GDataFeed):
"""The locales feed from Google Base.
This read-only feed defines the permitted locales for Google Base. The
locale value identifies the language, currency, and date formats used in a
feed.
"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
def GBaseLocalesFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseLocalesFeed, xml_string)
class GBaseItemTypesFeed(gdata.GDataFeed):
"""A feed from the Google Base item types feed"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GBaseItemTypeEntry])
def GBaseItemTypesFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseItemTypesFeed, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""GBaseService extends the GDataService to streamline Google Base operations.
GBaseService: Provides methods to query feeds and manipulate items. Extends
GDataService.
DictionaryToParamList: Function which converts a dictionary into a list of
URL arguments (represented as strings). This is a
utility function used in CRUD operations.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
import urllib
import gdata
import atom.service
import gdata.service
import gdata.base
import atom
# URL to which all batch requests are sent.
BASE_BATCH_URL = 'http://www.google.com/base/feeds/items/batch'
class Error(Exception):
pass
class RequestError(Error):
pass
class GBaseService(gdata.service.GDataService):
"""Client for the Google Base service."""
def __init__(self, email=None, password=None, source=None,
server='base.google.com', api_key=None,
additional_headers=None, handler=None):
gdata.service.GDataService.__init__(self, email=email, password=password,
service='gbase', source=source,
server=server,
additional_headers=additional_headers,
handler=handler)
self.api_key = api_key
def _SetAPIKey(self, api_key):
if not isinstance(self.additional_headers, dict):
self.additional_headers = {}
self.additional_headers['X-Google-Key'] = api_key
def __SetAPIKey(self, api_key):
self._SetAPIKey(api_key)
def _GetAPIKey(self):
if 'X-Google-Key' not in self.additional_headers:
return None
else:
return self.additional_headers['X-Google-Key']
def __GetAPIKey(self):
return self._GetAPIKey()
api_key = property(__GetAPIKey, __SetAPIKey,
doc="""Get or set the API key to be included in all requests.""")
def Query(self, uri, converter=None):
"""Performs a style query and returns a resulting feed or entry.
Args:
uri: string The full URI which be queried. Examples include
'/base/feeds/snippets?bq=digital+camera',
'http://www.google.com/base/feeds/snippets?bq=digital+camera'
'/base/feeds/items'
I recommend creating a URI using a query class.
converter: func (optional) A function which will be executed on the
server's response. Examples include GBaseItemFromString, etc.
Returns:
If converter was specified, returns the results of calling converter on
the server's response. If converter was not specified, and the result
was an Atom Entry, returns a GBaseItem, by default, the method returns
the result of calling gdata.service's Get method.
"""
result = self.Get(uri, converter=converter)
if converter:
return result
elif isinstance(result, atom.Entry):
return gdata.base.GBaseItemFromString(result.ToString())
return result
def QuerySnippetsFeed(self, uri):
return self.Get(uri, converter=gdata.base.GBaseSnippetFeedFromString)
def QueryItemsFeed(self, uri):
return self.Get(uri, converter=gdata.base.GBaseItemFeedFromString)
def QueryAttributesFeed(self, uri):
return self.Get(uri, converter=gdata.base.GBaseAttributesFeedFromString)
def QueryItemTypesFeed(self, uri):
return self.Get(uri, converter=gdata.base.GBaseItemTypesFeedFromString)
def QueryLocalesFeed(self, uri):
return self.Get(uri, converter=gdata.base.GBaseLocalesFeedFromString)
def GetItem(self, uri):
return self.Get(uri, converter=gdata.base.GBaseItemFromString)
def GetSnippet(self, uri):
return self.Get(uri, converter=gdata.base.GBaseSnippetFromString)
def GetAttribute(self, uri):
return self.Get(uri, converter=gdata.base.GBaseAttributeEntryFromString)
def GetItemType(self, uri):
return self.Get(uri, converter=gdata.base.GBaseItemTypeEntryFromString)
def GetLocale(self, uri):
return self.Get(uri, converter=gdata.base.GDataEntryFromString)
def InsertItem(self, new_item, url_params=None, escape_params=True,
converter=None):
"""Adds an item to Google Base.
Args:
new_item: atom.Entry or subclass A new item which is to be added to
Google Base.
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
converter: func (optional) Function which is executed on the server's
response before it is returned. Usually this is a function like
GBaseItemFromString which will parse the response and turn it into
an object.
Returns:
If converter is defined, the results of running converter on the server's
response. Otherwise, it will be a GBaseItem.
"""
response = self.Post(new_item, '/base/feeds/items', url_params=url_params,
escape_params=escape_params, converter=converter)
if not converter and isinstance(response, atom.Entry):
return gdata.base.GBaseItemFromString(response.ToString())
return response
def DeleteItem(self, item_id, url_params=None, escape_params=True):
"""Removes an item with the specified ID from Google Base.
Args:
item_id: string The ID of the item to be deleted. Example:
'http://www.google.com/base/feeds/items/13185446517496042648'
url_params: dict (optional) Additional URL parameters to be included
in the deletion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
True if the delete succeeded.
"""
return self.Delete('/%s' % (item_id.lstrip('http://www.google.com/')),
url_params=url_params, escape_params=escape_params)
def UpdateItem(self, item_id, updated_item, url_params=None,
escape_params=True,
converter=gdata.base.GBaseItemFromString):
"""Updates an existing item.
Args:
item_id: string The ID of the item to be updated. Example:
'http://www.google.com/base/feeds/items/13185446517496042648'
updated_item: atom.Entry, subclass, or string, containing
the Atom Entry which will replace the base item which is
stored at the item_id.
url_params: dict (optional) Additional URL parameters to be included
in the update request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
converter: func (optional) Function which is executed on the server's
response before it is returned. Usually this is a function like
GBaseItemFromString which will parse the response and turn it into
an object.
Returns:
If converter is defined, the results of running converter on the server's
response. Otherwise, it will be a GBaseItem.
"""
response = self.Put(updated_item,
item_id, url_params=url_params, escape_params=escape_params,
converter=converter)
if not converter and isinstance(response, atom.Entry):
return gdata.base.GBaseItemFromString(response.ToString())
return response
def ExecuteBatch(self, batch_feed,
converter=gdata.base.GBaseItemFeedFromString):
"""Sends a batch request feed to the server.
Args:
batch_feed: gdata.BatchFeed A feed containing BatchEntry elements which
contain the desired CRUD operation and any necessary entry data.
converter: Function (optional) Function to be executed on the server's
response. This function should take one string as a parameter. The
default value is GBaseItemFeedFromString which will turn the result
into a gdata.base.GBaseItem object.
Returns:
A gdata.BatchFeed containing the results.
"""
return self.Post(batch_feed, BASE_BATCH_URL, converter=converter)
class BaseQuery(gdata.service.Query):
def _GetBaseQuery(self):
return self['bq']
def _SetBaseQuery(self, base_query):
self['bq'] = base_query
bq = property(_GetBaseQuery, _SetBaseQuery,
doc="""The bq query parameter""")
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""GBaseService extends the GDataService to streamline Google Base operations.
GBaseService: Provides methods to query feeds and manipulate items. Extends
GDataService.
DictionaryToParamList: Function which converts a dictionary into a list of
URL arguments (represented as strings). This is a
utility function used in CRUD operations.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
import urllib
import gdata
import atom.service
import gdata.service
import gdata.base
import atom
# URL to which all batch requests are sent.
BASE_BATCH_URL = 'http://www.google.com/base/feeds/items/batch'
class Error(Exception):
pass
class RequestError(Error):
pass
class GBaseService(gdata.service.GDataService):
"""Client for the Google Base service."""
def __init__(self, email=None, password=None, source=None,
server='base.google.com', api_key=None,
additional_headers=None, handler=None):
gdata.service.GDataService.__init__(self, email=email, password=password,
service='gbase', source=source,
server=server,
additional_headers=additional_headers,
handler=handler)
self.api_key = api_key
def _SetAPIKey(self, api_key):
if not isinstance(self.additional_headers, dict):
self.additional_headers = {}
self.additional_headers['X-Google-Key'] = api_key
def __SetAPIKey(self, api_key):
self._SetAPIKey(api_key)
def _GetAPIKey(self):
if 'X-Google-Key' not in self.additional_headers:
return None
else:
return self.additional_headers['X-Google-Key']
def __GetAPIKey(self):
return self._GetAPIKey()
api_key = property(__GetAPIKey, __SetAPIKey,
doc="""Get or set the API key to be included in all requests.""")
def Query(self, uri, converter=None):
"""Performs a style query and returns a resulting feed or entry.
Args:
uri: string The full URI which be queried. Examples include
'/base/feeds/snippets?bq=digital+camera',
'http://www.google.com/base/feeds/snippets?bq=digital+camera'
'/base/feeds/items'
I recommend creating a URI using a query class.
converter: func (optional) A function which will be executed on the
server's response. Examples include GBaseItemFromString, etc.
Returns:
If converter was specified, returns the results of calling converter on
the server's response. If converter was not specified, and the result
was an Atom Entry, returns a GBaseItem, by default, the method returns
the result of calling gdata.service's Get method.
"""
result = self.Get(uri, converter=converter)
if converter:
return result
elif isinstance(result, atom.Entry):
return gdata.base.GBaseItemFromString(result.ToString())
return result
def QuerySnippetsFeed(self, uri):
return self.Get(uri, converter=gdata.base.GBaseSnippetFeedFromString)
def QueryItemsFeed(self, uri):
return self.Get(uri, converter=gdata.base.GBaseItemFeedFromString)
def QueryAttributesFeed(self, uri):
return self.Get(uri, converter=gdata.base.GBaseAttributesFeedFromString)
def QueryItemTypesFeed(self, uri):
return self.Get(uri, converter=gdata.base.GBaseItemTypesFeedFromString)
def QueryLocalesFeed(self, uri):
return self.Get(uri, converter=gdata.base.GBaseLocalesFeedFromString)
def GetItem(self, uri):
return self.Get(uri, converter=gdata.base.GBaseItemFromString)
def GetSnippet(self, uri):
return self.Get(uri, converter=gdata.base.GBaseSnippetFromString)
def GetAttribute(self, uri):
return self.Get(uri, converter=gdata.base.GBaseAttributeEntryFromString)
def GetItemType(self, uri):
return self.Get(uri, converter=gdata.base.GBaseItemTypeEntryFromString)
def GetLocale(self, uri):
return self.Get(uri, converter=gdata.base.GDataEntryFromString)
def InsertItem(self, new_item, url_params=None, escape_params=True,
converter=None):
"""Adds an item to Google Base.
Args:
new_item: atom.Entry or subclass A new item which is to be added to
Google Base.
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
converter: func (optional) Function which is executed on the server's
response before it is returned. Usually this is a function like
GBaseItemFromString which will parse the response and turn it into
an object.
Returns:
If converter is defined, the results of running converter on the server's
response. Otherwise, it will be a GBaseItem.
"""
response = self.Post(new_item, '/base/feeds/items', url_params=url_params,
escape_params=escape_params, converter=converter)
if not converter and isinstance(response, atom.Entry):
return gdata.base.GBaseItemFromString(response.ToString())
return response
def DeleteItem(self, item_id, url_params=None, escape_params=True):
"""Removes an item with the specified ID from Google Base.
Args:
item_id: string The ID of the item to be deleted. Example:
'http://www.google.com/base/feeds/items/13185446517496042648'
url_params: dict (optional) Additional URL parameters to be included
in the deletion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
True if the delete succeeded.
"""
return self.Delete('/%s' % (item_id.lstrip('http://www.google.com/')),
url_params=url_params, escape_params=escape_params)
def UpdateItem(self, item_id, updated_item, url_params=None,
escape_params=True,
converter=gdata.base.GBaseItemFromString):
"""Updates an existing item.
Args:
item_id: string The ID of the item to be updated. Example:
'http://www.google.com/base/feeds/items/13185446517496042648'
updated_item: atom.Entry, subclass, or string, containing
the Atom Entry which will replace the base item which is
stored at the item_id.
url_params: dict (optional) Additional URL parameters to be included
in the update request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
converter: func (optional) Function which is executed on the server's
response before it is returned. Usually this is a function like
GBaseItemFromString which will parse the response and turn it into
an object.
Returns:
If converter is defined, the results of running converter on the server's
response. Otherwise, it will be a GBaseItem.
"""
response = self.Put(updated_item,
item_id, url_params=url_params, escape_params=escape_params,
converter=converter)
if not converter and isinstance(response, atom.Entry):
return gdata.base.GBaseItemFromString(response.ToString())
return response
def ExecuteBatch(self, batch_feed,
converter=gdata.base.GBaseItemFeedFromString):
"""Sends a batch request feed to the server.
Args:
batch_feed: gdata.BatchFeed A feed containing BatchEntry elements which
contain the desired CRUD operation and any necessary entry data.
converter: Function (optional) Function to be executed on the server's
response. This function should take one string as a parameter. The
default value is GBaseItemFeedFromString which will turn the result
into a gdata.base.GBaseItem object.
Returns:
A gdata.BatchFeed containing the results.
"""
return self.Post(batch_feed, BASE_BATCH_URL, converter=converter)
class BaseQuery(gdata.service.Query):
def _GetBaseQuery(self):
return self['bq']
def _SetBaseQuery(self, base_query):
self['bq'] = base_query
bq = property(_GetBaseQuery, _SetBaseQuery,
doc="""The bq query parameter""")
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to Atom objects used with Google Base."""
__author__ = 'api.jscudder (Jeffrey Scudder)'
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import atom
import gdata
# XML namespaces which are often used in Google Base entities.
GBASE_NAMESPACE = 'http://base.google.com/ns/1.0'
GBASE_TEMPLATE = '{http://base.google.com/ns/1.0}%s'
GMETA_NAMESPACE = 'http://base.google.com/ns-metadata/1.0'
GMETA_TEMPLATE = '{http://base.google.com/ns-metadata/1.0}%s'
class ItemAttributeContainer(object):
"""Provides methods for finding Google Base Item attributes.
Google Base item attributes are child nodes in the gbase namespace. Google
Base allows you to define your own item attributes and this class provides
methods to interact with the custom attributes.
"""
def GetItemAttributes(self, name):
"""Returns a list of all item attributes which have the desired name.
Args:
name: str The tag of the desired base attributes. For example, calling
this method with 'rating' would return a list of ItemAttributes
represented by a 'g:rating' tag.
Returns:
A list of matching ItemAttribute objects.
"""
result = []
for attrib in self.item_attributes:
if attrib.name == name:
result.append(attrib)
return result
def FindItemAttribute(self, name):
"""Get the contents of the first Base item attribute which matches name.
This method is deprecated, please use GetItemAttributes instead.
Args:
name: str The tag of the desired base attribute. For example, calling
this method with name = 'rating' would search for a tag rating
in the GBase namespace in the item attributes.
Returns:
The text contents of the item attribute, or none if the attribute was
not found.
"""
for attrib in self.item_attributes:
if attrib.name == name:
return attrib.text
return None
def AddItemAttribute(self, name, value, value_type=None, access=None):
"""Adds a new item attribute tag containing the value.
Creates a new extension element in the GBase namespace to represent a
Google Base item attribute.
Args:
name: str The tag name for the new attribute. This must be a valid xml
tag name. The tag will be placed in the GBase namespace.
value: str Contents for the item attribute
value_type: str (optional) The type of data in the vlaue, Examples: text
float
access: str (optional) Used to hide attributes. The attribute is not
exposed in the snippets feed if access is set to 'private'.
"""
new_attribute = ItemAttribute(name, text=value,
text_type=value_type, access=access)
self.item_attributes.append(new_attribute)
def SetItemAttribute(self, name, value):
"""Changes an existing item attribute's value."""
for attrib in self.item_attributes:
if attrib.name == name:
attrib.text = value
return
def RemoveItemAttribute(self, name):
"""Deletes the first extension element which matches name.
Deletes the first extension element which matches name.
"""
for i in xrange(len(self.item_attributes)):
if self.item_attributes[i].name == name:
del self.item_attributes[i]
return
# We need to overwrite _ConvertElementTreeToMember to add special logic to
# convert custom attributes to members
def _ConvertElementTreeToMember(self, child_tree):
# Find the element's tag in this class's list of child members
if self.__class__._children.has_key(child_tree.tag):
member_name = self.__class__._children[child_tree.tag][0]
member_class = self.__class__._children[child_tree.tag][1]
# If the class member is supposed to contain a list, make sure the
# matching member is set to a list, then append the new member
# instance to the list.
if isinstance(member_class, list):
if getattr(self, member_name) is None:
setattr(self, member_name, [])
getattr(self, member_name).append(atom._CreateClassFromElementTree(
member_class[0], child_tree))
else:
setattr(self, member_name,
atom._CreateClassFromElementTree(member_class, child_tree))
elif child_tree.tag.find('{%s}' % GBASE_NAMESPACE) == 0:
# If this is in the gbase namespace, make it into an extension element.
name = child_tree.tag[child_tree.tag.index('}')+1:]
value = child_tree.text
if child_tree.attrib.has_key('type'):
value_type = child_tree.attrib['type']
else:
value_type = None
self.AddItemAttribute(name, value, value_type)
else:
atom.ExtensionContainer._ConvertElementTreeToMember(self, child_tree)
# We need to overwtite _AddMembersToElementTree to add special logic to
# convert custom members to XML nodes.
def _AddMembersToElementTree(self, tree):
# Convert the members of this class which are XML child nodes.
# This uses the class's _children dictionary to find the members which
# should become XML child nodes.
member_node_names = [values[0] for tag, values in
self.__class__._children.iteritems()]
for member_name in member_node_names:
member = getattr(self, member_name)
if member is None:
pass
elif isinstance(member, list):
for instance in member:
instance._BecomeChildElement(tree)
else:
member._BecomeChildElement(tree)
# Convert the members of this class which are XML attributes.
for xml_attribute, member_name in self.__class__._attributes.iteritems():
member = getattr(self, member_name)
if member is not None:
tree.attrib[xml_attribute] = member
# Convert all special custom item attributes to nodes
for attribute in self.item_attributes:
attribute._BecomeChildElement(tree)
# Lastly, call the ExtensionContainers's _AddMembersToElementTree to
# convert any extension attributes.
atom.ExtensionContainer._AddMembersToElementTree(self, tree)
class ItemAttribute(atom.Text):
"""An optional or user defined attribute for a GBase item.
Google Base allows items to have custom attribute child nodes. These nodes
have contents and a type attribute which tells Google Base whether the
contents are text, a float value with units, etc. The Atom text class has
the same structure, so this class inherits from Text.
"""
_namespace = GBASE_NAMESPACE
_children = atom.Text._children.copy()
_attributes = atom.Text._attributes.copy()
_attributes['access'] = 'access'
def __init__(self, name, text_type=None, access=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for a GBase item attribute
Args:
name: str The name of the attribute. Examples include
price, color, make, model, pages, salary, etc.
text_type: str (optional) The type associated with the text contents
access: str (optional) If the access attribute is set to 'private', the
attribute will not be included in the item's description in the
snippets feed
text: str (optional) The text data in the this element
extension_elements: list (optional) A list of ExtensionElement
instances
extension_attributes: dict (optional) A dictionary of attribute
value string pairs
"""
self.name = name
self.type = text_type
self.access = access
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def _BecomeChildElement(self, tree):
new_child = ElementTree.Element('')
tree.append(new_child)
new_child.tag = '{%s}%s' % (self.__class__._namespace,
self.name)
self._AddMembersToElementTree(new_child)
def _ToElementTree(self):
new_tree = ElementTree.Element('{%s}%s' % (self.__class__._namespace,
self.name))
self._AddMembersToElementTree(new_tree)
return new_tree
def ItemAttributeFromString(xml_string):
element_tree = ElementTree.fromstring(xml_string)
return _ItemAttributeFromElementTree(element_tree)
def _ItemAttributeFromElementTree(element_tree):
if element_tree.tag.find(GBASE_TEMPLATE % '') == 0:
to_return = ItemAttribute('')
to_return._HarvestElementTree(element_tree)
to_return.name = element_tree.tag[element_tree.tag.index('}')+1:]
if to_return.name and to_return.name != '':
return to_return
return None
class Label(atom.AtomBase):
"""The Google Base label element"""
_tag = 'label'
_namespace = GBASE_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def LabelFromString(xml_string):
return atom.CreateClassFromXMLString(Label, xml_string)
class Thumbnail(atom.AtomBase):
"""The Google Base thumbnail element"""
_tag = 'thumbnail'
_namespace = GMETA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['width'] = 'width'
_attributes['height'] = 'height'
def __init__(self, width=None, height=None, text=None, extension_elements=None,
extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.width = width
self.height = height
def ThumbnailFromString(xml_string):
return atom.CreateClassFromXMLString(Thumbnail, xml_string)
class ImageLink(atom.Text):
"""The Google Base image_link element"""
_tag = 'image_link'
_namespace = GBASE_NAMESPACE
_children = atom.Text._children.copy()
_attributes = atom.Text._attributes.copy()
_children['{%s}thumbnail' % GMETA_NAMESPACE] = ('thumbnail', [Thumbnail])
def __init__(self, thumbnail=None, text=None, extension_elements=None,
text_type=None, extension_attributes=None):
self.thumbnail = thumbnail or []
self.text = text
self.type = text_type
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ImageLinkFromString(xml_string):
return atom.CreateClassFromXMLString(ImageLink, xml_string)
class ItemType(atom.Text):
"""The Google Base item_type element"""
_tag = 'item_type'
_namespace = GBASE_NAMESPACE
_children = atom.Text._children.copy()
_attributes = atom.Text._attributes.copy()
def __init__(self, text=None, extension_elements=None,
text_type=None, extension_attributes=None):
self.text = text
self.type = text_type
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ItemTypeFromString(xml_string):
return atom.CreateClassFromXMLString(ItemType, xml_string)
class MetaItemType(ItemType):
"""The Google Base item_type element"""
_tag = 'item_type'
_namespace = GMETA_NAMESPACE
_children = ItemType._children.copy()
_attributes = ItemType._attributes.copy()
def MetaItemTypeFromString(xml_string):
return atom.CreateClassFromXMLString(MetaItemType, xml_string)
class Value(atom.AtomBase):
"""Metadata about common values for a given attribute
A value is a child of an attribute which comes from the attributes feed.
The value's text is a commonly used value paired with an attribute name
and the value's count tells how often this value appears for the given
attribute in the search results.
"""
_tag = 'value'
_namespace = GMETA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['count'] = 'count'
def __init__(self, count=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Attribute metadata element
Args:
count: str (optional) The number of times the value in text is given
for the parent attribute.
text: str (optional) The value which appears in the search results.
extension_elements: list (optional) A list of ExtensionElement
instances
extension_attributes: dict (optional) A dictionary of attribute value
string pairs
"""
self.count = count
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ValueFromString(xml_string):
return atom.CreateClassFromXMLString(Value, xml_string)
class Attribute(atom.Text):
"""Metadata about an attribute from the attributes feed
An entry from the attributes feed contains a list of attributes. Each
attribute describes the attribute's type and count of the items which
use the attribute.
"""
_tag = 'attribute'
_namespace = GMETA_NAMESPACE
_children = atom.Text._children.copy()
_attributes = atom.Text._attributes.copy()
_children['{%s}value' % GMETA_NAMESPACE] = ('value', [Value])
_attributes['count'] = 'count'
_attributes['name'] = 'name'
def __init__(self, name=None, attribute_type=None, count=None, value=None,
text=None, extension_elements=None, extension_attributes=None):
"""Constructor for Attribute metadata element
Args:
name: str (optional) The name of the attribute
attribute_type: str (optional) The type for the attribute. Examples:
test, float, etc.
count: str (optional) The number of times this attribute appears in
the query results.
value: list (optional) The values which are often used for this
attirbute.
text: str (optional) The text contents of the XML for this attribute.
extension_elements: list (optional) A list of ExtensionElement
instances
extension_attributes: dict (optional) A dictionary of attribute value
string pairs
"""
self.name = name
self.type = attribute_type
self.count = count
self.value = value or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def AttributeFromString(xml_string):
return atom.CreateClassFromXMLString(Attribute, xml_string)
class Attributes(atom.AtomBase):
"""A collection of Google Base metadata attributes"""
_tag = 'attributes'
_namespace = GMETA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}attribute' % GMETA_NAMESPACE] = ('attribute', [Attribute])
def __init__(self, attribute=None, extension_elements=None,
extension_attributes=None, text=None):
self.attribute = attribute or []
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
class GBaseItem(ItemAttributeContainer, gdata.BatchEntry):
"""An Google Base flavor of an Atom Entry.
Google Base items have required attributes, recommended attributes, and user
defined attributes. The required attributes are stored in this class as
members, and other attributes are stored as extension elements. You can
access the recommended and user defined attributes by using
AddItemAttribute, SetItemAttribute, FindItemAttribute, and
RemoveItemAttribute.
The Base Item
"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.BatchEntry._children.copy()
_attributes = gdata.BatchEntry._attributes.copy()
_children['{%s}label' % GBASE_NAMESPACE] = ('label', [Label])
_children['{%s}item_type' % GBASE_NAMESPACE] = ('item_type', ItemType)
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, updated=None, control=None,
label=None, item_type=None, item_attributes=None,
batch_operation=None, batch_id=None, batch_status=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.title = title
self.updated = updated
self.control = control
self.label = label or []
self.item_type = item_type
self.item_attributes = item_attributes or []
self.batch_operation = batch_operation
self.batch_id = batch_id
self.batch_status = batch_status
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GBaseItemFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseItem, xml_string)
class GBaseSnippet(GBaseItem):
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = GBaseItem._children.copy()
_attributes = GBaseItem._attributes.copy()
def GBaseSnippetFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseSnippet, xml_string)
class GBaseAttributeEntry(gdata.GDataEntry):
"""An Atom Entry from the attributes feed"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}attribute' % GMETA_NAMESPACE] = ('attribute', [Attribute])
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, updated=None, label=None,
attribute=None, control=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.control = control
self.title = title
self.updated = updated
self.label = label or []
self.attribute = attribute or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GBaseAttributeEntryFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseAttributeEntry, xml_string)
class GBaseItemTypeEntry(gdata.GDataEntry):
"""An Atom entry from the item types feed
These entries contain a list of attributes which are stored in one
XML node called attributes. This class simplifies the data structure
by treating attributes as a list of attribute instances.
Note that the item_type for an item type entry is in the Google Base meta
namespace as opposed to item_types encountered in other feeds.
"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}attributes' % GMETA_NAMESPACE] = ('attributes', Attributes)
_children['{%s}attribute' % GMETA_NAMESPACE] = ('attribute', [Attribute])
_children['{%s}item_type' % GMETA_NAMESPACE] = ('item_type', MetaItemType)
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, updated=None, label=None,
item_type=None, control=None, attribute=None, attributes=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.title = title
self.updated = updated
self.control = control
self.label = label or []
self.item_type = item_type
self.attributes = attributes
self.attribute = attribute or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GBaseItemTypeEntryFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseItemTypeEntry, xml_string)
class GBaseItemFeed(gdata.BatchFeed):
"""A feed containing Google Base Items"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.BatchFeed._children.copy()
_attributes = gdata.BatchFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GBaseItem])
def GBaseItemFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseItemFeed, xml_string)
class GBaseSnippetFeed(gdata.GDataFeed):
"""A feed containing Google Base Snippets"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GBaseSnippet])
def GBaseSnippetFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseSnippetFeed, xml_string)
class GBaseAttributesFeed(gdata.GDataFeed):
"""A feed containing Google Base Attributes
A query sent to the attributes feed will return a feed of
attributes which are present in the items that match the
query.
"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[GBaseAttributeEntry])
def GBaseAttributesFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseAttributesFeed, xml_string)
class GBaseLocalesFeed(gdata.GDataFeed):
"""The locales feed from Google Base.
This read-only feed defines the permitted locales for Google Base. The
locale value identifies the language, currency, and date formats used in a
feed.
"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
def GBaseLocalesFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseLocalesFeed, xml_string)
class GBaseItemTypesFeed(gdata.GDataFeed):
"""A feed from the Google Base item types feed"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GBaseItemTypeEntry])
def GBaseItemTypesFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseItemTypesFeed, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains classes representing Google Data elements.
Extends Atom classes to add Google Data specific elements.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
import os
import atom
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
# XML namespaces which are often used in GData entities.
GDATA_NAMESPACE = 'http://schemas.google.com/g/2005'
GDATA_TEMPLATE = '{http://schemas.google.com/g/2005}%s'
OPENSEARCH_NAMESPACE = 'http://a9.com/-/spec/opensearchrss/1.0/'
OPENSEARCH_TEMPLATE = '{http://a9.com/-/spec/opensearchrss/1.0/}%s'
BATCH_NAMESPACE = 'http://schemas.google.com/gdata/batch'
GACL_NAMESPACE = 'http://schemas.google.com/acl/2007'
GACL_TEMPLATE = '{http://schemas.google.com/acl/2007}%s'
# Labels used in batch request entries to specify the desired CRUD operation.
BATCH_INSERT = 'insert'
BATCH_UPDATE = 'update'
BATCH_DELETE = 'delete'
BATCH_QUERY = 'query'
class Error(Exception):
pass
class MissingRequiredParameters(Error):
pass
class MediaSource(object):
"""GData Entries can refer to media sources, so this class provides a
place to store references to these objects along with some metadata.
"""
def __init__(self, file_handle=None, content_type=None, content_length=None,
file_path=None, file_name=None):
"""Creates an object of type MediaSource.
Args:
file_handle: A file handle pointing to the file to be encapsulated in the
MediaSource
content_type: string The MIME type of the file. Required if a file_handle
is given.
content_length: int The size of the file. Required if a file_handle is
given.
file_path: string (optional) A full path name to the file. Used in
place of a file_handle.
file_name: string The name of the file without any path information.
Required if a file_handle is given.
"""
self.file_handle = file_handle
self.content_type = content_type
self.content_length = content_length
self.file_name = file_name
if (file_handle is None and content_type is not None and
file_path is not None):
self.setFile(file_path, content_type)
def setFile(self, file_name, content_type):
"""A helper function which can create a file handle from a given filename
and set the content type and length all at once.
Args:
file_name: string The path and file name to the file containing the media
content_type: string A MIME type representing the type of the media
"""
self.file_handle = open(file_name, 'rb')
self.content_type = content_type
self.content_length = os.path.getsize(file_name)
self.file_name = os.path.basename(file_name)
class LinkFinder(atom.LinkFinder):
"""An "interface" providing methods to find link elements
GData Entry elements often contain multiple links which differ in the rel
attribute or content type. Often, developers are interested in a specific
type of link so this class provides methods to find specific classes of
links.
This class is used as a mixin in GData entries.
"""
def GetSelfLink(self):
"""Find the first link with rel set to 'self'
Returns:
An atom.Link or none if none of the links had rel equal to 'self'
"""
for a_link in self.link:
if a_link.rel == 'self':
return a_link
return None
def GetEditLink(self):
for a_link in self.link:
if a_link.rel == 'edit':
return a_link
return None
def GetEditMediaLink(self):
"""The Picasa API mistakenly returns media-edit rather than edit-media, but
this may change soon.
"""
for a_link in self.link:
if a_link.rel == 'edit-media':
return a_link
if a_link.rel == 'media-edit':
return a_link
return None
def GetHtmlLink(self):
"""Find the first link with rel of alternate and type of text/html
Returns:
An atom.Link or None if no links matched
"""
for a_link in self.link:
if a_link.rel == 'alternate' and a_link.type == 'text/html':
return a_link
return None
def GetPostLink(self):
"""Get a link containing the POST target URL.
The POST target URL is used to insert new entries.
Returns:
A link object with a rel matching the POST type.
"""
for a_link in self.link:
if a_link.rel == 'http://schemas.google.com/g/2005#post':
return a_link
return None
def GetAclLink(self):
for a_link in self.link:
if a_link.rel == 'http://schemas.google.com/acl/2007#accessControlList':
return a_link
return None
def GetFeedLink(self):
for a_link in self.link:
if a_link.rel == 'http://schemas.google.com/g/2005#feed':
return a_link
return None
def GetNextLink(self):
for a_link in self.link:
if a_link.rel == 'next':
return a_link
return None
class TotalResults(atom.AtomBase):
"""opensearch:TotalResults for a GData feed"""
_tag = 'totalResults'
_namespace = OPENSEARCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def TotalResultsFromString(xml_string):
return atom.CreateClassFromXMLString(TotalResults, xml_string)
class StartIndex(atom.AtomBase):
"""The opensearch:startIndex element in GData feed"""
_tag = 'startIndex'
_namespace = OPENSEARCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def StartIndexFromString(xml_string):
return atom.CreateClassFromXMLString(StartIndex, xml_string)
class ItemsPerPage(atom.AtomBase):
"""The opensearch:itemsPerPage element in GData feed"""
_tag = 'itemsPerPage'
_namespace = OPENSEARCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ItemsPerPageFromString(xml_string):
return atom.CreateClassFromXMLString(ItemsPerPage, xml_string)
class ExtendedProperty(atom.AtomBase):
"""The Google Data extendedProperty element.
Used to store arbitrary key-value information specific to your
application. The value can either be a text string stored as an XML
attribute (.value), or an XML node (XmlBlob) as a child element.
This element is used in the Google Calendar data API and the Google
Contacts data API.
"""
_tag = 'extendedProperty'
_namespace = GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['name'] = 'name'
_attributes['value'] = 'value'
def __init__(self, name=None, value=None, extension_elements=None,
extension_attributes=None, text=None):
self.name = name
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GetXmlBlobExtensionElement(self):
"""Returns the XML blob as an atom.ExtensionElement.
Returns:
An atom.ExtensionElement representing the blob's XML, or None if no
blob was set.
"""
if len(self.extension_elements) < 1:
return None
else:
return self.extension_elements[0]
def GetXmlBlobString(self):
"""Returns the XML blob as a string.
Returns:
A string containing the blob's XML, or None if no blob was set.
"""
blob = self.GetXmlBlobExtensionElement()
if blob:
return blob.ToString()
return None
def SetXmlBlob(self, blob):
"""Sets the contents of the extendedProperty to XML as a child node.
Since the extendedProperty is only allowed one child element as an XML
blob, setting the XML blob will erase any preexisting extension elements
in this object.
Args:
blob: str, ElementTree Element or atom.ExtensionElement representing
the XML blob stored in the extendedProperty.
"""
# Erase any existing extension_elements, clears the child nodes from the
# extendedProperty.
self.extension_elements = []
if isinstance(blob, atom.ExtensionElement):
self.extension_elements.append(blob)
elif ElementTree.iselement(blob):
self.extension_elements.append(atom._ExtensionElementFromElementTree(
blob))
else:
self.extension_elements.append(atom.ExtensionElementFromString(blob))
def ExtendedPropertyFromString(xml_string):
return atom.CreateClassFromXMLString(ExtendedProperty, xml_string)
class GDataEntry(atom.Entry, LinkFinder):
"""Extends Atom Entry to provide data processing"""
_tag = atom.Entry._tag
_namespace = atom.Entry._namespace
_children = atom.Entry._children.copy()
_attributes = atom.Entry._attributes.copy()
def __GetId(self):
return self.__id
# This method was created to strip the unwanted whitespace from the id's
# text node.
def __SetId(self, id):
self.__id = id
if id is not None and id.text is not None:
self.__id.text = id.text.strip()
id = property(__GetId, __SetId)
def IsMedia(self):
"""Determines whether or not an entry is a GData Media entry.
"""
if (self.GetEditMediaLink()):
return True
else:
return False
def GetMediaURL(self):
"""Returns the URL to the media content, if the entry is a media entry.
Otherwise returns None.
"""
if not self.IsMedia():
return None
else:
return self.content.src
def GDataEntryFromString(xml_string):
"""Creates a new GDataEntry instance given a string of XML."""
return atom.CreateClassFromXMLString(GDataEntry, xml_string)
class GDataFeed(atom.Feed, LinkFinder):
"""A Feed from a GData service"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = atom.Feed._children.copy()
_attributes = atom.Feed._attributes.copy()
_children['{%s}totalResults' % OPENSEARCH_NAMESPACE] = ('total_results',
TotalResults)
_children['{%s}startIndex' % OPENSEARCH_NAMESPACE] = ('start_index',
StartIndex)
_children['{%s}itemsPerPage' % OPENSEARCH_NAMESPACE] = ('items_per_page',
ItemsPerPage)
# Add a conversion rule for atom:entry to make it into a GData
# Entry.
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GDataEntry])
def __GetId(self):
return self.__id
def __SetId(self, id):
self.__id = id
if id is not None and id.text is not None:
self.__id.text = id.text.strip()
id = property(__GetId, __SetId)
def __GetGenerator(self):
return self.__generator
def __SetGenerator(self, generator):
self.__generator = generator
if generator is not None:
self.__generator.text = generator.text.strip()
generator = property(__GetGenerator, __SetGenerator)
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None, entry=None,
total_results=None, start_index=None, items_per_page=None,
extension_elements=None, extension_attributes=None, text=None):
"""Constructor for Source
Args:
author: list (optional) A list of Author instances which belong to this
class.
category: list (optional) A list of Category instances
contributor: list (optional) A list on Contributor instances
generator: Generator (optional)
icon: Icon (optional)
id: Id (optional) The entry's Id element
link: list (optional) A list of Link instances
logo: Logo (optional)
rights: Rights (optional) The entry's Rights element
subtitle: Subtitle (optional) The entry's subtitle element
title: Title (optional) the entry's title element
updated: Updated (optional) the entry's updated element
entry: list (optional) A list of the Entry instances contained in the
feed.
text: String (optional) The text contents of the element. This is the
contents of the Entry's XML text node.
(Example: <foo>This is the text</foo>)
extension_elements: list (optional) A list of ExtensionElement instances
which are children of this element.
extension_attributes: dict (optional) A dictionary of strings which are
the values for additional XML attributes of this element.
"""
self.author = author or []
self.category = category or []
self.contributor = contributor or []
self.generator = generator
self.icon = icon
self.id = atom_id
self.link = link or []
self.logo = logo
self.rights = rights
self.subtitle = subtitle
self.title = title
self.updated = updated
self.entry = entry or []
self.total_results = total_results
self.start_index = start_index
self.items_per_page = items_per_page
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GDataFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GDataFeed, xml_string)
class BatchId(atom.AtomBase):
_tag = 'id'
_namespace = BATCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def BatchIdFromString(xml_string):
return atom.CreateClassFromXMLString(BatchId, xml_string)
class BatchOperation(atom.AtomBase):
_tag = 'operation'
_namespace = BATCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['type'] = 'type'
def __init__(self, op_type=None, extension_elements=None,
extension_attributes=None,
text=None):
self.type = op_type
atom.AtomBase.__init__(self,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def BatchOperationFromString(xml_string):
return atom.CreateClassFromXMLString(BatchOperation, xml_string)
class BatchStatus(atom.AtomBase):
"""The batch:status element present in a batch response entry.
A status element contains the code (HTTP response code) and
reason as elements. In a single request these fields would
be part of the HTTP response, but in a batch request each
Entry operation has a corresponding Entry in the response
feed which includes status information.
See http://code.google.com/apis/gdata/batch.html#Handling_Errors
"""
_tag = 'status'
_namespace = BATCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['code'] = 'code'
_attributes['reason'] = 'reason'
_attributes['content-type'] = 'content_type'
def __init__(self, code=None, reason=None, content_type=None,
extension_elements=None, extension_attributes=None, text=None):
self.code = code
self.reason = reason
self.content_type = content_type
atom.AtomBase.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def BatchStatusFromString(xml_string):
return atom.CreateClassFromXMLString(BatchStatus, xml_string)
class BatchEntry(GDataEntry):
"""An atom:entry for use in batch requests.
The BatchEntry contains additional members to specify the operation to be
performed on this entry and a batch ID so that the server can reference
individual operations in the response feed. For more information, see:
http://code.google.com/apis/gdata/batch.html
"""
_tag = GDataEntry._tag
_namespace = GDataEntry._namespace
_children = GDataEntry._children.copy()
_children['{%s}operation' % BATCH_NAMESPACE] = ('batch_operation', BatchOperation)
_children['{%s}id' % BATCH_NAMESPACE] = ('batch_id', BatchId)
_children['{%s}status' % BATCH_NAMESPACE] = ('batch_status', BatchStatus)
_attributes = GDataEntry._attributes.copy()
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, control=None, title=None, updated=None,
batch_operation=None, batch_id=None, batch_status=None,
extension_elements=None, extension_attributes=None, text=None):
self.batch_operation = batch_operation
self.batch_id = batch_id
self.batch_status = batch_status
GDataEntry.__init__(self, author=author, category=category,
content=content, contributor=contributor, atom_id=atom_id, link=link,
published=published, rights=rights, source=source, summary=summary,
control=control, title=title, updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes, text=text)
def BatchEntryFromString(xml_string):
return atom.CreateClassFromXMLString(BatchEntry, xml_string)
class BatchInterrupted(atom.AtomBase):
"""The batch:interrupted element sent if batch request was interrupted.
Only appears in a feed if some of the batch entries could not be processed.
See: http://code.google.com/apis/gdata/batch.html#Handling_Errors
"""
_tag = 'interrupted'
_namespace = BATCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['reason'] = 'reason'
_attributes['success'] = 'success'
_attributes['failures'] = 'failures'
_attributes['parsed'] = 'parsed'
def __init__(self, reason=None, success=None, failures=None, parsed=None,
extension_elements=None, extension_attributes=None, text=None):
self.reason = reason
self.success = success
self.failures = failures
self.parsed = parsed
atom.AtomBase.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def BatchInterruptedFromString(xml_string):
return atom.CreateClassFromXMLString(BatchInterrupted, xml_string)
class BatchFeed(GDataFeed):
"""A feed containing a list of batch request entries."""
_tag = GDataFeed._tag
_namespace = GDataFeed._namespace
_children = GDataFeed._children.copy()
_attributes = GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [BatchEntry])
_children['{%s}interrupted' % BATCH_NAMESPACE] = ('interrupted', BatchInterrupted)
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None, entry=None,
total_results=None, start_index=None, items_per_page=None,
interrupted=None,
extension_elements=None, extension_attributes=None, text=None):
self.interrupted = interrupted
GDataFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results, start_index=start_index,
items_per_page=items_per_page,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def AddBatchEntry(self, entry=None, id_url_string=None,
batch_id_string=None, operation_string=None):
"""Logic for populating members of a BatchEntry and adding to the feed.
If the entry is not a BatchEntry, it is converted to a BatchEntry so
that the batch specific members will be present.
The id_url_string can be used in place of an entry if the batch operation
applies to a URL. For example query and delete operations require just
the URL of an entry, no body is sent in the HTTP request. If an
id_url_string is sent instead of an entry, a BatchEntry is created and
added to the feed.
This method also assigns the desired batch id to the entry so that it
can be referenced in the server's response. If the batch_id_string is
None, this method will assign a batch_id to be the index at which this
entry will be in the feed's entry list.
Args:
entry: BatchEntry, atom.Entry, or another Entry flavor (optional) The
entry which will be sent to the server as part of the batch request.
The item must have a valid atom id so that the server knows which
entry this request references.
id_url_string: str (optional) The URL of the entry to be acted on. You
can find this URL in the text member of the atom id for an entry.
If an entry is not sent, this id will be used to construct a new
BatchEntry which will be added to the request feed.
batch_id_string: str (optional) The batch ID to be used to reference
this batch operation in the results feed. If this parameter is None,
the current length of the feed's entry array will be used as a
count. Note that batch_ids should either always be specified or
never, mixing could potentially result in duplicate batch ids.
operation_string: str (optional) The desired batch operation which will
set the batch_operation.type member of the entry. Options are
'insert', 'update', 'delete', and 'query'
Raises:
MissingRequiredParameters: Raised if neither an id_ url_string nor an
entry are provided in the request.
Returns:
The added entry.
"""
if entry is None and id_url_string is None:
raise MissingRequiredParameters('supply either an entry or URL string')
if entry is None and id_url_string is not None:
entry = BatchEntry(atom_id=atom.Id(text=id_url_string))
# TODO: handle cases in which the entry lacks batch_... members.
#if not isinstance(entry, BatchEntry):
# Convert the entry to a batch entry.
if batch_id_string is not None:
entry.batch_id = BatchId(text=batch_id_string)
elif entry.batch_id is None or entry.batch_id.text is None:
entry.batch_id = BatchId(text=str(len(self.entry)))
if operation_string is not None:
entry.batch_operation = BatchOperation(op_type=operation_string)
self.entry.append(entry)
return entry
def AddInsert(self, entry, batch_id_string=None):
"""Add an insert request to the operations in this batch request feed.
If the entry doesn't yet have an operation or a batch id, these will
be set to the insert operation and a batch_id specified as a parameter.
Args:
entry: BatchEntry The entry which will be sent in the batch feed as an
insert request.
batch_id_string: str (optional) The batch ID to be used to reference
this batch operation in the results feed. If this parameter is None,
the current length of the feed's entry array will be used as a
count. Note that batch_ids should either always be specified or
never, mixing could potentially result in duplicate batch ids.
"""
entry = self.AddBatchEntry(entry=entry, batch_id_string=batch_id_string,
operation_string=BATCH_INSERT)
def AddUpdate(self, entry, batch_id_string=None):
"""Add an update request to the list of batch operations in this feed.
Sets the operation type of the entry to insert if it is not already set
and assigns the desired batch id to the entry so that it can be
referenced in the server's response.
Args:
entry: BatchEntry The entry which will be sent to the server as an
update (HTTP PUT) request. The item must have a valid atom id
so that the server knows which entry to replace.
batch_id_string: str (optional) The batch ID to be used to reference
this batch operation in the results feed. If this parameter is None,
the current length of the feed's entry array will be used as a
count. See also comments for AddInsert.
"""
entry = self.AddBatchEntry(entry=entry, batch_id_string=batch_id_string,
operation_string=BATCH_UPDATE)
def AddDelete(self, url_string=None, entry=None, batch_id_string=None):
"""Adds a delete request to the batch request feed.
This method takes either the url_string which is the atom id of the item
to be deleted, or the entry itself. The atom id of the entry must be
present so that the server knows which entry should be deleted.
Args:
url_string: str (optional) The URL of the entry to be deleted. You can
find this URL in the text member of the atom id for an entry.
entry: BatchEntry (optional) The entry to be deleted.
batch_id_string: str (optional)
Raises:
MissingRequiredParameters: Raised if neither a url_string nor an entry
are provided in the request.
"""
entry = self.AddBatchEntry(entry=entry, id_url_string=url_string,
batch_id_string=batch_id_string,
operation_string=BATCH_DELETE)
def AddQuery(self, url_string=None, entry=None, batch_id_string=None):
"""Adds a query request to the batch request feed.
This method takes either the url_string which is the query URL
whose results will be added to the result feed. The query URL will
be encapsulated in a BatchEntry, and you may pass in the BatchEntry
with a query URL instead of sending a url_string.
Args:
url_string: str (optional)
entry: BatchEntry (optional)
batch_id_string: str (optional)
Raises:
MissingRequiredParameters
"""
entry = self.AddBatchEntry(entry=entry, id_url_string=url_string,
batch_id_string=batch_id_string,
operation_string=BATCH_QUERY)
def GetBatchLink(self):
for link in self.link:
if link.rel == 'http://schemas.google.com/g/2005#batch':
return link
return None
def BatchFeedFromString(xml_string):
return atom.CreateClassFromXMLString(BatchFeed, xml_string)
class EntryLink(atom.AtomBase):
"""The gd:entryLink element"""
_tag = 'entryLink'
_namespace = GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
# The entry used to be an atom.Entry, now it is a GDataEntry.
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', GDataEntry)
_attributes['rel'] = 'rel',
_attributes['readOnly'] = 'read_only'
_attributes['href'] = 'href'
def __init__(self, href=None, read_only=None, rel=None,
entry=None, extension_elements=None,
extension_attributes=None, text=None):
self.href = href
self.read_only = read_only
self.rel = rel
self.entry = entry
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def EntryLinkFromString(xml_string):
return atom.CreateClassFromXMLString(EntryLink, xml_string)
class FeedLink(atom.AtomBase):
"""The gd:feedLink element"""
_tag = 'feedLink'
_namespace = GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}feed' % atom.ATOM_NAMESPACE] = ('feed', GDataFeed)
_attributes['rel'] = 'rel'
_attributes['readOnly'] = 'read_only'
_attributes['countHint'] = 'count_hint'
_attributes['href'] = 'href'
def __init__(self, count_hint=None, href=None, read_only=None, rel=None,
feed=None, extension_elements=None, extension_attributes=None,
text=None):
self.count_hint = count_hint
self.href = href
self.read_only = read_only
self.rel = rel
self.feed = feed
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def FeedLinkFromString(xml_string):
return atom.CreateClassFromXMLString(EntryLink, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright Google 2007-2008, all rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import StringIO
import gdata
import gdata.service
import gdata.spreadsheet
import gdata.spreadsheet.service
import gdata.docs
import gdata.docs.service
"""Make the Google Documents API feel more like using a database.
This module contains a client and other classes which make working with the
Google Documents List Data API and the Google Spreadsheets Data API look a
bit more like working with a heirarchical database. Using the DatabaseClient,
you can create or find spreadsheets and use them like a database, with
worksheets representing tables and rows representing records.
Example Usage:
# Create a new database, a new table, and add records.
client = gdata.spreadsheet.text_db.DatabaseClient(username='jo@example.com',
password='12345')
database = client.CreateDatabase('My Text Database')
table = database.CreateTable('addresses', ['name','email',
'phonenumber', 'mailingaddress'])
record = table.AddRecord({'name':'Bob', 'email':'bob@example.com',
'phonenumber':'555-555-1234', 'mailingaddress':'900 Imaginary St.'})
# Edit a record
record.content['email'] = 'bob2@example.com'
record.Push()
# Delete a table
table.Delete
Warnings:
Care should be exercised when using this module on spreadsheets
which contain formulas. This module treats all rows as containing text and
updating a row will overwrite any formula with the output of the formula.
The intended use case is to allow easy storage of text data in a spreadsheet.
Error: Domain specific extension of Exception.
BadCredentials: Error raised is username or password was incorrect.
CaptchaRequired: Raised if a login attempt failed and a CAPTCHA challenge
was issued.
DatabaseClient: Communicates with Google Docs APIs servers.
Database: Represents a spreadsheet and interacts with tables.
Table: Represents a worksheet and interacts with records.
RecordResultSet: A list of records in a table.
Record: Represents a row in a worksheet allows manipulation of text data.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
class Error(Exception):
pass
class BadCredentials(Error):
pass
class CaptchaRequired(Error):
pass
class DatabaseClient(object):
"""Allows creation and finding of Google Spreadsheets databases.
The DatabaseClient simplifies the process of creating and finding Google
Spreadsheets and will talk to both the Google Spreadsheets API and the
Google Documents List API.
"""
def __init__(self, username=None, password=None):
"""Constructor for a Database Client.
If the username and password are present, the constructor will contact
the Google servers to authenticate.
Args:
username: str (optional) Example: jo@example.com
password: str (optional)
"""
self.__docs_client = gdata.docs.service.DocsService()
self.__spreadsheets_client = (
gdata.spreadsheet.service.SpreadsheetsService())
self.SetCredentials(username, password)
def SetCredentials(self, username, password):
"""Attempts to log in to Google APIs using the provided credentials.
If the username or password are None, the client will not request auth
tokens.
Args:
username: str (optional) Example: jo@example.com
password: str (optional)
"""
self.__docs_client.email = username
self.__docs_client.password = password
self.__spreadsheets_client.email = username
self.__spreadsheets_client.password = password
if username and password:
try:
self.__docs_client.ProgrammaticLogin()
self.__spreadsheets_client.ProgrammaticLogin()
except gdata.service.CaptchaRequired:
raise CaptchaRequired('Please visit https://www.google.com/accounts/'
'DisplayUnlockCaptcha to unlock your account.')
except gdata.service.BadAuthentication:
raise BadCredentials('Username or password incorrect.')
def CreateDatabase(self, name):
"""Creates a new Google Spreadsheet with the desired name.
Args:
name: str The title for the spreadsheet.
Returns:
A Database instance representing the new spreadsheet.
"""
# Create a Google Spreadsheet to form the foundation of this database.
# Spreadsheet is created by uploading a file to the Google Documents
# List API.
virtual_csv_file = StringIO.StringIO(',,,')
virtual_media_source = gdata.MediaSource(file_handle=virtual_csv_file, content_type='text/csv', content_length=3)
db_entry = self.__docs_client.UploadSpreadsheet(virtual_media_source, name)
return Database(spreadsheet_entry=db_entry, database_client=self)
def GetDatabases(self, spreadsheet_key=None, name=None):
"""Finds spreadsheets which have the unique key or title.
If querying on the spreadsheet_key there will be at most one result, but
searching by name could yield multiple results.
Args:
spreadsheet_key: str The unique key for the spreadsheet, this
usually in the the form 'pk23...We' or 'o23...423.12,,,3'.
name: str The title of the spreadsheets.
Returns:
A list of Database objects representing the desired spreadsheets.
"""
if spreadsheet_key:
db_entry = self.__docs_client.GetDocumentListEntry(
r'/feeds/documents/private/full/spreadsheet%3A' + spreadsheet_key)
return [Database(spreadsheet_entry=db_entry, database_client=self)]
else:
title_query = gdata.docs.service.DocumentQuery()
title_query['title'] = name
db_feed = self.__docs_client.QueryDocumentListFeed(title_query.ToUri())
matching_databases = []
for entry in db_feed.entry:
matching_databases.append(Database(spreadsheet_entry=entry,
database_client=self))
return matching_databases
def _GetDocsClient(self):
return self.__docs_client
def _GetSpreadsheetsClient(self):
return self.__spreadsheets_client
class Database(object):
"""Provides interface to find and create tables.
The database represents a Google Spreadsheet.
"""
def __init__(self, spreadsheet_entry=None, database_client=None):
"""Constructor for a database object.
Args:
spreadsheet_entry: gdata.docs.DocumentListEntry The
Atom entry which represents the Google Spreadsheet. The
spreadsheet's key is extracted from the entry and stored as a
member.
database_client: DatabaseClient A client which can talk to the
Google Spreadsheets servers to perform operations on worksheets
within this spreadsheet.
"""
self.entry = spreadsheet_entry
if self.entry:
id_parts = spreadsheet_entry.id.text.split('/')
self.spreadsheet_key = id_parts[-1].replace('spreadsheet%3A', '')
self.client = database_client
def CreateTable(self, name, fields=None):
"""Add a new worksheet to this spreadsheet and fill in column names.
Args:
name: str The title of the new worksheet.
fields: list of strings The column names which are placed in the
first row of this worksheet. These names are converted into XML
tags by the server. To avoid changes during the translation
process I recommend using all lowercase alphabetic names. For
example ['somelongname', 'theothername']
Returns:
Table representing the newly created worksheet.
"""
worksheet = self.client._GetSpreadsheetsClient().AddWorksheet(title=name,
row_count=1, col_count=len(fields), key=self.spreadsheet_key)
return Table(name=name, worksheet_entry=worksheet,
database_client=self.client,
spreadsheet_key=self.spreadsheet_key, fields=fields)
def GetTables(self, worksheet_id=None, name=None):
"""Searches for a worksheet with the specified ID or name.
The list of results should have one table at most, or no results
if the id or name were not found.
Args:
worksheet_id: str The ID of the worksheet, example: 'od6'
name: str The title of the worksheet.
Returns:
A list of length 0 or 1 containing the desired Table. A list is returned
to make this method feel like GetDatabases and GetRecords.
"""
if worksheet_id:
worksheet_entry = self.client._GetSpreadsheetsClient().GetWorksheetsFeed(
self.spreadsheet_key, wksht_id=worksheet_id)
return [Table(name=worksheet_entry.title.text,
worksheet_entry=worksheet_entry, database_client=self.client,
spreadsheet_key=self.spreadsheet_key)]
else:
matching_tables = []
title_query = gdata.spreadsheet.service.DocumentQuery()
title_query.title = name
worksheet_feed = self.client._GetSpreadsheetsClient().GetWorksheetsFeed(
self.spreadsheet_key, query=title_query)
for entry in worksheet_feed.entry:
matching_tables.append(Table(name=entry.title.text,
worksheet_entry=entry, database_client=self.client,
spreadsheet_key=self.spreadsheet_key))
return matching_tables
def Delete(self):
"""Deletes the entire database spreadsheet from Google Spreadsheets."""
entry = self.client._GetDocsClient().Get(
r'http://docs.google.com/feeds/documents/private/full/spreadsheet%3A' +
self.spreadsheet_key)
self.client._GetDocsClient().Delete(entry.GetEditLink().href)
class Table(object):
def __init__(self, name=None, worksheet_entry=None, database_client=None,
spreadsheet_key=None, fields=None):
self.name = name
self.entry = worksheet_entry
id_parts = worksheet_entry.id.text.split('/')
self.worksheet_id = id_parts[-1]
self.spreadsheet_key = spreadsheet_key
self.client = database_client
self.fields = fields or []
if fields:
self.SetFields(fields)
def LookupFields(self):
"""Queries to find the column names in the first row of the worksheet.
Useful when you have retrieved the table from the server and you don't
know the column names.
"""
if self.entry:
first_row_contents = []
query = gdata.spreadsheet.service.CellQuery()
query.max_row = '1'
query.min_row = '1'
feed = self.client._GetSpreadsheetsClient().GetCellsFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id, query=query)
for entry in feed.entry:
first_row_contents.append(entry.content.text)
# Get the next set of cells if needed.
next_link = feed.GetNextLink()
while next_link:
feed = self.client._GetSpreadsheetsClient().Get(next_link.href,
converter=gdata.spreadsheet.SpreadsheetsCellsFeedFromString)
for entry in feed.entry:
first_row_contents.append(entry.content.text)
next_link = feed.GetNextLink()
# Convert the contents of the cells to valid headers.
self.fields = ConvertStringsToColumnHeaders(first_row_contents)
def SetFields(self, fields):
"""Changes the contents of the cells in the first row of this worksheet.
Args:
fields: list of strings The names in the list comprise the
first row of the worksheet. These names are converted into XML
tags by the server. To avoid changes during the translation
process I recommend using all lowercase alphabetic names. For
example ['somelongname', 'theothername']
"""
# TODO: If the table already had fields, we might want to clear out the,
# current column headers.
self.fields = fields
i = 0
for column_name in fields:
i = i + 1
# TODO: speed this up by using a batch request to update cells.
self.client._GetSpreadsheetsClient().UpdateCell(1, i, column_name,
self.spreadsheet_key, self.worksheet_id)
def Delete(self):
"""Deletes this worksheet from the spreadsheet."""
worksheet = self.client._GetSpreadsheetsClient().GetWorksheetsFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id)
self.client._GetSpreadsheetsClient().DeleteWorksheet(
worksheet_entry=worksheet)
def AddRecord(self, data):
"""Adds a new row to this worksheet.
Args:
data: dict of strings Mapping of string values to column names.
Returns:
Record which represents this row of the spreadsheet.
"""
new_row = self.client._GetSpreadsheetsClient().InsertRow(data,
self.spreadsheet_key, wksht_id=self.worksheet_id)
return Record(content=data, row_entry=new_row,
spreadsheet_key=self.spreadsheet_key, worksheet_id=self.worksheet_id,
database_client=self.client)
def GetRecord(self, row_id=None, row_number=None):
"""Gets a single record from the worksheet based on row ID or number.
Args:
row_id: The ID for the individual row.
row_number: str or int The position of the desired row. Numbering
begins at 1, which refers to the second row in the worksheet since
the first row is used for column names.
Returns:
Record for the desired row.
"""
if row_id:
row_entry = self.client._GetSpreadsheetsClient().GetListFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id, row_id=row_id)
return Record(content=None, row_entry=row_entry,
spreadsheet_key=self.spreadsheet_key,
worksheet_id=self.worksheet_id, database_client=self.client)
else:
row_query = gdata.spreadsheet.service.ListQuery()
row_query.start_index = str(row_number)
row_query.max_results = '1'
row_feed = self.client._GetSpreadsheetsClient().GetListFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id, query=row_query)
if len(row_feed.entry) >= 1:
return Record(content=None, row_entry=row_feed.entry[0],
spreadsheet_key=self.spreadsheet_key,
worksheet_id=self.worksheet_id, database_client=self.client)
else:
return None
def GetRecords(self, start_row, end_row):
"""Gets all rows between the start and end row numbers inclusive.
Args:
start_row: str or int
end_row: str or int
Returns:
RecordResultSet for the desired rows.
"""
start_row = int(start_row)
end_row = int(end_row)
max_rows = end_row - start_row + 1
row_query = gdata.spreadsheet.service.ListQuery()
row_query.start_index = str(start_row)
row_query.max_results = str(max_rows)
rows_feed = self.client._GetSpreadsheetsClient().GetListFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id, query=row_query)
return RecordResultSet(rows_feed, self.client, self.spreadsheet_key,
self.worksheet_id)
def FindRecords(self, query_string):
"""Performs a query against the worksheet to find rows which match.
For details on query string syntax see the section on sq under
http://code.google.com/apis/spreadsheets/reference.html#list_Parameters
Args:
query_string: str Examples: 'name == john' to find all rows with john
in the name column, '(cost < 19.50 and name != toy) or cost > 500'
Returns:
RecordResultSet with the first group of matches.
"""
row_query = gdata.spreadsheet.service.ListQuery()
row_query.sq = query_string
matching_feed = self.client._GetSpreadsheetsClient().GetListFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id, query=row_query)
return RecordResultSet(matching_feed, self.client,
self.spreadsheet_key, self.worksheet_id)
class RecordResultSet(list):
"""A collection of rows which allows fetching of the next set of results.
The server may not send all rows in the requested range because there are
too many. Using this result set you can access the first set of results
as if it is a list, then get the next batch (if there are more results) by
calling GetNext().
"""
def __init__(self, feed, client, spreadsheet_key, worksheet_id):
self.client = client
self.spreadsheet_key = spreadsheet_key
self.worksheet_id = worksheet_id
self.feed = feed
list(self)
for entry in self.feed.entry:
self.append(Record(content=None, row_entry=entry,
spreadsheet_key=spreadsheet_key, worksheet_id=worksheet_id,
database_client=client))
def GetNext(self):
"""Fetches the next batch of rows in the result set.
Returns:
A new RecordResultSet.
"""
next_link = self.feed.GetNextLink()
if next_link and next_link.href:
new_feed = self.client._GetSpreadsheetsClient().Get(next_link.href,
converter=gdata.spreadsheet.SpreadsheetsListFeedFromString)
return RecordResultSet(new_feed, self.client, self.spreadsheet_key,
self.worksheet_id)
class Record(object):
"""Represents one row in a worksheet and provides a dictionary of values.
Attributes:
custom: dict Represents the contents of the row with cell values mapped
to column headers.
"""
def __init__(self, content=None, row_entry=None, spreadsheet_key=None,
worksheet_id=None, database_client=None):
"""Constructor for a record.
Args:
content: dict of strings Mapping of string values to column names.
row_entry: gdata.spreadsheet.SpreadsheetsList The Atom entry
representing this row in the worksheet.
spreadsheet_key: str The ID of the spreadsheet in which this row
belongs.
worksheet_id: str The ID of the worksheet in which this row belongs.
database_client: DatabaseClient The client which can be used to talk
the Google Spreadsheets server to edit this row.
"""
self.entry = row_entry
self.spreadsheet_key = spreadsheet_key
self.worksheet_id = worksheet_id
if row_entry:
self.row_id = row_entry.id.text.split('/')[-1]
else:
self.row_id = None
self.client = database_client
self.content = content or {}
if not content:
self.ExtractContentFromEntry(row_entry)
def ExtractContentFromEntry(self, entry):
"""Populates the content and row_id based on content of the entry.
This method is used in the Record's contructor.
Args:
entry: gdata.spreadsheet.SpreadsheetsList The Atom entry
representing this row in the worksheet.
"""
self.content = {}
if entry:
self.row_id = entry.id.text.split('/')[-1]
for label, custom in entry.custom.iteritems():
self.content[label] = custom.text
def Push(self):
"""Send the content of the record to spreadsheets to edit the row.
All items in the content dictionary will be sent. Items which have been
removed from the content may remain in the row. The content member
of the record will not be modified so additional fields in the row
might be absent from this local copy.
"""
self.entry = self.client._GetSpreadsheetsClient().UpdateRow(self.entry, self.content)
def Pull(self):
"""Query Google Spreadsheets to get the latest data from the server.
Fetches the entry for this row and repopulates the content dictionary
with the data found in the row.
"""
if self.row_id:
self.entry = self.client._GetSpreadsheetsClient().GetListFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id, row_id=self.row_id)
self.ExtractContentFromEntry(self.entry)
def Delete(self):
self.client._GetSpreadsheetsClient().DeleteRow(self.entry)
def ConvertStringsToColumnHeaders(proposed_headers):
"""Converts a list of strings to column names which spreadsheets accepts.
When setting values in a record, the keys which represent column names must
fit certain rules. They are all lower case, contain no spaces or special
characters. If two columns have the same name after being sanitized, the
columns further to the right have _2, _3 _4, etc. appended to them.
If there are column names which consist of all special characters, or if
the column header is blank, an obfuscated value will be used for a column
name. This method does not handle blank column names or column names with
only special characters.
"""
headers = []
for input_string in proposed_headers:
# TODO: probably a more efficient way to do this. Perhaps regex.
sanitized = input_string.lower().replace('_', '').replace(
':', '').replace(' ', '')
# When the same sanitized header appears multiple times in the first row
# of a spreadsheet, _n is appended to the name to make it unique.
header_count = headers.count(sanitized)
if header_count > 0:
headers.append('%s_%i' % (sanitized, header_count+1))
else:
headers.append(sanitized)
return headers
| Python |
#!/usr/bin/python
#
# Copyright (C) 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to Atom objects used with Google Spreadsheets.
"""
__author__ = 'api.laurabeth@gmail.com (Laura Beth Lincoln)'
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import atom
import gdata
import re
import string
# XML namespaces which are often used in Google Spreadsheets entities.
GSPREADSHEETS_NAMESPACE = 'http://schemas.google.com/spreadsheets/2006'
GSPREADSHEETS_TEMPLATE = '{http://schemas.google.com/spreadsheets/2006}%s'
GSPREADSHEETS_EXTENDED_NAMESPACE = ('http://schemas.google.com/spreadsheets'
'/2006/extended')
GSPREADSHEETS_EXTENDED_TEMPLATE = ('{http://schemas.google.com/spreadsheets'
'/2006/extended}%s')
class ColCount(atom.AtomBase):
"""The Google Spreadsheets colCount element """
_tag = 'colCount'
_namespace = GSPREADSHEETS_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ColCountFromString(xml_string):
return atom.CreateClassFromXMLString(ColCount, xml_string)
class RowCount(atom.AtomBase):
"""The Google Spreadsheets rowCount element """
_tag = 'rowCount'
_namespace = GSPREADSHEETS_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def RowCountFromString(xml_string):
return atom.CreateClassFromXMLString(RowCount, xml_string)
class Cell(atom.AtomBase):
"""The Google Spreadsheets cell element """
_tag = 'cell'
_namespace = GSPREADSHEETS_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['row'] = 'row'
_attributes['col'] = 'col'
_attributes['inputValue'] = 'inputValue'
_attributes['numericValue'] = 'numericValue'
def __init__(self, text=None, row=None, col=None, inputValue=None,
numericValue=None, extension_elements=None, extension_attributes=None):
self.text = text
self.row = row
self.col = col
self.inputValue = inputValue
self.numericValue = numericValue
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def CellFromString(xml_string):
return atom.CreateClassFromXMLString(Cell, xml_string)
class Custom(atom.AtomBase):
"""The Google Spreadsheets custom element"""
_namespace = GSPREADSHEETS_EXTENDED_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, column=None, text=None, extension_elements=None,
extension_attributes=None):
self.column = column # The name of the column
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def _BecomeChildElement(self, tree):
new_child = ElementTree.Element('')
tree.append(new_child)
new_child.tag = '{%s}%s' % (self.__class__._namespace,
self.column)
self._AddMembersToElementTree(new_child)
def _ToElementTree(self):
new_tree = ElementTree.Element('{%s}%s' % (self.__class__._namespace,
self.column))
self._AddMembersToElementTree(new_tree)
return new_tree
def _HarvestElementTree(self, tree):
namespace_uri, local_tag = string.split(tree.tag[1:], "}", 1)
self.column = local_tag
# Fill in the instance members from the contents of the XML tree.
for child in tree:
self._ConvertElementTreeToMember(child)
for attribute, value in tree.attrib.iteritems():
self._ConvertElementAttributeToMember(attribute, value)
self.text = tree.text
def CustomFromString(xml_string):
element_tree = ElementTree.fromstring(xml_string)
return _CustomFromElementTree(element_tree)
def _CustomFromElementTree(element_tree):
namespace_uri, local_tag = string.split(element_tree.tag[1:], "}", 1)
if namespace_uri == GSPREADSHEETS_EXTENDED_NAMESPACE:
new_custom = Custom()
new_custom._HarvestElementTree(element_tree)
new_custom.column = local_tag
return new_custom
return None
class SpreadsheetsSpreadsheet(gdata.GDataEntry):
"""A Google Spreadsheets flavor of a Spreadsheet Atom Entry """
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, control=None, updated=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.control = control
self.title = title
self.updated = updated
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SpreadsheetsSpreadsheetFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsSpreadsheet,
xml_string)
class SpreadsheetsWorksheet(gdata.GDataEntry):
"""A Google Spreadsheets flavor of a Worksheet Atom Entry """
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}rowCount' % GSPREADSHEETS_NAMESPACE] = ('row_count',
RowCount)
_children['{%s}colCount' % GSPREADSHEETS_NAMESPACE] = ('col_count',
ColCount)
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, control=None, updated=None,
row_count=None, col_count=None, text=None, extension_elements=None,
extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.control = control
self.title = title
self.updated = updated
self.row_count = row_count
self.col_count = col_count
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SpreadsheetsWorksheetFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsWorksheet,
xml_string)
class SpreadsheetsCell(gdata.BatchEntry):
"""A Google Spreadsheets flavor of a Cell Atom Entry """
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.BatchEntry._children.copy()
_attributes = gdata.BatchEntry._attributes.copy()
_children['{%s}cell' % GSPREADSHEETS_NAMESPACE] = ('cell', Cell)
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, control=None, updated=None,
cell=None, batch_operation=None, batch_id=None, batch_status=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.control = control
self.title = title
self.batch_operation = batch_operation
self.batch_id = batch_id
self.batch_status = batch_status
self.updated = updated
self.cell = cell
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SpreadsheetsCellFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsCell,
xml_string)
class SpreadsheetsList(gdata.GDataEntry):
"""A Google Spreadsheets flavor of a List Atom Entry """
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, control=None, updated=None,
custom=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.control = control
self.title = title
self.updated = updated
self.custom = custom or {}
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
# We need to overwrite _ConvertElementTreeToMember to add special logic to
# convert custom attributes to members
def _ConvertElementTreeToMember(self, child_tree):
# Find the element's tag in this class's list of child members
if self.__class__._children.has_key(child_tree.tag):
member_name = self.__class__._children[child_tree.tag][0]
member_class = self.__class__._children[child_tree.tag][1]
# If the class member is supposed to contain a list, make sure the
# matching member is set to a list, then append the new member
# instance to the list.
if isinstance(member_class, list):
if getattr(self, member_name) is None:
setattr(self, member_name, [])
getattr(self, member_name).append(atom._CreateClassFromElementTree(
member_class[0], child_tree))
else:
setattr(self, member_name,
atom._CreateClassFromElementTree(member_class, child_tree))
elif child_tree.tag.find('{%s}' % GSPREADSHEETS_EXTENDED_NAMESPACE) == 0:
# If this is in the custom namespace, make add it to the custom dict.
name = child_tree.tag[child_tree.tag.index('}')+1:]
custom = _CustomFromElementTree(child_tree)
if custom:
self.custom[name] = custom
else:
ExtensionContainer._ConvertElementTreeToMember(self, child_tree)
# We need to overwtite _AddMembersToElementTree to add special logic to
# convert custom members to XML nodes.
def _AddMembersToElementTree(self, tree):
# Convert the members of this class which are XML child nodes.
# This uses the class's _children dictionary to find the members which
# should become XML child nodes.
member_node_names = [values[0] for tag, values in
self.__class__._children.iteritems()]
for member_name in member_node_names:
member = getattr(self, member_name)
if member is None:
pass
elif isinstance(member, list):
for instance in member:
instance._BecomeChildElement(tree)
else:
member._BecomeChildElement(tree)
# Convert the members of this class which are XML attributes.
for xml_attribute, member_name in self.__class__._attributes.iteritems():
member = getattr(self, member_name)
if member is not None:
tree.attrib[xml_attribute] = member
# Convert all special custom item attributes to nodes
for name, custom in self.custom.iteritems():
custom._BecomeChildElement(tree)
# Lastly, call the ExtensionContainers's _AddMembersToElementTree to
# convert any extension attributes.
atom.ExtensionContainer._AddMembersToElementTree(self, tree)
def SpreadsheetsListFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsList,
xml_string)
element_tree = ElementTree.fromstring(xml_string)
return _SpreadsheetsListFromElementTree(element_tree)
class SpreadsheetsSpreadsheetsFeed(gdata.GDataFeed):
"""A feed containing Google Spreadsheets Spreadsheets"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[SpreadsheetsSpreadsheet])
def SpreadsheetsSpreadsheetsFeedFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsSpreadsheetsFeed,
xml_string)
class SpreadsheetsWorksheetsFeed(gdata.GDataFeed):
"""A feed containing Google Spreadsheets Spreadsheets"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[SpreadsheetsWorksheet])
def SpreadsheetsWorksheetsFeedFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsWorksheetsFeed,
xml_string)
class SpreadsheetsCellsFeed(gdata.BatchFeed):
"""A feed containing Google Spreadsheets Cells"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.BatchFeed._children.copy()
_attributes = gdata.BatchFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[SpreadsheetsCell])
_children['{%s}rowCount' % GSPREADSHEETS_NAMESPACE] = ('row_count',
RowCount)
_children['{%s}colCount' % GSPREADSHEETS_NAMESPACE] = ('col_count',
ColCount)
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None,
entry=None, total_results=None, start_index=None,
items_per_page=None, extension_elements=None,
extension_attributes=None, text=None, row_count=None,
col_count=None, interrupted=None):
gdata.BatchFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text, interrupted=interrupted)
self.row_count = row_count
self.col_count = col_count
def GetBatchLink(self):
for link in self.link:
if link.rel == 'http://schemas.google.com/g/2005#batch':
return link
return None
def SpreadsheetsCellsFeedFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsCellsFeed,
xml_string)
class SpreadsheetsListFeed(gdata.GDataFeed):
"""A feed containing Google Spreadsheets Spreadsheets"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[SpreadsheetsList])
def SpreadsheetsListFeedFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsListFeed,
xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""SpreadsheetsService extends the GDataService to streamline Google
Spreadsheets operations.
GBaseService: Provides methods to query feeds and manipulate items. Extends
GDataService.
DictionaryToParamList: Function which converts a dictionary into a list of
URL arguments (represented as strings). This is a
utility function used in CRUD operations.
"""
__author__ = 'api.laurabeth@gmail.com (Laura Beth Lincoln)'
import gdata
import atom.service
import gdata.service
import gdata.spreadsheet
import atom
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class RequestError(Error):
pass
class SpreadsheetsService(gdata.service.GDataService):
"""Client for the Google Spreadsheets service."""
def __init__(self, email=None, password=None, source=None,
server='spreadsheets.google.com',
additional_headers=None):
gdata.service.GDataService.__init__(self, email=email, password=password,
service='wise', source=source,
server=server,
additional_headers=additional_headers)
def GetSpreadsheetsFeed(self, key=None, query=None, visibility='private',
projection='full'):
"""Gets a spreadsheets feed or a specific entry if a key is defined
Args:
key: string (optional) The spreadsheet key defined in /ccc?key=
query: DocumentQuery (optional) Query parameters
Returns:
If there is no key, then a SpreadsheetsSpreadsheetsFeed.
If there is a key, then a SpreadsheetsSpreadsheet.
"""
uri = ('http://%s/feeds/spreadsheets/%s/%s'
% (self.server, visibility, projection))
if key is not None:
uri = '%s/%s' % (uri, key)
if query != None:
query.feed = uri
uri = query.ToUri()
if key:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsSpreadsheetFromString)
else:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsSpreadsheetsFeedFromString)
def GetWorksheetsFeed(self, key, wksht_id=None, query=None,
visibility='private', projection='full'):
"""Gets a worksheets feed or a specific entry if a wksht is defined
Args:
key: string The spreadsheet key defined in /ccc?key=
wksht_id: string (optional) The id for a specific worksheet entry
query: DocumentQuery (optional) Query parameters
Returns:
If there is no wksht_id, then a SpreadsheetsWorksheetsFeed.
If there is a wksht_id, then a SpreadsheetsWorksheet.
"""
uri = ('http://%s/feeds/worksheets/%s/%s/%s'
% (self.server, key, visibility, projection))
if wksht_id != None:
uri = '%s/%s' % (uri, wksht_id)
if query != None:
query.feed = uri
uri = query.ToUri()
if wksht_id:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsWorksheetFromString)
else:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsWorksheetsFeedFromString)
def AddWorksheet(self, title, row_count, col_count, key):
"""Creates a new worksheet in the desired spreadsheet.
The new worksheet is appended to the end of the list of worksheets. The
new worksheet will only have the available number of columns and cells
specified.
Args:
title: str The title which will be displayed in the list of worksheets.
row_count: int or str The number of rows in the new worksheet.
col_count: int or str The number of columns in the new worksheet.
key: str The spreadsheet key to the spreadsheet to which the new
worksheet should be added.
Returns:
A SpreadsheetsWorksheet if the new worksheet was created succesfully.
"""
new_worksheet = gdata.spreadsheet.SpreadsheetsWorksheet(
title=atom.Title(text=title),
row_count=gdata.spreadsheet.RowCount(text=str(row_count)),
col_count=gdata.spreadsheet.ColCount(text=str(col_count)))
return self.Post(new_worksheet,
'http://%s/feeds/worksheets/%s/private/full' % (self.server, key),
converter=gdata.spreadsheet.SpreadsheetsWorksheetFromString)
def UpdateWorksheet(self, worksheet_entry, url=None):
"""Changes the size and/or title of the desired worksheet.
Args:
worksheet_entry: SpreadsheetWorksheet The new contents of the
worksheet.
url: str (optional) The URL to which the edited worksheet entry should
be sent. If the url is None, the edit URL from the worksheet will
be used.
Returns:
A SpreadsheetsWorksheet with the new information about the worksheet.
"""
target_url = url or worksheet_entry.GetEditLink().href
return self.Put(worksheet_entry, target_url,
converter=gdata.spreadsheet.SpreadsheetsWorksheetFromString)
def DeleteWorksheet(self, worksheet_entry=None, url=None):
"""Removes the desired worksheet from the spreadsheet
Args:
worksheet_entry: SpreadsheetWorksheet (optional) The worksheet to
be deleted. If this is none, then the DELETE reqest is sent to
the url specified in the url parameter.
url: str (optaional) The URL to which the DELETE request should be
sent. If left as None, the worksheet's edit URL is used.
Returns:
True if the worksheet was deleted successfully.
"""
if url:
target_url = url
else:
target_url = worksheet_entry.GetEditLink().href
return self.Delete(target_url)
def GetCellsFeed(self, key, wksht_id='default', cell=None, query=None,
visibility='private', projection='full'):
"""Gets a cells feed or a specific entry if a cell is defined
Args:
key: string The spreadsheet key defined in /ccc?key=
wksht_id: string The id for a specific worksheet entry
cell: string (optional) The R1C1 address of the cell
query: DocumentQuery (optional) Query parameters
Returns:
If there is no cell, then a SpreadsheetsCellsFeed.
If there is a cell, then a SpreadsheetsCell.
"""
uri = ('http://%s/feeds/cells/%s/%s/%s/%s'
% (self.server, key, wksht_id, visibility, projection))
if cell != None:
uri = '%s/%s' % (uri, cell)
if query != None:
query.feed = uri
uri = query.ToUri()
if cell:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsCellFromString)
else:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsCellsFeedFromString)
def GetListFeed(self, key, wksht_id='default', row_id=None, query=None,
visibility='private', projection='full'):
"""Gets a list feed or a specific entry if a row_id is defined
Args:
key: string The spreadsheet key defined in /ccc?key=
wksht_id: string The id for a specific worksheet entry
row_id: string (optional) The row_id of a row in the list
query: DocumentQuery (optional) Query parameters
Returns:
If there is no row_id, then a SpreadsheetsListFeed.
If there is a row_id, then a SpreadsheetsList.
"""
uri = ('http://%s/feeds/list/%s/%s/%s/%s'
% (self.server, key, wksht_id, visibility, projection))
if row_id is not None:
uri = '%s/%s' % (uri, row_id)
if query is not None:
query.feed = uri
uri = query.ToUri()
if row_id:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsListFromString)
else:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsListFeedFromString)
def UpdateCell(self, row, col, inputValue, key, wksht_id='default'):
"""Updates an existing cell.
Args:
row: int The row the cell to be editted is in
col: int The column the cell to be editted is in
inputValue: str the new value of the cell
key: str The key of the spreadsheet in which this cell resides.
wksht_id: str The ID of the worksheet which holds this cell.
Returns:
The updated cell entry
"""
row = str(row)
col = str(col)
# make the new cell
new_cell = gdata.spreadsheet.Cell(row=row, col=col, inputValue=inputValue)
# get the edit uri and PUT
cell = 'R%sC%s' % (row, col)
entry = self.GetCellsFeed(key, wksht_id, cell)
for a_link in entry.link:
if a_link.rel == 'edit':
entry.cell = new_cell
return self.Put(entry, a_link.href,
converter=gdata.spreadsheet.SpreadsheetsCellFromString)
def _GenerateCellsBatchUrl(self, spreadsheet_key, worksheet_id):
return ('http://spreadsheets.google.com/feeds/cells/%s/%s/'
'private/full/batch' % (spreadsheet_key, worksheet_id))
def ExecuteBatch(self, batch_feed, url=None, spreadsheet_key=None,
worksheet_id=None,
converter=gdata.spreadsheet.SpreadsheetsCellsFeedFromString):
"""Sends a batch request feed to the server.
The batch request needs to be sent to the batch URL for a particular
worksheet. You can specify the worksheet by providing the spreadsheet_key
and worksheet_id, or by sending the URL from the cells feed's batch link.
Args:
batch_feed: gdata.spreadsheet.SpreadsheetsCellFeed A feed containing
BatchEntry elements which contain the desired CRUD operation and
any necessary data to modify a cell.
url: str (optional) The batch URL for the cells feed to which these
changes should be applied. This can be found by calling
cells_feed.GetBatchLink().href.
spreadsheet_key: str (optional) Used to generate the batch request URL
if the url argument is None. If using the spreadsheet key to
generate the URL, the worksheet id is also required.
worksheet_id: str (optional) Used if the url is not provided, it is
oart of the batch feed target URL. This is used with the spreadsheet
key.
converter: Function (optional) Function to be executed on the server's
response. This function should take one string as a parameter. The
default value is SpreadsheetsCellsFeedFromString which will turn the result
into a gdata.base.GBaseItem object.
Returns:
A gdata.BatchFeed containing the results.
"""
if url is None:
url = self._GenerateCellsBatchUrl(spreadsheet_key, worksheet_id)
return self.Post(batch_feed, url, converter=converter)
def InsertRow(self, row_data, key, wksht_id='default'):
"""Inserts a new row with the provided data
Args:
uri: string The post uri of the list feed
row_data: dict A dictionary of column header to row data
Returns:
The inserted row
"""
new_entry = gdata.spreadsheet.SpreadsheetsList()
for k, v in row_data.iteritems():
new_custom = gdata.spreadsheet.Custom()
new_custom.column = k
new_custom.text = v
new_entry.custom[new_custom.column] = new_custom
# Generate the post URL for the worksheet which will receive the new entry.
post_url = 'http://spreadsheets.google.com/feeds/list/%s/%s/private/full'%(
key, wksht_id)
return self.Post(new_entry, post_url,
converter=gdata.spreadsheet.SpreadsheetsListFromString)
def UpdateRow(self, entry, new_row_data):
"""Updates a row with the provided data
Args:
entry: gdata.spreadsheet.SpreadsheetsList The entry to be updated
new_row_data: dict A dictionary of column header to row data
Returns:
The updated row
"""
entry.custom = {}
for k, v in new_row_data.iteritems():
new_custom = gdata.spreadsheet.Custom()
new_custom.column = k
new_custom.text = v
entry.custom[k] = new_custom
for a_link in entry.link:
if a_link.rel == 'edit':
return self.Put(entry, a_link.href,
converter=gdata.spreadsheet.SpreadsheetsListFromString)
def DeleteRow(self, entry):
"""Deletes a row, the provided entry
Args:
entry: gdata.spreadsheet.SpreadsheetsList The row to be deleted
Returns:
The delete response
"""
for a_link in entry.link:
if a_link.rel == 'edit':
return self.Delete(a_link.href)
class DocumentQuery(gdata.service.Query):
def _GetTitleQuery(self):
return self['title']
def _SetTitleQuery(self, document_query):
self['title'] = document_query
title = property(_GetTitleQuery, _SetTitleQuery,
doc="""The title query parameter""")
def _GetTitleExactQuery(self):
return self['title-exact']
def _SetTitleExactQuery(self, document_query):
self['title-exact'] = document_query
title_exact = property(_GetTitleExactQuery, _SetTitleExactQuery,
doc="""The title-exact query parameter""")
class CellQuery(gdata.service.Query):
def _GetMinRowQuery(self):
return self['min-row']
def _SetMinRowQuery(self, cell_query):
self['min-row'] = cell_query
min_row = property(_GetMinRowQuery, _SetMinRowQuery,
doc="""The min-row query parameter""")
def _GetMaxRowQuery(self):
return self['max-row']
def _SetMaxRowQuery(self, cell_query):
self['max-row'] = cell_query
max_row = property(_GetMaxRowQuery, _SetMaxRowQuery,
doc="""The max-row query parameter""")
def _GetMinColQuery(self):
return self['min-col']
def _SetMinColQuery(self, cell_query):
self['min-col'] = cell_query
min_col = property(_GetMinColQuery, _SetMinColQuery,
doc="""The min-col query parameter""")
def _GetMaxColQuery(self):
return self['max-col']
def _SetMaxColQuery(self, cell_query):
self['max-col'] = cell_query
max_col = property(_GetMaxColQuery, _SetMaxColQuery,
doc="""The max-col query parameter""")
def _GetRangeQuery(self):
return self['range']
def _SetRangeQuery(self, cell_query):
self['range'] = cell_query
range = property(_GetRangeQuery, _SetRangeQuery,
doc="""The range query parameter""")
def _GetReturnEmptyQuery(self):
return self['return-empty']
def _SetReturnEmptyQuery(self, cell_query):
self['return-empty'] = cell_query
return_empty = property(_GetReturnEmptyQuery, _SetReturnEmptyQuery,
doc="""The return-empty query parameter""")
class ListQuery(gdata.service.Query):
def _GetSpreadsheetQuery(self):
return self['sq']
def _SetSpreadsheetQuery(self, list_query):
self['sq'] = list_query
sq = property(_GetSpreadsheetQuery, _SetSpreadsheetQuery,
doc="""The sq query parameter""")
def _GetOrderByQuery(self):
return self['orderby']
def _SetOrderByQuery(self, list_query):
self['orderby'] = list_query
orderby = property(_GetOrderByQuery, _SetOrderByQuery,
doc="""The orderby query parameter""")
def _GetReverseQuery(self):
return self['reverse']
def _SetReverseQuery(self, list_query):
self['reverse'] = list_query
reverse = property(_GetReverseQuery, _SetReverseQuery,
doc="""The reverse query parameter""")
| Python |
#!/usr/bin/python
#
# Copyright (C) 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""SpreadsheetsService extends the GDataService to streamline Google
Spreadsheets operations.
GBaseService: Provides methods to query feeds and manipulate items. Extends
GDataService.
DictionaryToParamList: Function which converts a dictionary into a list of
URL arguments (represented as strings). This is a
utility function used in CRUD operations.
"""
__author__ = 'api.laurabeth@gmail.com (Laura Beth Lincoln)'
import gdata
import atom.service
import gdata.service
import gdata.spreadsheet
import atom
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class RequestError(Error):
pass
class SpreadsheetsService(gdata.service.GDataService):
"""Client for the Google Spreadsheets service."""
def __init__(self, email=None, password=None, source=None,
server='spreadsheets.google.com',
additional_headers=None):
gdata.service.GDataService.__init__(self, email=email, password=password,
service='wise', source=source,
server=server,
additional_headers=additional_headers)
def GetSpreadsheetsFeed(self, key=None, query=None, visibility='private',
projection='full'):
"""Gets a spreadsheets feed or a specific entry if a key is defined
Args:
key: string (optional) The spreadsheet key defined in /ccc?key=
query: DocumentQuery (optional) Query parameters
Returns:
If there is no key, then a SpreadsheetsSpreadsheetsFeed.
If there is a key, then a SpreadsheetsSpreadsheet.
"""
uri = ('http://%s/feeds/spreadsheets/%s/%s'
% (self.server, visibility, projection))
if key is not None:
uri = '%s/%s' % (uri, key)
if query != None:
query.feed = uri
uri = query.ToUri()
if key:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsSpreadsheetFromString)
else:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsSpreadsheetsFeedFromString)
def GetWorksheetsFeed(self, key, wksht_id=None, query=None,
visibility='private', projection='full'):
"""Gets a worksheets feed or a specific entry if a wksht is defined
Args:
key: string The spreadsheet key defined in /ccc?key=
wksht_id: string (optional) The id for a specific worksheet entry
query: DocumentQuery (optional) Query parameters
Returns:
If there is no wksht_id, then a SpreadsheetsWorksheetsFeed.
If there is a wksht_id, then a SpreadsheetsWorksheet.
"""
uri = ('http://%s/feeds/worksheets/%s/%s/%s'
% (self.server, key, visibility, projection))
if wksht_id != None:
uri = '%s/%s' % (uri, wksht_id)
if query != None:
query.feed = uri
uri = query.ToUri()
if wksht_id:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsWorksheetFromString)
else:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsWorksheetsFeedFromString)
def AddWorksheet(self, title, row_count, col_count, key):
"""Creates a new worksheet in the desired spreadsheet.
The new worksheet is appended to the end of the list of worksheets. The
new worksheet will only have the available number of columns and cells
specified.
Args:
title: str The title which will be displayed in the list of worksheets.
row_count: int or str The number of rows in the new worksheet.
col_count: int or str The number of columns in the new worksheet.
key: str The spreadsheet key to the spreadsheet to which the new
worksheet should be added.
Returns:
A SpreadsheetsWorksheet if the new worksheet was created succesfully.
"""
new_worksheet = gdata.spreadsheet.SpreadsheetsWorksheet(
title=atom.Title(text=title),
row_count=gdata.spreadsheet.RowCount(text=str(row_count)),
col_count=gdata.spreadsheet.ColCount(text=str(col_count)))
return self.Post(new_worksheet,
'http://%s/feeds/worksheets/%s/private/full' % (self.server, key),
converter=gdata.spreadsheet.SpreadsheetsWorksheetFromString)
def UpdateWorksheet(self, worksheet_entry, url=None):
"""Changes the size and/or title of the desired worksheet.
Args:
worksheet_entry: SpreadsheetWorksheet The new contents of the
worksheet.
url: str (optional) The URL to which the edited worksheet entry should
be sent. If the url is None, the edit URL from the worksheet will
be used.
Returns:
A SpreadsheetsWorksheet with the new information about the worksheet.
"""
target_url = url or worksheet_entry.GetEditLink().href
return self.Put(worksheet_entry, target_url,
converter=gdata.spreadsheet.SpreadsheetsWorksheetFromString)
def DeleteWorksheet(self, worksheet_entry=None, url=None):
"""Removes the desired worksheet from the spreadsheet
Args:
worksheet_entry: SpreadsheetWorksheet (optional) The worksheet to
be deleted. If this is none, then the DELETE reqest is sent to
the url specified in the url parameter.
url: str (optaional) The URL to which the DELETE request should be
sent. If left as None, the worksheet's edit URL is used.
Returns:
True if the worksheet was deleted successfully.
"""
if url:
target_url = url
else:
target_url = worksheet_entry.GetEditLink().href
return self.Delete(target_url)
def GetCellsFeed(self, key, wksht_id='default', cell=None, query=None,
visibility='private', projection='full'):
"""Gets a cells feed or a specific entry if a cell is defined
Args:
key: string The spreadsheet key defined in /ccc?key=
wksht_id: string The id for a specific worksheet entry
cell: string (optional) The R1C1 address of the cell
query: DocumentQuery (optional) Query parameters
Returns:
If there is no cell, then a SpreadsheetsCellsFeed.
If there is a cell, then a SpreadsheetsCell.
"""
uri = ('http://%s/feeds/cells/%s/%s/%s/%s'
% (self.server, key, wksht_id, visibility, projection))
if cell != None:
uri = '%s/%s' % (uri, cell)
if query != None:
query.feed = uri
uri = query.ToUri()
if cell:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsCellFromString)
else:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsCellsFeedFromString)
def GetListFeed(self, key, wksht_id='default', row_id=None, query=None,
visibility='private', projection='full'):
"""Gets a list feed or a specific entry if a row_id is defined
Args:
key: string The spreadsheet key defined in /ccc?key=
wksht_id: string The id for a specific worksheet entry
row_id: string (optional) The row_id of a row in the list
query: DocumentQuery (optional) Query parameters
Returns:
If there is no row_id, then a SpreadsheetsListFeed.
If there is a row_id, then a SpreadsheetsList.
"""
uri = ('http://%s/feeds/list/%s/%s/%s/%s'
% (self.server, key, wksht_id, visibility, projection))
if row_id is not None:
uri = '%s/%s' % (uri, row_id)
if query is not None:
query.feed = uri
uri = query.ToUri()
if row_id:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsListFromString)
else:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsListFeedFromString)
def UpdateCell(self, row, col, inputValue, key, wksht_id='default'):
"""Updates an existing cell.
Args:
row: int The row the cell to be editted is in
col: int The column the cell to be editted is in
inputValue: str the new value of the cell
key: str The key of the spreadsheet in which this cell resides.
wksht_id: str The ID of the worksheet which holds this cell.
Returns:
The updated cell entry
"""
row = str(row)
col = str(col)
# make the new cell
new_cell = gdata.spreadsheet.Cell(row=row, col=col, inputValue=inputValue)
# get the edit uri and PUT
cell = 'R%sC%s' % (row, col)
entry = self.GetCellsFeed(key, wksht_id, cell)
for a_link in entry.link:
if a_link.rel == 'edit':
entry.cell = new_cell
return self.Put(entry, a_link.href,
converter=gdata.spreadsheet.SpreadsheetsCellFromString)
def _GenerateCellsBatchUrl(self, spreadsheet_key, worksheet_id):
return ('http://spreadsheets.google.com/feeds/cells/%s/%s/'
'private/full/batch' % (spreadsheet_key, worksheet_id))
def ExecuteBatch(self, batch_feed, url=None, spreadsheet_key=None,
worksheet_id=None,
converter=gdata.spreadsheet.SpreadsheetsCellsFeedFromString):
"""Sends a batch request feed to the server.
The batch request needs to be sent to the batch URL for a particular
worksheet. You can specify the worksheet by providing the spreadsheet_key
and worksheet_id, or by sending the URL from the cells feed's batch link.
Args:
batch_feed: gdata.spreadsheet.SpreadsheetsCellFeed A feed containing
BatchEntry elements which contain the desired CRUD operation and
any necessary data to modify a cell.
url: str (optional) The batch URL for the cells feed to which these
changes should be applied. This can be found by calling
cells_feed.GetBatchLink().href.
spreadsheet_key: str (optional) Used to generate the batch request URL
if the url argument is None. If using the spreadsheet key to
generate the URL, the worksheet id is also required.
worksheet_id: str (optional) Used if the url is not provided, it is
oart of the batch feed target URL. This is used with the spreadsheet
key.
converter: Function (optional) Function to be executed on the server's
response. This function should take one string as a parameter. The
default value is SpreadsheetsCellsFeedFromString which will turn the result
into a gdata.base.GBaseItem object.
Returns:
A gdata.BatchFeed containing the results.
"""
if url is None:
url = self._GenerateCellsBatchUrl(spreadsheet_key, worksheet_id)
return self.Post(batch_feed, url, converter=converter)
def InsertRow(self, row_data, key, wksht_id='default'):
"""Inserts a new row with the provided data
Args:
uri: string The post uri of the list feed
row_data: dict A dictionary of column header to row data
Returns:
The inserted row
"""
new_entry = gdata.spreadsheet.SpreadsheetsList()
for k, v in row_data.iteritems():
new_custom = gdata.spreadsheet.Custom()
new_custom.column = k
new_custom.text = v
new_entry.custom[new_custom.column] = new_custom
# Generate the post URL for the worksheet which will receive the new entry.
post_url = 'http://spreadsheets.google.com/feeds/list/%s/%s/private/full'%(
key, wksht_id)
return self.Post(new_entry, post_url,
converter=gdata.spreadsheet.SpreadsheetsListFromString)
def UpdateRow(self, entry, new_row_data):
"""Updates a row with the provided data
Args:
entry: gdata.spreadsheet.SpreadsheetsList The entry to be updated
new_row_data: dict A dictionary of column header to row data
Returns:
The updated row
"""
entry.custom = {}
for k, v in new_row_data.iteritems():
new_custom = gdata.spreadsheet.Custom()
new_custom.column = k
new_custom.text = v
entry.custom[k] = new_custom
for a_link in entry.link:
if a_link.rel == 'edit':
return self.Put(entry, a_link.href,
converter=gdata.spreadsheet.SpreadsheetsListFromString)
def DeleteRow(self, entry):
"""Deletes a row, the provided entry
Args:
entry: gdata.spreadsheet.SpreadsheetsList The row to be deleted
Returns:
The delete response
"""
for a_link in entry.link:
if a_link.rel == 'edit':
return self.Delete(a_link.href)
class DocumentQuery(gdata.service.Query):
def _GetTitleQuery(self):
return self['title']
def _SetTitleQuery(self, document_query):
self['title'] = document_query
title = property(_GetTitleQuery, _SetTitleQuery,
doc="""The title query parameter""")
def _GetTitleExactQuery(self):
return self['title-exact']
def _SetTitleExactQuery(self, document_query):
self['title-exact'] = document_query
title_exact = property(_GetTitleExactQuery, _SetTitleExactQuery,
doc="""The title-exact query parameter""")
class CellQuery(gdata.service.Query):
def _GetMinRowQuery(self):
return self['min-row']
def _SetMinRowQuery(self, cell_query):
self['min-row'] = cell_query
min_row = property(_GetMinRowQuery, _SetMinRowQuery,
doc="""The min-row query parameter""")
def _GetMaxRowQuery(self):
return self['max-row']
def _SetMaxRowQuery(self, cell_query):
self['max-row'] = cell_query
max_row = property(_GetMaxRowQuery, _SetMaxRowQuery,
doc="""The max-row query parameter""")
def _GetMinColQuery(self):
return self['min-col']
def _SetMinColQuery(self, cell_query):
self['min-col'] = cell_query
min_col = property(_GetMinColQuery, _SetMinColQuery,
doc="""The min-col query parameter""")
def _GetMaxColQuery(self):
return self['max-col']
def _SetMaxColQuery(self, cell_query):
self['max-col'] = cell_query
max_col = property(_GetMaxColQuery, _SetMaxColQuery,
doc="""The max-col query parameter""")
def _GetRangeQuery(self):
return self['range']
def _SetRangeQuery(self, cell_query):
self['range'] = cell_query
range = property(_GetRangeQuery, _SetRangeQuery,
doc="""The range query parameter""")
def _GetReturnEmptyQuery(self):
return self['return-empty']
def _SetReturnEmptyQuery(self, cell_query):
self['return-empty'] = cell_query
return_empty = property(_GetReturnEmptyQuery, _SetReturnEmptyQuery,
doc="""The return-empty query parameter""")
class ListQuery(gdata.service.Query):
def _GetSpreadsheetQuery(self):
return self['sq']
def _SetSpreadsheetQuery(self, list_query):
self['sq'] = list_query
sq = property(_GetSpreadsheetQuery, _SetSpreadsheetQuery,
doc="""The sq query parameter""")
def _GetOrderByQuery(self):
return self['orderby']
def _SetOrderByQuery(self, list_query):
self['orderby'] = list_query
orderby = property(_GetOrderByQuery, _SetOrderByQuery,
doc="""The orderby query parameter""")
def _GetReverseQuery(self):
return self['reverse']
def _SetReverseQuery(self, list_query):
self['reverse'] = list_query
reverse = property(_GetReverseQuery, _SetReverseQuery,
doc="""The reverse query parameter""")
| Python |
#!/usr/bin/python
#
# Copyright Google 2007-2008, all rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import StringIO
import gdata
import gdata.service
import gdata.spreadsheet
import gdata.spreadsheet.service
import gdata.docs
import gdata.docs.service
"""Make the Google Documents API feel more like using a database.
This module contains a client and other classes which make working with the
Google Documents List Data API and the Google Spreadsheets Data API look a
bit more like working with a heirarchical database. Using the DatabaseClient,
you can create or find spreadsheets and use them like a database, with
worksheets representing tables and rows representing records.
Example Usage:
# Create a new database, a new table, and add records.
client = gdata.spreadsheet.text_db.DatabaseClient(username='jo@example.com',
password='12345')
database = client.CreateDatabase('My Text Database')
table = database.CreateTable('addresses', ['name','email',
'phonenumber', 'mailingaddress'])
record = table.AddRecord({'name':'Bob', 'email':'bob@example.com',
'phonenumber':'555-555-1234', 'mailingaddress':'900 Imaginary St.'})
# Edit a record
record.content['email'] = 'bob2@example.com'
record.Push()
# Delete a table
table.Delete
Warnings:
Care should be exercised when using this module on spreadsheets
which contain formulas. This module treats all rows as containing text and
updating a row will overwrite any formula with the output of the formula.
The intended use case is to allow easy storage of text data in a spreadsheet.
Error: Domain specific extension of Exception.
BadCredentials: Error raised is username or password was incorrect.
CaptchaRequired: Raised if a login attempt failed and a CAPTCHA challenge
was issued.
DatabaseClient: Communicates with Google Docs APIs servers.
Database: Represents a spreadsheet and interacts with tables.
Table: Represents a worksheet and interacts with records.
RecordResultSet: A list of records in a table.
Record: Represents a row in a worksheet allows manipulation of text data.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
class Error(Exception):
pass
class BadCredentials(Error):
pass
class CaptchaRequired(Error):
pass
class DatabaseClient(object):
"""Allows creation and finding of Google Spreadsheets databases.
The DatabaseClient simplifies the process of creating and finding Google
Spreadsheets and will talk to both the Google Spreadsheets API and the
Google Documents List API.
"""
def __init__(self, username=None, password=None):
"""Constructor for a Database Client.
If the username and password are present, the constructor will contact
the Google servers to authenticate.
Args:
username: str (optional) Example: jo@example.com
password: str (optional)
"""
self.__docs_client = gdata.docs.service.DocsService()
self.__spreadsheets_client = (
gdata.spreadsheet.service.SpreadsheetsService())
self.SetCredentials(username, password)
def SetCredentials(self, username, password):
"""Attempts to log in to Google APIs using the provided credentials.
If the username or password are None, the client will not request auth
tokens.
Args:
username: str (optional) Example: jo@example.com
password: str (optional)
"""
self.__docs_client.email = username
self.__docs_client.password = password
self.__spreadsheets_client.email = username
self.__spreadsheets_client.password = password
if username and password:
try:
self.__docs_client.ProgrammaticLogin()
self.__spreadsheets_client.ProgrammaticLogin()
except gdata.service.CaptchaRequired:
raise CaptchaRequired('Please visit https://www.google.com/accounts/'
'DisplayUnlockCaptcha to unlock your account.')
except gdata.service.BadAuthentication:
raise BadCredentials('Username or password incorrect.')
def CreateDatabase(self, name):
"""Creates a new Google Spreadsheet with the desired name.
Args:
name: str The title for the spreadsheet.
Returns:
A Database instance representing the new spreadsheet.
"""
# Create a Google Spreadsheet to form the foundation of this database.
# Spreadsheet is created by uploading a file to the Google Documents
# List API.
virtual_csv_file = StringIO.StringIO(',,,')
virtual_media_source = gdata.MediaSource(file_handle=virtual_csv_file, content_type='text/csv', content_length=3)
db_entry = self.__docs_client.UploadSpreadsheet(virtual_media_source, name)
return Database(spreadsheet_entry=db_entry, database_client=self)
def GetDatabases(self, spreadsheet_key=None, name=None):
"""Finds spreadsheets which have the unique key or title.
If querying on the spreadsheet_key there will be at most one result, but
searching by name could yield multiple results.
Args:
spreadsheet_key: str The unique key for the spreadsheet, this
usually in the the form 'pk23...We' or 'o23...423.12,,,3'.
name: str The title of the spreadsheets.
Returns:
A list of Database objects representing the desired spreadsheets.
"""
if spreadsheet_key:
db_entry = self.__docs_client.GetDocumentListEntry(
r'/feeds/documents/private/full/spreadsheet%3A' + spreadsheet_key)
return [Database(spreadsheet_entry=db_entry, database_client=self)]
else:
title_query = gdata.docs.service.DocumentQuery()
title_query['title'] = name
db_feed = self.__docs_client.QueryDocumentListFeed(title_query.ToUri())
matching_databases = []
for entry in db_feed.entry:
matching_databases.append(Database(spreadsheet_entry=entry,
database_client=self))
return matching_databases
def _GetDocsClient(self):
return self.__docs_client
def _GetSpreadsheetsClient(self):
return self.__spreadsheets_client
class Database(object):
"""Provides interface to find and create tables.
The database represents a Google Spreadsheet.
"""
def __init__(self, spreadsheet_entry=None, database_client=None):
"""Constructor for a database object.
Args:
spreadsheet_entry: gdata.docs.DocumentListEntry The
Atom entry which represents the Google Spreadsheet. The
spreadsheet's key is extracted from the entry and stored as a
member.
database_client: DatabaseClient A client which can talk to the
Google Spreadsheets servers to perform operations on worksheets
within this spreadsheet.
"""
self.entry = spreadsheet_entry
if self.entry:
id_parts = spreadsheet_entry.id.text.split('/')
self.spreadsheet_key = id_parts[-1].replace('spreadsheet%3A', '')
self.client = database_client
def CreateTable(self, name, fields=None):
"""Add a new worksheet to this spreadsheet and fill in column names.
Args:
name: str The title of the new worksheet.
fields: list of strings The column names which are placed in the
first row of this worksheet. These names are converted into XML
tags by the server. To avoid changes during the translation
process I recommend using all lowercase alphabetic names. For
example ['somelongname', 'theothername']
Returns:
Table representing the newly created worksheet.
"""
worksheet = self.client._GetSpreadsheetsClient().AddWorksheet(title=name,
row_count=1, col_count=len(fields), key=self.spreadsheet_key)
return Table(name=name, worksheet_entry=worksheet,
database_client=self.client,
spreadsheet_key=self.spreadsheet_key, fields=fields)
def GetTables(self, worksheet_id=None, name=None):
"""Searches for a worksheet with the specified ID or name.
The list of results should have one table at most, or no results
if the id or name were not found.
Args:
worksheet_id: str The ID of the worksheet, example: 'od6'
name: str The title of the worksheet.
Returns:
A list of length 0 or 1 containing the desired Table. A list is returned
to make this method feel like GetDatabases and GetRecords.
"""
if worksheet_id:
worksheet_entry = self.client._GetSpreadsheetsClient().GetWorksheetsFeed(
self.spreadsheet_key, wksht_id=worksheet_id)
return [Table(name=worksheet_entry.title.text,
worksheet_entry=worksheet_entry, database_client=self.client,
spreadsheet_key=self.spreadsheet_key)]
else:
matching_tables = []
title_query = gdata.spreadsheet.service.DocumentQuery()
title_query.title = name
worksheet_feed = self.client._GetSpreadsheetsClient().GetWorksheetsFeed(
self.spreadsheet_key, query=title_query)
for entry in worksheet_feed.entry:
matching_tables.append(Table(name=entry.title.text,
worksheet_entry=entry, database_client=self.client,
spreadsheet_key=self.spreadsheet_key))
return matching_tables
def Delete(self):
"""Deletes the entire database spreadsheet from Google Spreadsheets."""
entry = self.client._GetDocsClient().Get(
r'http://docs.google.com/feeds/documents/private/full/spreadsheet%3A' +
self.spreadsheet_key)
self.client._GetDocsClient().Delete(entry.GetEditLink().href)
class Table(object):
def __init__(self, name=None, worksheet_entry=None, database_client=None,
spreadsheet_key=None, fields=None):
self.name = name
self.entry = worksheet_entry
id_parts = worksheet_entry.id.text.split('/')
self.worksheet_id = id_parts[-1]
self.spreadsheet_key = spreadsheet_key
self.client = database_client
self.fields = fields or []
if fields:
self.SetFields(fields)
def LookupFields(self):
"""Queries to find the column names in the first row of the worksheet.
Useful when you have retrieved the table from the server and you don't
know the column names.
"""
if self.entry:
first_row_contents = []
query = gdata.spreadsheet.service.CellQuery()
query.max_row = '1'
query.min_row = '1'
feed = self.client._GetSpreadsheetsClient().GetCellsFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id, query=query)
for entry in feed.entry:
first_row_contents.append(entry.content.text)
# Get the next set of cells if needed.
next_link = feed.GetNextLink()
while next_link:
feed = self.client._GetSpreadsheetsClient().Get(next_link.href,
converter=gdata.spreadsheet.SpreadsheetsCellsFeedFromString)
for entry in feed.entry:
first_row_contents.append(entry.content.text)
next_link = feed.GetNextLink()
# Convert the contents of the cells to valid headers.
self.fields = ConvertStringsToColumnHeaders(first_row_contents)
def SetFields(self, fields):
"""Changes the contents of the cells in the first row of this worksheet.
Args:
fields: list of strings The names in the list comprise the
first row of the worksheet. These names are converted into XML
tags by the server. To avoid changes during the translation
process I recommend using all lowercase alphabetic names. For
example ['somelongname', 'theothername']
"""
# TODO: If the table already had fields, we might want to clear out the,
# current column headers.
self.fields = fields
i = 0
for column_name in fields:
i = i + 1
# TODO: speed this up by using a batch request to update cells.
self.client._GetSpreadsheetsClient().UpdateCell(1, i, column_name,
self.spreadsheet_key, self.worksheet_id)
def Delete(self):
"""Deletes this worksheet from the spreadsheet."""
worksheet = self.client._GetSpreadsheetsClient().GetWorksheetsFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id)
self.client._GetSpreadsheetsClient().DeleteWorksheet(
worksheet_entry=worksheet)
def AddRecord(self, data):
"""Adds a new row to this worksheet.
Args:
data: dict of strings Mapping of string values to column names.
Returns:
Record which represents this row of the spreadsheet.
"""
new_row = self.client._GetSpreadsheetsClient().InsertRow(data,
self.spreadsheet_key, wksht_id=self.worksheet_id)
return Record(content=data, row_entry=new_row,
spreadsheet_key=self.spreadsheet_key, worksheet_id=self.worksheet_id,
database_client=self.client)
def GetRecord(self, row_id=None, row_number=None):
"""Gets a single record from the worksheet based on row ID or number.
Args:
row_id: The ID for the individual row.
row_number: str or int The position of the desired row. Numbering
begins at 1, which refers to the second row in the worksheet since
the first row is used for column names.
Returns:
Record for the desired row.
"""
if row_id:
row_entry = self.client._GetSpreadsheetsClient().GetListFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id, row_id=row_id)
return Record(content=None, row_entry=row_entry,
spreadsheet_key=self.spreadsheet_key,
worksheet_id=self.worksheet_id, database_client=self.client)
else:
row_query = gdata.spreadsheet.service.ListQuery()
row_query.start_index = str(row_number)
row_query.max_results = '1'
row_feed = self.client._GetSpreadsheetsClient().GetListFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id, query=row_query)
if len(row_feed.entry) >= 1:
return Record(content=None, row_entry=row_feed.entry[0],
spreadsheet_key=self.spreadsheet_key,
worksheet_id=self.worksheet_id, database_client=self.client)
else:
return None
def GetRecords(self, start_row, end_row):
"""Gets all rows between the start and end row numbers inclusive.
Args:
start_row: str or int
end_row: str or int
Returns:
RecordResultSet for the desired rows.
"""
start_row = int(start_row)
end_row = int(end_row)
max_rows = end_row - start_row + 1
row_query = gdata.spreadsheet.service.ListQuery()
row_query.start_index = str(start_row)
row_query.max_results = str(max_rows)
rows_feed = self.client._GetSpreadsheetsClient().GetListFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id, query=row_query)
return RecordResultSet(rows_feed, self.client, self.spreadsheet_key,
self.worksheet_id)
def FindRecords(self, query_string):
"""Performs a query against the worksheet to find rows which match.
For details on query string syntax see the section on sq under
http://code.google.com/apis/spreadsheets/reference.html#list_Parameters
Args:
query_string: str Examples: 'name == john' to find all rows with john
in the name column, '(cost < 19.50 and name != toy) or cost > 500'
Returns:
RecordResultSet with the first group of matches.
"""
row_query = gdata.spreadsheet.service.ListQuery()
row_query.sq = query_string
matching_feed = self.client._GetSpreadsheetsClient().GetListFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id, query=row_query)
return RecordResultSet(matching_feed, self.client,
self.spreadsheet_key, self.worksheet_id)
class RecordResultSet(list):
"""A collection of rows which allows fetching of the next set of results.
The server may not send all rows in the requested range because there are
too many. Using this result set you can access the first set of results
as if it is a list, then get the next batch (if there are more results) by
calling GetNext().
"""
def __init__(self, feed, client, spreadsheet_key, worksheet_id):
self.client = client
self.spreadsheet_key = spreadsheet_key
self.worksheet_id = worksheet_id
self.feed = feed
list(self)
for entry in self.feed.entry:
self.append(Record(content=None, row_entry=entry,
spreadsheet_key=spreadsheet_key, worksheet_id=worksheet_id,
database_client=client))
def GetNext(self):
"""Fetches the next batch of rows in the result set.
Returns:
A new RecordResultSet.
"""
next_link = self.feed.GetNextLink()
if next_link and next_link.href:
new_feed = self.client._GetSpreadsheetsClient().Get(next_link.href,
converter=gdata.spreadsheet.SpreadsheetsListFeedFromString)
return RecordResultSet(new_feed, self.client, self.spreadsheet_key,
self.worksheet_id)
class Record(object):
"""Represents one row in a worksheet and provides a dictionary of values.
Attributes:
custom: dict Represents the contents of the row with cell values mapped
to column headers.
"""
def __init__(self, content=None, row_entry=None, spreadsheet_key=None,
worksheet_id=None, database_client=None):
"""Constructor for a record.
Args:
content: dict of strings Mapping of string values to column names.
row_entry: gdata.spreadsheet.SpreadsheetsList The Atom entry
representing this row in the worksheet.
spreadsheet_key: str The ID of the spreadsheet in which this row
belongs.
worksheet_id: str The ID of the worksheet in which this row belongs.
database_client: DatabaseClient The client which can be used to talk
the Google Spreadsheets server to edit this row.
"""
self.entry = row_entry
self.spreadsheet_key = spreadsheet_key
self.worksheet_id = worksheet_id
if row_entry:
self.row_id = row_entry.id.text.split('/')[-1]
else:
self.row_id = None
self.client = database_client
self.content = content or {}
if not content:
self.ExtractContentFromEntry(row_entry)
def ExtractContentFromEntry(self, entry):
"""Populates the content and row_id based on content of the entry.
This method is used in the Record's contructor.
Args:
entry: gdata.spreadsheet.SpreadsheetsList The Atom entry
representing this row in the worksheet.
"""
self.content = {}
if entry:
self.row_id = entry.id.text.split('/')[-1]
for label, custom in entry.custom.iteritems():
self.content[label] = custom.text
def Push(self):
"""Send the content of the record to spreadsheets to edit the row.
All items in the content dictionary will be sent. Items which have been
removed from the content may remain in the row. The content member
of the record will not be modified so additional fields in the row
might be absent from this local copy.
"""
self.entry = self.client._GetSpreadsheetsClient().UpdateRow(self.entry, self.content)
def Pull(self):
"""Query Google Spreadsheets to get the latest data from the server.
Fetches the entry for this row and repopulates the content dictionary
with the data found in the row.
"""
if self.row_id:
self.entry = self.client._GetSpreadsheetsClient().GetListFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id, row_id=self.row_id)
self.ExtractContentFromEntry(self.entry)
def Delete(self):
self.client._GetSpreadsheetsClient().DeleteRow(self.entry)
def ConvertStringsToColumnHeaders(proposed_headers):
"""Converts a list of strings to column names which spreadsheets accepts.
When setting values in a record, the keys which represent column names must
fit certain rules. They are all lower case, contain no spaces or special
characters. If two columns have the same name after being sanitized, the
columns further to the right have _2, _3 _4, etc. appended to them.
If there are column names which consist of all special characters, or if
the column header is blank, an obfuscated value will be used for a column
name. This method does not handle blank column names or column names with
only special characters.
"""
headers = []
for input_string in proposed_headers:
# TODO: probably a more efficient way to do this. Perhaps regex.
sanitized = input_string.lower().replace('_', '').replace(
':', '').replace(' ', '')
# When the same sanitized header appears multiple times in the first row
# of a spreadsheet, _n is appended to the name to make it unique.
header_count = headers.count(sanitized)
if header_count > 0:
headers.append('%s_%i' % (sanitized, header_count+1))
else:
headers.append(sanitized)
return headers
| Python |
#!/usr/bin/python
#
# Copyright (C) 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to Atom objects used with Google Spreadsheets.
"""
__author__ = 'api.laurabeth@gmail.com (Laura Beth Lincoln)'
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import atom
import gdata
import re
import string
# XML namespaces which are often used in Google Spreadsheets entities.
GSPREADSHEETS_NAMESPACE = 'http://schemas.google.com/spreadsheets/2006'
GSPREADSHEETS_TEMPLATE = '{http://schemas.google.com/spreadsheets/2006}%s'
GSPREADSHEETS_EXTENDED_NAMESPACE = ('http://schemas.google.com/spreadsheets'
'/2006/extended')
GSPREADSHEETS_EXTENDED_TEMPLATE = ('{http://schemas.google.com/spreadsheets'
'/2006/extended}%s')
class ColCount(atom.AtomBase):
"""The Google Spreadsheets colCount element """
_tag = 'colCount'
_namespace = GSPREADSHEETS_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ColCountFromString(xml_string):
return atom.CreateClassFromXMLString(ColCount, xml_string)
class RowCount(atom.AtomBase):
"""The Google Spreadsheets rowCount element """
_tag = 'rowCount'
_namespace = GSPREADSHEETS_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def RowCountFromString(xml_string):
return atom.CreateClassFromXMLString(RowCount, xml_string)
class Cell(atom.AtomBase):
"""The Google Spreadsheets cell element """
_tag = 'cell'
_namespace = GSPREADSHEETS_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['row'] = 'row'
_attributes['col'] = 'col'
_attributes['inputValue'] = 'inputValue'
_attributes['numericValue'] = 'numericValue'
def __init__(self, text=None, row=None, col=None, inputValue=None,
numericValue=None, extension_elements=None, extension_attributes=None):
self.text = text
self.row = row
self.col = col
self.inputValue = inputValue
self.numericValue = numericValue
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def CellFromString(xml_string):
return atom.CreateClassFromXMLString(Cell, xml_string)
class Custom(atom.AtomBase):
"""The Google Spreadsheets custom element"""
_namespace = GSPREADSHEETS_EXTENDED_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, column=None, text=None, extension_elements=None,
extension_attributes=None):
self.column = column # The name of the column
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def _BecomeChildElement(self, tree):
new_child = ElementTree.Element('')
tree.append(new_child)
new_child.tag = '{%s}%s' % (self.__class__._namespace,
self.column)
self._AddMembersToElementTree(new_child)
def _ToElementTree(self):
new_tree = ElementTree.Element('{%s}%s' % (self.__class__._namespace,
self.column))
self._AddMembersToElementTree(new_tree)
return new_tree
def _HarvestElementTree(self, tree):
namespace_uri, local_tag = string.split(tree.tag[1:], "}", 1)
self.column = local_tag
# Fill in the instance members from the contents of the XML tree.
for child in tree:
self._ConvertElementTreeToMember(child)
for attribute, value in tree.attrib.iteritems():
self._ConvertElementAttributeToMember(attribute, value)
self.text = tree.text
def CustomFromString(xml_string):
element_tree = ElementTree.fromstring(xml_string)
return _CustomFromElementTree(element_tree)
def _CustomFromElementTree(element_tree):
namespace_uri, local_tag = string.split(element_tree.tag[1:], "}", 1)
if namespace_uri == GSPREADSHEETS_EXTENDED_NAMESPACE:
new_custom = Custom()
new_custom._HarvestElementTree(element_tree)
new_custom.column = local_tag
return new_custom
return None
class SpreadsheetsSpreadsheet(gdata.GDataEntry):
"""A Google Spreadsheets flavor of a Spreadsheet Atom Entry """
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, control=None, updated=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.control = control
self.title = title
self.updated = updated
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SpreadsheetsSpreadsheetFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsSpreadsheet,
xml_string)
class SpreadsheetsWorksheet(gdata.GDataEntry):
"""A Google Spreadsheets flavor of a Worksheet Atom Entry """
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}rowCount' % GSPREADSHEETS_NAMESPACE] = ('row_count',
RowCount)
_children['{%s}colCount' % GSPREADSHEETS_NAMESPACE] = ('col_count',
ColCount)
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, control=None, updated=None,
row_count=None, col_count=None, text=None, extension_elements=None,
extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.control = control
self.title = title
self.updated = updated
self.row_count = row_count
self.col_count = col_count
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SpreadsheetsWorksheetFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsWorksheet,
xml_string)
class SpreadsheetsCell(gdata.BatchEntry):
"""A Google Spreadsheets flavor of a Cell Atom Entry """
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.BatchEntry._children.copy()
_attributes = gdata.BatchEntry._attributes.copy()
_children['{%s}cell' % GSPREADSHEETS_NAMESPACE] = ('cell', Cell)
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, control=None, updated=None,
cell=None, batch_operation=None, batch_id=None, batch_status=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.control = control
self.title = title
self.batch_operation = batch_operation
self.batch_id = batch_id
self.batch_status = batch_status
self.updated = updated
self.cell = cell
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SpreadsheetsCellFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsCell,
xml_string)
class SpreadsheetsList(gdata.GDataEntry):
"""A Google Spreadsheets flavor of a List Atom Entry """
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, control=None, updated=None,
custom=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.control = control
self.title = title
self.updated = updated
self.custom = custom or {}
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
# We need to overwrite _ConvertElementTreeToMember to add special logic to
# convert custom attributes to members
def _ConvertElementTreeToMember(self, child_tree):
# Find the element's tag in this class's list of child members
if self.__class__._children.has_key(child_tree.tag):
member_name = self.__class__._children[child_tree.tag][0]
member_class = self.__class__._children[child_tree.tag][1]
# If the class member is supposed to contain a list, make sure the
# matching member is set to a list, then append the new member
# instance to the list.
if isinstance(member_class, list):
if getattr(self, member_name) is None:
setattr(self, member_name, [])
getattr(self, member_name).append(atom._CreateClassFromElementTree(
member_class[0], child_tree))
else:
setattr(self, member_name,
atom._CreateClassFromElementTree(member_class, child_tree))
elif child_tree.tag.find('{%s}' % GSPREADSHEETS_EXTENDED_NAMESPACE) == 0:
# If this is in the custom namespace, make add it to the custom dict.
name = child_tree.tag[child_tree.tag.index('}')+1:]
custom = _CustomFromElementTree(child_tree)
if custom:
self.custom[name] = custom
else:
ExtensionContainer._ConvertElementTreeToMember(self, child_tree)
# We need to overwtite _AddMembersToElementTree to add special logic to
# convert custom members to XML nodes.
def _AddMembersToElementTree(self, tree):
# Convert the members of this class which are XML child nodes.
# This uses the class's _children dictionary to find the members which
# should become XML child nodes.
member_node_names = [values[0] for tag, values in
self.__class__._children.iteritems()]
for member_name in member_node_names:
member = getattr(self, member_name)
if member is None:
pass
elif isinstance(member, list):
for instance in member:
instance._BecomeChildElement(tree)
else:
member._BecomeChildElement(tree)
# Convert the members of this class which are XML attributes.
for xml_attribute, member_name in self.__class__._attributes.iteritems():
member = getattr(self, member_name)
if member is not None:
tree.attrib[xml_attribute] = member
# Convert all special custom item attributes to nodes
for name, custom in self.custom.iteritems():
custom._BecomeChildElement(tree)
# Lastly, call the ExtensionContainers's _AddMembersToElementTree to
# convert any extension attributes.
atom.ExtensionContainer._AddMembersToElementTree(self, tree)
def SpreadsheetsListFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsList,
xml_string)
element_tree = ElementTree.fromstring(xml_string)
return _SpreadsheetsListFromElementTree(element_tree)
class SpreadsheetsSpreadsheetsFeed(gdata.GDataFeed):
"""A feed containing Google Spreadsheets Spreadsheets"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[SpreadsheetsSpreadsheet])
def SpreadsheetsSpreadsheetsFeedFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsSpreadsheetsFeed,
xml_string)
class SpreadsheetsWorksheetsFeed(gdata.GDataFeed):
"""A feed containing Google Spreadsheets Spreadsheets"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[SpreadsheetsWorksheet])
def SpreadsheetsWorksheetsFeedFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsWorksheetsFeed,
xml_string)
class SpreadsheetsCellsFeed(gdata.BatchFeed):
"""A feed containing Google Spreadsheets Cells"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.BatchFeed._children.copy()
_attributes = gdata.BatchFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[SpreadsheetsCell])
_children['{%s}rowCount' % GSPREADSHEETS_NAMESPACE] = ('row_count',
RowCount)
_children['{%s}colCount' % GSPREADSHEETS_NAMESPACE] = ('col_count',
ColCount)
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None,
entry=None, total_results=None, start_index=None,
items_per_page=None, extension_elements=None,
extension_attributes=None, text=None, row_count=None,
col_count=None, interrupted=None):
gdata.BatchFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text, interrupted=interrupted)
self.row_count = row_count
self.col_count = col_count
def GetBatchLink(self):
for link in self.link:
if link.rel == 'http://schemas.google.com/g/2005#batch':
return link
return None
def SpreadsheetsCellsFeedFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsCellsFeed,
xml_string)
class SpreadsheetsListFeed(gdata.GDataFeed):
"""A feed containing Google Spreadsheets Spreadsheets"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[SpreadsheetsList])
def SpreadsheetsListFeedFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsListFeed,
xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains classes representing Atom elements.
Module objective: provide data classes for Atom constructs. These classes hide
the XML-ness of Atom and provide a set of native Python classes to interact
with.
Conversions to and from XML should only be necessary when the Atom classes
"touch the wire" and are sent over HTTP. For this reason this module
provides methods and functions to convert Atom classes to and from strings.
For more information on the Atom data model, see RFC 4287
(http://www.ietf.org/rfc/rfc4287.txt)
AtomBase: A foundation class on which Atom classes are built. It
handles the parsing of attributes and children which are common to all
Atom classes. By default, the AtomBase class translates all XML child
nodes into ExtensionElements.
ExtensionElement: Atom allows Atom objects to contain XML which is not part
of the Atom specification, these are called extension elements. If a
classes parser encounters an unexpected XML construct, it is translated
into an ExtensionElement instance. ExtensionElement is designed to fully
capture the information in the XML. Child nodes in an XML extension are
turned into ExtensionElements as well.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
# XML namespaces which are often used in Atom entities.
ATOM_NAMESPACE = 'http://www.w3.org/2005/Atom'
ELEMENT_TEMPLATE = '{http://www.w3.org/2005/Atom}%s'
APP_NAMESPACE = 'http://purl.org/atom/app#'
APP_TEMPLATE = '{http://purl.org/atom/app#}%s'
# This encoding is used for converting strings before translating the XML
# into an object.
XML_STRING_ENCODING = 'utf-8'
# The desired string encoding for object members.
MEMBER_STRING_ENCODING = 'utf-8'
def CreateClassFromXMLString(target_class, xml_string, string_encoding=None):
"""Creates an instance of the target class from the string contents.
Args:
target_class: class The class which will be instantiated and populated
with the contents of the XML. This class must have a _tag and a
_namespace class variable.
xml_string: str A string which contains valid XML. The root element
of the XML string should match the tag and namespace of the desired
class.
string_encoding: str The character encoding which the xml_string should
be converted to before it is interpreted and translated into
objects. The default is None in which case the string encoding
is not changed.
Returns:
An instance of the target class with members assigned according to the
contents of the XML - or None if the root XML tag and namespace did not
match those of the target class.
"""
encoding = string_encoding or XML_STRING_ENCODING
if encoding and isinstance(xml_string, unicode):
xml_string = xml_string.encode(encoding)
tree = ElementTree.fromstring(xml_string)
return _CreateClassFromElementTree(target_class, tree)
def _CreateClassFromElementTree(target_class, tree, namespace=None, tag=None):
"""Instantiates the class and populates members according to the tree.
Note: Only use this function with classes that have _namespace and _tag
class members.
Args:
target_class: class The class which will be instantiated and populated
with the contents of the XML.
tree: ElementTree An element tree whose contents will be converted into
members of the new target_class instance.
namespace: str (optional) The namespace which the XML tree's root node must
match. If omitted, the namespace defaults to the _namespace of the
target class.
tag: str (optional) The tag which the XML tree's root node must match. If
omitted, the tag defaults to the _tag class member of the target
class.
Returns:
An instance of the target class - or None if the tag and namespace of
the XML tree's root node did not match the desired namespace and tag.
"""
if namespace is None:
namespace = target_class._namespace
if tag is None:
tag = target_class._tag
if tree.tag == '{%s}%s' % (namespace, tag):
target = target_class()
target._HarvestElementTree(tree)
return target
else:
return None
class ExtensionContainer(object):
def __init__(self, extension_elements=None, extension_attributes=None,
text=None):
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
# Three methods to create an object from an ElementTree
def _HarvestElementTree(self, tree):
# Fill in the instance members from the contents of the XML tree.
for child in tree:
self._ConvertElementTreeToMember(child)
for attribute, value in tree.attrib.iteritems():
self._ConvertElementAttributeToMember(attribute, value)
# Encode the text string according to the desired encoding type. (UTF-8)
if tree.text:
self.text = tree.text.encode(MEMBER_STRING_ENCODING)
def _ConvertElementTreeToMember(self, child_tree, current_class=None):
self.extension_elements.append(_ExtensionElementFromElementTree(
child_tree))
def _ConvertElementAttributeToMember(self, attribute, value):
# Encode the attribute value's string with the desired type Default UTF-8
if value:
self.extension_attributes[attribute] = value.encode(
MEMBER_STRING_ENCODING)
# One method to create an ElementTree from an object
def _AddMembersToElementTree(self, tree):
for child in self.extension_elements:
child._BecomeChildElement(tree)
for attribute, value in self.extension_attributes.iteritems():
if value:
# Decode the value from the desired encoding (default UTF-8).
tree.attrib[attribute] = value.decode(MEMBER_STRING_ENCODING)
if self.text and not isinstance(self.text, unicode):
tree.text = self.text.decode(MEMBER_STRING_ENCODING)
else:
tree.text = self.text
def FindExtensions(self, tag=None, namespace=None):
"""Searches extension elements for child nodes with the desired name.
Returns a list of extension elements within this object whose tag
and/or namespace match those passed in. To find all extensions in
a particular namespace, specify the namespace but not the tag name.
If you specify only the tag, the result list may contain extension
elements in multiple namespaces.
Args:
tag: str (optional) The desired tag
namespace: str (optional) The desired namespace
Returns:
A list of elements whose tag and/or namespace match the parameters
values
"""
results = []
if tag and namespace:
for element in self.extension_elements:
if element.tag == tag and element.namespace == namespace:
results.append(element)
elif tag and not namespace:
for element in self.extension_elements:
if element.tag == tag:
results.append(element)
elif namespace and not tag:
for element in self.extension_elements:
if element.namespace == namespace:
results.append(element)
else:
for element in self.extension_elements:
results.append(element)
return results
class AtomBase(ExtensionContainer):
_children = {}
_attributes = {}
def __init__(self, extension_elements=None, extension_attributes=None,
text=None):
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
def _ConvertElementTreeToMember(self, child_tree):
# Find the element's tag in this class's list of child members
if self.__class__._children.has_key(child_tree.tag):
member_name = self.__class__._children[child_tree.tag][0]
member_class = self.__class__._children[child_tree.tag][1]
# If the class member is supposed to contain a list, make sure the
# matching member is set to a list, then append the new member
# instance to the list.
if isinstance(member_class, list):
if getattr(self, member_name) is None:
setattr(self, member_name, [])
getattr(self, member_name).append(_CreateClassFromElementTree(
member_class[0], child_tree))
else:
setattr(self, member_name,
_CreateClassFromElementTree(member_class, child_tree))
else:
ExtensionContainer._ConvertElementTreeToMember(self, child_tree)
def _ConvertElementAttributeToMember(self, attribute, value):
# Find the attribute in this class's list of attributes.
if self.__class__._attributes.has_key(attribute):
# Find the member of this class which corresponds to the XML attribute
# (lookup in current_class._attributes) and set this member to the
# desired value (using self.__dict__).
if value:
# Encode the string to capture non-ascii characters (default UTF-8)
setattr(self, self.__class__._attributes[attribute],
value.encode(MEMBER_STRING_ENCODING))
else:
ExtensionContainer._ConvertElementAttributeToMember(self, attribute,
value)
# Three methods to create an ElementTree from an object
def _AddMembersToElementTree(self, tree):
# Convert the members of this class which are XML child nodes.
# This uses the class's _children dictionary to find the members which
# should become XML child nodes.
member_node_names = [values[0] for tag, values in
self.__class__._children.iteritems()]
for member_name in member_node_names:
member = getattr(self, member_name)
if member is None:
pass
elif isinstance(member, list):
for instance in member:
instance._BecomeChildElement(tree)
else:
member._BecomeChildElement(tree)
# Convert the members of this class which are XML attributes.
for xml_attribute, member_name in self.__class__._attributes.iteritems():
member = getattr(self, member_name)
if member is not None:
tree.attrib[xml_attribute] = member.decode(MEMBER_STRING_ENCODING)
# Lastly, call the ExtensionContainers's _AddMembersToElementTree to
# convert any extension attributes.
ExtensionContainer._AddMembersToElementTree(self, tree)
def _BecomeChildElement(self, tree):
"""
Note: Only for use with classes that have a _tag and _namespace class
member. It is in AtomBase so that it can be inherited but it should
not be called on instances of AtomBase.
"""
new_child = ElementTree.Element('')
tree.append(new_child)
new_child.tag = '{%s}%s' % (self.__class__._namespace,
self.__class__._tag)
self._AddMembersToElementTree(new_child)
def _ToElementTree(self):
"""
Note, this method is designed to be used only with classes that have a
_tag and _namespace. It is placed in AtomBase for inheritance but should
not be called on this class.
"""
new_tree = ElementTree.Element('{%s}%s' % (self.__class__._namespace,
self.__class__._tag))
self._AddMembersToElementTree(new_tree)
return new_tree
def ToString(self, string_encoding='UTF-8'):
"""Converts the Atom object to a string containing XML."""
return ElementTree.tostring(self._ToElementTree(), encoding=string_encoding)
def __str__(self):
return self.ToString()
class Name(AtomBase):
"""The atom:name element"""
_tag = 'name'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Name
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def NameFromString(xml_string):
return CreateClassFromXMLString(Name, xml_string)
class Email(AtomBase):
"""The atom:email element"""
_tag = 'email'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Email
Args:
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def EmailFromString(xml_string):
return CreateClassFromXMLString(Email, xml_string)
class Uri(AtomBase):
"""The atom:uri element"""
_tag = 'uri'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Uri
Args:
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def UriFromString(xml_string):
return CreateClassFromXMLString(Uri, xml_string)
class Person(AtomBase):
"""A foundation class from which atom:author and atom:contributor extend.
A person contains information like name, email address, and web page URI for
an author or contributor to an Atom feed.
"""
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_children['{%s}name' % (ATOM_NAMESPACE)] = ('name', Name)
_children['{%s}email' % (ATOM_NAMESPACE)] = ('email', Email)
_children['{%s}uri' % (ATOM_NAMESPACE)] = ('uri', Uri)
def __init__(self, name=None, email=None, uri=None,
extension_elements=None, extension_attributes=None, text=None):
"""Foundation from which author and contributor are derived.
The constructor is provided for illustrative purposes, you should not
need to instantiate a Person.
Args:
name: Name The person's name
email: Email The person's email address
uri: Uri The URI of the person's webpage
extension_elements: list A list of ExtensionElement instances which are
children of this element.
extension_attributes: dict A dictionary of strings which are the values
for additional XML attributes of this element.
text: String The text contents of the element. This is the contents
of the Entry's XML text node. (Example: <foo>This is the text</foo>)
"""
self.name = name
self.email = email
self.uri = uri
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
class Author(Person):
"""The atom:author element
An author is a required element in Feed.
"""
_tag = 'author'
_namespace = ATOM_NAMESPACE
_children = Person._children.copy()
_attributes = Person._attributes.copy()
#_children = {}
#_attributes = {}
def __init__(self, name=None, email=None, uri=None,
extension_elements=None, extension_attributes=None, text=None):
"""Constructor for Author
Args:
name: Name
email: Email
uri: Uri
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.name = name
self.email = email
self.uri = uri
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
def AuthorFromString(xml_string):
return CreateClassFromXMLString(Author, xml_string)
class Contributor(Person):
"""The atom:contributor element"""
_tag = 'contributor'
_namespace = ATOM_NAMESPACE
_children = Person._children.copy()
_attributes = Person._attributes.copy()
def __init__(self, name=None, email=None, uri=None,
extension_elements=None, extension_attributes=None, text=None):
"""Constructor for Contributor
Args:
name: Name
email: Email
uri: Uri
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.name = name
self.email = email
self.uri = uri
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
def ContributorFromString(xml_string):
return CreateClassFromXMLString(Contributor, xml_string)
class Link(AtomBase):
"""The atom:link element"""
_tag = 'link'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_attributes['rel'] = 'rel'
_attributes['href'] = 'href'
_attributes['type'] = 'type'
_attributes['title'] = 'title'
_attributes['length'] = 'length'
_attributes['hreflang'] = 'hreflang'
def __init__(self, href=None, rel=None, link_type=None, hreflang=None,
title=None, length=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Link
Args:
href: string The href attribute of the link
rel: string
type: string
hreflang: string The language for the href
title: string
length: string The length of the href's destination
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.href = href
self.rel = rel
self.type = link_type
self.hreflang = hreflang
self.title = title
self.length = length
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def LinkFromString(xml_string):
return CreateClassFromXMLString(Link, xml_string)
class Generator(AtomBase):
"""The atom:generator element"""
_tag = 'generator'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_attributes['uri'] = 'uri'
_attributes['version'] = 'version'
def __init__(self, uri=None, version=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for Generator
Args:
uri: string
version: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.uri = uri
self.version = version
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GeneratorFromString(xml_string):
return CreateClassFromXMLString(Generator, xml_string)
class Text(AtomBase):
"""A foundation class from which atom:title, summary, etc. extend.
This class should never be instantiated.
"""
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_attributes['type'] = 'type'
def __init__(self, text_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Text
Args:
text_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = text_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Title(Text):
"""The atom:title element"""
_tag = 'title'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
def __init__(self, title_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Title
Args:
title_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = title_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def TitleFromString(xml_string):
return CreateClassFromXMLString(Title, xml_string)
class Subtitle(Text):
"""The atom:subtitle element"""
_tag = 'subtitle'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
def __init__(self, subtitle_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Subtitle
Args:
subtitle_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = subtitle_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SubtitleFromString(xml_string):
return CreateClassFromXMLString(Subtitle, xml_string)
class Rights(Text):
"""The atom:rights element"""
_tag = 'rights'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
def __init__(self, rights_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Rights
Args:
rights_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = rights_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def RightsFromString(xml_string):
return CreateClassFromXMLString(Rights, xml_string)
class Summary(Text):
"""The atom:summary element"""
_tag = 'summary'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
def __init__(self, summary_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Summary
Args:
summary_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = summary_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SummaryFromString(xml_string):
return CreateClassFromXMLString(Summary, xml_string)
class Content(Text):
"""The atom:content element"""
_tag = 'content'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
_attributes['src'] = 'src'
def __init__(self, content_type=None, src=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for Content
Args:
content_type: string
src: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = content_type
self.src = src
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ContentFromString(xml_string):
return CreateClassFromXMLString(Content, xml_string)
class Category(AtomBase):
"""The atom:category element"""
_tag = 'category'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_attributes['term'] = 'term'
_attributes['scheme'] = 'scheme'
_attributes['label'] = 'label'
def __init__(self, term=None, scheme=None, label=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for Category
Args:
term: str
scheme: str
label: str
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.term = term
self.scheme = scheme
self.label = label
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def CategoryFromString(xml_string):
return CreateClassFromXMLString(Category, xml_string)
class Id(AtomBase):
"""The atom:id element."""
_tag = 'id'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Id
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def IdFromString(xml_string):
return CreateClassFromXMLString(Id, xml_string)
class Icon(AtomBase):
"""The atom:icon element."""
_tag = 'icon'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Icon
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def IconFromString(xml_string):
return CreateClassFromXMLString(Icon, xml_string)
class Logo(AtomBase):
"""The atom:logo element."""
_tag = 'logo'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Logo
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def LogoFromString(xml_string):
return CreateClassFromXMLString(Logo, xml_string)
class Draft(AtomBase):
"""The app:draft element which indicates if this entry should be public."""
_tag = 'draft'
_namespace = APP_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for app:draft
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def DraftFromString(xml_string):
return CreateClassFromXMLString(Draft, xml_string)
class Control(AtomBase):
"""The app:control element indicating restrictions on publication.
The APP control element may contain a draft element indicating whether or
not this entry should be publicly available.
"""
_tag = 'control'
_namespace = APP_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_children['{%s}draft' % APP_NAMESPACE] = ('draft', Draft)
def __init__(self, draft=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for app:control"""
self.draft = draft
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ControlFromString(xml_string):
return CreateClassFromXMLString(Control, xml_string)
class Date(AtomBase):
"""A parent class for atom:updated, published, etc."""
#TODO Add text to and from time conversion methods to allow users to set
# the contents of a Date to a python DateTime object.
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Updated(Date):
"""The atom:updated element."""
_tag = 'updated'
_namespace = ATOM_NAMESPACE
_children = Date._children.copy()
_attributes = Date._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Updated
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def UpdatedFromString(xml_string):
return CreateClassFromXMLString(Updated, xml_string)
class Published(Date):
"""The atom:published element."""
_tag = 'published'
_namespace = ATOM_NAMESPACE
_children = Date._children.copy()
_attributes = Date._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Published
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def PublishedFromString(xml_string):
return CreateClassFromXMLString(Published, xml_string)
class LinkFinder(object):
"""An "interface" providing methods to find link elements
Entry elements often contain multiple links which differ in the rel
attribute or content type. Often, developers are interested in a specific
type of link so this class provides methods to find specific classes of
links.
This class is used as a mixin in Atom entries and feeds.
"""
def GetSelfLink(self):
"""Find the first link with rel set to 'self'
Returns:
An atom.Link or none if none of the links had rel equal to 'self'
"""
for a_link in self.link:
if a_link.rel == 'self':
return a_link
return None
def GetEditLink(self):
for a_link in self.link:
if a_link.rel == 'edit':
return a_link
return None
def GetNextLink(self):
for a_link in self.link:
if a_link.rel == 'next':
return a_link
return None
def GetLicenseLink(self):
for a_link in self.link:
if a_link.rel == 'license':
return a_link
return None
def GetAlternateLink(self):
for a_link in self.link:
if a_link.rel == 'alternate':
return a_link
return None
class FeedEntryParent(AtomBase, LinkFinder):
"""A super class for atom:feed and entry, contains shared attributes"""
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_children['{%s}author' % ATOM_NAMESPACE] = ('author', [Author])
_children['{%s}category' % ATOM_NAMESPACE] = ('category', [Category])
_children['{%s}contributor' % ATOM_NAMESPACE] = ('contributor', [Contributor])
_children['{%s}id' % ATOM_NAMESPACE] = ('id', Id)
_children['{%s}link' % ATOM_NAMESPACE] = ('link', [Link])
_children['{%s}rights' % ATOM_NAMESPACE] = ('rights', Rights)
_children['{%s}title' % ATOM_NAMESPACE] = ('title', Title)
_children['{%s}updated' % ATOM_NAMESPACE] = ('updated', Updated)
def __init__(self, author=None, category=None, contributor=None,
atom_id=None, link=None, rights=None, title=None, updated=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.rights = rights
self.title = title
self.updated = updated
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Source(FeedEntryParent):
"""The atom:source element"""
_tag = 'source'
_namespace = ATOM_NAMESPACE
_children = FeedEntryParent._children.copy()
_attributes = FeedEntryParent._attributes.copy()
_children['{%s}generator' % ATOM_NAMESPACE] = ('generator', Generator)
_children['{%s}icon' % ATOM_NAMESPACE] = ('icon', Icon)
_children['{%s}logo' % ATOM_NAMESPACE] = ('logo', Logo)
_children['{%s}subtitle' % ATOM_NAMESPACE] = ('subtitle', Subtitle)
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for Source
Args:
author: list (optional) A list of Author instances which belong to this
class.
category: list (optional) A list of Category instances
contributor: list (optional) A list on Contributor instances
generator: Generator (optional)
icon: Icon (optional)
id: Id (optional) The entry's Id element
link: list (optional) A list of Link instances
logo: Logo (optional)
rights: Rights (optional) The entry's Rights element
subtitle: Subtitle (optional) The entry's subtitle element
title: Title (optional) the entry's title element
updated: Updated (optional) the entry's updated element
text: String (optional) The text contents of the element. This is the
contents of the Entry's XML text node.
(Example: <foo>This is the text</foo>)
extension_elements: list (optional) A list of ExtensionElement instances
which are children of this element.
extension_attributes: dict (optional) A dictionary of strings which are
the values for additional XML attributes of this element.
"""
self.author = author or []
self.category = category or []
self.contributor = contributor or []
self.generator = generator
self.icon = icon
self.id = atom_id
self.link = link or []
self.logo = logo
self.rights = rights
self.subtitle = subtitle
self.title = title
self.updated = updated
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SourceFromString(xml_string):
return CreateClassFromXMLString(Source, xml_string)
class Entry(FeedEntryParent):
"""The atom:entry element"""
_tag = 'entry'
_namespace = ATOM_NAMESPACE
_children = FeedEntryParent._children.copy()
_attributes = FeedEntryParent._attributes.copy()
_children['{%s}content' % ATOM_NAMESPACE] = ('content', Content)
_children['{%s}published' % ATOM_NAMESPACE] = ('published', Published)
_children['{%s}source' % ATOM_NAMESPACE] = ('source', Source)
_children['{%s}summary' % ATOM_NAMESPACE] = ('summary', Summary)
_children['{%s}control' % APP_NAMESPACE] = ('control', Control)
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, control=None, title=None, updated=None,
extension_elements=None, extension_attributes=None, text=None):
"""Constructor for atom:entry
Args:
author: list A list of Author instances which belong to this class.
category: list A list of Category instances
content: Content The entry's Content
contributor: list A list on Contributor instances
id: Id The entry's Id element
link: list A list of Link instances
published: Published The entry's Published element
rights: Rights The entry's Rights element
source: Source the entry's source element
summary: Summary the entry's summary element
title: Title the entry's title element
updated: Updated the entry's updated element
control: The entry's app:control element which can be used to mark an
entry as a draft which should not be publicly viewable.
text: String The text contents of the element. This is the contents
of the Entry's XML text node. (Example: <foo>This is the text</foo>)
extension_elements: list A list of ExtensionElement instances which are
children of this element.
extension_attributes: dict A dictionary of strings which are the values
for additional XML attributes of this element.
"""
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.title = title
self.updated = updated
self.control = control
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def EntryFromString(xml_string):
return CreateClassFromXMLString(Entry, xml_string)
class Feed(Source):
"""The atom:feed element"""
_tag = 'feed'
_namespace = ATOM_NAMESPACE
_children = Source._children.copy()
_attributes = Source._attributes.copy()
_children['{%s}entry' % ATOM_NAMESPACE] = ('entry', [Entry])
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None, entry=None,
text=None, extension_elements=None, extension_attributes=None):
"""Constructor for Source
Args:
author: list (optional) A list of Author instances which belong to this
class.
category: list (optional) A list of Category instances
contributor: list (optional) A list on Contributor instances
generator: Generator (optional)
icon: Icon (optional)
id: Id (optional) The entry's Id element
link: list (optional) A list of Link instances
logo: Logo (optional)
rights: Rights (optional) The entry's Rights element
subtitle: Subtitle (optional) The entry's subtitle element
title: Title (optional) the entry's title element
updated: Updated (optional) the entry's updated element
entry: list (optional) A list of the Entry instances contained in the
feed.
text: String (optional) The text contents of the element. This is the
contents of the Entry's XML text node.
(Example: <foo>This is the text</foo>)
extension_elements: list (optional) A list of ExtensionElement instances
which are children of this element.
extension_attributes: dict (optional) A dictionary of strings which are
the values for additional XML attributes of this element.
"""
self.author = author or []
self.category = category or []
self.contributor = contributor or []
self.generator = generator
self.icon = icon
self.id = atom_id
self.link = link or []
self.logo = logo
self.rights = rights
self.subtitle = subtitle
self.title = title
self.updated = updated
self.entry = entry or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def FeedFromString(xml_string):
return CreateClassFromXMLString(Feed, xml_string)
class ExtensionElement(object):
"""Represents extra XML elements contained in Atom classes."""
def __init__(self, tag, namespace=None, attributes=None,
children=None, text=None):
"""Constructor for EtensionElement
Args:
namespace: string (optional) The XML namespace for this element.
tag: string (optional) The tag (without the namespace qualifier) for
this element. To reconstruct the full qualified name of the element,
combine this tag with the namespace.
attributes: dict (optinal) The attribute value string pairs for the XML
attributes of this element.
children: list (optional) A list of ExtensionElements which represent
the XML child nodes of this element.
"""
self.namespace = namespace
self.tag = tag
self.attributes = attributes or {}
self.children = children or []
self.text = text
def ToString(self):
element_tree = self._TransferToElementTree(ElementTree.Element(''))
return ElementTree.tostring(element_tree, encoding="UTF-8")
def _TransferToElementTree(self, element_tree):
if self.tag is None:
return None
if self.namespace is not None:
element_tree.tag = '{%s}%s' % (self.namespace, self.tag)
else:
element_tree.tag = self.tag
for key, value in self.attributes.iteritems():
element_tree.attrib[key] = value
for child in self.children:
child._BecomeChildElement(element_tree)
element_tree.text = self.text
return element_tree
def _BecomeChildElement(self, element_tree):
"""Converts this object into an etree element and adds it as a child node.
Adds self to the ElementTree. This method is required to avoid verbose XML
which constantly redefines the namespace.
Args:
element_tree: ElementTree._Element The element to which this object's XML
will be added.
"""
new_element = ElementTree.Element('')
element_tree.append(new_element)
self._TransferToElementTree(new_element)
def FindChildren(self, tag=None, namespace=None):
"""Searches child nodes for objects with the desired tag/namespace.
Returns a list of extension elements within this object whose tag
and/or namespace match those passed in. To find all children in
a particular namespace, specify the namespace but not the tag name.
If you specify only the tag, the result list may contain extension
elements in multiple namespaces.
Args:
tag: str (optional) The desired tag
namespace: str (optional) The desired namespace
Returns:
A list of elements whose tag and/or namespace match the parameters
values
"""
results = []
if tag and namespace:
for element in self.children:
if element.tag == tag and element.namespace == namespace:
results.append(element)
elif tag and not namespace:
for element in self.children:
if element.tag == tag:
results.append(element)
elif namespace and not tag:
for element in self.children:
if element.namespace == namespace:
results.append(element)
else:
for element in self.children:
results.append(element)
return results
def ExtensionElementFromString(xml_string):
element_tree = ElementTree.fromstring(xml_string)
return _ExtensionElementFromElementTree(element_tree)
def _ExtensionElementFromElementTree(element_tree):
element_tag = element_tree.tag
if '}' in element_tag:
namespace = element_tag[1:element_tag.index('}')]
tag = element_tag[element_tag.index('}')+1:]
else:
namespace = None
tag = element_tag
extension = ExtensionElement(namespace=namespace, tag=tag)
for key, value in element_tree.attrib.iteritems():
extension.attributes[key] = value
for child in element_tree:
extension.children.append(_ExtensionElementFromElementTree(child))
extension.text = element_tree.text
return extension
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006, 2007, 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""AtomService provides CRUD ops. in line with the Atom Publishing Protocol.
AtomService: Encapsulates the ability to perform insert, update and delete
operations with the Atom Publishing Protocol on which GData is
based. An instance can perform query, insertion, deletion, and
update.
HttpRequest: Function that performs a GET, POST, PUT, or DELETE HTTP request
to the specified end point. An AtomService object or a subclass can be
used to specify information about the request.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
import os
import httplib
import urllib
import re
import base64
import socket
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
URL_REGEX = re.compile('http(s)?\://([\w\.-]*)(\:(\d+))?(/.*)?')
class AtomService(object):
"""Performs Atom Publishing Protocol CRUD operations.
The AtomService contains methods to perform HTTP CRUD operations.
"""
# Default values for members
port = 80
ssl = False
# If debug is True, the HTTPConnection will display debug information
debug = False
def __init__(self, server=None, additional_headers=None):
"""Creates a new AtomService client.
Args:
server: string (optional) The start of a URL for the server
to which all operations should be directed. Example:
'www.google.com'
additional_headers: dict (optional) Any additional HTTP headers which
should be included with CRUD operations.
"""
self.server = server
self.additional_headers = additional_headers or {}
self.additional_headers['User-Agent'] = 'Python Google Data Client Lib'
def _ProcessUrl(self, url, for_proxy=False):
"""Processes a passed URL. If the URL does not begin with https?, then
the default value for self.server is used"""
return ProcessUrl(self, url, for_proxy=for_proxy)
def 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
"""
UseBasicAuth(self, username, password, for_proxy=for_proxy)
def PrepareConnection(self, full_uri):
"""Opens a connection to the server based on the full URI.
Examines the target URI and the proxy settings, which are set as
environment variables, to open a connection with the server. This
connection is used to make an HTTP request.
Args:
full_uri: str Which is the target relative (lacks protocol and host) or
absolute URL to be opened. Example:
'https://www.google.com/accounts/ClientLogin' or
'base/feeds/snippets' where the server is set to www.google.com.
Returns:
A tuple containing the httplib.HTTPConnection and the full_uri for the
request.
"""
return PrepareConnection(self, full_uri)
# Alias the old name for the above method to preserve backwards
# compatibility.
_PrepareConnection = PrepareConnection
# CRUD operations
def Get(self, uri, extra_headers=None, url_params=None, escape_params=True):
"""Query the APP server with the given URI
The uri is the portion of the URI after the server value
(server example: 'www.google.com').
Example use:
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: dicty (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.
url_params: dict (optional) Additional URL parameters to be included
in the query. 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.
Returns:
httplib.HTTPResponse The server's response to the GET request.
"""
return HttpRequest(self, 'GET', None, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params)
def Post(self, data, uri, extra_headers=None, url_params=None,
escape_params=True, content_type='application/atom+xml'):
"""Insert data into an APP server at the given URI.
Args:
data: string, ElementTree._Element, or something with a __str__ method
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.
Returns:
httplib.HTTPResponse Server's response to the POST request.
"""
return HttpRequest(self, 'POST', data, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params,
content_type=content_type)
def Put(self, data, uri, extra_headers=None, url_params=None,
escape_params=True, content_type='application/atom+xml'):
"""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.
Returns:
httplib.HTTPResponse Server's response to the PUT request.
"""
return HttpRequest(self, 'PUT', data, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params,
content_type=content_type)
def Delete(self, uri, extra_headers=None, url_params=None,
escape_params=True):
"""Deletes the entry at the given URI.
Args:
uri: string The URI of the entry to be deleted. Example:
'/base/feeds/items/ITEM-ID'
extra_headers: dict (optional) HTTP headers which are to be included.
The client automatically sets the Content-Type and
Authorization 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.
Returns:
httplib.HTTPResponse Server's response to the DELETE request.
"""
return HttpRequest(self, 'DELETE', None, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params)
def HttpRequest(service, operation, data, uri, extra_headers=None,
url_params=None, escape_params=True, content_type='application/atom+xml'):
"""Performs an HTTP call to the server, supports GET, POST, PUT, and DELETE.
Usage example, perform and HTTP GET on http://www.google.com/:
import atom.service
client = atom.service.AtomService()
http_response = client.Get('http://www.google.com/')
or you could set the client.server to 'www.google.com' and use the
following:
client.server = 'www.google.com'
http_response = client.Get('/')
Args:
service: atom.AtomService object which contains some of the parameters
needed to make the request. The following members are used to
construct the HTTP call: server (str), additional_headers (dict),
port (int), and ssl (bool).
operation: str The HTTP operation to be performed. This is usually one of
'GET', 'POST', 'PUT', or 'DELETE'
data: ElementTree, filestream, list of parts, or other object which can be
converted to a string.
Should be set to None when performing a GET or PUT.
If data is a file-like object which can be read, this method will read
a chunk of 100K bytes at a time and send them.
If the data is a list of parts to be sent, each part will be evaluated
and sent.
uri: The beginning of the URL to which the request should be sent.
Examples: '/', '/base/feeds/snippets',
'/m8/feeds/contacts/default/base'
extra_headers: dict of strings. HTTP headers which should be sent
in the request. These headers are in addition to those stored in
service.additional_headers.
url_params: dict of strings. Key value pairs to be added to the URL as
URL parameters. For example {'foo':'bar', 'test':'param'} will
become ?foo=bar&test=param.
escape_params: bool default True. If true, the keys and values in
url_params will be URL escaped when the form is constructed
(Special characters converted to %XX form.)
content_type: str The MIME type for the data being sent. Defaults to
'application/atom+xml', this is only used if data is set.
"""
full_uri = BuildUri(uri, url_params, escape_params)
(connection, full_uri) = PrepareConnection(service, full_uri)
if extra_headers is None:
extra_headers = {}
# Turn on debug mode if the debug member is set.
if service.debug:
connection.debuglevel = 1
connection.putrequest(operation, full_uri)
# If the list of headers does not include a Content-Length, attempt to
# calculate it based on the data object.
if (data and not service.additional_headers.has_key('Content-Length') and
not extra_headers.has_key('Content-Length')):
content_length = __CalculateDataLength(data)
if content_length:
extra_headers['Content-Length'] = str(content_length)
if content_type:
extra_headers['Content-Type'] = content_type
# Send the HTTP headers.
if isinstance(service.additional_headers, dict):
for header in service.additional_headers:
connection.putheader(header, service.additional_headers[header])
if isinstance(extra_headers, dict):
for header in extra_headers:
connection.putheader(header, extra_headers[header])
connection.endheaders()
# If there is data, send it in the request.
if data:
if isinstance(data, list):
for data_part in data:
__SendDataPart(data_part, connection)
else:
__SendDataPart(data, connection)
# Return the HTTP Response from the server.
return connection.getresponse()
def __SendDataPart(data, connection):
if isinstance(data, str):
#TODO add handling for unicode.
connection.send(data)
return
elif ElementTree.iselement(data):
connection.send(ElementTree.tostring(data))
return
# Check to see if data is a file-like object that has a read method.
elif hasattr(data, 'read'):
# Read the file and send it a chunk at a time.
while 1:
binarydata = data.read(100000)
if binarydata == '': break
connection.send(binarydata)
return
else:
# The data object was not a file.
# Try to convert to a string and send the data.
connection.send(str(data))
return
def __CalculateDataLength(data):
"""Attempts to determine the length of the data to send.
This method will respond with a length only if the data is a string or
and ElementTree element.
Args:
data: object If this is not a string or ElementTree element this funtion
will return None.
"""
if isinstance(data, str):
return len(data)
elif isinstance(data, list):
return None
elif ElementTree.iselement(data):
return len(ElementTree.tostring(data))
elif hasattr(data, 'read'):
# If this is a file-like object, don't try to guess the length.
return None
else:
return len(str(data))
def PrepareConnection(service, full_uri):
"""Opens a connection to the server based on the full URI.
Examines the target URI and the proxy settings, which are set as
environment variables, to open a connection with the server. This
connection is used to make an HTTP request.
Args:
service: atom.AtomService or a subclass. It must have a server string which
represents the server host to which the request should be made. It may also
have a dictionary of additional_headers to send in the HTTP request.
full_uri: str Which is the target relative (lacks protocol and host) or
absolute URL to be opened. Example:
'https://www.google.com/accounts/ClientLogin' or
'base/feeds/snippets' where the server is set to www.google.com.
Returns:
A tuple containing the httplib.HTTPConnection and the full_uri for the
request.
"""
(server, port, ssl, partial_uri) = ProcessUrl(service, full_uri)
if ssl:
# destination is https
proxy = os.environ.get('https_proxy')
if proxy:
(p_server, p_port, p_ssl, p_uri) = ProcessUrl(service, proxy, True)
proxy_username = os.environ.get('proxy-username')
if not proxy_username:
proxy_username = os.environ.get('proxy_username')
proxy_password = os.environ.get('proxy-password')
if not proxy_password:
proxy_password = os.environ.get('proxy_password')
if proxy_username:
user_auth = base64.encodestring('%s:%s' % (proxy_username,
proxy_password))
proxy_authorization = ('Proxy-authorization: Basic %s\r\n' % (
user_auth.strip()))
else:
proxy_authorization = ''
proxy_connect = 'CONNECT %s:%s HTTP/1.0\r\n' % (server, port)
user_agent = 'User-Agent: %s\r\n' % (
service.additional_headers['User-Agent'])
proxy_pieces = (proxy_connect + proxy_authorization + user_agent
+ '\r\n')
#now connect, very simple recv and error checking
p_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
p_sock.connect((p_server,p_port))
p_sock.sendall(proxy_pieces)
response = ''
# Wait for the full response.
while response.find("\r\n\r\n") == -1:
response += p_sock.recv(8192)
p_status=response.split()[1]
if p_status!=str(200):
raise 'Error status=',str(p_status)
# Trivial setup for ssl socket.
ssl = socket.ssl(p_sock, None, None)
fake_sock = httplib.FakeSocket(p_sock, ssl)
# Initalize httplib and replace with the proxy socket.
connection = httplib.HTTPConnection(server)
connection.sock=fake_sock
full_uri = partial_uri
else:
connection = httplib.HTTPSConnection(server, port)
full_uri = partial_uri
else:
# destination is http
proxy = os.environ.get('http_proxy')
if proxy:
(p_server, p_port, p_ssl, p_uri) = ProcessUrl(service.server, proxy, True)
proxy_username = os.environ.get('proxy-username')
if not proxy_username:
proxy_username = os.environ.get('proxy_username')
proxy_password = os.environ.get('proxy-password')
if not proxy_password:
proxy_password = os.environ.get('proxy_password')
if proxy_username:
UseBasicAuth(service, proxy_username, proxy_password, True)
connection = httplib.HTTPConnection(p_server, p_port)
if not full_uri.startswith("http://"):
if full_uri.startswith("/"):
full_uri = "http://%s%s" % (service.server, full_uri)
else:
full_uri = "http://%s/%s" % (service.server, full_uri)
else:
connection = httplib.HTTPConnection(server, port)
full_uri = partial_uri
return (connection, full_uri)
def UseBasicAuth(service, 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. The auth header is added to the
additional_headers dictionary in the service object.
Args:
service: atom.AtomService or a subclass which has an
additional_headers dict as a member.
username: str
password: str
"""
base_64_string = base64.encodestring('%s:%s' % (username, password))
base_64_string = base_64_string.strip()
if for_proxy:
header_name = 'Proxy-Authorization'
else:
header_name = 'Authorization'
service.additional_headers[header_name] = 'Basic %s' % (base_64_string,)
def ProcessUrl(service, url, for_proxy=False):
"""Processes a passed URL. If the URL does not begin with https?, then
the default value for server is used"""
server = None
port = 80
ssl = False
if hasattr(service, 'server'):
server = service.server
else:
server = service
if not for_proxy:
if hasattr(service, 'port'):
port = service.port
if hasattr(service, 'ssl'):
ssl = service.ssl
uri = url
m = URL_REGEX.match(url)
if m is None:
return (server, port, ssl, uri)
else:
if m.group(1) is not None:
port = 443
ssl = True
if m.group(3) is None:
server = m.group(2)
else:
server = m.group(2)
port = int(m.group(4))
if m.group(5) is not None:
uri = m.group(5)
else:
uri = '/'
return (server, port, ssl, uri)
def DictionaryToParamList(url_parameters, escape_params=True):
"""Convert a dictionary of URL arguments into a URL parameter string.
Args:
url_parameters: The dictionaty of key-value pairs which will be converted
into URL parameters. For example,
{'dry-run': 'true', 'foo': 'bar'}
will become ['dry-run=true', 'foo=bar'].
Returns:
A list which contains a string for each key-value pair. The strings are
ready to be incorporated into a URL by using '&'.join([] + parameter_list)
"""
# Choose which function to use when modifying the query and parameters.
# Use quote_plus when escape_params is true.
transform_op = [str, urllib.quote_plus][bool(escape_params)]
# Create a list of tuples containing the escaped version of the
# parameter-value pairs.
parameter_tuples = [(transform_op(param), transform_op(value))
for param, value in (url_parameters or {}).items()]
# Turn parameter-value tuples into a list of strings in the form
# 'PARAMETER=VALUE'.
return ['='.join(x) for x in parameter_tuples]
def BuildUri(uri, url_params=None, escape_params=True):
"""Converts a uri string and a collection of parameters into a URI.
Args:
uri: string
url_params: dict (optional)
escape_params: boolean (optional)
uri: string The start of the desired URI. This string can alrady contain
URL parameters. Examples: '/base/feeds/snippets',
'/base/feeds/snippets?bq=digital+camera'
url_parameters: dict (optional) Additional URL parameters to be included
in the query. 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.
Returns:
string The URI consisting of the escaped URL parameters appended to the
initial uri string.
"""
# Prepare URL parameters for inclusion into the GET request.
parameter_list = DictionaryToParamList(url_params, escape_params)
# Append the URL parameters to the URL.
if parameter_list:
if uri.find('?') != -1:
# If there are already URL parameters in the uri string, add the
# parameters after a new & character.
full_uri = '&'.join([uri] + parameter_list)
else:
# The uri string did not have any URL parameters (no ? character)
# so put a ? between the uri and URL parameters.
full_uri = '%s%s' % (uri, '?%s' % ('&'.join([] + parameter_list)))
else:
full_uri = uri
return full_uri
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006, 2007, 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""AtomService provides CRUD ops. in line with the Atom Publishing Protocol.
AtomService: Encapsulates the ability to perform insert, update and delete
operations with the Atom Publishing Protocol on which GData is
based. An instance can perform query, insertion, deletion, and
update.
HttpRequest: Function that performs a GET, POST, PUT, or DELETE HTTP request
to the specified end point. An AtomService object or a subclass can be
used to specify information about the request.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
import os
import httplib
import urllib
import re
import base64
import socket
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
URL_REGEX = re.compile('http(s)?\://([\w\.-]*)(\:(\d+))?(/.*)?')
class AtomService(object):
"""Performs Atom Publishing Protocol CRUD operations.
The AtomService contains methods to perform HTTP CRUD operations.
"""
# Default values for members
port = 80
ssl = False
# If debug is True, the HTTPConnection will display debug information
debug = False
def __init__(self, server=None, additional_headers=None):
"""Creates a new AtomService client.
Args:
server: string (optional) The start of a URL for the server
to which all operations should be directed. Example:
'www.google.com'
additional_headers: dict (optional) Any additional HTTP headers which
should be included with CRUD operations.
"""
self.server = server
self.additional_headers = additional_headers or {}
self.additional_headers['User-Agent'] = 'Python Google Data Client Lib'
def _ProcessUrl(self, url, for_proxy=False):
"""Processes a passed URL. If the URL does not begin with https?, then
the default value for self.server is used"""
return ProcessUrl(self, url, for_proxy=for_proxy)
def 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
"""
UseBasicAuth(self, username, password, for_proxy=for_proxy)
def PrepareConnection(self, full_uri):
"""Opens a connection to the server based on the full URI.
Examines the target URI and the proxy settings, which are set as
environment variables, to open a connection with the server. This
connection is used to make an HTTP request.
Args:
full_uri: str Which is the target relative (lacks protocol and host) or
absolute URL to be opened. Example:
'https://www.google.com/accounts/ClientLogin' or
'base/feeds/snippets' where the server is set to www.google.com.
Returns:
A tuple containing the httplib.HTTPConnection and the full_uri for the
request.
"""
return PrepareConnection(self, full_uri)
# Alias the old name for the above method to preserve backwards
# compatibility.
_PrepareConnection = PrepareConnection
# CRUD operations
def Get(self, uri, extra_headers=None, url_params=None, escape_params=True):
"""Query the APP server with the given URI
The uri is the portion of the URI after the server value
(server example: 'www.google.com').
Example use:
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: dicty (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.
url_params: dict (optional) Additional URL parameters to be included
in the query. 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.
Returns:
httplib.HTTPResponse The server's response to the GET request.
"""
return HttpRequest(self, 'GET', None, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params)
def Post(self, data, uri, extra_headers=None, url_params=None,
escape_params=True, content_type='application/atom+xml'):
"""Insert data into an APP server at the given URI.
Args:
data: string, ElementTree._Element, or something with a __str__ method
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.
Returns:
httplib.HTTPResponse Server's response to the POST request.
"""
return HttpRequest(self, 'POST', data, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params,
content_type=content_type)
def Put(self, data, uri, extra_headers=None, url_params=None,
escape_params=True, content_type='application/atom+xml'):
"""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.
Returns:
httplib.HTTPResponse Server's response to the PUT request.
"""
return HttpRequest(self, 'PUT', data, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params,
content_type=content_type)
def Delete(self, uri, extra_headers=None, url_params=None,
escape_params=True):
"""Deletes the entry at the given URI.
Args:
uri: string The URI of the entry to be deleted. Example:
'/base/feeds/items/ITEM-ID'
extra_headers: dict (optional) HTTP headers which are to be included.
The client automatically sets the Content-Type and
Authorization 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.
Returns:
httplib.HTTPResponse Server's response to the DELETE request.
"""
return HttpRequest(self, 'DELETE', None, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params)
def HttpRequest(service, operation, data, uri, extra_headers=None,
url_params=None, escape_params=True, content_type='application/atom+xml'):
"""Performs an HTTP call to the server, supports GET, POST, PUT, and DELETE.
Usage example, perform and HTTP GET on http://www.google.com/:
import atom.service
client = atom.service.AtomService()
http_response = client.Get('http://www.google.com/')
or you could set the client.server to 'www.google.com' and use the
following:
client.server = 'www.google.com'
http_response = client.Get('/')
Args:
service: atom.AtomService object which contains some of the parameters
needed to make the request. The following members are used to
construct the HTTP call: server (str), additional_headers (dict),
port (int), and ssl (bool).
operation: str The HTTP operation to be performed. This is usually one of
'GET', 'POST', 'PUT', or 'DELETE'
data: ElementTree, filestream, list of parts, or other object which can be
converted to a string.
Should be set to None when performing a GET or PUT.
If data is a file-like object which can be read, this method will read
a chunk of 100K bytes at a time and send them.
If the data is a list of parts to be sent, each part will be evaluated
and sent.
uri: The beginning of the URL to which the request should be sent.
Examples: '/', '/base/feeds/snippets',
'/m8/feeds/contacts/default/base'
extra_headers: dict of strings. HTTP headers which should be sent
in the request. These headers are in addition to those stored in
service.additional_headers.
url_params: dict of strings. Key value pairs to be added to the URL as
URL parameters. For example {'foo':'bar', 'test':'param'} will
become ?foo=bar&test=param.
escape_params: bool default True. If true, the keys and values in
url_params will be URL escaped when the form is constructed
(Special characters converted to %XX form.)
content_type: str The MIME type for the data being sent. Defaults to
'application/atom+xml', this is only used if data is set.
"""
full_uri = BuildUri(uri, url_params, escape_params)
(connection, full_uri) = PrepareConnection(service, full_uri)
if extra_headers is None:
extra_headers = {}
# Turn on debug mode if the debug member is set.
if service.debug:
connection.debuglevel = 1
connection.putrequest(operation, full_uri)
# If the list of headers does not include a Content-Length, attempt to
# calculate it based on the data object.
if (data and not service.additional_headers.has_key('Content-Length') and
not extra_headers.has_key('Content-Length')):
content_length = __CalculateDataLength(data)
if content_length:
extra_headers['Content-Length'] = str(content_length)
if content_type:
extra_headers['Content-Type'] = content_type
# Send the HTTP headers.
if isinstance(service.additional_headers, dict):
for header in service.additional_headers:
connection.putheader(header, service.additional_headers[header])
if isinstance(extra_headers, dict):
for header in extra_headers:
connection.putheader(header, extra_headers[header])
connection.endheaders()
# If there is data, send it in the request.
if data:
if isinstance(data, list):
for data_part in data:
__SendDataPart(data_part, connection)
else:
__SendDataPart(data, connection)
# Return the HTTP Response from the server.
return connection.getresponse()
def __SendDataPart(data, connection):
if isinstance(data, str):
#TODO add handling for unicode.
connection.send(data)
return
elif ElementTree.iselement(data):
connection.send(ElementTree.tostring(data))
return
# Check to see if data is a file-like object that has a read method.
elif hasattr(data, 'read'):
# Read the file and send it a chunk at a time.
while 1:
binarydata = data.read(100000)
if binarydata == '': break
connection.send(binarydata)
return
else:
# The data object was not a file.
# Try to convert to a string and send the data.
connection.send(str(data))
return
def __CalculateDataLength(data):
"""Attempts to determine the length of the data to send.
This method will respond with a length only if the data is a string or
and ElementTree element.
Args:
data: object If this is not a string or ElementTree element this funtion
will return None.
"""
if isinstance(data, str):
return len(data)
elif isinstance(data, list):
return None
elif ElementTree.iselement(data):
return len(ElementTree.tostring(data))
elif hasattr(data, 'read'):
# If this is a file-like object, don't try to guess the length.
return None
else:
return len(str(data))
def PrepareConnection(service, full_uri):
"""Opens a connection to the server based on the full URI.
Examines the target URI and the proxy settings, which are set as
environment variables, to open a connection with the server. This
connection is used to make an HTTP request.
Args:
service: atom.AtomService or a subclass. It must have a server string which
represents the server host to which the request should be made. It may also
have a dictionary of additional_headers to send in the HTTP request.
full_uri: str Which is the target relative (lacks protocol and host) or
absolute URL to be opened. Example:
'https://www.google.com/accounts/ClientLogin' or
'base/feeds/snippets' where the server is set to www.google.com.
Returns:
A tuple containing the httplib.HTTPConnection and the full_uri for the
request.
"""
(server, port, ssl, partial_uri) = ProcessUrl(service, full_uri)
if ssl:
# destination is https
proxy = os.environ.get('https_proxy')
if proxy:
(p_server, p_port, p_ssl, p_uri) = ProcessUrl(service, proxy, True)
proxy_username = os.environ.get('proxy-username')
if not proxy_username:
proxy_username = os.environ.get('proxy_username')
proxy_password = os.environ.get('proxy-password')
if not proxy_password:
proxy_password = os.environ.get('proxy_password')
if proxy_username:
user_auth = base64.encodestring('%s:%s' % (proxy_username,
proxy_password))
proxy_authorization = ('Proxy-authorization: Basic %s\r\n' % (
user_auth.strip()))
else:
proxy_authorization = ''
proxy_connect = 'CONNECT %s:%s HTTP/1.0\r\n' % (server, port)
user_agent = 'User-Agent: %s\r\n' % (
service.additional_headers['User-Agent'])
proxy_pieces = (proxy_connect + proxy_authorization + user_agent
+ '\r\n')
#now connect, very simple recv and error checking
p_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
p_sock.connect((p_server,p_port))
p_sock.sendall(proxy_pieces)
response = ''
# Wait for the full response.
while response.find("\r\n\r\n") == -1:
response += p_sock.recv(8192)
p_status=response.split()[1]
if p_status!=str(200):
raise 'Error status=',str(p_status)
# Trivial setup for ssl socket.
ssl = socket.ssl(p_sock, None, None)
fake_sock = httplib.FakeSocket(p_sock, ssl)
# Initalize httplib and replace with the proxy socket.
connection = httplib.HTTPConnection(server)
connection.sock=fake_sock
full_uri = partial_uri
else:
connection = httplib.HTTPSConnection(server, port)
full_uri = partial_uri
else:
# destination is http
proxy = os.environ.get('http_proxy')
if proxy:
(p_server, p_port, p_ssl, p_uri) = ProcessUrl(service.server, proxy, True)
proxy_username = os.environ.get('proxy-username')
if not proxy_username:
proxy_username = os.environ.get('proxy_username')
proxy_password = os.environ.get('proxy-password')
if not proxy_password:
proxy_password = os.environ.get('proxy_password')
if proxy_username:
UseBasicAuth(service, proxy_username, proxy_password, True)
connection = httplib.HTTPConnection(p_server, p_port)
if not full_uri.startswith("http://"):
if full_uri.startswith("/"):
full_uri = "http://%s%s" % (service.server, full_uri)
else:
full_uri = "http://%s/%s" % (service.server, full_uri)
else:
connection = httplib.HTTPConnection(server, port)
full_uri = partial_uri
return (connection, full_uri)
def UseBasicAuth(service, 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. The auth header is added to the
additional_headers dictionary in the service object.
Args:
service: atom.AtomService or a subclass which has an
additional_headers dict as a member.
username: str
password: str
"""
base_64_string = base64.encodestring('%s:%s' % (username, password))
base_64_string = base_64_string.strip()
if for_proxy:
header_name = 'Proxy-Authorization'
else:
header_name = 'Authorization'
service.additional_headers[header_name] = 'Basic %s' % (base_64_string,)
def ProcessUrl(service, url, for_proxy=False):
"""Processes a passed URL. If the URL does not begin with https?, then
the default value for server is used"""
server = None
port = 80
ssl = False
if hasattr(service, 'server'):
server = service.server
else:
server = service
if not for_proxy:
if hasattr(service, 'port'):
port = service.port
if hasattr(service, 'ssl'):
ssl = service.ssl
uri = url
m = URL_REGEX.match(url)
if m is None:
return (server, port, ssl, uri)
else:
if m.group(1) is not None:
port = 443
ssl = True
if m.group(3) is None:
server = m.group(2)
else:
server = m.group(2)
port = int(m.group(4))
if m.group(5) is not None:
uri = m.group(5)
else:
uri = '/'
return (server, port, ssl, uri)
def DictionaryToParamList(url_parameters, escape_params=True):
"""Convert a dictionary of URL arguments into a URL parameter string.
Args:
url_parameters: The dictionaty of key-value pairs which will be converted
into URL parameters. For example,
{'dry-run': 'true', 'foo': 'bar'}
will become ['dry-run=true', 'foo=bar'].
Returns:
A list which contains a string for each key-value pair. The strings are
ready to be incorporated into a URL by using '&'.join([] + parameter_list)
"""
# Choose which function to use when modifying the query and parameters.
# Use quote_plus when escape_params is true.
transform_op = [str, urllib.quote_plus][bool(escape_params)]
# Create a list of tuples containing the escaped version of the
# parameter-value pairs.
parameter_tuples = [(transform_op(param), transform_op(value))
for param, value in (url_parameters or {}).items()]
# Turn parameter-value tuples into a list of strings in the form
# 'PARAMETER=VALUE'.
return ['='.join(x) for x in parameter_tuples]
def BuildUri(uri, url_params=None, escape_params=True):
"""Converts a uri string and a collection of parameters into a URI.
Args:
uri: string
url_params: dict (optional)
escape_params: boolean (optional)
uri: string The start of the desired URI. This string can alrady contain
URL parameters. Examples: '/base/feeds/snippets',
'/base/feeds/snippets?bq=digital+camera'
url_parameters: dict (optional) Additional URL parameters to be included
in the query. 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.
Returns:
string The URI consisting of the escaped URL parameters appended to the
initial uri string.
"""
# Prepare URL parameters for inclusion into the GET request.
parameter_list = DictionaryToParamList(url_params, escape_params)
# Append the URL parameters to the URL.
if parameter_list:
if uri.find('?') != -1:
# If there are already URL parameters in the uri string, add the
# parameters after a new & character.
full_uri = '&'.join([uri] + parameter_list)
else:
# The uri string did not have any URL parameters (no ? character)
# so put a ? between the uri and URL parameters.
full_uri = '%s%s' % (uri, '?%s' % ('&'.join([] + parameter_list)))
else:
full_uri = uri
return full_uri
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains classes representing Atom elements.
Module objective: provide data classes for Atom constructs. These classes hide
the XML-ness of Atom and provide a set of native Python classes to interact
with.
Conversions to and from XML should only be necessary when the Atom classes
"touch the wire" and are sent over HTTP. For this reason this module
provides methods and functions to convert Atom classes to and from strings.
For more information on the Atom data model, see RFC 4287
(http://www.ietf.org/rfc/rfc4287.txt)
AtomBase: A foundation class on which Atom classes are built. It
handles the parsing of attributes and children which are common to all
Atom classes. By default, the AtomBase class translates all XML child
nodes into ExtensionElements.
ExtensionElement: Atom allows Atom objects to contain XML which is not part
of the Atom specification, these are called extension elements. If a
classes parser encounters an unexpected XML construct, it is translated
into an ExtensionElement instance. ExtensionElement is designed to fully
capture the information in the XML. Child nodes in an XML extension are
turned into ExtensionElements as well.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
# XML namespaces which are often used in Atom entities.
ATOM_NAMESPACE = 'http://www.w3.org/2005/Atom'
ELEMENT_TEMPLATE = '{http://www.w3.org/2005/Atom}%s'
APP_NAMESPACE = 'http://purl.org/atom/app#'
APP_TEMPLATE = '{http://purl.org/atom/app#}%s'
# This encoding is used for converting strings before translating the XML
# into an object.
XML_STRING_ENCODING = 'utf-8'
# The desired string encoding for object members.
MEMBER_STRING_ENCODING = 'utf-8'
def CreateClassFromXMLString(target_class, xml_string, string_encoding=None):
"""Creates an instance of the target class from the string contents.
Args:
target_class: class The class which will be instantiated and populated
with the contents of the XML. This class must have a _tag and a
_namespace class variable.
xml_string: str A string which contains valid XML. The root element
of the XML string should match the tag and namespace of the desired
class.
string_encoding: str The character encoding which the xml_string should
be converted to before it is interpreted and translated into
objects. The default is None in which case the string encoding
is not changed.
Returns:
An instance of the target class with members assigned according to the
contents of the XML - or None if the root XML tag and namespace did not
match those of the target class.
"""
encoding = string_encoding or XML_STRING_ENCODING
if encoding and isinstance(xml_string, unicode):
xml_string = xml_string.encode(encoding)
tree = ElementTree.fromstring(xml_string)
return _CreateClassFromElementTree(target_class, tree)
def _CreateClassFromElementTree(target_class, tree, namespace=None, tag=None):
"""Instantiates the class and populates members according to the tree.
Note: Only use this function with classes that have _namespace and _tag
class members.
Args:
target_class: class The class which will be instantiated and populated
with the contents of the XML.
tree: ElementTree An element tree whose contents will be converted into
members of the new target_class instance.
namespace: str (optional) The namespace which the XML tree's root node must
match. If omitted, the namespace defaults to the _namespace of the
target class.
tag: str (optional) The tag which the XML tree's root node must match. If
omitted, the tag defaults to the _tag class member of the target
class.
Returns:
An instance of the target class - or None if the tag and namespace of
the XML tree's root node did not match the desired namespace and tag.
"""
if namespace is None:
namespace = target_class._namespace
if tag is None:
tag = target_class._tag
if tree.tag == '{%s}%s' % (namespace, tag):
target = target_class()
target._HarvestElementTree(tree)
return target
else:
return None
class ExtensionContainer(object):
def __init__(self, extension_elements=None, extension_attributes=None,
text=None):
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
# Three methods to create an object from an ElementTree
def _HarvestElementTree(self, tree):
# Fill in the instance members from the contents of the XML tree.
for child in tree:
self._ConvertElementTreeToMember(child)
for attribute, value in tree.attrib.iteritems():
self._ConvertElementAttributeToMember(attribute, value)
# Encode the text string according to the desired encoding type. (UTF-8)
if tree.text:
self.text = tree.text.encode(MEMBER_STRING_ENCODING)
def _ConvertElementTreeToMember(self, child_tree, current_class=None):
self.extension_elements.append(_ExtensionElementFromElementTree(
child_tree))
def _ConvertElementAttributeToMember(self, attribute, value):
# Encode the attribute value's string with the desired type Default UTF-8
if value:
self.extension_attributes[attribute] = value.encode(
MEMBER_STRING_ENCODING)
# One method to create an ElementTree from an object
def _AddMembersToElementTree(self, tree):
for child in self.extension_elements:
child._BecomeChildElement(tree)
for attribute, value in self.extension_attributes.iteritems():
if value:
# Decode the value from the desired encoding (default UTF-8).
tree.attrib[attribute] = value.decode(MEMBER_STRING_ENCODING)
if self.text and not isinstance(self.text, unicode):
tree.text = self.text.decode(MEMBER_STRING_ENCODING)
else:
tree.text = self.text
def FindExtensions(self, tag=None, namespace=None):
"""Searches extension elements for child nodes with the desired name.
Returns a list of extension elements within this object whose tag
and/or namespace match those passed in. To find all extensions in
a particular namespace, specify the namespace but not the tag name.
If you specify only the tag, the result list may contain extension
elements in multiple namespaces.
Args:
tag: str (optional) The desired tag
namespace: str (optional) The desired namespace
Returns:
A list of elements whose tag and/or namespace match the parameters
values
"""
results = []
if tag and namespace:
for element in self.extension_elements:
if element.tag == tag and element.namespace == namespace:
results.append(element)
elif tag and not namespace:
for element in self.extension_elements:
if element.tag == tag:
results.append(element)
elif namespace and not tag:
for element in self.extension_elements:
if element.namespace == namespace:
results.append(element)
else:
for element in self.extension_elements:
results.append(element)
return results
class AtomBase(ExtensionContainer):
_children = {}
_attributes = {}
def __init__(self, extension_elements=None, extension_attributes=None,
text=None):
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
def _ConvertElementTreeToMember(self, child_tree):
# Find the element's tag in this class's list of child members
if self.__class__._children.has_key(child_tree.tag):
member_name = self.__class__._children[child_tree.tag][0]
member_class = self.__class__._children[child_tree.tag][1]
# If the class member is supposed to contain a list, make sure the
# matching member is set to a list, then append the new member
# instance to the list.
if isinstance(member_class, list):
if getattr(self, member_name) is None:
setattr(self, member_name, [])
getattr(self, member_name).append(_CreateClassFromElementTree(
member_class[0], child_tree))
else:
setattr(self, member_name,
_CreateClassFromElementTree(member_class, child_tree))
else:
ExtensionContainer._ConvertElementTreeToMember(self, child_tree)
def _ConvertElementAttributeToMember(self, attribute, value):
# Find the attribute in this class's list of attributes.
if self.__class__._attributes.has_key(attribute):
# Find the member of this class which corresponds to the XML attribute
# (lookup in current_class._attributes) and set this member to the
# desired value (using self.__dict__).
if value:
# Encode the string to capture non-ascii characters (default UTF-8)
setattr(self, self.__class__._attributes[attribute],
value.encode(MEMBER_STRING_ENCODING))
else:
ExtensionContainer._ConvertElementAttributeToMember(self, attribute,
value)
# Three methods to create an ElementTree from an object
def _AddMembersToElementTree(self, tree):
# Convert the members of this class which are XML child nodes.
# This uses the class's _children dictionary to find the members which
# should become XML child nodes.
member_node_names = [values[0] for tag, values in
self.__class__._children.iteritems()]
for member_name in member_node_names:
member = getattr(self, member_name)
if member is None:
pass
elif isinstance(member, list):
for instance in member:
instance._BecomeChildElement(tree)
else:
member._BecomeChildElement(tree)
# Convert the members of this class which are XML attributes.
for xml_attribute, member_name in self.__class__._attributes.iteritems():
member = getattr(self, member_name)
if member is not None:
tree.attrib[xml_attribute] = member.decode(MEMBER_STRING_ENCODING)
# Lastly, call the ExtensionContainers's _AddMembersToElementTree to
# convert any extension attributes.
ExtensionContainer._AddMembersToElementTree(self, tree)
def _BecomeChildElement(self, tree):
"""
Note: Only for use with classes that have a _tag and _namespace class
member. It is in AtomBase so that it can be inherited but it should
not be called on instances of AtomBase.
"""
new_child = ElementTree.Element('')
tree.append(new_child)
new_child.tag = '{%s}%s' % (self.__class__._namespace,
self.__class__._tag)
self._AddMembersToElementTree(new_child)
def _ToElementTree(self):
"""
Note, this method is designed to be used only with classes that have a
_tag and _namespace. It is placed in AtomBase for inheritance but should
not be called on this class.
"""
new_tree = ElementTree.Element('{%s}%s' % (self.__class__._namespace,
self.__class__._tag))
self._AddMembersToElementTree(new_tree)
return new_tree
def ToString(self, string_encoding='UTF-8'):
"""Converts the Atom object to a string containing XML."""
return ElementTree.tostring(self._ToElementTree(), encoding=string_encoding)
def __str__(self):
return self.ToString()
class Name(AtomBase):
"""The atom:name element"""
_tag = 'name'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Name
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def NameFromString(xml_string):
return CreateClassFromXMLString(Name, xml_string)
class Email(AtomBase):
"""The atom:email element"""
_tag = 'email'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Email
Args:
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def EmailFromString(xml_string):
return CreateClassFromXMLString(Email, xml_string)
class Uri(AtomBase):
"""The atom:uri element"""
_tag = 'uri'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Uri
Args:
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def UriFromString(xml_string):
return CreateClassFromXMLString(Uri, xml_string)
class Person(AtomBase):
"""A foundation class from which atom:author and atom:contributor extend.
A person contains information like name, email address, and web page URI for
an author or contributor to an Atom feed.
"""
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_children['{%s}name' % (ATOM_NAMESPACE)] = ('name', Name)
_children['{%s}email' % (ATOM_NAMESPACE)] = ('email', Email)
_children['{%s}uri' % (ATOM_NAMESPACE)] = ('uri', Uri)
def __init__(self, name=None, email=None, uri=None,
extension_elements=None, extension_attributes=None, text=None):
"""Foundation from which author and contributor are derived.
The constructor is provided for illustrative purposes, you should not
need to instantiate a Person.
Args:
name: Name The person's name
email: Email The person's email address
uri: Uri The URI of the person's webpage
extension_elements: list A list of ExtensionElement instances which are
children of this element.
extension_attributes: dict A dictionary of strings which are the values
for additional XML attributes of this element.
text: String The text contents of the element. This is the contents
of the Entry's XML text node. (Example: <foo>This is the text</foo>)
"""
self.name = name
self.email = email
self.uri = uri
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
class Author(Person):
"""The atom:author element
An author is a required element in Feed.
"""
_tag = 'author'
_namespace = ATOM_NAMESPACE
_children = Person._children.copy()
_attributes = Person._attributes.copy()
#_children = {}
#_attributes = {}
def __init__(self, name=None, email=None, uri=None,
extension_elements=None, extension_attributes=None, text=None):
"""Constructor for Author
Args:
name: Name
email: Email
uri: Uri
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.name = name
self.email = email
self.uri = uri
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
def AuthorFromString(xml_string):
return CreateClassFromXMLString(Author, xml_string)
class Contributor(Person):
"""The atom:contributor element"""
_tag = 'contributor'
_namespace = ATOM_NAMESPACE
_children = Person._children.copy()
_attributes = Person._attributes.copy()
def __init__(self, name=None, email=None, uri=None,
extension_elements=None, extension_attributes=None, text=None):
"""Constructor for Contributor
Args:
name: Name
email: Email
uri: Uri
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.name = name
self.email = email
self.uri = uri
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
def ContributorFromString(xml_string):
return CreateClassFromXMLString(Contributor, xml_string)
class Link(AtomBase):
"""The atom:link element"""
_tag = 'link'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_attributes['rel'] = 'rel'
_attributes['href'] = 'href'
_attributes['type'] = 'type'
_attributes['title'] = 'title'
_attributes['length'] = 'length'
_attributes['hreflang'] = 'hreflang'
def __init__(self, href=None, rel=None, link_type=None, hreflang=None,
title=None, length=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Link
Args:
href: string The href attribute of the link
rel: string
type: string
hreflang: string The language for the href
title: string
length: string The length of the href's destination
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.href = href
self.rel = rel
self.type = link_type
self.hreflang = hreflang
self.title = title
self.length = length
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def LinkFromString(xml_string):
return CreateClassFromXMLString(Link, xml_string)
class Generator(AtomBase):
"""The atom:generator element"""
_tag = 'generator'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_attributes['uri'] = 'uri'
_attributes['version'] = 'version'
def __init__(self, uri=None, version=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for Generator
Args:
uri: string
version: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.uri = uri
self.version = version
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GeneratorFromString(xml_string):
return CreateClassFromXMLString(Generator, xml_string)
class Text(AtomBase):
"""A foundation class from which atom:title, summary, etc. extend.
This class should never be instantiated.
"""
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_attributes['type'] = 'type'
def __init__(self, text_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Text
Args:
text_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = text_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Title(Text):
"""The atom:title element"""
_tag = 'title'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
def __init__(self, title_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Title
Args:
title_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = title_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def TitleFromString(xml_string):
return CreateClassFromXMLString(Title, xml_string)
class Subtitle(Text):
"""The atom:subtitle element"""
_tag = 'subtitle'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
def __init__(self, subtitle_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Subtitle
Args:
subtitle_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = subtitle_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SubtitleFromString(xml_string):
return CreateClassFromXMLString(Subtitle, xml_string)
class Rights(Text):
"""The atom:rights element"""
_tag = 'rights'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
def __init__(self, rights_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Rights
Args:
rights_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = rights_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def RightsFromString(xml_string):
return CreateClassFromXMLString(Rights, xml_string)
class Summary(Text):
"""The atom:summary element"""
_tag = 'summary'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
def __init__(self, summary_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Summary
Args:
summary_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = summary_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SummaryFromString(xml_string):
return CreateClassFromXMLString(Summary, xml_string)
class Content(Text):
"""The atom:content element"""
_tag = 'content'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
_attributes['src'] = 'src'
def __init__(self, content_type=None, src=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for Content
Args:
content_type: string
src: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = content_type
self.src = src
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ContentFromString(xml_string):
return CreateClassFromXMLString(Content, xml_string)
class Category(AtomBase):
"""The atom:category element"""
_tag = 'category'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_attributes['term'] = 'term'
_attributes['scheme'] = 'scheme'
_attributes['label'] = 'label'
def __init__(self, term=None, scheme=None, label=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for Category
Args:
term: str
scheme: str
label: str
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.term = term
self.scheme = scheme
self.label = label
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def CategoryFromString(xml_string):
return CreateClassFromXMLString(Category, xml_string)
class Id(AtomBase):
"""The atom:id element."""
_tag = 'id'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Id
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def IdFromString(xml_string):
return CreateClassFromXMLString(Id, xml_string)
class Icon(AtomBase):
"""The atom:icon element."""
_tag = 'icon'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Icon
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def IconFromString(xml_string):
return CreateClassFromXMLString(Icon, xml_string)
class Logo(AtomBase):
"""The atom:logo element."""
_tag = 'logo'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Logo
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def LogoFromString(xml_string):
return CreateClassFromXMLString(Logo, xml_string)
class Draft(AtomBase):
"""The app:draft element which indicates if this entry should be public."""
_tag = 'draft'
_namespace = APP_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for app:draft
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def DraftFromString(xml_string):
return CreateClassFromXMLString(Draft, xml_string)
class Control(AtomBase):
"""The app:control element indicating restrictions on publication.
The APP control element may contain a draft element indicating whether or
not this entry should be publicly available.
"""
_tag = 'control'
_namespace = APP_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_children['{%s}draft' % APP_NAMESPACE] = ('draft', Draft)
def __init__(self, draft=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for app:control"""
self.draft = draft
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ControlFromString(xml_string):
return CreateClassFromXMLString(Control, xml_string)
class Date(AtomBase):
"""A parent class for atom:updated, published, etc."""
#TODO Add text to and from time conversion methods to allow users to set
# the contents of a Date to a python DateTime object.
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Updated(Date):
"""The atom:updated element."""
_tag = 'updated'
_namespace = ATOM_NAMESPACE
_children = Date._children.copy()
_attributes = Date._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Updated
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def UpdatedFromString(xml_string):
return CreateClassFromXMLString(Updated, xml_string)
class Published(Date):
"""The atom:published element."""
_tag = 'published'
_namespace = ATOM_NAMESPACE
_children = Date._children.copy()
_attributes = Date._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Published
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def PublishedFromString(xml_string):
return CreateClassFromXMLString(Published, xml_string)
class LinkFinder(object):
"""An "interface" providing methods to find link elements
Entry elements often contain multiple links which differ in the rel
attribute or content type. Often, developers are interested in a specific
type of link so this class provides methods to find specific classes of
links.
This class is used as a mixin in Atom entries and feeds.
"""
def GetSelfLink(self):
"""Find the first link with rel set to 'self'
Returns:
An atom.Link or none if none of the links had rel equal to 'self'
"""
for a_link in self.link:
if a_link.rel == 'self':
return a_link
return None
def GetEditLink(self):
for a_link in self.link:
if a_link.rel == 'edit':
return a_link
return None
def GetNextLink(self):
for a_link in self.link:
if a_link.rel == 'next':
return a_link
return None
def GetLicenseLink(self):
for a_link in self.link:
if a_link.rel == 'license':
return a_link
return None
def GetAlternateLink(self):
for a_link in self.link:
if a_link.rel == 'alternate':
return a_link
return None
class FeedEntryParent(AtomBase, LinkFinder):
"""A super class for atom:feed and entry, contains shared attributes"""
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_children['{%s}author' % ATOM_NAMESPACE] = ('author', [Author])
_children['{%s}category' % ATOM_NAMESPACE] = ('category', [Category])
_children['{%s}contributor' % ATOM_NAMESPACE] = ('contributor', [Contributor])
_children['{%s}id' % ATOM_NAMESPACE] = ('id', Id)
_children['{%s}link' % ATOM_NAMESPACE] = ('link', [Link])
_children['{%s}rights' % ATOM_NAMESPACE] = ('rights', Rights)
_children['{%s}title' % ATOM_NAMESPACE] = ('title', Title)
_children['{%s}updated' % ATOM_NAMESPACE] = ('updated', Updated)
def __init__(self, author=None, category=None, contributor=None,
atom_id=None, link=None, rights=None, title=None, updated=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.rights = rights
self.title = title
self.updated = updated
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Source(FeedEntryParent):
"""The atom:source element"""
_tag = 'source'
_namespace = ATOM_NAMESPACE
_children = FeedEntryParent._children.copy()
_attributes = FeedEntryParent._attributes.copy()
_children['{%s}generator' % ATOM_NAMESPACE] = ('generator', Generator)
_children['{%s}icon' % ATOM_NAMESPACE] = ('icon', Icon)
_children['{%s}logo' % ATOM_NAMESPACE] = ('logo', Logo)
_children['{%s}subtitle' % ATOM_NAMESPACE] = ('subtitle', Subtitle)
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for Source
Args:
author: list (optional) A list of Author instances which belong to this
class.
category: list (optional) A list of Category instances
contributor: list (optional) A list on Contributor instances
generator: Generator (optional)
icon: Icon (optional)
id: Id (optional) The entry's Id element
link: list (optional) A list of Link instances
logo: Logo (optional)
rights: Rights (optional) The entry's Rights element
subtitle: Subtitle (optional) The entry's subtitle element
title: Title (optional) the entry's title element
updated: Updated (optional) the entry's updated element
text: String (optional) The text contents of the element. This is the
contents of the Entry's XML text node.
(Example: <foo>This is the text</foo>)
extension_elements: list (optional) A list of ExtensionElement instances
which are children of this element.
extension_attributes: dict (optional) A dictionary of strings which are
the values for additional XML attributes of this element.
"""
self.author = author or []
self.category = category or []
self.contributor = contributor or []
self.generator = generator
self.icon = icon
self.id = atom_id
self.link = link or []
self.logo = logo
self.rights = rights
self.subtitle = subtitle
self.title = title
self.updated = updated
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SourceFromString(xml_string):
return CreateClassFromXMLString(Source, xml_string)
class Entry(FeedEntryParent):
"""The atom:entry element"""
_tag = 'entry'
_namespace = ATOM_NAMESPACE
_children = FeedEntryParent._children.copy()
_attributes = FeedEntryParent._attributes.copy()
_children['{%s}content' % ATOM_NAMESPACE] = ('content', Content)
_children['{%s}published' % ATOM_NAMESPACE] = ('published', Published)
_children['{%s}source' % ATOM_NAMESPACE] = ('source', Source)
_children['{%s}summary' % ATOM_NAMESPACE] = ('summary', Summary)
_children['{%s}control' % APP_NAMESPACE] = ('control', Control)
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, control=None, title=None, updated=None,
extension_elements=None, extension_attributes=None, text=None):
"""Constructor for atom:entry
Args:
author: list A list of Author instances which belong to this class.
category: list A list of Category instances
content: Content The entry's Content
contributor: list A list on Contributor instances
id: Id The entry's Id element
link: list A list of Link instances
published: Published The entry's Published element
rights: Rights The entry's Rights element
source: Source the entry's source element
summary: Summary the entry's summary element
title: Title the entry's title element
updated: Updated the entry's updated element
control: The entry's app:control element which can be used to mark an
entry as a draft which should not be publicly viewable.
text: String The text contents of the element. This is the contents
of the Entry's XML text node. (Example: <foo>This is the text</foo>)
extension_elements: list A list of ExtensionElement instances which are
children of this element.
extension_attributes: dict A dictionary of strings which are the values
for additional XML attributes of this element.
"""
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.title = title
self.updated = updated
self.control = control
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def EntryFromString(xml_string):
return CreateClassFromXMLString(Entry, xml_string)
class Feed(Source):
"""The atom:feed element"""
_tag = 'feed'
_namespace = ATOM_NAMESPACE
_children = Source._children.copy()
_attributes = Source._attributes.copy()
_children['{%s}entry' % ATOM_NAMESPACE] = ('entry', [Entry])
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None, entry=None,
text=None, extension_elements=None, extension_attributes=None):
"""Constructor for Source
Args:
author: list (optional) A list of Author instances which belong to this
class.
category: list (optional) A list of Category instances
contributor: list (optional) A list on Contributor instances
generator: Generator (optional)
icon: Icon (optional)
id: Id (optional) The entry's Id element
link: list (optional) A list of Link instances
logo: Logo (optional)
rights: Rights (optional) The entry's Rights element
subtitle: Subtitle (optional) The entry's subtitle element
title: Title (optional) the entry's title element
updated: Updated (optional) the entry's updated element
entry: list (optional) A list of the Entry instances contained in the
feed.
text: String (optional) The text contents of the element. This is the
contents of the Entry's XML text node.
(Example: <foo>This is the text</foo>)
extension_elements: list (optional) A list of ExtensionElement instances
which are children of this element.
extension_attributes: dict (optional) A dictionary of strings which are
the values for additional XML attributes of this element.
"""
self.author = author or []
self.category = category or []
self.contributor = contributor or []
self.generator = generator
self.icon = icon
self.id = atom_id
self.link = link or []
self.logo = logo
self.rights = rights
self.subtitle = subtitle
self.title = title
self.updated = updated
self.entry = entry or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def FeedFromString(xml_string):
return CreateClassFromXMLString(Feed, xml_string)
class ExtensionElement(object):
"""Represents extra XML elements contained in Atom classes."""
def __init__(self, tag, namespace=None, attributes=None,
children=None, text=None):
"""Constructor for EtensionElement
Args:
namespace: string (optional) The XML namespace for this element.
tag: string (optional) The tag (without the namespace qualifier) for
this element. To reconstruct the full qualified name of the element,
combine this tag with the namespace.
attributes: dict (optinal) The attribute value string pairs for the XML
attributes of this element.
children: list (optional) A list of ExtensionElements which represent
the XML child nodes of this element.
"""
self.namespace = namespace
self.tag = tag
self.attributes = attributes or {}
self.children = children or []
self.text = text
def ToString(self):
element_tree = self._TransferToElementTree(ElementTree.Element(''))
return ElementTree.tostring(element_tree, encoding="UTF-8")
def _TransferToElementTree(self, element_tree):
if self.tag is None:
return None
if self.namespace is not None:
element_tree.tag = '{%s}%s' % (self.namespace, self.tag)
else:
element_tree.tag = self.tag
for key, value in self.attributes.iteritems():
element_tree.attrib[key] = value
for child in self.children:
child._BecomeChildElement(element_tree)
element_tree.text = self.text
return element_tree
def _BecomeChildElement(self, element_tree):
"""Converts this object into an etree element and adds it as a child node.
Adds self to the ElementTree. This method is required to avoid verbose XML
which constantly redefines the namespace.
Args:
element_tree: ElementTree._Element The element to which this object's XML
will be added.
"""
new_element = ElementTree.Element('')
element_tree.append(new_element)
self._TransferToElementTree(new_element)
def FindChildren(self, tag=None, namespace=None):
"""Searches child nodes for objects with the desired tag/namespace.
Returns a list of extension elements within this object whose tag
and/or namespace match those passed in. To find all children in
a particular namespace, specify the namespace but not the tag name.
If you specify only the tag, the result list may contain extension
elements in multiple namespaces.
Args:
tag: str (optional) The desired tag
namespace: str (optional) The desired namespace
Returns:
A list of elements whose tag and/or namespace match the parameters
values
"""
results = []
if tag and namespace:
for element in self.children:
if element.tag == tag and element.namespace == namespace:
results.append(element)
elif tag and not namespace:
for element in self.children:
if element.tag == tag:
results.append(element)
elif namespace and not tag:
for element in self.children:
if element.namespace == namespace:
results.append(element)
else:
for element in self.children:
results.append(element)
return results
def ExtensionElementFromString(xml_string):
element_tree = ElementTree.fromstring(xml_string)
return _ExtensionElementFromElementTree(element_tree)
def _ExtensionElementFromElementTree(element_tree):
element_tag = element_tree.tag
if '}' in element_tag:
namespace = element_tag[1:element_tag.index('}')]
tag = element_tag[element_tag.index('}')+1:]
else:
namespace = None
tag = element_tag
extension = ExtensionElement(namespace=namespace, tag=tag)
for key, value in element_tree.attrib.iteritems():
extension.attributes[key] = value
for child in element_tree:
extension.children.append(_ExtensionElementFromElementTree(child))
extension.text = element_tree.text
return extension
| Python |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import cgi
import gdata.service
import gdata.urlfetch
# Configure gdata python client to use app engine URL Fetch
gdata.service.http_request_handler = gdata.urlfetch
from gdata.spreadsheet.service import SpreadsheetsService
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class CardflasherClient(SpreadsheetsService):
"""Handle communication with the spreadsheet gdata service"""
def __init__(self):
SpreadsheetsService.__init__(self)
self.source = "markstahl-cardflasher-0.9"
self.email = 'markstahl.api@gmail.com'
self.password = 'testtest'
self.ProgrammaticLogin()
self.spreadsheet_key = 'pFTNU5W-U0barlRKCdCAaKg'
self.worksheet_key = 'od6'
def getAllEntries(self):
""" Get all cards in the card stack"""
feed = self.GetListFeed(self.spreadsheet_key, self.worksheet_key)
return feed.entry
def getEntry(self, url):
"""Get one card in the card stack"""
return self.Get(url, converter=gdata.spreadsheet.SpreadsheetsListFromString)
def updateEntry(self, url, entry):
return self.Put(entry, url, converter=gdata.spreadsheet.SpreadsheetsListFromString)
def insertEntry(self, row_dict):
return self.InsertRow(row_dict, self.spreadsheet_key, self.worksheet_key)
def deleteEntry(self, edit_url):
return self.Delete(edit_url)
class ListCards(webapp.RequestHandler):
def get(self):
client = CardflasherClient()
entries = client.getAllEntries()
self.response.out.write("<center><h1>Flashcard List</h1>")
self.response.out.write("<blockquote><table width='100%' border='1'>")
for entry in entries:
self.response.out.write("""
<tr align='center'>
<td>%s</td>
<td>%s</td>
<td>%s</td>
</tr>""" % (
entry.custom["front"].text,
entry.custom["back"].text,
entry.custom["score"].text))
self.response.out.write("</table></blockquote>")
class UnknownUrl(webapp.RequestHandler):
def get(self):
self.redirect('/')
def main():
application = webapp.WSGIApplication(
[
('/', ListCards),
(r'/.*', UnknownUrl),
],
debug=True)
run_wsgi_app(application)
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import cgi
import gdata.service
import gdata.urlfetch
# Configure gdata python client to use app engine URL Fetch
gdata.service.http_request_handler = gdata.urlfetch
from gdata.spreadsheet.service import SpreadsheetsService
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class CardflasherClient(SpreadsheetsService):
"""Handle communication with the spreadsheet gdata service"""
def __init__(self):
SpreadsheetsService.__init__(self)
self.source = "markstahl-cardflasher-0.9"
self.email = 'markstahl.api@gmail.com'
self.password = 'testtest'
self.ProgrammaticLogin()
self.spreadsheet_key = 'pFTNU5W-U0barlRKCdCAaKg'
self.worksheet_key = 'od6'
def getAllEntries(self):
""" Get all cards in the card stack"""
feed = self.GetListFeed(self.spreadsheet_key, self.worksheet_key)
return feed.entry
def getEntry(self, url):
"""Get one card in the card stack"""
return self.Get(url, converter=gdata.spreadsheet.SpreadsheetsListFromString)
def updateEntry(self, url, entry):
return self.Put(entry, url, converter=gdata.spreadsheet.SpreadsheetsListFromString)
def insertEntry(self, row_dict):
return self.InsertRow(row_dict, self.spreadsheet_key, self.worksheet_key)
def deleteEntry(self, edit_url):
return self.Delete(edit_url)
class ListCards(webapp.RequestHandler):
def get(self):
client = CardflasherClient()
entries = client.getAllEntries()
self.response.out.write("<center><h1>Flashcard List</h1>")
self.response.out.write("<blockquote><table width='100%' border='1'>")
for entry in entries:
self.response.out.write("""
<tr align='center'>
<td>%s</td>
<td>%s</td>
<td>%s</td>
</tr>""" % (
entry.custom["front"].text,
entry.custom["back"].text,
entry.custom["score"].text))
self.response.out.write("</table></blockquote>")
class UnknownUrl(webapp.RequestHandler):
def get(self):
self.redirect('/')
def main():
application = webapp.WSGIApplication(
[
('/', ListCards),
(r'/.*', UnknownUrl),
],
debug=True)
run_wsgi_app(application)
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
#
# Copyright (C) 2007, 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to Atom objects used with Blogger."""
__author__ = 'api.jscudder (Jeffrey Scudder)'
import atom
import gdata
import re
LABEL_SCHEME = 'http://www.blogger.com/atom/ns#'
THR_NAMESPACE = 'http://purl.org/syndication/thread/1.0'
class BloggerEntry(gdata.GDataEntry):
"""Adds convenience methods inherited by all Blogger entries."""
blog_name_pattern = re.compile('(http://)(\w*)')
blog_id_pattern = re.compile('(tag:blogger.com,1999:blog-)(\w*)')
def GetBlogId(self):
"""Extracts the Blogger id of this blog.
This method is useful when contructing URLs by hand. The blog id is
often used in blogger operation URLs. This should not be confused with
the id member of a BloggerBlog. The id element is the Atom id XML element.
The blog id which this method returns is a part of the Atom id.
Returns:
The blog's unique id as a string.
"""
if self.id.text:
return self.blog_id_pattern.match(self.id.text).group(2)
return None
def GetBlogName(self):
"""Finds the name of this blog as used in the 'alternate' URL.
An alternate URL is in the form 'http://blogName.blogspot.com/'. For an
entry representing the above example, this method would return 'blogName'.
Returns:
The blog's URL name component as a string.
"""
for link in self.link:
if link.rel == 'alternate':
return self.blog_name_pattern.match(link.href).group(2)
return None
class BlogEntry(BloggerEntry):
"""Describes a blog entry in the feed listing a user's blogs."""
def BlogEntryFromString(xml_string):
return atom.CreateClassFromXMLString(BlogEntry, xml_string)
class BlogFeed(gdata.GDataFeed):
"""Describes a feed of a user's blogs."""
_children = gdata.GDataFeed._children.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [BlogEntry])
def BlogFeedFromString(xml_string):
return atom.CreateClassFromXMLString(BlogFeed, xml_string)
class BlogPostEntry(BloggerEntry):
"""Describes a blog post entry in the feed of a blog's posts."""
post_id_pattern = re.compile('(tag:blogger.com,1999:blog-)(\w*)(.post-)(\w*)')
def AddLabel(self, label):
"""Adds a label to the blog post.
The label is represented by an Atom category element, so this method
is shorthand for appending a new atom.Category object.
Args:
label: str
"""
self.category.append(atom.Category(scheme=LABEL_SCHEME, term=label))
def GetPostId(self):
"""Extracts the postID string from the entry's Atom id.
Returns: A string of digits which identify this post within the blog.
"""
if self.id.text:
return self.post_id_pattern.match(self.id.text).group(4)
return None
def BlogPostEntryFromString(xml_string):
return atom.CreateClassFromXMLString(BlogPostEntry, xml_string)
class BlogPostFeed(gdata.GDataFeed):
"""Describes a feed of a blog's posts."""
_children = gdata.GDataFeed._children.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [BlogPostEntry])
def BlogPostFeedFromString(xml_string):
return atom.CreateClassFromXMLString(BlogPostFeed, xml_string)
class InReplyTo(atom.AtomBase):
_tag = 'in-reply-to'
_namespace = THR_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['href'] = 'href'
_attributes['ref'] = 'ref'
_attributes['source'] = 'source'
_attributes['type'] = 'type'
def __init__(self, href=None, ref=None, source=None, type=None,
extension_elements=None, extension_attributes=None, text=None):
self.href = href
self.ref = ref
self.source = source
self.type = type
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
def InReplyToFromString(xml_string):
return atom.CreateClassFromXMLString(InReplyTo, xml_string)
class CommentEntry(BloggerEntry):
"""Describes a blog post comment entry in the feed of a blog post's
comments."""
_children = BloggerEntry._children.copy()
_children['{%s}in-reply-to' % THR_NAMESPACE] = ('in_reply_to', InReplyTo)
comment_id_pattern = re.compile('.*-(\w*)$')
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, control=None, title=None, updated=None,
in_reply_to=None, extension_elements=None, extension_attributes=None,
text=None):
BloggerEntry.__init__(self, author=author, category=category,
content=content, contributor=contributor, atom_id=atom_id, link=link,
published=published, rights=rights, source=source, summary=summary,
control=control, title=title, updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes, text=text)
self.in_reply_to = in_reply_to
def GetCommentId(self):
"""Extracts the commentID string from the entry's Atom id.
Returns: A string of digits which identify this post within the blog.
"""
if self.id.text:
return self.comment_id_pattern.match(self.id.text).group(1)
return None
def CommentEntryFromString(xml_string):
return atom.CreateClassFromXMLString(CommentEntry, xml_string)
class CommentFeed(gdata.GDataFeed):
"""Describes a feed of a blog post's comments."""
_children = gdata.GDataFeed._children.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CommentEntry])
def CommentFeedFromString(xml_string):
return atom.CreateClassFromXMLString(CommentFeed, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Classes to interact with the Blogger server."""
__author__ = 'api.jscudder (Jeffrey Scudder)'
import gdata.service
import gdata.blogger
class BloggerService(gdata.service.GDataService):
def __init__(self, email=None, password=None, source=None,
server=None, api_key=None,
additional_headers=None):
gdata.service.GDataService.__init__(self, email=email, password=password,
service='blogger', source=source,
server=server,
additional_headers=additional_headers)
self.accountType = 'GOOGLE'
def GetBlogFeed(self, uri=None):
"""Retrieve a list of the blogs to which the current user may manage."""
if not uri:
uri = 'http://www.blogger.com/feeds/default/blogs'
return self.Get(uri, converter=gdata.blogger.BlogFeedFromString)
def GetBlogCommentFeed(self, blog_id=None, uri=None):
"""Retrieve a list of the comments for this blog."""
if blog_id:
uri = 'http://www.blogger.com/feeds/%s/comments/default' % blog_id
return self.Get(uri, converter=gdata.blogger.CommentFeedFromString)
def GetBlogPostFeed(self, blog_id=None, uri=None):
if blog_id:
uri = 'http://www.blogger.com/feeds/%s/posts/default' % blog_id
return self.Get(uri, converter=gdata.blogger.BlogPostFeedFromString)
def GetPostCommentFeed(self, blog_id=None, post_id=None, uri=None):
"""Retrieve a list of the comments for this particular blog post."""
if blog_id and post_id:
uri = 'http://www.blogger.com/feeds/%s/%s/comments/default' % (blog_id,
post_id)
return self.Get(uri, converter=gdata.blogger.CommentFeedFromString)
def AddPost(self, entry, blog_id=None, uri=None):
if blog_id:
uri = 'http://www.blogger.com/feeds/%s/posts/default' % blog_id
return self.Post(entry, uri,
converter=gdata.blogger.BlogPostEntryFromString)
def UpdatePost(self, entry, uri=None):
if not uri:
uri = entry.GetEditLink().href
return self.Put(entry, uri,
converter=gdata.blogger.BlogPostEntryFromString)
def DeletePost(self, entry=None, uri=None):
if not uri:
uri = entry.GetEditLink().href
return self.Delete(uri)
def AddComment(self, comment_entry, blog_id=None, post_id=None, uri=None):
"""Adds a new comment to the specified blog post."""
if blog_id and post_id:
uri = 'http://www.blogger.com/feeds/%s/%s/comments/default' % (
blog_id, post_id)
return self.Post(comment_entry, uri,
converter=gdata.blogger.CommentEntryFromString)
def DeleteComment(self, entry=None, uri=None):
if not uri:
uri = entry.GetEditLink().href
return self.Delete(uri)
class BlogQuery(gdata.service.Query):
def __init__(self, feed=None, params=None, categories=None, blog_id=None):
"""Constructs a query object for the list of a user's Blogger blogs.
Args:
feed: str (optional) The beginning of the URL to be queried. If the
feed is not set, and there is no blog_id passed in, the default
value is used ('http://www.blogger.com/feeds/default/blogs').
params: dict (optional)
categories: list (optional)
blog_id: str (optional)
"""
if not feed and blog_id:
feed = 'http://www.blogger.com/feeds/default/blogs/%s' % blog_id
elif not feed:
feed = 'http://www.blogger.com/feeds/default/blogs'
gdata.service.Query.__init__(self, feed=feed, params=params,
categories=categories)
class BlogPostQuery(gdata.service.Query):
def __init__(self, feed=None, params=None, categories=None, blog_id=None,
post_id=None):
if not feed and blog_id and post_id:
feed = 'http://www.blogger.com/feeds/%s/posts/default/%s' % (blog_id,
post_id)
elif not feed and blog_id:
feed = 'http://www.blogger.com/feeds/%s/posts/default' % blog_id
gdata.service.Query.__init__(self, feed=feed, params=params,
categories=categories)
class BlogCommentQuery(gdata.service.Query):
def __init__(self, feed=None, params=None, categories=None, blog_id=None,
post_id=None, comment_id=None):
if not feed and blog_id and comment_id:
feed = 'http://www.blogger.com/feeds/%s/comments/default/%s' % (
blog_id, comment_id)
elif not feed and blog_id and post_id:
feed = 'http://www.blogger.com/feeds/%s/%s/comments/default' % (
blog_id, post_id)
elif not feed and blog_id:
feed = 'http://www.blogger.com/feeds/%s/comments/default' % blog_id
gdata.service.Query.__init__(self, feed=feed, params=params,
categories=categories)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Classes to interact with the Blogger server."""
__author__ = 'api.jscudder (Jeffrey Scudder)'
import gdata.service
import gdata.blogger
class BloggerService(gdata.service.GDataService):
def __init__(self, email=None, password=None, source=None,
server=None, api_key=None,
additional_headers=None):
gdata.service.GDataService.__init__(self, email=email, password=password,
service='blogger', source=source,
server=server,
additional_headers=additional_headers)
self.accountType = 'GOOGLE'
def GetBlogFeed(self, uri=None):
"""Retrieve a list of the blogs to which the current user may manage."""
if not uri:
uri = 'http://www.blogger.com/feeds/default/blogs'
return self.Get(uri, converter=gdata.blogger.BlogFeedFromString)
def GetBlogCommentFeed(self, blog_id=None, uri=None):
"""Retrieve a list of the comments for this blog."""
if blog_id:
uri = 'http://www.blogger.com/feeds/%s/comments/default' % blog_id
return self.Get(uri, converter=gdata.blogger.CommentFeedFromString)
def GetBlogPostFeed(self, blog_id=None, uri=None):
if blog_id:
uri = 'http://www.blogger.com/feeds/%s/posts/default' % blog_id
return self.Get(uri, converter=gdata.blogger.BlogPostFeedFromString)
def GetPostCommentFeed(self, blog_id=None, post_id=None, uri=None):
"""Retrieve a list of the comments for this particular blog post."""
if blog_id and post_id:
uri = 'http://www.blogger.com/feeds/%s/%s/comments/default' % (blog_id,
post_id)
return self.Get(uri, converter=gdata.blogger.CommentFeedFromString)
def AddPost(self, entry, blog_id=None, uri=None):
if blog_id:
uri = 'http://www.blogger.com/feeds/%s/posts/default' % blog_id
return self.Post(entry, uri,
converter=gdata.blogger.BlogPostEntryFromString)
def UpdatePost(self, entry, uri=None):
if not uri:
uri = entry.GetEditLink().href
return self.Put(entry, uri,
converter=gdata.blogger.BlogPostEntryFromString)
def DeletePost(self, entry=None, uri=None):
if not uri:
uri = entry.GetEditLink().href
return self.Delete(uri)
def AddComment(self, comment_entry, blog_id=None, post_id=None, uri=None):
"""Adds a new comment to the specified blog post."""
if blog_id and post_id:
uri = 'http://www.blogger.com/feeds/%s/%s/comments/default' % (
blog_id, post_id)
return self.Post(comment_entry, uri,
converter=gdata.blogger.CommentEntryFromString)
def DeleteComment(self, entry=None, uri=None):
if not uri:
uri = entry.GetEditLink().href
return self.Delete(uri)
class BlogQuery(gdata.service.Query):
def __init__(self, feed=None, params=None, categories=None, blog_id=None):
"""Constructs a query object for the list of a user's Blogger blogs.
Args:
feed: str (optional) The beginning of the URL to be queried. If the
feed is not set, and there is no blog_id passed in, the default
value is used ('http://www.blogger.com/feeds/default/blogs').
params: dict (optional)
categories: list (optional)
blog_id: str (optional)
"""
if not feed and blog_id:
feed = 'http://www.blogger.com/feeds/default/blogs/%s' % blog_id
elif not feed:
feed = 'http://www.blogger.com/feeds/default/blogs'
gdata.service.Query.__init__(self, feed=feed, params=params,
categories=categories)
class BlogPostQuery(gdata.service.Query):
def __init__(self, feed=None, params=None, categories=None, blog_id=None,
post_id=None):
if not feed and blog_id and post_id:
feed = 'http://www.blogger.com/feeds/%s/posts/default/%s' % (blog_id,
post_id)
elif not feed and blog_id:
feed = 'http://www.blogger.com/feeds/%s/posts/default' % blog_id
gdata.service.Query.__init__(self, feed=feed, params=params,
categories=categories)
class BlogCommentQuery(gdata.service.Query):
def __init__(self, feed=None, params=None, categories=None, blog_id=None,
post_id=None, comment_id=None):
if not feed and blog_id and comment_id:
feed = 'http://www.blogger.com/feeds/%s/comments/default/%s' % (
blog_id, comment_id)
elif not feed and blog_id and post_id:
feed = 'http://www.blogger.com/feeds/%s/%s/comments/default' % (
blog_id, post_id)
elif not feed and blog_id:
feed = 'http://www.blogger.com/feeds/%s/comments/default' % blog_id
gdata.service.Query.__init__(self, feed=feed, params=params,
categories=categories)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2007, 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to Atom objects used with Blogger."""
__author__ = 'api.jscudder (Jeffrey Scudder)'
import atom
import gdata
import re
LABEL_SCHEME = 'http://www.blogger.com/atom/ns#'
THR_NAMESPACE = 'http://purl.org/syndication/thread/1.0'
class BloggerEntry(gdata.GDataEntry):
"""Adds convenience methods inherited by all Blogger entries."""
blog_name_pattern = re.compile('(http://)(\w*)')
blog_id_pattern = re.compile('(tag:blogger.com,1999:blog-)(\w*)')
def GetBlogId(self):
"""Extracts the Blogger id of this blog.
This method is useful when contructing URLs by hand. The blog id is
often used in blogger operation URLs. This should not be confused with
the id member of a BloggerBlog. The id element is the Atom id XML element.
The blog id which this method returns is a part of the Atom id.
Returns:
The blog's unique id as a string.
"""
if self.id.text:
return self.blog_id_pattern.match(self.id.text).group(2)
return None
def GetBlogName(self):
"""Finds the name of this blog as used in the 'alternate' URL.
An alternate URL is in the form 'http://blogName.blogspot.com/'. For an
entry representing the above example, this method would return 'blogName'.
Returns:
The blog's URL name component as a string.
"""
for link in self.link:
if link.rel == 'alternate':
return self.blog_name_pattern.match(link.href).group(2)
return None
class BlogEntry(BloggerEntry):
"""Describes a blog entry in the feed listing a user's blogs."""
def BlogEntryFromString(xml_string):
return atom.CreateClassFromXMLString(BlogEntry, xml_string)
class BlogFeed(gdata.GDataFeed):
"""Describes a feed of a user's blogs."""
_children = gdata.GDataFeed._children.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [BlogEntry])
def BlogFeedFromString(xml_string):
return atom.CreateClassFromXMLString(BlogFeed, xml_string)
class BlogPostEntry(BloggerEntry):
"""Describes a blog post entry in the feed of a blog's posts."""
post_id_pattern = re.compile('(tag:blogger.com,1999:blog-)(\w*)(.post-)(\w*)')
def AddLabel(self, label):
"""Adds a label to the blog post.
The label is represented by an Atom category element, so this method
is shorthand for appending a new atom.Category object.
Args:
label: str
"""
self.category.append(atom.Category(scheme=LABEL_SCHEME, term=label))
def GetPostId(self):
"""Extracts the postID string from the entry's Atom id.
Returns: A string of digits which identify this post within the blog.
"""
if self.id.text:
return self.post_id_pattern.match(self.id.text).group(4)
return None
def BlogPostEntryFromString(xml_string):
return atom.CreateClassFromXMLString(BlogPostEntry, xml_string)
class BlogPostFeed(gdata.GDataFeed):
"""Describes a feed of a blog's posts."""
_children = gdata.GDataFeed._children.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [BlogPostEntry])
def BlogPostFeedFromString(xml_string):
return atom.CreateClassFromXMLString(BlogPostFeed, xml_string)
class InReplyTo(atom.AtomBase):
_tag = 'in-reply-to'
_namespace = THR_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['href'] = 'href'
_attributes['ref'] = 'ref'
_attributes['source'] = 'source'
_attributes['type'] = 'type'
def __init__(self, href=None, ref=None, source=None, type=None,
extension_elements=None, extension_attributes=None, text=None):
self.href = href
self.ref = ref
self.source = source
self.type = type
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
def InReplyToFromString(xml_string):
return atom.CreateClassFromXMLString(InReplyTo, xml_string)
class CommentEntry(BloggerEntry):
"""Describes a blog post comment entry in the feed of a blog post's
comments."""
_children = BloggerEntry._children.copy()
_children['{%s}in-reply-to' % THR_NAMESPACE] = ('in_reply_to', InReplyTo)
comment_id_pattern = re.compile('.*-(\w*)$')
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, control=None, title=None, updated=None,
in_reply_to=None, extension_elements=None, extension_attributes=None,
text=None):
BloggerEntry.__init__(self, author=author, category=category,
content=content, contributor=contributor, atom_id=atom_id, link=link,
published=published, rights=rights, source=source, summary=summary,
control=control, title=title, updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes, text=text)
self.in_reply_to = in_reply_to
def GetCommentId(self):
"""Extracts the commentID string from the entry's Atom id.
Returns: A string of digits which identify this post within the blog.
"""
if self.id.text:
return self.comment_id_pattern.match(self.id.text).group(1)
return None
def CommentEntryFromString(xml_string):
return atom.CreateClassFromXMLString(CommentEntry, xml_string)
class CommentFeed(gdata.GDataFeed):
"""Describes a feed of a blog post's comments."""
_children = gdata.GDataFeed._children.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CommentEntry])
def CommentFeedFromString(xml_string):
return atom.CreateClassFromXMLString(CommentFeed, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2007 SIOS Technology, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains objects used with Google Apps."""
__author__ = 'tmatsuo@sios.com (Takashi MATSUO)'
import atom
import gdata
# XML namespaces which are often used in Google Apps entity.
APPS_NAMESPACE = 'http://schemas.google.com/apps/2006'
APPS_TEMPLATE = '{http://schemas.google.com/apps/2006}%s'
class EmailList(atom.AtomBase):
"""The Google Apps EmailList element"""
_tag = 'emailList'
_namespace = APPS_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['name'] = 'name'
def __init__(self, name=None, extension_elements=None,
extension_attributes=None, text=None):
self.name = name
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def EmailListFromString(xml_string):
return atom.CreateClassFromXMLString(EmailList, xml_string)
class Who(atom.AtomBase):
"""The Google Apps Who element"""
_tag = 'who'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['rel'] = 'rel'
_attributes['email'] = 'email'
def __init__(self, rel=None, email=None, extension_elements=None,
extension_attributes=None, text=None):
self.rel = rel
self.email = email
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def WhoFromString(xml_string):
return atom.CreateClassFromXMLString(Who, xml_string)
class Login(atom.AtomBase):
"""The Google Apps Login element"""
_tag = 'login'
_namespace = APPS_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['userName'] = 'user_name'
_attributes['password'] = 'password'
_attributes['suspended'] = 'suspended'
_attributes['admin'] = 'admin'
_attributes['changePasswordAtNextLogin'] = 'change_password'
_attributes['agreedToTerms'] = 'agreed_to_terms'
_attributes['ipWhitelisted'] = 'ip_whitelisted'
_attributes['hashFunctionName'] = 'hash_function_name'
def __init__(self, user_name=None, password=None, suspended=None,
ip_whitelisted=None, hash_function_name=None,
admin=None, change_password=None, agreed_to_terms=None,
extension_elements=None, extension_attributes=None,
text=None):
self.user_name = user_name
self.password = password
self.suspended = suspended
self.admin = admin
self.change_password = change_password
self.agreed_to_terms = agreed_to_terms
self.ip_whitelisted = ip_whitelisted
self.hash_function_name = hash_function_name
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def LoginFromString(xml_string):
return atom.CreateClassFromXMLString(Login, xml_string)
class Quota(atom.AtomBase):
"""The Google Apps Quota element"""
_tag = 'quota'
_namespace = APPS_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['limit'] = 'limit'
def __init__(self, limit=None, extension_elements=None,
extension_attributes=None, text=None):
self.limit = limit
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def QuotaFromString(xml_string):
return atom.CreateClassFromXMLString(Quota, xml_string)
class Name(atom.AtomBase):
"""The Google Apps Name element"""
_tag = 'name'
_namespace = APPS_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['familyName'] = 'family_name'
_attributes['givenName'] = 'given_name'
def __init__(self, family_name=None, given_name=None,
extension_elements=None, extension_attributes=None, text=None):
self.family_name = family_name
self.given_name = given_name
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def NameFromString(xml_string):
return atom.CreateClassFromXMLString(Name, xml_string)
class Nickname(atom.AtomBase):
"""The Google Apps Nickname element"""
_tag = 'nickname'
_namespace = APPS_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['name'] = 'name'
def __init__(self, name=None,
extension_elements=None, extension_attributes=None, text=None):
self.name = name
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def NicknameFromString(xml_string):
return atom.CreateClassFromXMLString(Nickname, xml_string)
class NicknameEntry(gdata.GDataEntry):
"""A Google Apps flavor of an Atom Entry for Nickname"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}login' % APPS_NAMESPACE] = ('login', Login)
_children['{%s}nickname' % APPS_NAMESPACE] = ('nickname', Nickname)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
login=None, nickname=None,
extended_property=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
title=title, updated=updated)
self.login = login
self.nickname = nickname
self.extended_property = extended_property or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def NicknameEntryFromString(xml_string):
return atom.CreateClassFromXMLString(NicknameEntry, xml_string)
class NicknameFeed(gdata.GDataFeed, gdata.LinkFinder):
"""A Google Apps Nickname feed flavor of an Atom Feed"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [NicknameEntry])
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None,
entry=None, total_results=None, start_index=None,
items_per_page=None, extension_elements=None,
extension_attributes=None, text=None):
gdata.GDataFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def NicknameFeedFromString(xml_string):
return atom.CreateClassFromXMLString(NicknameFeed, xml_string)
class UserEntry(gdata.GDataEntry):
"""A Google Apps flavor of an Atom Entry"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}login' % APPS_NAMESPACE] = ('login', Login)
_children['{%s}name' % APPS_NAMESPACE] = ('name', Name)
_children['{%s}quota' % APPS_NAMESPACE] = ('quota', Quota)
# This child may already be defined in GDataEntry, confirm before removing.
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
[gdata.FeedLink])
_children['{%s}who' % gdata.GDATA_NAMESPACE] = ('who', Who)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
login=None, name=None, quota=None, who=None, feed_link=None,
extended_property=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
title=title, updated=updated)
self.login = login
self.name = name
self.quota = quota
self.who = who
self.feed_link = feed_link or []
self.extended_property = extended_property or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def UserEntryFromString(xml_string):
return atom.CreateClassFromXMLString(UserEntry, xml_string)
class UserFeed(gdata.GDataFeed, gdata.LinkFinder):
"""A Google Apps User feed flavor of an Atom Feed"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [UserEntry])
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None,
entry=None, total_results=None, start_index=None,
items_per_page=None, extension_elements=None,
extension_attributes=None, text=None):
gdata.GDataFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def UserFeedFromString(xml_string):
return atom.CreateClassFromXMLString(UserFeed, xml_string)
class EmailListEntry(gdata.GDataEntry):
"""A Google Apps EmailList flavor of an Atom Entry"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}emailList' % APPS_NAMESPACE] = ('email_list', EmailList)
# Might be able to remove this _children entry.
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
[gdata.FeedLink])
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
email_list=None, feed_link=None,
extended_property=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
title=title, updated=updated)
self.email_list = email_list
self.feed_link = feed_link or []
self.extended_property = extended_property or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def EmailListEntryFromString(xml_string):
return atom.CreateClassFromXMLString(EmailListEntry, xml_string)
class EmailListFeed(gdata.GDataFeed, gdata.LinkFinder):
"""A Google Apps EmailList feed flavor of an Atom Feed"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [EmailListEntry])
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None,
entry=None, total_results=None, start_index=None,
items_per_page=None, extension_elements=None,
extension_attributes=None, text=None):
gdata.GDataFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def EmailListFeedFromString(xml_string):
return atom.CreateClassFromXMLString(EmailListFeed, xml_string)
class EmailListRecipientEntry(gdata.GDataEntry):
"""A Google Apps EmailListRecipient flavor of an Atom Entry"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}who' % gdata.GDATA_NAMESPACE] = ('who', Who)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
who=None,
extended_property=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
title=title, updated=updated)
self.who = who
self.extended_property = extended_property or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def EmailListRecipientEntryFromString(xml_string):
return atom.CreateClassFromXMLString(EmailListRecipientEntry, xml_string)
class EmailListRecipientFeed(gdata.GDataFeed, gdata.LinkFinder):
"""A Google Apps EmailListRecipient feed flavor of an Atom Feed"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[EmailListRecipientEntry])
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None,
entry=None, total_results=None, start_index=None,
items_per_page=None, extension_elements=None,
extension_attributes=None, text=None):
gdata.GDataFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def EmailListRecipientFeedFromString(xml_string):
return atom.CreateClassFromXMLString(EmailListRecipientFeed, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2007 SIOS Technology, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = 'tmatsuo@sios.com (Takashi MATSUO)'
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import urllib
import gdata
import atom.service
import gdata.service
import gdata.apps
import atom
API_VER="2.0"
HTTP_OK=200
UNKOWN_ERROR=1000
USER_DELETED_RECENTLY=1100
USER_SUSPENDED=1101
DOMAIN_USER_LIMIT_EXCEEDED=1200
DOMAIN_ALIAS_LIMIT_EXCEEDED=1201
DOMAIN_SUSPENDED=1202
DOMAIN_FEATURE_UNAVAILABLE=1203
ENTITY_EXISTS=1300
ENTITY_DOES_NOT_EXIST=1301
ENTITY_NAME_IS_RESERVED=1302
ENTITY_NAME_NOT_VALID=1303
INVALID_GIVEN_NAME=1400
INVALID_FAMILY_NAME=1401
INVALID_PASSWORD=1402
INVALID_USERNAME=1403
INVALID_HASH_FUNCTION_NAME=1404
INVALID_HASH_DIGGEST_LENGTH=1405
INVALID_EMAIL_ADDRESS=1406
INVALID_QUERY_PARAMETER_VALUE=1407
TOO_MANY_RECIPIENTS_ON_EMAIL_LIST=1500
DEFAULT_QUOTA_LIMIT='2048'
class Error(Exception):
pass
class AppsForYourDomainException(Error):
def __init__(self, response):
self.args = response
try:
self.element_tree = ElementTree.fromstring(response['body'])
self.error_code = int(self.element_tree[0].attrib['errorCode'])
self.reason = self.element_tree[0].attrib['reason']
self.invalidInput = self.element_tree[0].attrib['invalidInput']
except:
self.error_code = UNKOWN_ERROR
class AppsService(gdata.service.GDataService):
"""Client for the Google Apps Provisioning service."""
def __init__(self, email=None, password=None, domain=None, source=None,
server='www.google.com', additional_headers=None):
gdata.service.GDataService.__init__(self, email=email, password=password,
service='apps', source=source,
server=server,
additional_headers=additional_headers)
self.ssl = True
self.port = 443
self.domain = domain
def _baseURL(self):
return "/a/feeds/%s" % self.domain
def GetGenaratorFromLinkFinder(self, link_finder, func):
"""returns a generator for pagination"""
yield link_finder
next = link_finder.GetNextLink()
while next is not None:
next_feed = func(str(self.Get(next.href)))
yield next_feed
next = next_feed.GetNextLink()
def AddAllElementsFromAllPages(self, link_finder, func):
"""retrieve all pages and add all elements"""
next = link_finder.GetNextLink()
while next is not None:
next_feed = func(str(self.Get(next.href)))
for a_entry in next_feed.entry:
link_finder.entry.append(a_entry)
next = next_feed.GetNextLink()
return link_finder
def RetrievePageOfEmailLists(self, start_email_list_name=None):
"""Retrieve one page of email list"""
uri = "%s/emailList/%s" % (self._baseURL(), API_VER)
if start_email_list_name is not None:
uri += "?startEmailListName=%s" % start_email_list_name
try:
return gdata.apps.EmailListFeedFromString(str(self.Get(uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def RetrieveAllEmailLists(self):
"""Retrieve all email list of a domain."""
ret = self.RetrievePageOfEmailLists()
# pagination
return self.AddAllElementsFromAllPages(
ret, gdata.apps.EmailListFeedFromString)
def RetrieveEmailList(self, list_name):
"""Retreive a single email list by the list's name."""
uri = "%s/emailList/%s/%s" % (
self._baseURL(), API_VER, list_name)
try:
return self.Get(uri, converter=gdata.apps.EmailListEntryFromString)
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def RetrieveEmailLists(self, recipient):
"""Retrieve All Email List Subscriptions for an Email Address."""
uri = "%s/emailList/%s?recipient=%s" % (
self._baseURL(), API_VER, recipient)
try:
ret = gdata.apps.EmailListFeedFromString(str(self.Get(uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
# pagination
return self.AddAllElementsFromAllPages(
ret, gdata.apps.EmailListFeedFromString)
def RemoveRecipientFromEmailList(self, recipient, list_name):
"""Remove recipient from email list."""
uri = "%s/emailList/%s/%s/recipient/%s" % (
self._baseURL(), API_VER, list_name, recipient)
try:
self.Delete(uri)
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def RetrievePageOfRecipients(self, list_name, start_recipient=None):
"""Retrieve one page of recipient of an email list. """
uri = "%s/emailList/%s/%s/recipient" % (
self._baseURL(), API_VER, list_name)
if start_recipient is not None:
uri += "?startRecipient=%s" % start_recipient
try:
return gdata.apps.EmailListRecipientFeedFromString(str(self.Get(uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def RetrieveAllRecipients(self, list_name):
"""Retrieve all recipient of an email list."""
ret = self.RetrievePageOfRecipients(list_name)
# pagination
return self.AddAllElementsFromAllPages(
ret, gdata.apps.EmailListRecipientFeedFromString)
def AddRecipientToEmailList(self, recipient, list_name):
"""Add a recipient to a email list."""
uri = "%s/emailList/%s/%s/recipient" % (
self._baseURL(), API_VER, list_name)
recipient_entry = gdata.apps.EmailListRecipientEntry()
recipient_entry.who = gdata.apps.Who(email=recipient)
try:
return gdata.apps.EmailListRecipientEntryFromString(
str(self.Post(recipient_entry, uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def DeleteEmailList(self, list_name):
"""Delete a email list"""
uri = "%s/emailList/%s/%s" % (self._baseURL(), API_VER, list_name)
try:
self.Delete(uri)
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def CreateEmailList(self, list_name):
"""Create a email list. """
uri = "%s/emailList/%s" % (self._baseURL(), API_VER)
email_list_entry = gdata.apps.EmailListEntry()
email_list_entry.email_list = gdata.apps.EmailList(name=list_name)
try:
return gdata.apps.EmailListEntryFromString(
str(self.Post(email_list_entry, uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def DeleteNickname(self, nickname):
"""Delete a nickname"""
uri = "%s/nickname/%s/%s" % (self._baseURL(), API_VER, nickname)
try:
self.Delete(uri)
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def RetrievePageOfNicknames(self, start_nickname=None):
"""Retrieve one page of nicknames in the domain"""
uri = "%s/nickname/%s" % (self._baseURL(), API_VER)
if start_nickname is not None:
uri += "?startNickname=%s" % start_nickname
try:
return gdata.apps.NicknameFeedFromString(str(self.Get(uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def RetrieveAllNicknames(self):
"""Retrieve all nicknames in the domain"""
ret = self.RetrievePageOfNicknames()
# pagination
return self.AddAllElementsFromAllPages(
ret, gdata.apps.NicknameFeedFromString)
def RetrieveNicknames(self, user_name):
"""Retrieve nicknames of the user"""
uri = "%s/nickname/%s?username=%s" % (self._baseURL(), API_VER, user_name)
try:
ret = gdata.apps.NicknameFeedFromString(str(self.Get(uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
# pagination
return self.AddAllElementsFromAllPages(
ret, gdata.apps.NicknameFeedFromString)
def RetrieveNickname(self, nickname):
"""Retrieve a nickname.
Args:
nickname: string The nickname to retrieve
Returns:
gdata.apps.NicknameEntry
"""
uri = "%s/nickname/%s/%s" % (self._baseURL(), API_VER, nickname)
try:
return gdata.apps.NicknameEntryFromString(str(self.Get(uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def CreateNickname(self, user_name, nickname):
"""Create a nickname"""
uri = "%s/nickname/%s" % (self._baseURL(), API_VER)
nickname_entry = gdata.apps.NicknameEntry()
nickname_entry.login = gdata.apps.Login(user_name=user_name)
nickname_entry.nickname = gdata.apps.Nickname(name=nickname)
try:
return gdata.apps.NicknameEntryFromString(
str(self.Post(nickname_entry, uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def DeleteUser(self, user_name):
"""Delete a user account"""
uri = "%s/user/%s/%s" % (self._baseURL(), API_VER, user_name)
try:
return self.Delete(uri)
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def UpdateUser(self, user_name, user_entry):
"""Update a user account."""
uri = "%s/user/%s/%s" % (self._baseURL(), API_VER, user_name)
try:
return gdata.apps.UserEntryFromString(str(self.Put(user_entry, uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def CreateUser(self, user_name, family_name, given_name, password,
suspended='false', quota_limit=None,
password_hash_function=None):
"""Create a user account. """
uri = "%s/user/%s" % (self._baseURL(), API_VER)
user_entry = gdata.apps.UserEntry()
user_entry.login = gdata.apps.Login(
user_name=user_name, password=password, suspended=suspended,
hash_function_name=password_hash_function)
user_entry.name = gdata.apps.Name(family_name=family_name,
given_name=given_name)
if quota_limit is not None:
user_entry.quota = gdata.apps.Quota(limit=str(quota_limit))
try:
return gdata.apps.UserEntryFromString(str(self.Post(user_entry, uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def SuspendUser(self, user_name):
user_entry = self.RetrieveUser(user_name)
if user_entry.login.suspended != 'true':
user_entry.login.suspended = 'true'
user_entry = self.UpdateUser(user_name, user_entry)
return user_entry
def RestoreUser(self, user_name):
user_entry = self.RetrieveUser(user_name)
if user_entry.login.suspended != 'false':
user_entry.login.suspended = 'false'
user_entry = self.UpdateUser(user_name, user_entry)
return user_entry
def RetrieveUser(self, user_name):
"""Retrieve an user account.
Args:
user_name: string The user name to retrieve
Returns:
gdata.apps.UserEntry
"""
uri = "%s/user/%s/%s" % (self._baseURL(), API_VER, user_name)
try:
return gdata.apps.UserEntryFromString(str(self.Get(uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def RetrievePageOfUsers(self, start_username=None):
"""Retrieve one page of users in this domain."""
uri = "%s/user/%s" % (self._baseURL(), API_VER)
if start_username is not None:
uri += "?startUsername=%s" % start_username
try:
return gdata.apps.UserFeedFromString(str(self.Get(uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def GetGeneratorForAllUsers(self):
"""Retrieve a generator for all users in this domain."""
first_page = self.RetrievePageOfUsers()
return self.GetGenaratorFromLinkFinder(first_page,
gdata.apps.UserFeedFromString)
def RetrieveAllUsers(self):
"""Retrieve all users in this domain. OBSOLETE"""
ret = self.RetrievePageOfUsers()
# pagination
return self.AddAllElementsFromAllPages(
ret, gdata.apps.UserFeedFromString)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2007 SIOS Technology, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = 'tmatsuo@sios.com (Takashi MATSUO)'
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import urllib
import gdata
import atom.service
import gdata.service
import gdata.apps
import atom
API_VER="2.0"
HTTP_OK=200
UNKOWN_ERROR=1000
USER_DELETED_RECENTLY=1100
USER_SUSPENDED=1101
DOMAIN_USER_LIMIT_EXCEEDED=1200
DOMAIN_ALIAS_LIMIT_EXCEEDED=1201
DOMAIN_SUSPENDED=1202
DOMAIN_FEATURE_UNAVAILABLE=1203
ENTITY_EXISTS=1300
ENTITY_DOES_NOT_EXIST=1301
ENTITY_NAME_IS_RESERVED=1302
ENTITY_NAME_NOT_VALID=1303
INVALID_GIVEN_NAME=1400
INVALID_FAMILY_NAME=1401
INVALID_PASSWORD=1402
INVALID_USERNAME=1403
INVALID_HASH_FUNCTION_NAME=1404
INVALID_HASH_DIGGEST_LENGTH=1405
INVALID_EMAIL_ADDRESS=1406
INVALID_QUERY_PARAMETER_VALUE=1407
TOO_MANY_RECIPIENTS_ON_EMAIL_LIST=1500
DEFAULT_QUOTA_LIMIT='2048'
class Error(Exception):
pass
class AppsForYourDomainException(Error):
def __init__(self, response):
self.args = response
try:
self.element_tree = ElementTree.fromstring(response['body'])
self.error_code = int(self.element_tree[0].attrib['errorCode'])
self.reason = self.element_tree[0].attrib['reason']
self.invalidInput = self.element_tree[0].attrib['invalidInput']
except:
self.error_code = UNKOWN_ERROR
class AppsService(gdata.service.GDataService):
"""Client for the Google Apps Provisioning service."""
def __init__(self, email=None, password=None, domain=None, source=None,
server='www.google.com', additional_headers=None):
gdata.service.GDataService.__init__(self, email=email, password=password,
service='apps', source=source,
server=server,
additional_headers=additional_headers)
self.ssl = True
self.port = 443
self.domain = domain
def _baseURL(self):
return "/a/feeds/%s" % self.domain
def GetGenaratorFromLinkFinder(self, link_finder, func):
"""returns a generator for pagination"""
yield link_finder
next = link_finder.GetNextLink()
while next is not None:
next_feed = func(str(self.Get(next.href)))
yield next_feed
next = next_feed.GetNextLink()
def AddAllElementsFromAllPages(self, link_finder, func):
"""retrieve all pages and add all elements"""
next = link_finder.GetNextLink()
while next is not None:
next_feed = func(str(self.Get(next.href)))
for a_entry in next_feed.entry:
link_finder.entry.append(a_entry)
next = next_feed.GetNextLink()
return link_finder
def RetrievePageOfEmailLists(self, start_email_list_name=None):
"""Retrieve one page of email list"""
uri = "%s/emailList/%s" % (self._baseURL(), API_VER)
if start_email_list_name is not None:
uri += "?startEmailListName=%s" % start_email_list_name
try:
return gdata.apps.EmailListFeedFromString(str(self.Get(uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def RetrieveAllEmailLists(self):
"""Retrieve all email list of a domain."""
ret = self.RetrievePageOfEmailLists()
# pagination
return self.AddAllElementsFromAllPages(
ret, gdata.apps.EmailListFeedFromString)
def RetrieveEmailList(self, list_name):
"""Retreive a single email list by the list's name."""
uri = "%s/emailList/%s/%s" % (
self._baseURL(), API_VER, list_name)
try:
return self.Get(uri, converter=gdata.apps.EmailListEntryFromString)
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def RetrieveEmailLists(self, recipient):
"""Retrieve All Email List Subscriptions for an Email Address."""
uri = "%s/emailList/%s?recipient=%s" % (
self._baseURL(), API_VER, recipient)
try:
ret = gdata.apps.EmailListFeedFromString(str(self.Get(uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
# pagination
return self.AddAllElementsFromAllPages(
ret, gdata.apps.EmailListFeedFromString)
def RemoveRecipientFromEmailList(self, recipient, list_name):
"""Remove recipient from email list."""
uri = "%s/emailList/%s/%s/recipient/%s" % (
self._baseURL(), API_VER, list_name, recipient)
try:
self.Delete(uri)
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def RetrievePageOfRecipients(self, list_name, start_recipient=None):
"""Retrieve one page of recipient of an email list. """
uri = "%s/emailList/%s/%s/recipient" % (
self._baseURL(), API_VER, list_name)
if start_recipient is not None:
uri += "?startRecipient=%s" % start_recipient
try:
return gdata.apps.EmailListRecipientFeedFromString(str(self.Get(uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def RetrieveAllRecipients(self, list_name):
"""Retrieve all recipient of an email list."""
ret = self.RetrievePageOfRecipients(list_name)
# pagination
return self.AddAllElementsFromAllPages(
ret, gdata.apps.EmailListRecipientFeedFromString)
def AddRecipientToEmailList(self, recipient, list_name):
"""Add a recipient to a email list."""
uri = "%s/emailList/%s/%s/recipient" % (
self._baseURL(), API_VER, list_name)
recipient_entry = gdata.apps.EmailListRecipientEntry()
recipient_entry.who = gdata.apps.Who(email=recipient)
try:
return gdata.apps.EmailListRecipientEntryFromString(
str(self.Post(recipient_entry, uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def DeleteEmailList(self, list_name):
"""Delete a email list"""
uri = "%s/emailList/%s/%s" % (self._baseURL(), API_VER, list_name)
try:
self.Delete(uri)
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def CreateEmailList(self, list_name):
"""Create a email list. """
uri = "%s/emailList/%s" % (self._baseURL(), API_VER)
email_list_entry = gdata.apps.EmailListEntry()
email_list_entry.email_list = gdata.apps.EmailList(name=list_name)
try:
return gdata.apps.EmailListEntryFromString(
str(self.Post(email_list_entry, uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def DeleteNickname(self, nickname):
"""Delete a nickname"""
uri = "%s/nickname/%s/%s" % (self._baseURL(), API_VER, nickname)
try:
self.Delete(uri)
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def RetrievePageOfNicknames(self, start_nickname=None):
"""Retrieve one page of nicknames in the domain"""
uri = "%s/nickname/%s" % (self._baseURL(), API_VER)
if start_nickname is not None:
uri += "?startNickname=%s" % start_nickname
try:
return gdata.apps.NicknameFeedFromString(str(self.Get(uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def RetrieveAllNicknames(self):
"""Retrieve all nicknames in the domain"""
ret = self.RetrievePageOfNicknames()
# pagination
return self.AddAllElementsFromAllPages(
ret, gdata.apps.NicknameFeedFromString)
def RetrieveNicknames(self, user_name):
"""Retrieve nicknames of the user"""
uri = "%s/nickname/%s?username=%s" % (self._baseURL(), API_VER, user_name)
try:
ret = gdata.apps.NicknameFeedFromString(str(self.Get(uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
# pagination
return self.AddAllElementsFromAllPages(
ret, gdata.apps.NicknameFeedFromString)
def RetrieveNickname(self, nickname):
"""Retrieve a nickname.
Args:
nickname: string The nickname to retrieve
Returns:
gdata.apps.NicknameEntry
"""
uri = "%s/nickname/%s/%s" % (self._baseURL(), API_VER, nickname)
try:
return gdata.apps.NicknameEntryFromString(str(self.Get(uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def CreateNickname(self, user_name, nickname):
"""Create a nickname"""
uri = "%s/nickname/%s" % (self._baseURL(), API_VER)
nickname_entry = gdata.apps.NicknameEntry()
nickname_entry.login = gdata.apps.Login(user_name=user_name)
nickname_entry.nickname = gdata.apps.Nickname(name=nickname)
try:
return gdata.apps.NicknameEntryFromString(
str(self.Post(nickname_entry, uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def DeleteUser(self, user_name):
"""Delete a user account"""
uri = "%s/user/%s/%s" % (self._baseURL(), API_VER, user_name)
try:
return self.Delete(uri)
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def UpdateUser(self, user_name, user_entry):
"""Update a user account."""
uri = "%s/user/%s/%s" % (self._baseURL(), API_VER, user_name)
try:
return gdata.apps.UserEntryFromString(str(self.Put(user_entry, uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def CreateUser(self, user_name, family_name, given_name, password,
suspended='false', quota_limit=None,
password_hash_function=None):
"""Create a user account. """
uri = "%s/user/%s" % (self._baseURL(), API_VER)
user_entry = gdata.apps.UserEntry()
user_entry.login = gdata.apps.Login(
user_name=user_name, password=password, suspended=suspended,
hash_function_name=password_hash_function)
user_entry.name = gdata.apps.Name(family_name=family_name,
given_name=given_name)
if quota_limit is not None:
user_entry.quota = gdata.apps.Quota(limit=str(quota_limit))
try:
return gdata.apps.UserEntryFromString(str(self.Post(user_entry, uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def SuspendUser(self, user_name):
user_entry = self.RetrieveUser(user_name)
if user_entry.login.suspended != 'true':
user_entry.login.suspended = 'true'
user_entry = self.UpdateUser(user_name, user_entry)
return user_entry
def RestoreUser(self, user_name):
user_entry = self.RetrieveUser(user_name)
if user_entry.login.suspended != 'false':
user_entry.login.suspended = 'false'
user_entry = self.UpdateUser(user_name, user_entry)
return user_entry
def RetrieveUser(self, user_name):
"""Retrieve an user account.
Args:
user_name: string The user name to retrieve
Returns:
gdata.apps.UserEntry
"""
uri = "%s/user/%s/%s" % (self._baseURL(), API_VER, user_name)
try:
return gdata.apps.UserEntryFromString(str(self.Get(uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def RetrievePageOfUsers(self, start_username=None):
"""Retrieve one page of users in this domain."""
uri = "%s/user/%s" % (self._baseURL(), API_VER)
if start_username is not None:
uri += "?startUsername=%s" % start_username
try:
return gdata.apps.UserFeedFromString(str(self.Get(uri)))
except gdata.service.RequestError, e:
raise AppsForYourDomainException(e.args[0])
def GetGeneratorForAllUsers(self):
"""Retrieve a generator for all users in this domain."""
first_page = self.RetrievePageOfUsers()
return self.GetGenaratorFromLinkFinder(first_page,
gdata.apps.UserFeedFromString)
def RetrieveAllUsers(self):
"""Retrieve all users in this domain. OBSOLETE"""
ret = self.RetrievePageOfUsers()
# pagination
return self.AddAllElementsFromAllPages(
ret, gdata.apps.UserFeedFromString)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2007 SIOS Technology, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains objects used with Google Apps."""
__author__ = 'tmatsuo@sios.com (Takashi MATSUO)'
import atom
import gdata
# XML namespaces which are often used in Google Apps entity.
APPS_NAMESPACE = 'http://schemas.google.com/apps/2006'
APPS_TEMPLATE = '{http://schemas.google.com/apps/2006}%s'
class EmailList(atom.AtomBase):
"""The Google Apps EmailList element"""
_tag = 'emailList'
_namespace = APPS_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['name'] = 'name'
def __init__(self, name=None, extension_elements=None,
extension_attributes=None, text=None):
self.name = name
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def EmailListFromString(xml_string):
return atom.CreateClassFromXMLString(EmailList, xml_string)
class Who(atom.AtomBase):
"""The Google Apps Who element"""
_tag = 'who'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['rel'] = 'rel'
_attributes['email'] = 'email'
def __init__(self, rel=None, email=None, extension_elements=None,
extension_attributes=None, text=None):
self.rel = rel
self.email = email
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def WhoFromString(xml_string):
return atom.CreateClassFromXMLString(Who, xml_string)
class Login(atom.AtomBase):
"""The Google Apps Login element"""
_tag = 'login'
_namespace = APPS_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['userName'] = 'user_name'
_attributes['password'] = 'password'
_attributes['suspended'] = 'suspended'
_attributes['admin'] = 'admin'
_attributes['changePasswordAtNextLogin'] = 'change_password'
_attributes['agreedToTerms'] = 'agreed_to_terms'
_attributes['ipWhitelisted'] = 'ip_whitelisted'
_attributes['hashFunctionName'] = 'hash_function_name'
def __init__(self, user_name=None, password=None, suspended=None,
ip_whitelisted=None, hash_function_name=None,
admin=None, change_password=None, agreed_to_terms=None,
extension_elements=None, extension_attributes=None,
text=None):
self.user_name = user_name
self.password = password
self.suspended = suspended
self.admin = admin
self.change_password = change_password
self.agreed_to_terms = agreed_to_terms
self.ip_whitelisted = ip_whitelisted
self.hash_function_name = hash_function_name
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def LoginFromString(xml_string):
return atom.CreateClassFromXMLString(Login, xml_string)
class Quota(atom.AtomBase):
"""The Google Apps Quota element"""
_tag = 'quota'
_namespace = APPS_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['limit'] = 'limit'
def __init__(self, limit=None, extension_elements=None,
extension_attributes=None, text=None):
self.limit = limit
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def QuotaFromString(xml_string):
return atom.CreateClassFromXMLString(Quota, xml_string)
class Name(atom.AtomBase):
"""The Google Apps Name element"""
_tag = 'name'
_namespace = APPS_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['familyName'] = 'family_name'
_attributes['givenName'] = 'given_name'
def __init__(self, family_name=None, given_name=None,
extension_elements=None, extension_attributes=None, text=None):
self.family_name = family_name
self.given_name = given_name
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def NameFromString(xml_string):
return atom.CreateClassFromXMLString(Name, xml_string)
class Nickname(atom.AtomBase):
"""The Google Apps Nickname element"""
_tag = 'nickname'
_namespace = APPS_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['name'] = 'name'
def __init__(self, name=None,
extension_elements=None, extension_attributes=None, text=None):
self.name = name
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def NicknameFromString(xml_string):
return atom.CreateClassFromXMLString(Nickname, xml_string)
class NicknameEntry(gdata.GDataEntry):
"""A Google Apps flavor of an Atom Entry for Nickname"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}login' % APPS_NAMESPACE] = ('login', Login)
_children['{%s}nickname' % APPS_NAMESPACE] = ('nickname', Nickname)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
login=None, nickname=None,
extended_property=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
title=title, updated=updated)
self.login = login
self.nickname = nickname
self.extended_property = extended_property or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def NicknameEntryFromString(xml_string):
return atom.CreateClassFromXMLString(NicknameEntry, xml_string)
class NicknameFeed(gdata.GDataFeed, gdata.LinkFinder):
"""A Google Apps Nickname feed flavor of an Atom Feed"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [NicknameEntry])
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None,
entry=None, total_results=None, start_index=None,
items_per_page=None, extension_elements=None,
extension_attributes=None, text=None):
gdata.GDataFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def NicknameFeedFromString(xml_string):
return atom.CreateClassFromXMLString(NicknameFeed, xml_string)
class UserEntry(gdata.GDataEntry):
"""A Google Apps flavor of an Atom Entry"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}login' % APPS_NAMESPACE] = ('login', Login)
_children['{%s}name' % APPS_NAMESPACE] = ('name', Name)
_children['{%s}quota' % APPS_NAMESPACE] = ('quota', Quota)
# This child may already be defined in GDataEntry, confirm before removing.
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
[gdata.FeedLink])
_children['{%s}who' % gdata.GDATA_NAMESPACE] = ('who', Who)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
login=None, name=None, quota=None, who=None, feed_link=None,
extended_property=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
title=title, updated=updated)
self.login = login
self.name = name
self.quota = quota
self.who = who
self.feed_link = feed_link or []
self.extended_property = extended_property or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def UserEntryFromString(xml_string):
return atom.CreateClassFromXMLString(UserEntry, xml_string)
class UserFeed(gdata.GDataFeed, gdata.LinkFinder):
"""A Google Apps User feed flavor of an Atom Feed"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [UserEntry])
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None,
entry=None, total_results=None, start_index=None,
items_per_page=None, extension_elements=None,
extension_attributes=None, text=None):
gdata.GDataFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def UserFeedFromString(xml_string):
return atom.CreateClassFromXMLString(UserFeed, xml_string)
class EmailListEntry(gdata.GDataEntry):
"""A Google Apps EmailList flavor of an Atom Entry"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}emailList' % APPS_NAMESPACE] = ('email_list', EmailList)
# Might be able to remove this _children entry.
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
[gdata.FeedLink])
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
email_list=None, feed_link=None,
extended_property=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
title=title, updated=updated)
self.email_list = email_list
self.feed_link = feed_link or []
self.extended_property = extended_property or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def EmailListEntryFromString(xml_string):
return atom.CreateClassFromXMLString(EmailListEntry, xml_string)
class EmailListFeed(gdata.GDataFeed, gdata.LinkFinder):
"""A Google Apps EmailList feed flavor of an Atom Feed"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [EmailListEntry])
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None,
entry=None, total_results=None, start_index=None,
items_per_page=None, extension_elements=None,
extension_attributes=None, text=None):
gdata.GDataFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def EmailListFeedFromString(xml_string):
return atom.CreateClassFromXMLString(EmailListFeed, xml_string)
class EmailListRecipientEntry(gdata.GDataEntry):
"""A Google Apps EmailListRecipient flavor of an Atom Entry"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}who' % gdata.GDATA_NAMESPACE] = ('who', Who)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
who=None,
extended_property=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
title=title, updated=updated)
self.who = who
self.extended_property = extended_property or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def EmailListRecipientEntryFromString(xml_string):
return atom.CreateClassFromXMLString(EmailListRecipientEntry, xml_string)
class EmailListRecipientFeed(gdata.GDataFeed, gdata.LinkFinder):
"""A Google Apps EmailListRecipient feed flavor of an Atom Feed"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[EmailListRecipientEntry])
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None,
entry=None, total_results=None, start_index=None,
items_per_page=None, extension_elements=None,
extension_attributes=None, text=None):
gdata.GDataFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def EmailListRecipientFeedFromString(xml_string):
return atom.CreateClassFromXMLString(EmailListRecipientFeed, xml_string)
| Python |
#/usr/bin/python
#
# Copyright (C) 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
import urllib
__author__ = 'api.jscudder (Jeffrey Scudder)'
AUTH_SUB_KEY_PATTERN = re.compile('.*\?.*token=(.*)(&?)')
def GenerateClientLoginRequestBody(email, password, service, source,
account_type='HOSTED_OR_GOOGLE', captcha_token=None,
captcha_response=None):
"""Creates the body of the autentication request
See http://code.google.com/apis/accounts/AuthForInstalledApps.html#Request
for more details.
Args:
email: str
password: str
service: str
source: str
account_type: str (optional) Defaul is 'HOSTED_OR_GOOGLE', other valid
values are 'GOOGLE' and 'HOSTED'
captcha_token: str (optional)
captcha_response: str (optional)
Returns:
The HTTP body to send in a request for a client login token.
"""
# Create a POST body containing the user's credentials.
request_fields = {'Email': email,
'Passwd': password,
'accountType': account_type,
'service': service,
'source': source}
if captcha_token and captcha_response:
# Send the captcha token and response as part of the POST body if the
# user is responding to a captch challenge.
request_fields['logintoken'] = captcha_token
request_fields['logincaptcha'] = captcha_response
return urllib.urlencode(request_fields)
def GenerateClientLoginAuthToken(http_body):
"""Returns the token value to use in Authorization headers.
Reads the token from the server's response to a Client Login request and
creates header value to use in requests.
Args:
http_body: str The body of the server's HTTP response to a Client Login
request
Returns:
The value half of an Authorization header.
"""
for response_line in http_body.splitlines():
if response_line.startswith('Auth='):
# Strip off the leading Auth= and return the Authorization value.
return 'GoogleLogin auth=%s' % response_line[5:]
return None
def GetCaptchChallenge(http_body,
captcha_base_url='http://www.google.com/accounts/'):
"""Returns the URL and token for a CAPTCHA challenge issued bu the server.
Args:
http_body: str The body of the HTTP response from the server which
contains the CAPTCHA challenge.
captcha_base_url: str This function returns a full URL for viewing the
challenge image which is built from the server's response. This
base_url is used as the beginning of the URL because the server
only provides the end of the URL. For example the server provides
'Captcha?ctoken=Hi...N' and the URL for the image is
'http://www.google.com/accounts/Captcha?ctoken=Hi...N'
Returns:
A dictionary containing the information needed to repond to the CAPTCHA
challenge, the image URL and the ID token of the challenge. The
dictionary is in the form:
{'token': string identifying the CAPTCHA image,
'url': string containing the URL of the image}
Returns None if there was no CAPTCHA challenge in the response.
"""
contains_captcha_challenge = False
captcha_parameters = {}
for response_line in http_body.splitlines():
if response_line.startswith('Error=CaptchaRequired'):
contains_captcha_challenge = True
elif response_line.startswith('CaptchaToken='):
# Strip off the leading CaptchaToken=
captcha_parameters['token'] = response_line[13:]
elif response_line.startswith('CaptchaUrl='):
captcha_parameters['url'] = '%s%s' % (captcha_base_url,
response_line[11:])
if contains_captcha_challenge:
return captcha_parameters
else:
return None
def GenerateAuthSubUrl(next, scope, secure=False, session=True,
request_url='https://www.google.com/accounts/AuthSubRequest'):
"""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:
request_url: str The beginning of the request URL. This is normally
'http://www.google.com/accounts/AuthSubRequest' or
'/accounts/AuthSubRequest'
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.
"""
# Translate True/False values for parameters into numeric values acceoted
# by the AuthSub service.
if secure:
secure = 1
else:
secure = 0
if session:
session = 1
else:
session = 0
request_params = urllib.urlencode({'next': next, 'scope': scope,
'secure': secure, 'session': session})
if request_url.find('?') == -1:
return '%s?%s' % (request_url, request_params)
else:
# The request URL already contained url parameters so we should add
# the parameters using the & seperator
return '%s&%s' % (request_url, request_params)
def AuthSubTokenFromUrl(url):
"""Extracts the AuthSub token from the URL.
Used after the AuthSub redirect has sent the user to the 'next' page and
appended the token to the URL.
Args:
url: str The URL of the current page which contains the AuthSub token as
a URL parameter.
"""
m = AUTH_SUB_KEY_PATTERN.match(url)
if m:
return 'AuthSub token=%s' % m.group(1)
return None
def AuthSubTokenFromHttpBody(http_body):
"""Extracts the AuthSub token from an HTTP body string.
Used to find the new session token after making a request to upgrade a
single use AuthSub token.
Args:
http_body: str The repsonse from the server which contains the AuthSub
key. For example, this function would find the new session token
from the server's response to an upgrade token request.
Returns:
The header value to use for Authorization which contains the AuthSub
token.
"""
for response_line in http_body.splitlines():
if response_line.startswith('Token='):
# Strip off Token= and construct the Authorization value.
auth_token = response_line[6:]
return 'AuthSub token=%s' % auth_token
return None
| Python |
# -*-*- encoding: utf-8 -*-*-
#
# This is gdata.photos.exif, implementing the exif namespace in gdata
#
# $Id: __init__.py 81 2007-10-03 14:41:42Z havard.gulldahl $
#
# Copyright 2007 Håvard Gulldahl
# Portions copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This module maps elements from the {EXIF} namespace[1] to GData objects.
These elements describe image data, using exif attributes[2].
Picasa Web Albums uses the exif namespace to represent Exif data encoded
in a photo [3].
Picasa Web Albums uses the following exif elements:
exif:distance
exif:exposure
exif:flash
exif:focallength
exif:fstop
exif:imageUniqueID
exif:iso
exif:make
exif:model
exif:tags
exif:time
[1]: http://schemas.google.com/photos/exif/2007.
[2]: http://en.wikipedia.org/wiki/Exif
[3]: http://code.google.com/apis/picasaweb/reference.html#exif_reference
"""
__author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: pydoc chokes on non-ascii chars in __author__
__license__ = 'Apache License v2'
import atom
import gdata
EXIF_NAMESPACE = 'http://schemas.google.com/photos/exif/2007'
class ExifBaseElement(atom.AtomBase):
"""Base class for elements in the EXIF_NAMESPACE (%s). To add new elements, you only need to add the element tag name to self._tag
""" % EXIF_NAMESPACE
_tag = ''
_namespace = EXIF_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, name=None, extension_elements=None,
extension_attributes=None, text=None):
self.name = name
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Distance(ExifBaseElement):
"(float) The distance to the subject, e.g. 0.0"
_tag = 'distance'
def DistanceFromString(xml_string):
return atom.CreateClassFromXMLString(Distance, xml_string)
class Exposure(ExifBaseElement):
"(float) The exposure time used, e.g. 0.025 or 8.0E4"
_tag = 'exposure'
def ExposureFromString(xml_string):
return atom.CreateClassFromXMLString(Exposure, xml_string)
class Flash(ExifBaseElement):
"""(string) Boolean value indicating whether the flash was used.
The .text attribute will either be `true' or `false'
As a convenience, this object's .bool method will return what you want,
so you can say:
flash_used = bool(Flash)
"""
_tag = 'flash'
def __bool__(self):
if self.text.lower() in ('true','false'):
return self.text.lower() == 'true'
def FlashFromString(xml_string):
return atom.CreateClassFromXMLString(Flash, xml_string)
class Focallength(ExifBaseElement):
"(float) The focal length used, e.g. 23.7"
_tag = 'focallength'
def FocallengthFromString(xml_string):
return atom.CreateClassFromXMLString(Focallength, xml_string)
class Fstop(ExifBaseElement):
"(float) The fstop value used, e.g. 5.0"
_tag = 'fstop'
def FstopFromString(xml_string):
return atom.CreateClassFromXMLString(Fstop, xml_string)
class ImageUniqueID(ExifBaseElement):
"(string) The unique image ID for the photo. Generated by Google Photo servers"
_tag = 'imageUniqueID'
def ImageUniqueIDFromString(xml_string):
return atom.CreateClassFromXMLString(ImageUniqueID, xml_string)
class Iso(ExifBaseElement):
"(int) The iso equivalent value used, e.g. 200"
_tag = 'iso'
def IsoFromString(xml_string):
return atom.CreateClassFromXMLString(Iso, xml_string)
class Make(ExifBaseElement):
"(string) The make of the camera used, e.g. Fictitious Camera Company"
_tag = 'make'
def MakeFromString(xml_string):
return atom.CreateClassFromXMLString(Make, xml_string)
class Model(ExifBaseElement):
"(string) The model of the camera used,e.g AMAZING-100D"
_tag = 'model'
def ModelFromString(xml_string):
return atom.CreateClassFromXMLString(Model, xml_string)
class Time(ExifBaseElement):
"""(int) The date/time the photo was taken, e.g. 1180294337000.
Represented as the number of milliseconds since January 1st, 1970.
The value of this element will always be identical to the value
of the <gphoto:timestamp>.
Look at this object's .isoformat() for a human friendly datetime string:
photo_epoch = Time.text # 1180294337000
photo_isostring = Time.isoformat() # '2007-05-27T19:32:17.000Z'
Alternatively:
photo_datetime = Time.datetime() # (requires python >= 2.3)
"""
_tag = 'time'
def isoformat(self):
"""(string) Return the timestamp as a ISO 8601 formatted string,
e.g. '2007-05-27T19:32:17.000Z'
"""
import time
epoch = float(self.text)/1000
return time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(epoch))
def datetime(self):
"""(datetime.datetime) Return the timestamp as a datetime.datetime object
Requires python 2.3
"""
import datetime
epoch = float(self.text)/1000
return datetime.datetime.fromtimestamp(epoch)
def TimeFromString(xml_string):
return atom.CreateClassFromXMLString(Time, xml_string)
class Tags(ExifBaseElement):
"""The container for all exif elements.
The <exif:tags> element can appear as a child of a photo entry.
"""
_tag = 'tags'
_children = atom.AtomBase._children.copy()
_children['{%s}fstop' % EXIF_NAMESPACE] = ('fstop', Fstop)
_children['{%s}make' % EXIF_NAMESPACE] = ('make', Make)
_children['{%s}model' % EXIF_NAMESPACE] = ('model', Model)
_children['{%s}distance' % EXIF_NAMESPACE] = ('distance', Distance)
_children['{%s}exposure' % EXIF_NAMESPACE] = ('exposure', Exposure)
_children['{%s}flash' % EXIF_NAMESPACE] = ('flash', Flash)
_children['{%s}focallength' % EXIF_NAMESPACE] = ('focallength', Focallength)
_children['{%s}iso' % EXIF_NAMESPACE] = ('iso', Iso)
_children['{%s}time' % EXIF_NAMESPACE] = ('time', Time)
_children['{%s}imageUniqueID' % EXIF_NAMESPACE] = ('imageUniqueID', ImageUniqueID)
def __init__(self, extension_elements=None, extension_attributes=None, text=None):
ExifBaseElement.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.fstop=None
self.make=None
self.model=None
self.distance=None
self.exposure=None
self.flash=None
self.focallength=None
self.iso=None
self.time=None
self.imageUniqueID=None
def TagsFromString(xml_string):
return atom.CreateClassFromXMLString(Tags, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = ('api.stephaniel@gmail.com (Stephanie Liu)'
', api.jhartmann@gmail.com (Jochen Hartmann)')
import atom
import gdata
import gdata.media as Media
import gdata.geo as Geo
YOUTUBE_NAMESPACE = 'http://gdata.youtube.com/schemas/2007'
YOUTUBE_FORMAT = '{http://gdata.youtube.com/schemas/2007}format'
YOUTUBE_DEVELOPER_TAG_SCHEME = '%s/%s' % (YOUTUBE_NAMESPACE,
'developertags.cat')
YOUTUBE_SUBSCRIPTION_TYPE_SCHEME = '%s/%s' % (YOUTUBE_NAMESPACE,
'subscriptiontypes.cat')
class Username(atom.AtomBase):
"""The YouTube Username element"""
_tag = 'username'
_namespace = YOUTUBE_NAMESPACE
class QueryString(atom.AtomBase):
"""The YouTube QueryString element"""
_tag = 'queryString'
_namespace = YOUTUBE_NAMESPACE
class FirstName(atom.AtomBase):
"""The YouTube FirstName element"""
_tag = 'firstName'
_namespace = YOUTUBE_NAMESPACE
class LastName(atom.AtomBase):
"""The YouTube LastName element"""
_tag = 'lastName'
_namespace = YOUTUBE_NAMESPACE
class Age(atom.AtomBase):
"""The YouTube Age element"""
_tag = 'age'
_namespace = YOUTUBE_NAMESPACE
class Books(atom.AtomBase):
"""The YouTube Books element"""
_tag = 'books'
_namespace = YOUTUBE_NAMESPACE
class Gender(atom.AtomBase):
"""The YouTube Gender element"""
_tag = 'gender'
_namespace = YOUTUBE_NAMESPACE
class Company(atom.AtomBase):
"""The YouTube Company element"""
_tag = 'company'
_namespace = YOUTUBE_NAMESPACE
class Hobbies(atom.AtomBase):
"""The YouTube Hobbies element"""
_tag = 'hobbies'
_namespace = YOUTUBE_NAMESPACE
class Hometown(atom.AtomBase):
"""The YouTube Hometown element"""
_tag = 'hometown'
_namespace = YOUTUBE_NAMESPACE
class Location(atom.AtomBase):
"""The YouTube Location element"""
_tag = 'location'
_namespace = YOUTUBE_NAMESPACE
class Movies(atom.AtomBase):
"""The YouTube Movies element"""
_tag = 'movies'
_namespace = YOUTUBE_NAMESPACE
class Music(atom.AtomBase):
"""The YouTube Music element"""
_tag = 'music'
_namespace = YOUTUBE_NAMESPACE
class Occupation(atom.AtomBase):
"""The YouTube Occupation element"""
_tag = 'occupation'
_namespace = YOUTUBE_NAMESPACE
class School(atom.AtomBase):
"""The YouTube School element"""
_tag = 'school'
_namespace = YOUTUBE_NAMESPACE
class Relationship(atom.AtomBase):
"""The YouTube Relationship element"""
_tag = 'relationship'
_namespace = YOUTUBE_NAMESPACE
class Recorded(atom.AtomBase):
"""The YouTube Recorded element"""
_tag = 'recorded'
_namespace = YOUTUBE_NAMESPACE
class Statistics(atom.AtomBase):
"""The YouTube Statistics element."""
_tag = 'statistics'
_namespace = YOUTUBE_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['viewCount'] = 'view_count'
_attributes['videoWatchCount'] = 'video_watch_count'
_attributes['subscriberCount'] = 'subscriber_count'
_attributes['lastWebAccess'] = 'last_web_access'
_attributes['favoriteCount'] = 'favorite_count'
def __init__(self, view_count=None, video_watch_count=None,
favorite_count=None, subscriber_count=None, last_web_access=None,
extension_elements=None, extension_attributes=None, text=None):
self.view_count = view_count
self.video_watch_count = video_watch_count
self.subscriber_count = subscriber_count
self.last_web_access = last_web_access
self.favorite_count = favorite_count
atom.AtomBase.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes, text=text)
class Status(atom.AtomBase):
"""The YouTube Status element"""
_tag = 'status'
_namespace = YOUTUBE_NAMESPACE
class Position(atom.AtomBase):
"""The YouTube Position element. The position in a playlist feed."""
_tag = 'position'
_namespace = YOUTUBE_NAMESPACE
class Racy(atom.AtomBase):
"""The YouTube Racy element."""
_tag = 'racy'
_namespace = YOUTUBE_NAMESPACE
class Description(atom.AtomBase):
"""The YouTube Description element."""
_tag = 'description'
_namespace = YOUTUBE_NAMESPACE
class Private(atom.AtomBase):
"""The YouTube Private element."""
_tag = 'private'
_namespace = YOUTUBE_NAMESPACE
class NoEmbed(atom.AtomBase):
"""The YouTube VideoShare element. Whether a video can be embedded or not."""
_tag = 'noembed'
_namespace = YOUTUBE_NAMESPACE
class Comments(atom.AtomBase):
"""The GData Comments element"""
_tag = 'comments'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
[gdata.FeedLink])
def __init__(self, feed_link=None, extension_elements=None,
extension_attributes=None, text=None):
self.feed_link = feed_link
atom.AtomBase.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes, text=text)
class Rating(atom.AtomBase):
"""The GData Rating element"""
_tag = 'rating'
_namespace = gdata.GDATA_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['min'] = 'min'
_attributes['max'] = 'max'
_attributes['numRaters'] = 'num_raters'
_attributes['average'] = 'average'
def __init__(self, min=None, max=None,
num_raters=None, average=None, extension_elements=None,
extension_attributes=None, text=None):
self.min = min
self.max = max
self.num_raters = num_raters
self.average = average
atom.AtomBase.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes, text=text)
class YouTubePlaylistVideoEntry(gdata.GDataEntry):
"""Represents a YouTubeVideoEntry on a YouTubePlaylist."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
[gdata.FeedLink])
_children['{%s}description' % YOUTUBE_NAMESPACE] = ('description',
Description)
_children['{%s}rating' % gdata.GDATA_NAMESPACE] = ('rating', Rating)
_children['{%s}comments' % gdata.GDATA_NAMESPACE] = ('comments', Comments)
_children['{%s}statistics' % YOUTUBE_NAMESPACE] = ('statistics', Statistics)
_children['{%s}location' % YOUTUBE_NAMESPACE] = ('location', Location)
_children['{%s}position' % YOUTUBE_NAMESPACE] = ('position', Position)
_children['{%s}group' % gdata.media.MEDIA_NAMESPACE] = ('media', Media.Group)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None, title=None,
updated=None, feed_link=None, description=None,
rating=None, comments=None, statistics=None,
location=None, position=None, media=None,
extension_elements=None, extension_attributes=None):
self.feed_link = feed_link
self.description = description
self.rating = rating
self.comments = comments
self.statistics = statistics
self.location = location
self.position = position
self.media = media
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id,
link=link, published=published, title=title,
updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
class YouTubeVideoCommentEntry(gdata.GDataEntry):
"""Represents a comment on YouTube."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
class YouTubeSubscriptionEntry(gdata.GDataEntry):
"""Represents a subscription entry on YouTube."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}username' % YOUTUBE_NAMESPACE] = ('username', Username)
_children['{%s}queryString' % YOUTUBE_NAMESPACE] = (
'query_string', QueryString)
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
[gdata.FeedLink])
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None, title=None,
updated=None, username=None, query_string=None, feed_link=None,
extension_elements=None, extension_attributes=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title, updated=updated)
self.username = username
self.query_string = query_string
self.feed_link = feed_link
def GetSubscriptionType(self):
"""Retrieve the type of this subscription.
Returns:
A string that is either 'channel, 'query' or 'favorites'
"""
for category in self.category:
if category.scheme == YOUTUBE_SUBSCRIPTION_TYPE_SCHEME:
return category.term
class YouTubeVideoResponseEntry(gdata.GDataEntry):
"""Represents a video response. """
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}rating' % gdata.GDATA_NAMESPACE] = ('rating', Rating)
_children['{%s}noembed' % YOUTUBE_NAMESPACE] = ('noembed', NoEmbed)
_children['{%s}statistics' % YOUTUBE_NAMESPACE] = ('statistics', Statistics)
_children['{%s}racy' % YOUTUBE_NAMESPACE] = ('racy', Racy)
_children['{%s}group' % gdata.media.MEDIA_NAMESPACE] = ('media', Media.Group)
def __init__(self, author=None, category=None, content=None, atom_id=None,
link=None, published=None, title=None, updated=None, rating=None,
noembed=None, statistics=None, racy=None, media=None,
extension_elements=None, extension_attributes=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title, updated=updated)
self.rating = rating
self.noembed = noembed
self.statistics = statistics
self.racy = racy
self.media = media or Media.Group()
class YouTubeContactEntry(gdata.GDataEntry):
"""Represents a contact entry."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}username' % YOUTUBE_NAMESPACE] = ('username', Username)
_children['{%s}status' % YOUTUBE_NAMESPACE] = ('status', Status)
def __init__(self, author=None, category=None, content=None, atom_id=None,
link=None, published=None, title=None, updated=None,
username=None, status=None, extension_elements=None,
extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title, updated=updated)
self.username = username
self.status = status
class YouTubeVideoEntry(gdata.GDataEntry):
"""Represents a video on YouTube."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}rating' % gdata.GDATA_NAMESPACE] = ('rating', Rating)
_children['{%s}comments' % gdata.GDATA_NAMESPACE] = ('comments', Comments)
_children['{%s}noembed' % YOUTUBE_NAMESPACE] = ('noembed', NoEmbed)
_children['{%s}statistics' % YOUTUBE_NAMESPACE] = ('statistics', Statistics)
_children['{%s}recorded' % YOUTUBE_NAMESPACE] = ('recorded', Recorded)
_children['{%s}racy' % YOUTUBE_NAMESPACE] = ('racy', Racy)
_children['{%s}group' % gdata.media.MEDIA_NAMESPACE] = ('media', Media.Group)
_children['{%s}where' % gdata.geo.GEORSS_NAMESPACE] = ('geo', Geo.Where)
def __init__(self, author=None, category=None, content=None, atom_id=None,
link=None, published=None, title=None, updated=None, rating=None,
noembed=None, statistics=None, racy=None, media=None, geo=None,
recorded=None, comments=None, extension_elements=None,
extension_attributes=None):
self.rating = rating
self.noembed = noembed
self.statistics = statistics
self.racy = racy
self.comments = comments
self.media = media or Media.Group()
self.geo = geo
self.recorded = recorded
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title, updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
def GetSwfUrl(self):
"""Return the URL for the embeddable Video
Returns:
URL of the embeddable video
"""
if self.media.content:
for content in self.media.content:
if content.extension_attributes[YOUTUBE_FORMAT] == '5':
return content.url
else:
return None
def AddDeveloperTags(self, developer_tags):
"""Add a developer tag for this entry.
Developer tags can only be set during the initial upload.
Arguments:
developer_tags: A list of developer tags as strings.
Returns:
A list of all developer tags for this video entry.
"""
for tag_text in developer_tags:
self.media.category.append(gdata.media.Category(
text=tag_text, label=tag_text, scheme=YOUTUBE_DEVELOPER_TAG_SCHEME))
return self.GetDeveloperTags()
def GetDeveloperTags(self):
"""Retrieve developer tags for this video entry."""
developer_tags = []
for category in self.media.category:
if category.scheme == YOUTUBE_DEVELOPER_TAG_SCHEME:
developer_tags.append(category)
if len(developer_tags) > 0:
return developer_tags
def GetYouTubeCategoryAsString(self):
"""Convenience method to return the YouTube category as string.
YouTubeVideoEntries can contain multiple Category objects with differing
schemes. This method returns only the category with the correct
scheme, ignoring developer tags.
"""
for category in self.media.category:
if category.scheme != YOUTUBE_DEVELOPER_TAG_SCHEME:
return category.text
class YouTubeUserEntry(gdata.GDataEntry):
"""Represents a user on YouTube."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}username' % YOUTUBE_NAMESPACE] = ('username', Username)
_children['{%s}firstName' % YOUTUBE_NAMESPACE] = ('first_name', FirstName)
_children['{%s}lastName' % YOUTUBE_NAMESPACE] = ('last_name', LastName)
_children['{%s}age' % YOUTUBE_NAMESPACE] = ('age', Age)
_children['{%s}books' % YOUTUBE_NAMESPACE] = ('books', Books)
_children['{%s}gender' % YOUTUBE_NAMESPACE] = ('gender', Gender)
_children['{%s}company' % YOUTUBE_NAMESPACE] = ('company', Company)
_children['{%s}description' % YOUTUBE_NAMESPACE] = ('description',
Description)
_children['{%s}hobbies' % YOUTUBE_NAMESPACE] = ('hobbies', Hobbies)
_children['{%s}hometown' % YOUTUBE_NAMESPACE] = ('hometown', Hometown)
_children['{%s}location' % YOUTUBE_NAMESPACE] = ('location', Location)
_children['{%s}movies' % YOUTUBE_NAMESPACE] = ('movies', Movies)
_children['{%s}music' % YOUTUBE_NAMESPACE] = ('music', Music)
_children['{%s}occupation' % YOUTUBE_NAMESPACE] = ('occupation', Occupation)
_children['{%s}school' % YOUTUBE_NAMESPACE] = ('school', School)
_children['{%s}relationship' % YOUTUBE_NAMESPACE] = ('relationship',
Relationship)
_children['{%s}statistics' % YOUTUBE_NAMESPACE] = ('statistics', Statistics)
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
[gdata.FeedLink])
_children['{%s}thumbnail' % gdata.media.MEDIA_NAMESPACE] = ('thumbnail',
Media.Thumbnail)
def __init__(self, author=None, category=None, content=None, atom_id=None,
link=None, published=None, title=None, updated=None,
username=None, first_name=None, last_name=None, age=None,
books=None, gender=None, company=None, description=None,
hobbies=None, hometown=None, location=None, movies=None,
music=None, occupation=None, school=None, relationship=None,
statistics=None, feed_link=None, extension_elements=None,
extension_attributes=None, text=None):
self.username = username
self.first_name = first_name
self.last_name = last_name
self.age = age
self.books = books
self.gender = gender
self.company = company
self.description = description
self.hobbies = hobbies
self.hometown = hometown
self.location = location
self.movies = movies
self.music = music
self.occupation = occupation
self.school = school
self.relationship = relationship
self.statistics = statistics
self.feed_link = feed_link
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id,
link=link, published=published,
title=title, updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
class YouTubeVideoFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a video feed on YouTube."""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [YouTubeVideoEntry])
class YouTubePlaylistEntry(gdata.GDataEntry):
"""Represents a playlist in YouTube."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}description' % YOUTUBE_NAMESPACE] = ('description',
Description)
_children['{%s}private' % YOUTUBE_NAMESPACE] = ('private',
Private)
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
[gdata.FeedLink])
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None, title=None,
updated=None, private=None, feed_link=None,
description=None, extension_elements=None,
extension_attributes=None):
self.description = description
self.private = private
self.feed_link = feed_link
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id,
link=link, published=published, title=title,
updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
class YouTubePlaylistFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a feed of a user's playlists """
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[YouTubePlaylistEntry])
class YouTubePlaylistVideoFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a feed of video entry on a playlist."""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[YouTubePlaylistVideoEntry])
class YouTubeContactFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a feed of a users contacts."""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[YouTubeContactEntry])
class YouTubeSubscriptionFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a feed of a users subscriptions."""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[YouTubeSubscriptionEntry])
class YouTubeVideoCommentFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a feed of comments for a video."""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[YouTubeVideoCommentEntry])
class YouTubeVideoResponseFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a feed of video responses."""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[YouTubeVideoResponseEntry])
def YouTubeVideoFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoFeed, xml_string)
def YouTubeVideoEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoEntry, xml_string)
def YouTubeContactFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeContactFeed, xml_string)
def YouTubeContactEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeContactEntry, xml_string)
def YouTubeVideoCommentFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoCommentFeed, xml_string)
def YouTubeVideoCommentEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoCommentEntry, xml_string)
def YouTubeUserFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoFeed, xml_string)
def YouTubeUserEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeUserEntry, xml_string)
def YouTubePlaylistFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubePlaylistFeed, xml_string)
def YouTubePlaylistVideoFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubePlaylistVideoFeed, xml_string)
def YouTubePlaylistEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubePlaylistEntry, xml_string)
def YouTubePlaylistVideoEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubePlaylistVideoEntry, xml_string)
def YouTubeSubscriptionFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeSubscriptionFeed, xml_string)
def YouTubeSubscriptionEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeSubscriptionEntry, xml_string)
def YouTubeVideoResponseFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoResponseFeed, xml_string)
def YouTubeVideoResponseEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoResponseEntry, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""YouTubeService extends GDataService to streamline YouTube operations.
YouTubeService: Provides methods to perform CRUD operations on YouTube feeds.
Extends GDataService.
"""
__author__ = ('api.stephaniel@gmail.com (Stephanie Liu), '
'api.jhartmann@gmail.com (Jochen Hartmann)')
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import os
import urllib
import atom
import gdata
import gdata.service
import gdata.youtube
YOUTUBE_SERVER = 'gdata.youtube.com'
YOUTUBE_SERVICE = 'youtube'
YOUTUBE_SUPPORTED_UPLOAD_TYPES = ('mov', 'avi', 'wmv', 'mpg', 'quicktime')
YOUTUBE_QUERY_VALID_TIME_PARAMETERS = ('today', 'this_week', 'this_month',
'all_time')
YOUTUBE_QUERY_VALID_ORDERBY_PARAMETERS = ('published', 'viewCount', 'rating',
'relevance')
YOUTUBE_QUERY_VALID_RACY_PARAMETERS = ('include', 'exclude')
YOUTUBE_QUERY_VALID_FORMAT_PARAMETERS = ('1', '5', '6')
YOUTUBE_STANDARDFEEDS = ('most_recent', 'recently_featured',
'top_rated', 'most_viewed','watch_on_mobile')
YOUTUBE_UPLOAD_URI = 'http://uploads.gdata.youtube.com/feeds/api/users'
YOUTUBE_UPLOAD_TOKEN_URI = 'http://gdata.youtube.com/action/GetUploadToken'
YOUTUBE_VIDEO_URI = 'http://gdata.youtube.com/feeds/api/videos'
YOUTUBE_USER_FEED_URI = 'http://gdata.youtube.com/feeds/api/users'
YOUTUBE_PLAYLIST_FEED_URI = 'http://gdata.youtube.com/feeds/api/playlists'
YOUTUBE_STANDARD_FEEDS = 'http://gdata.youtube.com/feeds/api/standardfeeds'
YOUTUBE_STANDARD_TOP_RATED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'top_rated')
YOUTUBE_STANDARD_MOST_VIEWED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'most_viewed')
YOUTUBE_STANDARD_RECENTLY_FEATURED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'recently_featured')
YOUTUBE_STANDARD_WATCH_ON_MOBILE_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'watch_on_mobile')
YOUTUBE_STANDARD_TOP_FAVORITES_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'top_favorites')
YOUTUBE_STANDARD_MOST_RECENT_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'most_recent')
YOUTUBE_STANDARD_MOST_DISCUSSED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'most_discussed')
YOUTUBE_STANDARD_MOST_LINKED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'most_linked')
YOUTUBE_STANDARD_MOST_RESPONDED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'most_responded')
YOUTUBE_SCHEMA = 'http://gdata.youtube.com/schemas'
YOUTUBE_RATING_LINK_REL = '%s#video.ratings' % YOUTUBE_SCHEMA
YOUTUBE_COMPLAINT_CATEGORY_SCHEME = '%s/%s' % (YOUTUBE_SCHEMA,
'complaint-reasons.cat')
YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME = '%s/%s' % (YOUTUBE_SCHEMA,
'subscriptiontypes.cat')
YOUTUBE_COMPLAINT_CATEGORY_TERMS = ('PORN', 'VIOLENCE', 'HATE', 'DANGEROUS',
'RIGHTS', 'SPAM')
YOUTUBE_CONTACT_STATUS = ('accepted', 'rejected')
YOUTUBE_CONTACT_CATEGORY = ('Friends', 'Family')
UNKOWN_ERROR = 1000
YOUTUBE_BAD_REQUEST = 400
YOUTUBE_CONFLICT = 409
YOUTUBE_INTERNAL_SERVER_ERROR = 500
YOUTUBE_INVALID_ARGUMENT = 601
YOUTUBE_INVALID_CONTENT_TYPE = 602
YOUTUBE_NOT_A_VIDEO = 603
YOUTUBE_INVALID_KIND = 604
class Error(Exception):
"""Base class for errors within the YouTube service."""
pass
class RequestError(Error):
"""Error class that is thrown in response to an invalid HTTP Request."""
pass
class YouTubeError(Error):
"""YouTube service specific error class."""
pass
class YouTubeService(gdata.service.GDataService):
"""Client for the YouTube service.
Performs all documented Google Data YouTube API functions, such as inserting,
updating and deleting videos, comments, playlist, subscriptions etc.
YouTube Service requires authentication for any write, update or delete
actions.
Attributes:
email: An optional string identifying the user. Required only for
authenticated actions.
password: An optional string identifying the user's password.
source: An optional string identifying the name of your application.
server: An optional address of the YouTube API server. gdata.youtube.com
is provided as the default value.
additional_headers: An optional dictionary containing additional headers
to be passed along with each request. Use to store developer key.
client_id: An optional string identifying your application, required for
authenticated requests, along with a developer key.
developer_key: An optional string value. Register your application at
http://code.google.com/apis/youtube/dashboard to obtain a (free) key.
"""
def __init__(self, email=None, password=None, source=None,
server=YOUTUBE_SERVER, additional_headers=None, client_id=None,
developer_key=None):
if client_id is not None and developer_key is not None:
self.additional_headers = {'X-Gdata-Client': self.client_id,
'X-GData-Key': 'key=%s' % self.developer_key}
gdata.service.GDataService.__init__(
self, email=email, password=password, service=YOUTUBE_SERVICE,
source=source, server=server,
additional_headers=self.additional_headers)
elif developer_key and not client_id:
raise YouTubeError('You must also specify the clientId')
else:
gdata.service.GDataService.__init__(
self, email=email, password=password, service=YOUTUBE_SERVICE,
source=source, server=server, additional_headers=additional_headers)
def GetYouTubeVideoFeed(self, uri):
"""Retrieve a YouTubeVideoFeed.
Args:
uri: A string representing the URI of the feed that is to be retrieved.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.Get(uri, converter=gdata.youtube.YouTubeVideoFeedFromString)
def GetYouTubeVideoEntry(self, uri=None, video_id=None):
"""Retrieve a YouTubeVideoEntry.
Either a uri or a video_id must be provided.
Args:
uri: An optional string representing the URI of the entry that is to
be retrieved.
video_id: An optional string representing the ID of the video.
Returns:
A YouTubeVideoFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a video_id to the
GetYouTubeVideoEntry() method.
"""
if uri is None and video_id is None:
raise YouTubeError('You must provide at least a uri or a video_id '
'to the GetYouTubeVideoEntry() method')
elif video_id and not uri:
uri = '%s/%s' % (YOUTUBE_VIDEO_URI, video_id)
return self.Get(uri, converter=gdata.youtube.YouTubeVideoEntryFromString)
def GetYouTubeContactFeed(self, uri=None, username='default'):
"""Retrieve a YouTubeContactFeed.
Either a uri or a username must be provided.
Args:
uri: An optional string representing the URI of the contact feed that
is to be retrieved.
username: An optional string representing the username. Defaults to the
currently authenticated user.
Returns:
A YouTubeContactFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a username to the
GetYouTubeContactFeed() method.
"""
if uri is None:
uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'contacts')
return self.Get(uri, converter=gdata.youtube.YouTubeContactFeedFromString)
def GetYouTubeContactEntry(self, uri):
"""Retrieve a YouTubeContactEntry.
Args:
uri: A string representing the URI of the contact entry that is to
be retrieved.
Returns:
A YouTubeContactEntry if successfully retrieved.
"""
return self.Get(uri, converter=gdata.youtube.YouTubeContactEntryFromString)
def GetYouTubeVideoCommentFeed(self, uri=None, video_id=None):
"""Retrieve a YouTubeVideoCommentFeed.
Either a uri or a video_id must be provided.
Args:
uri: An optional string representing the URI of the comment feed that
is to be retrieved.
video_id: An optional string representing the ID of the video for which
to retrieve the comment feed.
Returns:
A YouTubeVideoCommentFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a video_id to the
GetYouTubeVideoCommentFeed() method.
"""
if uri is None and video_id is None:
raise YouTubeError('You must provide at least a uri or a video_id '
'to the GetYouTubeVideoCommentFeed() method')
elif video_id and not uri:
uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'comments')
return self.Get(
uri, converter=gdata.youtube.YouTubeVideoCommentFeedFromString)
def GetYouTubeVideoCommentEntry(self, uri):
"""Retrieve a YouTubeVideoCommentEntry.
Args:
uri: A string representing the URI of the comment entry that is to
be retrieved.
Returns:
A YouTubeCommentEntry if successfully retrieved.
"""
return self.Get(
uri, converter=gdata.youtube.YouTubeVideoCommentEntryFromString)
def GetYouTubeUserFeed(self, uri=None, username=None):
"""Retrieve a YouTubeUserFeed.
Either a uri or a username must be provided.
Args:
uri: An optional string representing the URI of the user feed that is
to be retrieved.
username: An optional string representing the username.
Returns:
A YouTubeUserFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a username to the
GetYouTubeUserFeed() method.
"""
if uri is None and username is None:
raise YouTubeError('You must provide at least a uri or a username '
'to the GetYouTubeUserFeed() method')
elif username and not uri:
uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'uploads')
return self.Get(uri, converter=gdata.youtube.YouTubeUserFeedFromString)
def GetYouTubeUserEntry(self, uri=None, username=None):
"""Retrieve a YouTubeUserEntry.
Either a uri or a username must be provided.
Args:
uri: An optional string representing the URI of the user entry that is
to be retrieved.
username: An optional string representing the username.
Returns:
A YouTubeUserEntry if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a username to the
GetYouTubeUserEntry() method.
"""
if uri is None and username is None:
raise YouTubeError('You must provide at least a uri or a username '
'to the GetYouTubeUserEntry() method')
elif username and not uri:
uri = '%s/%s' % (YOUTUBE_USER_FEED_URI, username)
return self.Get(uri, converter=gdata.youtube.YouTubeUserEntryFromString)
def GetYouTubePlaylistFeed(self, uri=None, username='default'):
"""Retrieve a YouTubePlaylistFeed (a feed of playlists for a user).
Either a uri or a username must be provided.
Args:
uri: An optional string representing the URI of the playlist feed that
is to be retrieved.
username: An optional string representing the username. Defaults to the
currently authenticated user.
Returns:
A YouTubePlaylistFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a username to the
GetYouTubePlaylistFeed() method.
"""
if uri is None:
uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'playlists')
return self.Get(uri, converter=gdata.youtube.YouTubePlaylistFeedFromString)
def GetYouTubePlaylistEntry(self, uri):
"""Retrieve a YouTubePlaylistEntry.
Args:
uri: A string representing the URI of the playlist feed that is to
be retrieved.
Returns:
A YouTubePlaylistEntry if successfully retrieved.
"""
return self.Get(uri, converter=gdata.youtube.YouTubePlaylistEntryFromString)
def GetYouTubePlaylistVideoFeed(self, uri=None, playlist_id=None):
"""Retrieve a YouTubePlaylistVideoFeed (a feed of videos on a playlist).
Either a uri or a playlist_id must be provided.
Args:
uri: An optional string representing the URI of the playlist video feed
that is to be retrieved.
playlist_id: An optional string representing the Id of the playlist whose
playlist video feed is to be retrieved.
Returns:
A YouTubePlaylistVideoFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a playlist_id to the
GetYouTubePlaylistVideoFeed() method.
"""
if uri is None and playlist_id is None:
raise YouTubeError('You must provide at least a uri or a playlist_id '
'to the GetYouTubePlaylistVideoFeed() method')
elif playlist_id and not uri:
uri = '%s/%s' % (YOUTUBE_PLAYLIST_FEED_URI, playlist_id)
return self.Get(
uri, converter=gdata.youtube.YouTubePlaylistVideoFeedFromString)
def GetYouTubeVideoResponseFeed(self, uri=None, video_id=None):
"""Retrieve a YouTubeVideoResponseFeed.
Either a uri or a playlist_id must be provided.
Args:
uri: An optional string representing the URI of the video response feed
that is to be retrieved.
video_id: An optional string representing the ID of the video whose
response feed is to be retrieved.
Returns:
A YouTubeVideoResponseFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a video_id to the
GetYouTubeVideoResponseFeed() method.
"""
if uri is None and video_id is None:
raise YouTubeError('You must provide at least a uri or a video_id '
'to the GetYouTubeVideoResponseFeed() method')
elif video_id and not uri:
uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'responses')
return self.Get(
uri, converter=gdata.youtube.YouTubeVideoResponseFeedFromString)
def GetYouTubeVideoResponseEntry(self, uri):
"""Retrieve a YouTubeVideoResponseEntry.
Args:
uri: A string representing the URI of the video response entry that
is to be retrieved.
Returns:
A YouTubeVideoResponseEntry if successfully retrieved.
"""
return self.Get(
uri, converter=gdata.youtube.YouTubeVideoResponseEntryFromString)
def GetYouTubeSubscriptionFeed(self, uri=None, username='default'):
"""Retrieve a YouTubeSubscriptionFeed.
Either the uri of the feed or a username must be provided.
Args:
uri: An optional string representing the URI of the feed that is to
be retrieved.
username: An optional string representing the username whose subscription
feed is to be retrieved. Defaults to the currently authenticted user.
Returns:
A YouTubeVideoSubscriptionFeed if successfully retrieved.
"""
if uri is None:
uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'subscriptions')
return self.Get(
uri, converter=gdata.youtube.YouTubeSubscriptionFeedFromString)
def GetYouTubeSubscriptionEntry(self, uri):
"""Retrieve a YouTubeSubscriptionEntry.
Args:
uri: A string representing the URI of the entry that is to be retrieved.
Returns:
A YouTubeVideoSubscriptionEntry if successfully retrieved.
"""
return self.Get(
uri, converter=gdata.youtube.YouTubeSubscriptionEntryFromString)
def GetYouTubeRelatedVideoFeed(self, uri=None, video_id=None):
"""Retrieve a YouTubeRelatedVideoFeed.
Either a uri for the feed or a video_id is required.
Args:
uri: An optional string representing the URI of the feed that is to
be retrieved.
video_id: An optional string representing the ID of the video for which
to retrieve the related video feed.
Returns:
A YouTubeRelatedVideoFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a video_id to the
GetYouTubeRelatedVideoFeed() method.
"""
if uri is None and video_id is None:
raise YouTubeError('You must provide at least a uri or a video_id '
'to the GetYouTubeRelatedVideoFeed() method')
elif video_id and not uri:
uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'related')
return self.Get(
uri, converter=gdata.youtube.YouTubeVideoFeedFromString)
def GetTopRatedVideoFeed(self):
"""Retrieve the 'top_rated' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_TOP_RATED_URI)
def GetMostViewedVideoFeed(self):
"""Retrieve the 'most_viewed' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_VIEWED_URI)
def GetRecentlyFeaturedVideoFeed(self):
"""Retrieve the 'recently_featured' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_RECENTLY_FEATURED_URI)
def GetWatchOnMobileVideoFeed(self):
"""Retrieve the 'watch_on_mobile' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_WATCH_ON_MOBILE_URI)
def GetTopFavoritesVideoFeed(self):
"""Retrieve the 'top_favorites' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_TOP_FAVORITES_URI)
def GetMostRecentVideoFeed(self):
"""Retrieve the 'most_recent' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_RECENT_URI)
def GetMostDiscussedVideoFeed(self):
"""Retrieve the 'most_discussed' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_DISCUSSED_URI)
def GetMostLinkedVideoFeed(self):
"""Retrieve the 'most_linked' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_LINKED_URI)
def GetMostRespondedVideoFeed(self):
"""Retrieve the 'most_responded' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_RESPONDED_URI)
def GetUserFavoritesFeed(self, username='default'):
"""Retrieve the favorites feed for a given user.
Args:
username: An optional string representing the username whose favorites
feed is to be retrieved. Defaults to the currently authenticated user.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
favorites_feed_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username,
'favorites')
return self.GetYouTubeVideoFeed(favorites_feed_uri)
def InsertVideoEntry(self, video_entry, filename_or_handle,
youtube_username='default',
content_type='video/quicktime'):
"""Upload a new video to YouTube using the direct upload mechanism.
Needs authentication.
Args:
video_entry: The YouTubeVideoEntry to upload.
filename_or_handle: A file-like object or file name where the video
will be read from.
youtube_username: An optional string representing the username into whose
account this video is to be uploaded to. Defaults to the currently
authenticated user.
content_type: An optional string representing internet media type
(a.k.a. mime type) of the media object. Currently the YouTube API
supports these types:
o video/mpeg
o video/quicktime
o video/x-msvideo
o video/mp4
Returns:
The newly created YouTubeVideoEntry if successful.
Raises:
AssertionError: video_entry must be a gdata.youtube.VideoEntry instance.
YouTubeError: An error occurred trying to read the video file provided.
gdata.service.RequestError: An error occurred trying to upload the video
to the API server.
"""
# We need to perform a series of checks on the video_entry and on the
# file that we plan to upload, such as checking whether we have a valid
# video_entry and that the file is the correct type and readable, prior
# to performing the actual POST request.
try:
assert(isinstance(video_entry, gdata.youtube.YouTubeVideoEntry))
except AssertionError:
raise YouTubeError({'status':YOUTUBE_INVALID_ARGUMENT,
'body':'`video_entry` must be a gdata.youtube.VideoEntry instance',
'reason':'Found %s, not VideoEntry' % type(video_entry)
})
majtype, mintype = content_type.split('/')
try:
assert(mintype in YOUTUBE_SUPPORTED_UPLOAD_TYPES)
except (ValueError, AssertionError):
raise YouTubeError({'status':YOUTUBE_INVALID_CONTENT_TYPE,
'body':'This is not a valid content type: %s' % content_type,
'reason':'Accepted content types: %s' %
['video/%s' % (t) for t in YOUTUBE_SUPPORTED_UPLOAD_TYPES]})
if (isinstance(filename_or_handle, (str, unicode))
and os.path.exists(filename_or_handle)):
mediasource = gdata.MediaSource()
mediasource.setFile(filename_or_handle, content_type)
elif hasattr(filename_or_handle, 'read'):
if hasattr(filename_or_handle, 'seek'):
filename_or_handle.seek(0)
file_handle = StringIO.StringIO(filename_or_handle.read())
name = 'video'
if hasattr(filename_or_handle, 'name'):
name = filename_or_handle.name
mediasource = gdata.MediaSource(file_handle, content_type,
content_length=file_handle.len, file_name=name)
else:
raise YouTubeError({'status':YOUTUBE_INVALID_ARGUMENT, 'body':
'`filename_or_handle` must be a path name or a file-like object',
'reason': ('Found %s, not path name or object '
'with a .read() method' % type(filename_or_handle))})
upload_uri = '%s/%s/%s' % (YOUTUBE_UPLOAD_URI, youtube_username,
'uploads')
self.additional_headers['Slug'] = mediasource.file_name
# Using a nested try statement to retain Python 2.4 compatibility
try:
try:
return self.Post(video_entry, uri=upload_uri, media_source=mediasource,
converter=gdata.youtube.YouTubeVideoEntryFromString)
except gdata.service.RequestError, e:
raise YouTubeError(e.args[0])
finally:
del(self.additional_headers['Slug'])
def CheckUploadStatus(self, video_entry=None, video_id=None):
"""Check upload status on a recently uploaded video entry.
Needs authentication. Either video_entry or video_id must be provided.
Args:
video_entry: An optional YouTubeVideoEntry whose upload status to check
video_id: An optional string representing the ID of the uploaded video
whose status is to be checked.
Returns:
A tuple containing (video_upload_state, detailed_message) or None if
no status information is found.
Raises:
YouTubeError: You must provide at least a video_entry or a video_id to the
CheckUploadStatus() method.
"""
if video_entry is None and video_id is None:
raise YouTubeError('You must provide at least a uri or a video_id '
'to the CheckUploadStatus() method')
elif video_id and not video_entry:
video_entry = self.GetYouTubeVideoEntry(video_id=video_id)
control = video_entry.control
if control is not None:
draft = control.draft
if draft is not None:
if draft.text == 'yes':
yt_state = control.extension_elements[0]
if yt_state is not None:
state_value = yt_state.attributes['name']
message = ''
if yt_state.text is not None:
message = yt_state.text
return (state_value, message)
def GetFormUploadToken(self, video_entry, uri=YOUTUBE_UPLOAD_TOKEN_URI):
"""Receives a YouTube Token and a YouTube PostUrl from a YouTubeVideoEntry.
Needs authentication.
Args:
video_entry: The YouTubeVideoEntry to upload (meta-data only).
uri: An optional string representing the URI from where to fetch the
token information. Defaults to the YOUTUBE_UPLOADTOKEN_URI.
Returns:
A tuple containing the URL to which to post your video file, along
with the youtube token that must be included with your upload in the
form of: (post_url, youtube_token).
"""
try:
response = self.Post(video_entry, uri)
except gdata.service.RequestError, e:
raise YouTubeError(e.args[0])
tree = ElementTree.fromstring(response)
for child in tree:
if child.tag == 'url':
post_url = child.text
elif child.tag == 'token':
youtube_token = child.text
return (post_url, youtube_token)
def UpdateVideoEntry(self, video_entry):
"""Updates a video entry's meta-data.
Needs authentication.
Args:
video_entry: The YouTubeVideoEntry to update, containing updated
meta-data.
Returns:
An updated YouTubeVideoEntry on success or None.
"""
for link in video_entry.link:
if link.rel == 'edit':
edit_uri = link.href
return self.Put(video_entry, uri=edit_uri,
converter=gdata.youtube.YouTubeVideoEntryFromString)
def DeleteVideoEntry(self, video_entry):
"""Deletes a video entry.
Needs authentication.
Args:
video_entry: The YouTubeVideoEntry to be deleted.
Returns:
True if entry was deleted successfully.
"""
for link in video_entry.link:
if link.rel == 'edit':
edit_uri = link.href
return self.Delete(edit_uri)
def AddRating(self, rating_value, video_entry):
"""Add a rating to a video entry.
Needs authentication.
Args:
rating_value: The integer value for the rating (between 1 and 5).
video_entry: The YouTubeVideoEntry to be rated.
Returns:
True if the rating was added successfully.
Raises:
YouTubeError: rating_value must be between 1 and 5 in AddRating().
"""
if rating_value < 1 or rating_value > 5:
raise YouTubeError('rating_value must be between 1 and 5 in AddRating()')
entry = gdata.GDataEntry()
rating = gdata.youtube.Rating(min='1', max='5')
rating.extension_attributes['name'] = 'value'
rating.extension_attributes['value'] = str(rating_value)
entry.extension_elements.append(rating)
for link in video_entry.link:
if link.rel == YOUTUBE_RATING_LINK_REL:
rating_uri = link.href
return self.Post(entry, uri=rating_uri)
def AddComment(self, comment_text, video_entry):
"""Add a comment to a video entry.
Needs authentication. Note that each comment that is posted must contain
the video entry that it is to be posted to.
Args:
comment_text: A string representing the text of the comment.
video_entry: The YouTubeVideoEntry to be commented on.
Returns:
True if the comment was added successfully.
"""
content = atom.Content(text=comment_text)
comment_entry = gdata.youtube.YouTubeVideoCommentEntry(content=content)
comment_post_uri = video_entry.comments.feed_link[0].href
return self.Post(comment_entry, uri=comment_post_uri)
def AddVideoResponse(self, video_id_to_respond_to, video_response):
"""Add a video response.
Needs authentication.
Args:
video_id_to_respond_to: A string representing the ID of the video to be
responded to.
video_response: YouTubeVideoEntry to be posted as a response.
Returns:
True if video response was posted successfully.
"""
post_uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id_to_respond_to,
'responses')
return self.Post(video_response, uri=post_uri)
def DeleteVideoResponse(self, video_id, response_video_id):
"""Delete a video response.
Needs authentication.
Args:
video_id: A string representing the ID of video that contains the
response.
response_video_id: A string representing the ID of the video that was
posted as a response.
Returns:
True if video response was deleted succcessfully.
"""
delete_uri = '%s/%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'responses',
response_video_id)
return self.Delete(delete_uri)
def AddComplaint(self, complaint_text, complaint_term, video_id):
"""Add a complaint for a particular video entry.
Needs authentication.
Args:
complaint_text: A string representing the complaint text.
complaint_term: A string representing the complaint category term.
video_id: A string representing the ID of YouTubeVideoEntry to
complain about.
Returns:
True if posted successfully.
Raises:
YouTubeError: Your complaint_term is not valid.
"""
if complaint_term not in YOUTUBE_COMPLAINT_CATEGORY_TERMS:
raise YouTubeError('Your complaint_term is not valid')
content = atom.Content(text=complaint_text)
category = atom.Category(term=complaint_term,
scheme=YOUTUBE_COMPLAINT_CATEGORY_SCHEME)
complaint_entry = gdata.GDataEntry(content=content, category=[category])
post_uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'complaints')
return self.Post(complaint_entry, post_uri)
def AddVideoEntryToFavorites(self, video_entry, username='default'):
"""Add a video entry to a users favorite feed.
Needs authentication.
Args:
video_entry: The YouTubeVideoEntry to add.
username: An optional string representing the username to whose favorite
feed you wish to add the entry. Defaults to the currently
authenticated user.
Returns:
The posted YouTubeVideoEntry if successfully posted.
"""
post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'favorites')
return self.Post(video_entry, post_uri,
converter=gdata.youtube.YouTubeVideoEntryFromString)
def DeleteVideoEntryFromFavorites(self, video_id, username='default'):
"""Delete a video entry from the users favorite feed.
Needs authentication.
Args:
video_id: A string representing the ID of the video that is to be removed
username: An optional string representing the username of the user's
favorite feed. Defaults to the currently authenticated user.
Returns:
True if entry was successfully deleted.
"""
edit_link = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'favorites',
video_id)
return self.Delete(edit_link)
def AddPlaylist(self, playlist_title, playlist_description,
playlist_private=None):
"""Add a new playlist to the currently authenticated users account.
Needs authentication.
Args:
playlist_title: A string representing the title for the new playlist.
playlist_description: A string representing the description of the
playlist.
playlist_private: An optional boolean, set to True if the playlist is
to be private.
Returns:
The YouTubePlaylistEntry if successfully posted.
"""
playlist_entry = gdata.youtube.YouTubePlaylistEntry(
title=atom.Title(text=playlist_title),
description=gdata.youtube.Description(text=playlist_description))
if playlist_private:
playlist_entry.private = gdata.youtube.Private()
playlist_post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, 'default',
'playlists')
return self.Post(playlist_entry, playlist_post_uri,
converter=gdata.youtube.YouTubePlaylistEntryFromString)
def UpdatePlaylist(self, playlist_id, new_playlist_title,
new_playlist_description, playlist_private=None,
username='default'):
"""Update a playlist with new meta-data.
Needs authentication.
Args:
playlist_id: A string representing the ID of the playlist to be updated.
new_playlist_title: A string representing a new title for the playlist.
new_playlist_description: A string representing a new description for the
playlist.
playlist_private: An optional boolean, set to True if the playlist is
to be private.
username: An optional string representing the username whose playlist is
to be updated. Defaults to the currently authenticated user.
Returns:
A YouTubePlaylistEntry if the update was successful.
"""
updated_playlist = gdata.youtube.YouTubePlaylistEntry(
title=atom.Title(text=new_playlist_title),
description=gdata.youtube.Description(text=new_playlist_description))
if playlist_private:
updated_playlist.private = gdata.youtube.Private()
playlist_put_uri = '%s/%s/playlists/%s' % (YOUTUBE_USER_FEED_URI, username,
playlist_id)
return self.Put(updated_playlist, playlist_put_uri,
converter=gdata.youtube.YouTubePlaylistEntryFromString)
def DeletePlaylist(self, playlist_uri):
"""Delete a playlist from the currently authenticated users playlists.
Needs authentication.
Args:
playlist_uri: A string representing the URI of the playlist that is
to be deleted.
Returns:
True if successfully deleted.
"""
return self.Delete(playlist_uri)
def AddPlaylistVideoEntryToPlaylist(
self, playlist_uri, video_id, custom_video_title=None,
custom_video_description=None):
"""Add a video entry to a playlist, optionally providing a custom title
and description.
Needs authentication.
Args:
playlist_uri: A string representing the URI of the playlist to which this
video entry is to be added.
video_id: A string representing the ID of the video entry to add.
custom_video_title: An optional string representing a custom title for
the video (only shown on the playlist).
custom_video_description: An optional string representing a custom
description for the video (only shown on the playlist).
Returns:
A YouTubePlaylistVideoEntry if successfully posted.
"""
playlist_video_entry = gdata.youtube.YouTubePlaylistVideoEntry(
atom_id=atom.Id(text=video_id))
if custom_video_title:
playlist_video_entry.title = atom.Title(text=custom_video_title)
if custom_video_description:
playlist_video_entry.description = gdata.youtube.Description(
text=custom_video_description)
return self.Post(playlist_video_entry, playlist_uri,
converter=gdata.youtube.YouTubePlaylistVideoEntryFromString)
def UpdatePlaylistVideoEntryMetaData(
self, playlist_uri, playlist_entry_id, new_video_title,
new_video_description, new_video_position):
"""Update the meta data for a YouTubePlaylistVideoEntry.
Needs authentication.
Args:
playlist_uri: A string representing the URI of the playlist that contains
the entry to be updated.
playlist_entry_id: A string representing the ID of the entry to be
updated.
new_video_title: A string representing the new title for the video entry.
new_video_description: A string representing the new description for
the video entry.
new_video_position: An integer representing the new position on the
playlist for the video.
Returns:
A YouTubePlaylistVideoEntry if the update was successful.
"""
playlist_video_entry = gdata.youtube.YouTubePlaylistVideoEntry(
title=atom.Title(text=new_video_title),
description=gdata.youtube.Description(text=new_video_description),
position=gdata.youtube.Position(text=str(new_video_position)))
playlist_put_uri = playlist_uri + '/' + playlist_entry_id
return self.Put(playlist_video_entry, playlist_put_uri,
converter=gdata.youtube.YouTubePlaylistVideoEntryFromString)
def DeletePlaylistVideoEntry(self, playlist_uri, playlist_video_entry_id):
"""Delete a playlist video entry from a playlist.
Needs authentication.
Args:
playlist_uri: A URI representing the playlist from which the playlist
video entry is to be removed from.
playlist_video_entry_id: A string representing id of the playlist video
entry that is to be removed.
Returns:
True if entry was successfully deleted.
"""
delete_uri = '%s/%s' % (playlist_uri, playlist_video_entry_id)
return self.Delete(delete_uri)
def AddSubscriptionToChannel(self, username_to_subscribe_to,
my_username = 'default'):
"""Add a new channel subscription to the currently authenticated users
account.
Needs authentication.
Args:
username_to_subscribe_to: A string representing the username of the
channel to which we want to subscribe to.
my_username: An optional string representing the name of the user which
we want to subscribe. Defaults to currently authenticated user.
Returns:
A new YouTubeSubscriptionEntry if successfully posted.
"""
subscription_category = atom.Category(
scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME,
term='channel')
subscription_username = gdata.youtube.Username(
text=username_to_subscribe_to)
subscription_entry = gdata.youtube.YouTubeSubscriptionEntry(
category=subscription_category,
username=subscription_username)
post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'subscriptions')
return self.Post(subscription_entry, post_uri,
converter=gdata.youtube.YouTubeSubscriptionEntryFromString)
def AddSubscriptionToFavorites(self, username, my_username = 'default'):
"""Add a new subscription to a users favorites to the currently
authenticated user's account.
Needs authentication
Args:
username: A string representing the username of the user's favorite feed
to subscribe to.
my_username: An optional string representing the username of the user
that is to be subscribed. Defaults to currently authenticated user.
Returns:
A new YouTubeSubscriptionEntry if successful.
"""
subscription_category = atom.Category(
scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME,
term='favorites')
subscription_username = gdata.youtube.Username(text=username)
subscription_entry = gdata.youtube.YouTubeSubscriptionEntry(
category=subscription_category,
username=subscription_username)
post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'subscriptions')
return self.Post(subscription_entry, post_uri,
converter=gdata.youtube.YouTubeSubscriptionEntryFromString)
def AddSubscriptionToQuery(self, query, my_username = 'default'):
"""Add a new subscription to a specific keyword query to the currently
authenticated user's account.
Needs authentication
Args:
query: A string representing the keyword query to subscribe to.
my_username: An optional string representing the username of the user
that is to be subscribed. Defaults to currently authenticated user.
Returns:
A new YouTubeSubscriptionEntry if successful.
"""
subscription_category = atom.Category(
scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME,
term='query')
subscription_query_string = gdata.youtube.QueryString(text=query)
subscription_entry = gdata.youtube.YouTubeSubscriptionEntry(
category=subscription_category,
query_string=subscription_query_string)
post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'subscriptions')
return self.Post(subscription_entry, post_uri,
converter=gdata.youtube.YouTubeSubscriptionEntryFromString)
def DeleteSubscription(self, subscription_uri):
"""Delete a subscription from the currently authenticated user's account.
Needs authentication.
Args:
subscription_uri: A string representing the URI of the subscription that
is to be deleted.
Returns:
True if deleted successfully.
"""
return self.Delete(subscription_uri)
def AddContact(self, contact_username, my_username='default'):
"""Add a new contact to the currently authenticated user's contact feed.
Needs authentication.
Args:
contact_username: A string representing the username of the contact
that you wish to add.
my_username: An optional string representing the username to whose
contact the new contact is to be added.
Returns:
A YouTubeContactEntry if added successfully.
"""
contact_category = atom.Category(
scheme = 'http://gdata.youtube.com/schemas/2007/contact.cat',
term = 'Friends')
contact_username = gdata.youtube.Username(text=contact_username)
contact_entry = gdata.youtube.YouTubeContactEntry(
category=contact_category,
username=contact_username)
contact_post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'contacts')
return self.Post(contact_entry, contact_post_uri,
converter=gdata.youtube.YouTubeContactEntryFromString)
def UpdateContact(self, contact_username, new_contact_status,
new_contact_category, my_username='default'):
"""Update a contact, providing a new status and a new category.
Needs authentication.
Args:
contact_username: A string representing the username of the contact
that is to be updated.
new_contact_status: A string representing the new status of the contact.
This can either be set to 'accepted' or 'rejected'.
new_contact_category: A string representing the new category for the
contact, either 'Friends' or 'Family'.
my_username: An optional string representing the username of the user
whose contact feed we are modifying. Defaults to the currently
authenticated user.
Returns:
A YouTubeContactEntry if updated succesfully.
Raises:
YouTubeError: New contact status must be within the accepted values. Or
new contact category must be within the accepted categories.
"""
if new_contact_status not in YOUTUBE_CONTACT_STATUS:
raise YouTubeError('New contact status must be one of %s' %
(' '.join(YOUTUBE_CONTACT_STATUS)))
if new_contact_category not in YOUTUBE_CONTACT_CATEGORY:
raise YouTubeError('New contact category must be one of %s' %
(' '.join(YOUTUBE_CONTACT_CATEGORY)))
contact_category = atom.Category(
scheme='http://gdata.youtube.com/schemas/2007/contact.cat',
term=new_contact_category)
contact_status = gdata.youtube.Status(text=new_contact_status)
contact_entry = gdata.youtube.YouTubeContactEntry(
category=contact_category,
status=contact_status)
contact_put_uri = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'contacts', contact_username)
return self.Put(contact_entry, contact_put_uri,
converter=gdata.youtube.YouTubeContactEntryFromString)
def DeleteContact(self, contact_username, my_username='default'):
"""Delete a contact from a users contact feed.
Needs authentication.
Args:
contact_username: A string representing the username of the contact
that is to be deleted.
my_username: An optional string representing the username of the user's
contact feed from which to delete the contact. Defaults to the
currently authenticated user.
Returns:
True if the contact was deleted successfully
"""
contact_edit_uri = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'contacts', contact_username)
return self.Delete(contact_edit_uri)
def _GetDeveloperKey(self):
"""Getter for Developer Key property.
Returns:
If the developer key has been set, a string representing the developer key
is returned or None.
"""
if 'X-GData-Key' in self.additional_headers:
return self.additional_headers['X-GData-Key'][4:]
else:
return None
def _SetDeveloperKey(self, developer_key):
"""Setter for Developer Key property.
Sets the developer key in the 'X-GData-Key' header. The actual value that
is set is 'key=' plus the developer_key that was passed.
"""
self.additional_headers['X-GData-Key'] = 'key=' + developer_key
developer_key = property(_GetDeveloperKey, _SetDeveloperKey,
doc="""The Developer Key property""")
def _GetClientId(self):
"""Getter for Client Id property.
Returns:
If the client_id has been set, a string representing it is returned
or None.
"""
if 'X-Gdata-Client' in self.additional_headers:
return self.additional_headers['X-Gdata-Client']
else:
return None
def _SetClientId(self, client_id):
"""Setter for Client Id property.
Sets the 'X-Gdata-Client' header.
"""
self.additional_headers['X-Gdata-Client'] = client_id
client_id = property(_GetClientId, _SetClientId,
doc="""The ClientId property""")
def Query(self, uri):
"""Performs a query and returns a resulting feed or entry.
Args:
uri: A string representing the URI of the feed that is to be queried.
Returns:
On success, a tuple in the form:
(boolean succeeded=True, ElementTree._Element result)
On failure, a tuple in the form:
(boolean succeeded=False, {'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response})
"""
result = self.Get(uri)
return result
def YouTubeQuery(self, query):
"""Performs a YouTube specific query and returns a resulting feed or entry.
Args:
query: A Query object or one if its sub-classes (YouTubeVideoQuery,
YouTubeUserQuery or YouTubePlaylistQuery).
Returns:
Depending on the type of Query object submitted returns either a
YouTubeVideoFeed, a YouTubeUserFeed, a YouTubePlaylistFeed. If the
Query object provided was not YouTube-related, a tuple is returned.
On success the tuple will be in this form:
(boolean succeeded=True, ElementTree._Element result)
On failure, the tuple will be in this form:
(boolean succeeded=False, {'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server response})
"""
result = self.Query(query.ToUri())
if isinstance(query, YouTubeVideoQuery):
return gdata.youtube.YouTubeVideoFeedFromString(result.ToString())
elif isinstance(query, YouTubeUserQuery):
return gdata.youtube.YouTubeUserFeedFromString(result.ToString())
elif isinstance(query, YouTubePlaylistQuery):
return gdata.youtube.YouTubePlaylistFeedFromString(result.ToString())
else:
return result
class YouTubeVideoQuery(gdata.service.Query):
"""Subclasses gdata.service.Query to represent a YouTube Data API query.
Attributes are set dynamically via properties. Properties correspond to
the standard Google Data API query parameters with YouTube Data API
extensions. Please refer to the API documentation for details.
Attributes:
vq: The vq parameter, which is only supported for video feeds, specifies a
search query term. Refer to API documentation for further details.
orderby: The orderby parameter, which is only supported for video feeds,
specifies the value that will be used to sort videos in the search
result set. Valid values for this parameter are relevance, published,
viewCount and rating.
time: The time parameter, which is only available for the top_rated,
top_favorites, most_viewed, most_discussed, most_linked and
most_responded standard feeds, restricts the search to videos uploaded
within the specified time. Valid values for this parameter are today
(1 day), this_week (7 days), this_month (1 month) and all_time.
The default value for this parameter is all_time.
format: The format parameter specifies that videos must be available in a
particular video format. Refer to the API documentation for details.
racy: The racy parameter allows a search result set to include restricted
content as well as standard content. Valid values for this parameter
are include and exclude. By default, restricted content is excluded.
lr: The lr parameter restricts the search to videos that have a title,
description or keywords in a specific language. Valid values for the lr
parameter are ISO 639-1 two-letter language codes.
restriction: The restriction parameter identifies the IP address that
should be used to filter videos that can only be played in specific
countries.
"""
def __init__(self, video_id=None, feed_type=None, text_query=None,
params=None, categories=None):
if feed_type in YOUTUBE_STANDARDFEEDS:
feed = 'http://%s/feeds/standardfeeds/%s' % (YOUTUBE_SERVER, feed_type)
elif feed_type is 'responses' or feed_type is 'comments' and video_id:
feed = 'http://%s/feeds/videos/%s/%s' % (YOUTUBE_SERVER, video_id,
feed_type)
else:
feed = 'http://%s/feeds/videos' % (YOUTUBE_SERVER)
gdata.service.Query.__init__(self, feed, text_query=text_query,
params=params, categories=categories)
def _GetVideoQuery(self):
if 'vq' in self:
return self['vq']
else:
return None
def _SetVideoQuery(self, val):
self['vq'] = val
vq = property(_GetVideoQuery, _SetVideoQuery,
doc="""The video query (vq) query parameter""")
def _GetOrderBy(self):
if 'orderby' in self:
return self['orderby']
else:
return None
def _SetOrderBy(self, val):
if val not in YOUTUBE_QUERY_VALID_ORDERBY_PARAMETERS:
raise YouTubeError('OrderBy must be one of: %s ' %
' '.join(YOUTUBE_QUERY_VALID_ORDERBY_PARAMETERS))
self['orderby'] = val
orderby = property(_GetOrderBy, _SetOrderBy,
doc="""The orderby query parameter""")
def _GetTime(self):
if 'time' in self:
return self['time']
else:
return None
def _SetTime(self, val):
if val not in YOUTUBE_QUERY_VALID_TIME_PARAMETERS:
raise YouTubeError('Time must be one of: %s ' %
' '.join(YOUTUBE_QUERY_VALID_TIME_PARAMETERS))
self['time'] = val
time = property(_GetTime, _SetTime,
doc="""The time query parameter""")
def _GetFormat(self):
if 'format' in self:
return self['format']
else:
return None
def _SetFormat(self, val):
if val not in YOUTUBE_QUERY_VALID_FORMAT_PARAMETERS:
raise YouTubeError('Format must be one of: %s ' %
' '.join(YOUTUBE_QUERY_VALID_FORMAT_PARAMETERS))
self['format'] = val
format = property(_GetFormat, _SetFormat,
doc="""The format query parameter""")
def _GetRacy(self):
if 'racy' in self:
return self['racy']
else:
return None
def _SetRacy(self, val):
if val not in YOUTUBE_QUERY_VALID_RACY_PARAMETERS:
raise YouTubeError('Racy must be one of: %s ' %
' '.join(YOUTUBE_QUERY_VALID_RACY_PARAMETERS))
self['racy'] = val
racy = property(_GetRacy, _SetRacy,
doc="""The racy query parameter""")
def _GetLanguageRestriction(self):
if 'lr' in self:
return self['lr']
else:
return None
def _SetLanguageRestriction(self, val):
self['lr'] = val
lr = property(_GetLanguageRestriction, _SetLanguageRestriction,
doc="""The lr (language restriction) query parameter""")
def _GetIPRestriction(self):
if 'restriction' in self:
return self['restriction']
else:
return None
def _SetIPRestriction(self, val):
self['restriction'] = val
restriction = property(_GetIPRestriction, _SetIPRestriction,
doc="""The restriction query parameter""")
class YouTubeUserQuery(YouTubeVideoQuery):
"""Subclasses YouTubeVideoQuery to perform user-specific queries.
Attributes are set dynamically via properties. Properties correspond to
the standard Google Data API query parameters with YouTube Data API
extensions.
"""
def __init__(self, username=None, feed_type=None, subscription_id=None,
text_query=None, params=None, categories=None):
uploads_favorites_playlists = ('uploads', 'favorites', 'playlists')
if feed_type is 'subscriptions' and subscription_id and username:
feed = "http://%s/feeds/users/%s/%s/%s" % (YOUTUBE_SERVER, username,
feed_type, subscription_id)
elif feed_type is 'subscriptions' and not subscription_id and username:
feed = "http://%s/feeds/users/%s/%s" % (YOUTUBE_SERVER, username,
feed_type)
elif feed_type in uploads_favorites_playlists:
feed = "http://%s/feeds/users/%s/%s" % (YOUTUBE_SERVER, username,
feed_type)
else:
feed = "http://%s/feeds/users" % (YOUTUBE_SERVER)
YouTubeVideoQuery.__init__(self, feed, text_query=text_query,
params=params, categories=categories)
class YouTubePlaylistQuery(YouTubeVideoQuery):
"""Subclasses YouTubeVideoQuery to perform playlist-specific queries.
Attributes are set dynamically via properties. Properties correspond to
the standard Google Data API query parameters with YouTube Data API
extensions.
"""
def __init__(self, playlist_id, text_query=None, params=None,
categories=None):
if playlist_id:
feed = "http://%s/feeds/playlists/%s" % (YOUTUBE_SERVER, playlist_id)
else:
feed = "http://%s/feeds/playlists" % (YOUTUBE_SERVER)
YouTubeVideoQuery.__init__(self, feed, text_query=text_query,
params=params, categories=categories)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""YouTubeService extends GDataService to streamline YouTube operations.
YouTubeService: Provides methods to perform CRUD operations on YouTube feeds.
Extends GDataService.
"""
__author__ = ('api.stephaniel@gmail.com (Stephanie Liu), '
'api.jhartmann@gmail.com (Jochen Hartmann)')
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import os
import urllib
import atom
import gdata
import gdata.service
import gdata.youtube
YOUTUBE_SERVER = 'gdata.youtube.com'
YOUTUBE_SERVICE = 'youtube'
YOUTUBE_SUPPORTED_UPLOAD_TYPES = ('mov', 'avi', 'wmv', 'mpg', 'quicktime')
YOUTUBE_QUERY_VALID_TIME_PARAMETERS = ('today', 'this_week', 'this_month',
'all_time')
YOUTUBE_QUERY_VALID_ORDERBY_PARAMETERS = ('published', 'viewCount', 'rating',
'relevance')
YOUTUBE_QUERY_VALID_RACY_PARAMETERS = ('include', 'exclude')
YOUTUBE_QUERY_VALID_FORMAT_PARAMETERS = ('1', '5', '6')
YOUTUBE_STANDARDFEEDS = ('most_recent', 'recently_featured',
'top_rated', 'most_viewed','watch_on_mobile')
YOUTUBE_UPLOAD_URI = 'http://uploads.gdata.youtube.com/feeds/api/users'
YOUTUBE_UPLOAD_TOKEN_URI = 'http://gdata.youtube.com/action/GetUploadToken'
YOUTUBE_VIDEO_URI = 'http://gdata.youtube.com/feeds/api/videos'
YOUTUBE_USER_FEED_URI = 'http://gdata.youtube.com/feeds/api/users'
YOUTUBE_PLAYLIST_FEED_URI = 'http://gdata.youtube.com/feeds/api/playlists'
YOUTUBE_STANDARD_FEEDS = 'http://gdata.youtube.com/feeds/api/standardfeeds'
YOUTUBE_STANDARD_TOP_RATED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'top_rated')
YOUTUBE_STANDARD_MOST_VIEWED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'most_viewed')
YOUTUBE_STANDARD_RECENTLY_FEATURED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'recently_featured')
YOUTUBE_STANDARD_WATCH_ON_MOBILE_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'watch_on_mobile')
YOUTUBE_STANDARD_TOP_FAVORITES_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'top_favorites')
YOUTUBE_STANDARD_MOST_RECENT_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'most_recent')
YOUTUBE_STANDARD_MOST_DISCUSSED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'most_discussed')
YOUTUBE_STANDARD_MOST_LINKED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'most_linked')
YOUTUBE_STANDARD_MOST_RESPONDED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
'most_responded')
YOUTUBE_SCHEMA = 'http://gdata.youtube.com/schemas'
YOUTUBE_RATING_LINK_REL = '%s#video.ratings' % YOUTUBE_SCHEMA
YOUTUBE_COMPLAINT_CATEGORY_SCHEME = '%s/%s' % (YOUTUBE_SCHEMA,
'complaint-reasons.cat')
YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME = '%s/%s' % (YOUTUBE_SCHEMA,
'subscriptiontypes.cat')
YOUTUBE_COMPLAINT_CATEGORY_TERMS = ('PORN', 'VIOLENCE', 'HATE', 'DANGEROUS',
'RIGHTS', 'SPAM')
YOUTUBE_CONTACT_STATUS = ('accepted', 'rejected')
YOUTUBE_CONTACT_CATEGORY = ('Friends', 'Family')
UNKOWN_ERROR = 1000
YOUTUBE_BAD_REQUEST = 400
YOUTUBE_CONFLICT = 409
YOUTUBE_INTERNAL_SERVER_ERROR = 500
YOUTUBE_INVALID_ARGUMENT = 601
YOUTUBE_INVALID_CONTENT_TYPE = 602
YOUTUBE_NOT_A_VIDEO = 603
YOUTUBE_INVALID_KIND = 604
class Error(Exception):
"""Base class for errors within the YouTube service."""
pass
class RequestError(Error):
"""Error class that is thrown in response to an invalid HTTP Request."""
pass
class YouTubeError(Error):
"""YouTube service specific error class."""
pass
class YouTubeService(gdata.service.GDataService):
"""Client for the YouTube service.
Performs all documented Google Data YouTube API functions, such as inserting,
updating and deleting videos, comments, playlist, subscriptions etc.
YouTube Service requires authentication for any write, update or delete
actions.
Attributes:
email: An optional string identifying the user. Required only for
authenticated actions.
password: An optional string identifying the user's password.
source: An optional string identifying the name of your application.
server: An optional address of the YouTube API server. gdata.youtube.com
is provided as the default value.
additional_headers: An optional dictionary containing additional headers
to be passed along with each request. Use to store developer key.
client_id: An optional string identifying your application, required for
authenticated requests, along with a developer key.
developer_key: An optional string value. Register your application at
http://code.google.com/apis/youtube/dashboard to obtain a (free) key.
"""
def __init__(self, email=None, password=None, source=None,
server=YOUTUBE_SERVER, additional_headers=None, client_id=None,
developer_key=None):
if client_id is not None and developer_key is not None:
self.additional_headers = {'X-Gdata-Client': self.client_id,
'X-GData-Key': 'key=%s' % self.developer_key}
gdata.service.GDataService.__init__(
self, email=email, password=password, service=YOUTUBE_SERVICE,
source=source, server=server,
additional_headers=self.additional_headers)
elif developer_key and not client_id:
raise YouTubeError('You must also specify the clientId')
else:
gdata.service.GDataService.__init__(
self, email=email, password=password, service=YOUTUBE_SERVICE,
source=source, server=server, additional_headers=additional_headers)
def GetYouTubeVideoFeed(self, uri):
"""Retrieve a YouTubeVideoFeed.
Args:
uri: A string representing the URI of the feed that is to be retrieved.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.Get(uri, converter=gdata.youtube.YouTubeVideoFeedFromString)
def GetYouTubeVideoEntry(self, uri=None, video_id=None):
"""Retrieve a YouTubeVideoEntry.
Either a uri or a video_id must be provided.
Args:
uri: An optional string representing the URI of the entry that is to
be retrieved.
video_id: An optional string representing the ID of the video.
Returns:
A YouTubeVideoFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a video_id to the
GetYouTubeVideoEntry() method.
"""
if uri is None and video_id is None:
raise YouTubeError('You must provide at least a uri or a video_id '
'to the GetYouTubeVideoEntry() method')
elif video_id and not uri:
uri = '%s/%s' % (YOUTUBE_VIDEO_URI, video_id)
return self.Get(uri, converter=gdata.youtube.YouTubeVideoEntryFromString)
def GetYouTubeContactFeed(self, uri=None, username='default'):
"""Retrieve a YouTubeContactFeed.
Either a uri or a username must be provided.
Args:
uri: An optional string representing the URI of the contact feed that
is to be retrieved.
username: An optional string representing the username. Defaults to the
currently authenticated user.
Returns:
A YouTubeContactFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a username to the
GetYouTubeContactFeed() method.
"""
if uri is None:
uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'contacts')
return self.Get(uri, converter=gdata.youtube.YouTubeContactFeedFromString)
def GetYouTubeContactEntry(self, uri):
"""Retrieve a YouTubeContactEntry.
Args:
uri: A string representing the URI of the contact entry that is to
be retrieved.
Returns:
A YouTubeContactEntry if successfully retrieved.
"""
return self.Get(uri, converter=gdata.youtube.YouTubeContactEntryFromString)
def GetYouTubeVideoCommentFeed(self, uri=None, video_id=None):
"""Retrieve a YouTubeVideoCommentFeed.
Either a uri or a video_id must be provided.
Args:
uri: An optional string representing the URI of the comment feed that
is to be retrieved.
video_id: An optional string representing the ID of the video for which
to retrieve the comment feed.
Returns:
A YouTubeVideoCommentFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a video_id to the
GetYouTubeVideoCommentFeed() method.
"""
if uri is None and video_id is None:
raise YouTubeError('You must provide at least a uri or a video_id '
'to the GetYouTubeVideoCommentFeed() method')
elif video_id and not uri:
uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'comments')
return self.Get(
uri, converter=gdata.youtube.YouTubeVideoCommentFeedFromString)
def GetYouTubeVideoCommentEntry(self, uri):
"""Retrieve a YouTubeVideoCommentEntry.
Args:
uri: A string representing the URI of the comment entry that is to
be retrieved.
Returns:
A YouTubeCommentEntry if successfully retrieved.
"""
return self.Get(
uri, converter=gdata.youtube.YouTubeVideoCommentEntryFromString)
def GetYouTubeUserFeed(self, uri=None, username=None):
"""Retrieve a YouTubeUserFeed.
Either a uri or a username must be provided.
Args:
uri: An optional string representing the URI of the user feed that is
to be retrieved.
username: An optional string representing the username.
Returns:
A YouTubeUserFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a username to the
GetYouTubeUserFeed() method.
"""
if uri is None and username is None:
raise YouTubeError('You must provide at least a uri or a username '
'to the GetYouTubeUserFeed() method')
elif username and not uri:
uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'uploads')
return self.Get(uri, converter=gdata.youtube.YouTubeUserFeedFromString)
def GetYouTubeUserEntry(self, uri=None, username=None):
"""Retrieve a YouTubeUserEntry.
Either a uri or a username must be provided.
Args:
uri: An optional string representing the URI of the user entry that is
to be retrieved.
username: An optional string representing the username.
Returns:
A YouTubeUserEntry if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a username to the
GetYouTubeUserEntry() method.
"""
if uri is None and username is None:
raise YouTubeError('You must provide at least a uri or a username '
'to the GetYouTubeUserEntry() method')
elif username and not uri:
uri = '%s/%s' % (YOUTUBE_USER_FEED_URI, username)
return self.Get(uri, converter=gdata.youtube.YouTubeUserEntryFromString)
def GetYouTubePlaylistFeed(self, uri=None, username='default'):
"""Retrieve a YouTubePlaylistFeed (a feed of playlists for a user).
Either a uri or a username must be provided.
Args:
uri: An optional string representing the URI of the playlist feed that
is to be retrieved.
username: An optional string representing the username. Defaults to the
currently authenticated user.
Returns:
A YouTubePlaylistFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a username to the
GetYouTubePlaylistFeed() method.
"""
if uri is None:
uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'playlists')
return self.Get(uri, converter=gdata.youtube.YouTubePlaylistFeedFromString)
def GetYouTubePlaylistEntry(self, uri):
"""Retrieve a YouTubePlaylistEntry.
Args:
uri: A string representing the URI of the playlist feed that is to
be retrieved.
Returns:
A YouTubePlaylistEntry if successfully retrieved.
"""
return self.Get(uri, converter=gdata.youtube.YouTubePlaylistEntryFromString)
def GetYouTubePlaylistVideoFeed(self, uri=None, playlist_id=None):
"""Retrieve a YouTubePlaylistVideoFeed (a feed of videos on a playlist).
Either a uri or a playlist_id must be provided.
Args:
uri: An optional string representing the URI of the playlist video feed
that is to be retrieved.
playlist_id: An optional string representing the Id of the playlist whose
playlist video feed is to be retrieved.
Returns:
A YouTubePlaylistVideoFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a playlist_id to the
GetYouTubePlaylistVideoFeed() method.
"""
if uri is None and playlist_id is None:
raise YouTubeError('You must provide at least a uri or a playlist_id '
'to the GetYouTubePlaylistVideoFeed() method')
elif playlist_id and not uri:
uri = '%s/%s' % (YOUTUBE_PLAYLIST_FEED_URI, playlist_id)
return self.Get(
uri, converter=gdata.youtube.YouTubePlaylistVideoFeedFromString)
def GetYouTubeVideoResponseFeed(self, uri=None, video_id=None):
"""Retrieve a YouTubeVideoResponseFeed.
Either a uri or a playlist_id must be provided.
Args:
uri: An optional string representing the URI of the video response feed
that is to be retrieved.
video_id: An optional string representing the ID of the video whose
response feed is to be retrieved.
Returns:
A YouTubeVideoResponseFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a video_id to the
GetYouTubeVideoResponseFeed() method.
"""
if uri is None and video_id is None:
raise YouTubeError('You must provide at least a uri or a video_id '
'to the GetYouTubeVideoResponseFeed() method')
elif video_id and not uri:
uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'responses')
return self.Get(
uri, converter=gdata.youtube.YouTubeVideoResponseFeedFromString)
def GetYouTubeVideoResponseEntry(self, uri):
"""Retrieve a YouTubeVideoResponseEntry.
Args:
uri: A string representing the URI of the video response entry that
is to be retrieved.
Returns:
A YouTubeVideoResponseEntry if successfully retrieved.
"""
return self.Get(
uri, converter=gdata.youtube.YouTubeVideoResponseEntryFromString)
def GetYouTubeSubscriptionFeed(self, uri=None, username='default'):
"""Retrieve a YouTubeSubscriptionFeed.
Either the uri of the feed or a username must be provided.
Args:
uri: An optional string representing the URI of the feed that is to
be retrieved.
username: An optional string representing the username whose subscription
feed is to be retrieved. Defaults to the currently authenticted user.
Returns:
A YouTubeVideoSubscriptionFeed if successfully retrieved.
"""
if uri is None:
uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'subscriptions')
return self.Get(
uri, converter=gdata.youtube.YouTubeSubscriptionFeedFromString)
def GetYouTubeSubscriptionEntry(self, uri):
"""Retrieve a YouTubeSubscriptionEntry.
Args:
uri: A string representing the URI of the entry that is to be retrieved.
Returns:
A YouTubeVideoSubscriptionEntry if successfully retrieved.
"""
return self.Get(
uri, converter=gdata.youtube.YouTubeSubscriptionEntryFromString)
def GetYouTubeRelatedVideoFeed(self, uri=None, video_id=None):
"""Retrieve a YouTubeRelatedVideoFeed.
Either a uri for the feed or a video_id is required.
Args:
uri: An optional string representing the URI of the feed that is to
be retrieved.
video_id: An optional string representing the ID of the video for which
to retrieve the related video feed.
Returns:
A YouTubeRelatedVideoFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a video_id to the
GetYouTubeRelatedVideoFeed() method.
"""
if uri is None and video_id is None:
raise YouTubeError('You must provide at least a uri or a video_id '
'to the GetYouTubeRelatedVideoFeed() method')
elif video_id and not uri:
uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'related')
return self.Get(
uri, converter=gdata.youtube.YouTubeVideoFeedFromString)
def GetTopRatedVideoFeed(self):
"""Retrieve the 'top_rated' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_TOP_RATED_URI)
def GetMostViewedVideoFeed(self):
"""Retrieve the 'most_viewed' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_VIEWED_URI)
def GetRecentlyFeaturedVideoFeed(self):
"""Retrieve the 'recently_featured' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_RECENTLY_FEATURED_URI)
def GetWatchOnMobileVideoFeed(self):
"""Retrieve the 'watch_on_mobile' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_WATCH_ON_MOBILE_URI)
def GetTopFavoritesVideoFeed(self):
"""Retrieve the 'top_favorites' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_TOP_FAVORITES_URI)
def GetMostRecentVideoFeed(self):
"""Retrieve the 'most_recent' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_RECENT_URI)
def GetMostDiscussedVideoFeed(self):
"""Retrieve the 'most_discussed' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_DISCUSSED_URI)
def GetMostLinkedVideoFeed(self):
"""Retrieve the 'most_linked' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_LINKED_URI)
def GetMostRespondedVideoFeed(self):
"""Retrieve the 'most_responded' standard video feed.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_RESPONDED_URI)
def GetUserFavoritesFeed(self, username='default'):
"""Retrieve the favorites feed for a given user.
Args:
username: An optional string representing the username whose favorites
feed is to be retrieved. Defaults to the currently authenticated user.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
favorites_feed_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username,
'favorites')
return self.GetYouTubeVideoFeed(favorites_feed_uri)
def InsertVideoEntry(self, video_entry, filename_or_handle,
youtube_username='default',
content_type='video/quicktime'):
"""Upload a new video to YouTube using the direct upload mechanism.
Needs authentication.
Args:
video_entry: The YouTubeVideoEntry to upload.
filename_or_handle: A file-like object or file name where the video
will be read from.
youtube_username: An optional string representing the username into whose
account this video is to be uploaded to. Defaults to the currently
authenticated user.
content_type: An optional string representing internet media type
(a.k.a. mime type) of the media object. Currently the YouTube API
supports these types:
o video/mpeg
o video/quicktime
o video/x-msvideo
o video/mp4
Returns:
The newly created YouTubeVideoEntry if successful.
Raises:
AssertionError: video_entry must be a gdata.youtube.VideoEntry instance.
YouTubeError: An error occurred trying to read the video file provided.
gdata.service.RequestError: An error occurred trying to upload the video
to the API server.
"""
# We need to perform a series of checks on the video_entry and on the
# file that we plan to upload, such as checking whether we have a valid
# video_entry and that the file is the correct type and readable, prior
# to performing the actual POST request.
try:
assert(isinstance(video_entry, gdata.youtube.YouTubeVideoEntry))
except AssertionError:
raise YouTubeError({'status':YOUTUBE_INVALID_ARGUMENT,
'body':'`video_entry` must be a gdata.youtube.VideoEntry instance',
'reason':'Found %s, not VideoEntry' % type(video_entry)
})
majtype, mintype = content_type.split('/')
try:
assert(mintype in YOUTUBE_SUPPORTED_UPLOAD_TYPES)
except (ValueError, AssertionError):
raise YouTubeError({'status':YOUTUBE_INVALID_CONTENT_TYPE,
'body':'This is not a valid content type: %s' % content_type,
'reason':'Accepted content types: %s' %
['video/%s' % (t) for t in YOUTUBE_SUPPORTED_UPLOAD_TYPES]})
if (isinstance(filename_or_handle, (str, unicode))
and os.path.exists(filename_or_handle)):
mediasource = gdata.MediaSource()
mediasource.setFile(filename_or_handle, content_type)
elif hasattr(filename_or_handle, 'read'):
if hasattr(filename_or_handle, 'seek'):
filename_or_handle.seek(0)
file_handle = StringIO.StringIO(filename_or_handle.read())
name = 'video'
if hasattr(filename_or_handle, 'name'):
name = filename_or_handle.name
mediasource = gdata.MediaSource(file_handle, content_type,
content_length=file_handle.len, file_name=name)
else:
raise YouTubeError({'status':YOUTUBE_INVALID_ARGUMENT, 'body':
'`filename_or_handle` must be a path name or a file-like object',
'reason': ('Found %s, not path name or object '
'with a .read() method' % type(filename_or_handle))})
upload_uri = '%s/%s/%s' % (YOUTUBE_UPLOAD_URI, youtube_username,
'uploads')
self.additional_headers['Slug'] = mediasource.file_name
# Using a nested try statement to retain Python 2.4 compatibility
try:
try:
return self.Post(video_entry, uri=upload_uri, media_source=mediasource,
converter=gdata.youtube.YouTubeVideoEntryFromString)
except gdata.service.RequestError, e:
raise YouTubeError(e.args[0])
finally:
del(self.additional_headers['Slug'])
def CheckUploadStatus(self, video_entry=None, video_id=None):
"""Check upload status on a recently uploaded video entry.
Needs authentication. Either video_entry or video_id must be provided.
Args:
video_entry: An optional YouTubeVideoEntry whose upload status to check
video_id: An optional string representing the ID of the uploaded video
whose status is to be checked.
Returns:
A tuple containing (video_upload_state, detailed_message) or None if
no status information is found.
Raises:
YouTubeError: You must provide at least a video_entry or a video_id to the
CheckUploadStatus() method.
"""
if video_entry is None and video_id is None:
raise YouTubeError('You must provide at least a uri or a video_id '
'to the CheckUploadStatus() method')
elif video_id and not video_entry:
video_entry = self.GetYouTubeVideoEntry(video_id=video_id)
control = video_entry.control
if control is not None:
draft = control.draft
if draft is not None:
if draft.text == 'yes':
yt_state = control.extension_elements[0]
if yt_state is not None:
state_value = yt_state.attributes['name']
message = ''
if yt_state.text is not None:
message = yt_state.text
return (state_value, message)
def GetFormUploadToken(self, video_entry, uri=YOUTUBE_UPLOAD_TOKEN_URI):
"""Receives a YouTube Token and a YouTube PostUrl from a YouTubeVideoEntry.
Needs authentication.
Args:
video_entry: The YouTubeVideoEntry to upload (meta-data only).
uri: An optional string representing the URI from where to fetch the
token information. Defaults to the YOUTUBE_UPLOADTOKEN_URI.
Returns:
A tuple containing the URL to which to post your video file, along
with the youtube token that must be included with your upload in the
form of: (post_url, youtube_token).
"""
try:
response = self.Post(video_entry, uri)
except gdata.service.RequestError, e:
raise YouTubeError(e.args[0])
tree = ElementTree.fromstring(response)
for child in tree:
if child.tag == 'url':
post_url = child.text
elif child.tag == 'token':
youtube_token = child.text
return (post_url, youtube_token)
def UpdateVideoEntry(self, video_entry):
"""Updates a video entry's meta-data.
Needs authentication.
Args:
video_entry: The YouTubeVideoEntry to update, containing updated
meta-data.
Returns:
An updated YouTubeVideoEntry on success or None.
"""
for link in video_entry.link:
if link.rel == 'edit':
edit_uri = link.href
return self.Put(video_entry, uri=edit_uri,
converter=gdata.youtube.YouTubeVideoEntryFromString)
def DeleteVideoEntry(self, video_entry):
"""Deletes a video entry.
Needs authentication.
Args:
video_entry: The YouTubeVideoEntry to be deleted.
Returns:
True if entry was deleted successfully.
"""
for link in video_entry.link:
if link.rel == 'edit':
edit_uri = link.href
return self.Delete(edit_uri)
def AddRating(self, rating_value, video_entry):
"""Add a rating to a video entry.
Needs authentication.
Args:
rating_value: The integer value for the rating (between 1 and 5).
video_entry: The YouTubeVideoEntry to be rated.
Returns:
True if the rating was added successfully.
Raises:
YouTubeError: rating_value must be between 1 and 5 in AddRating().
"""
if rating_value < 1 or rating_value > 5:
raise YouTubeError('rating_value must be between 1 and 5 in AddRating()')
entry = gdata.GDataEntry()
rating = gdata.youtube.Rating(min='1', max='5')
rating.extension_attributes['name'] = 'value'
rating.extension_attributes['value'] = str(rating_value)
entry.extension_elements.append(rating)
for link in video_entry.link:
if link.rel == YOUTUBE_RATING_LINK_REL:
rating_uri = link.href
return self.Post(entry, uri=rating_uri)
def AddComment(self, comment_text, video_entry):
"""Add a comment to a video entry.
Needs authentication. Note that each comment that is posted must contain
the video entry that it is to be posted to.
Args:
comment_text: A string representing the text of the comment.
video_entry: The YouTubeVideoEntry to be commented on.
Returns:
True if the comment was added successfully.
"""
content = atom.Content(text=comment_text)
comment_entry = gdata.youtube.YouTubeVideoCommentEntry(content=content)
comment_post_uri = video_entry.comments.feed_link[0].href
return self.Post(comment_entry, uri=comment_post_uri)
def AddVideoResponse(self, video_id_to_respond_to, video_response):
"""Add a video response.
Needs authentication.
Args:
video_id_to_respond_to: A string representing the ID of the video to be
responded to.
video_response: YouTubeVideoEntry to be posted as a response.
Returns:
True if video response was posted successfully.
"""
post_uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id_to_respond_to,
'responses')
return self.Post(video_response, uri=post_uri)
def DeleteVideoResponse(self, video_id, response_video_id):
"""Delete a video response.
Needs authentication.
Args:
video_id: A string representing the ID of video that contains the
response.
response_video_id: A string representing the ID of the video that was
posted as a response.
Returns:
True if video response was deleted succcessfully.
"""
delete_uri = '%s/%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'responses',
response_video_id)
return self.Delete(delete_uri)
def AddComplaint(self, complaint_text, complaint_term, video_id):
"""Add a complaint for a particular video entry.
Needs authentication.
Args:
complaint_text: A string representing the complaint text.
complaint_term: A string representing the complaint category term.
video_id: A string representing the ID of YouTubeVideoEntry to
complain about.
Returns:
True if posted successfully.
Raises:
YouTubeError: Your complaint_term is not valid.
"""
if complaint_term not in YOUTUBE_COMPLAINT_CATEGORY_TERMS:
raise YouTubeError('Your complaint_term is not valid')
content = atom.Content(text=complaint_text)
category = atom.Category(term=complaint_term,
scheme=YOUTUBE_COMPLAINT_CATEGORY_SCHEME)
complaint_entry = gdata.GDataEntry(content=content, category=[category])
post_uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'complaints')
return self.Post(complaint_entry, post_uri)
def AddVideoEntryToFavorites(self, video_entry, username='default'):
"""Add a video entry to a users favorite feed.
Needs authentication.
Args:
video_entry: The YouTubeVideoEntry to add.
username: An optional string representing the username to whose favorite
feed you wish to add the entry. Defaults to the currently
authenticated user.
Returns:
The posted YouTubeVideoEntry if successfully posted.
"""
post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'favorites')
return self.Post(video_entry, post_uri,
converter=gdata.youtube.YouTubeVideoEntryFromString)
def DeleteVideoEntryFromFavorites(self, video_id, username='default'):
"""Delete a video entry from the users favorite feed.
Needs authentication.
Args:
video_id: A string representing the ID of the video that is to be removed
username: An optional string representing the username of the user's
favorite feed. Defaults to the currently authenticated user.
Returns:
True if entry was successfully deleted.
"""
edit_link = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'favorites',
video_id)
return self.Delete(edit_link)
def AddPlaylist(self, playlist_title, playlist_description,
playlist_private=None):
"""Add a new playlist to the currently authenticated users account.
Needs authentication.
Args:
playlist_title: A string representing the title for the new playlist.
playlist_description: A string representing the description of the
playlist.
playlist_private: An optional boolean, set to True if the playlist is
to be private.
Returns:
The YouTubePlaylistEntry if successfully posted.
"""
playlist_entry = gdata.youtube.YouTubePlaylistEntry(
title=atom.Title(text=playlist_title),
description=gdata.youtube.Description(text=playlist_description))
if playlist_private:
playlist_entry.private = gdata.youtube.Private()
playlist_post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, 'default',
'playlists')
return self.Post(playlist_entry, playlist_post_uri,
converter=gdata.youtube.YouTubePlaylistEntryFromString)
def UpdatePlaylist(self, playlist_id, new_playlist_title,
new_playlist_description, playlist_private=None,
username='default'):
"""Update a playlist with new meta-data.
Needs authentication.
Args:
playlist_id: A string representing the ID of the playlist to be updated.
new_playlist_title: A string representing a new title for the playlist.
new_playlist_description: A string representing a new description for the
playlist.
playlist_private: An optional boolean, set to True if the playlist is
to be private.
username: An optional string representing the username whose playlist is
to be updated. Defaults to the currently authenticated user.
Returns:
A YouTubePlaylistEntry if the update was successful.
"""
updated_playlist = gdata.youtube.YouTubePlaylistEntry(
title=atom.Title(text=new_playlist_title),
description=gdata.youtube.Description(text=new_playlist_description))
if playlist_private:
updated_playlist.private = gdata.youtube.Private()
playlist_put_uri = '%s/%s/playlists/%s' % (YOUTUBE_USER_FEED_URI, username,
playlist_id)
return self.Put(updated_playlist, playlist_put_uri,
converter=gdata.youtube.YouTubePlaylistEntryFromString)
def DeletePlaylist(self, playlist_uri):
"""Delete a playlist from the currently authenticated users playlists.
Needs authentication.
Args:
playlist_uri: A string representing the URI of the playlist that is
to be deleted.
Returns:
True if successfully deleted.
"""
return self.Delete(playlist_uri)
def AddPlaylistVideoEntryToPlaylist(
self, playlist_uri, video_id, custom_video_title=None,
custom_video_description=None):
"""Add a video entry to a playlist, optionally providing a custom title
and description.
Needs authentication.
Args:
playlist_uri: A string representing the URI of the playlist to which this
video entry is to be added.
video_id: A string representing the ID of the video entry to add.
custom_video_title: An optional string representing a custom title for
the video (only shown on the playlist).
custom_video_description: An optional string representing a custom
description for the video (only shown on the playlist).
Returns:
A YouTubePlaylistVideoEntry if successfully posted.
"""
playlist_video_entry = gdata.youtube.YouTubePlaylistVideoEntry(
atom_id=atom.Id(text=video_id))
if custom_video_title:
playlist_video_entry.title = atom.Title(text=custom_video_title)
if custom_video_description:
playlist_video_entry.description = gdata.youtube.Description(
text=custom_video_description)
return self.Post(playlist_video_entry, playlist_uri,
converter=gdata.youtube.YouTubePlaylistVideoEntryFromString)
def UpdatePlaylistVideoEntryMetaData(
self, playlist_uri, playlist_entry_id, new_video_title,
new_video_description, new_video_position):
"""Update the meta data for a YouTubePlaylistVideoEntry.
Needs authentication.
Args:
playlist_uri: A string representing the URI of the playlist that contains
the entry to be updated.
playlist_entry_id: A string representing the ID of the entry to be
updated.
new_video_title: A string representing the new title for the video entry.
new_video_description: A string representing the new description for
the video entry.
new_video_position: An integer representing the new position on the
playlist for the video.
Returns:
A YouTubePlaylistVideoEntry if the update was successful.
"""
playlist_video_entry = gdata.youtube.YouTubePlaylistVideoEntry(
title=atom.Title(text=new_video_title),
description=gdata.youtube.Description(text=new_video_description),
position=gdata.youtube.Position(text=str(new_video_position)))
playlist_put_uri = playlist_uri + '/' + playlist_entry_id
return self.Put(playlist_video_entry, playlist_put_uri,
converter=gdata.youtube.YouTubePlaylistVideoEntryFromString)
def DeletePlaylistVideoEntry(self, playlist_uri, playlist_video_entry_id):
"""Delete a playlist video entry from a playlist.
Needs authentication.
Args:
playlist_uri: A URI representing the playlist from which the playlist
video entry is to be removed from.
playlist_video_entry_id: A string representing id of the playlist video
entry that is to be removed.
Returns:
True if entry was successfully deleted.
"""
delete_uri = '%s/%s' % (playlist_uri, playlist_video_entry_id)
return self.Delete(delete_uri)
def AddSubscriptionToChannel(self, username_to_subscribe_to,
my_username = 'default'):
"""Add a new channel subscription to the currently authenticated users
account.
Needs authentication.
Args:
username_to_subscribe_to: A string representing the username of the
channel to which we want to subscribe to.
my_username: An optional string representing the name of the user which
we want to subscribe. Defaults to currently authenticated user.
Returns:
A new YouTubeSubscriptionEntry if successfully posted.
"""
subscription_category = atom.Category(
scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME,
term='channel')
subscription_username = gdata.youtube.Username(
text=username_to_subscribe_to)
subscription_entry = gdata.youtube.YouTubeSubscriptionEntry(
category=subscription_category,
username=subscription_username)
post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'subscriptions')
return self.Post(subscription_entry, post_uri,
converter=gdata.youtube.YouTubeSubscriptionEntryFromString)
def AddSubscriptionToFavorites(self, username, my_username = 'default'):
"""Add a new subscription to a users favorites to the currently
authenticated user's account.
Needs authentication
Args:
username: A string representing the username of the user's favorite feed
to subscribe to.
my_username: An optional string representing the username of the user
that is to be subscribed. Defaults to currently authenticated user.
Returns:
A new YouTubeSubscriptionEntry if successful.
"""
subscription_category = atom.Category(
scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME,
term='favorites')
subscription_username = gdata.youtube.Username(text=username)
subscription_entry = gdata.youtube.YouTubeSubscriptionEntry(
category=subscription_category,
username=subscription_username)
post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'subscriptions')
return self.Post(subscription_entry, post_uri,
converter=gdata.youtube.YouTubeSubscriptionEntryFromString)
def AddSubscriptionToQuery(self, query, my_username = 'default'):
"""Add a new subscription to a specific keyword query to the currently
authenticated user's account.
Needs authentication
Args:
query: A string representing the keyword query to subscribe to.
my_username: An optional string representing the username of the user
that is to be subscribed. Defaults to currently authenticated user.
Returns:
A new YouTubeSubscriptionEntry if successful.
"""
subscription_category = atom.Category(
scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME,
term='query')
subscription_query_string = gdata.youtube.QueryString(text=query)
subscription_entry = gdata.youtube.YouTubeSubscriptionEntry(
category=subscription_category,
query_string=subscription_query_string)
post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'subscriptions')
return self.Post(subscription_entry, post_uri,
converter=gdata.youtube.YouTubeSubscriptionEntryFromString)
def DeleteSubscription(self, subscription_uri):
"""Delete a subscription from the currently authenticated user's account.
Needs authentication.
Args:
subscription_uri: A string representing the URI of the subscription that
is to be deleted.
Returns:
True if deleted successfully.
"""
return self.Delete(subscription_uri)
def AddContact(self, contact_username, my_username='default'):
"""Add a new contact to the currently authenticated user's contact feed.
Needs authentication.
Args:
contact_username: A string representing the username of the contact
that you wish to add.
my_username: An optional string representing the username to whose
contact the new contact is to be added.
Returns:
A YouTubeContactEntry if added successfully.
"""
contact_category = atom.Category(
scheme = 'http://gdata.youtube.com/schemas/2007/contact.cat',
term = 'Friends')
contact_username = gdata.youtube.Username(text=contact_username)
contact_entry = gdata.youtube.YouTubeContactEntry(
category=contact_category,
username=contact_username)
contact_post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'contacts')
return self.Post(contact_entry, contact_post_uri,
converter=gdata.youtube.YouTubeContactEntryFromString)
def UpdateContact(self, contact_username, new_contact_status,
new_contact_category, my_username='default'):
"""Update a contact, providing a new status and a new category.
Needs authentication.
Args:
contact_username: A string representing the username of the contact
that is to be updated.
new_contact_status: A string representing the new status of the contact.
This can either be set to 'accepted' or 'rejected'.
new_contact_category: A string representing the new category for the
contact, either 'Friends' or 'Family'.
my_username: An optional string representing the username of the user
whose contact feed we are modifying. Defaults to the currently
authenticated user.
Returns:
A YouTubeContactEntry if updated succesfully.
Raises:
YouTubeError: New contact status must be within the accepted values. Or
new contact category must be within the accepted categories.
"""
if new_contact_status not in YOUTUBE_CONTACT_STATUS:
raise YouTubeError('New contact status must be one of %s' %
(' '.join(YOUTUBE_CONTACT_STATUS)))
if new_contact_category not in YOUTUBE_CONTACT_CATEGORY:
raise YouTubeError('New contact category must be one of %s' %
(' '.join(YOUTUBE_CONTACT_CATEGORY)))
contact_category = atom.Category(
scheme='http://gdata.youtube.com/schemas/2007/contact.cat',
term=new_contact_category)
contact_status = gdata.youtube.Status(text=new_contact_status)
contact_entry = gdata.youtube.YouTubeContactEntry(
category=contact_category,
status=contact_status)
contact_put_uri = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'contacts', contact_username)
return self.Put(contact_entry, contact_put_uri,
converter=gdata.youtube.YouTubeContactEntryFromString)
def DeleteContact(self, contact_username, my_username='default'):
"""Delete a contact from a users contact feed.
Needs authentication.
Args:
contact_username: A string representing the username of the contact
that is to be deleted.
my_username: An optional string representing the username of the user's
contact feed from which to delete the contact. Defaults to the
currently authenticated user.
Returns:
True if the contact was deleted successfully
"""
contact_edit_uri = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'contacts', contact_username)
return self.Delete(contact_edit_uri)
def _GetDeveloperKey(self):
"""Getter for Developer Key property.
Returns:
If the developer key has been set, a string representing the developer key
is returned or None.
"""
if 'X-GData-Key' in self.additional_headers:
return self.additional_headers['X-GData-Key'][4:]
else:
return None
def _SetDeveloperKey(self, developer_key):
"""Setter for Developer Key property.
Sets the developer key in the 'X-GData-Key' header. The actual value that
is set is 'key=' plus the developer_key that was passed.
"""
self.additional_headers['X-GData-Key'] = 'key=' + developer_key
developer_key = property(_GetDeveloperKey, _SetDeveloperKey,
doc="""The Developer Key property""")
def _GetClientId(self):
"""Getter for Client Id property.
Returns:
If the client_id has been set, a string representing it is returned
or None.
"""
if 'X-Gdata-Client' in self.additional_headers:
return self.additional_headers['X-Gdata-Client']
else:
return None
def _SetClientId(self, client_id):
"""Setter for Client Id property.
Sets the 'X-Gdata-Client' header.
"""
self.additional_headers['X-Gdata-Client'] = client_id
client_id = property(_GetClientId, _SetClientId,
doc="""The ClientId property""")
def Query(self, uri):
"""Performs a query and returns a resulting feed or entry.
Args:
uri: A string representing the URI of the feed that is to be queried.
Returns:
On success, a tuple in the form:
(boolean succeeded=True, ElementTree._Element result)
On failure, a tuple in the form:
(boolean succeeded=False, {'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response})
"""
result = self.Get(uri)
return result
def YouTubeQuery(self, query):
"""Performs a YouTube specific query and returns a resulting feed or entry.
Args:
query: A Query object or one if its sub-classes (YouTubeVideoQuery,
YouTubeUserQuery or YouTubePlaylistQuery).
Returns:
Depending on the type of Query object submitted returns either a
YouTubeVideoFeed, a YouTubeUserFeed, a YouTubePlaylistFeed. If the
Query object provided was not YouTube-related, a tuple is returned.
On success the tuple will be in this form:
(boolean succeeded=True, ElementTree._Element result)
On failure, the tuple will be in this form:
(boolean succeeded=False, {'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server response})
"""
result = self.Query(query.ToUri())
if isinstance(query, YouTubeVideoQuery):
return gdata.youtube.YouTubeVideoFeedFromString(result.ToString())
elif isinstance(query, YouTubeUserQuery):
return gdata.youtube.YouTubeUserFeedFromString(result.ToString())
elif isinstance(query, YouTubePlaylistQuery):
return gdata.youtube.YouTubePlaylistFeedFromString(result.ToString())
else:
return result
class YouTubeVideoQuery(gdata.service.Query):
"""Subclasses gdata.service.Query to represent a YouTube Data API query.
Attributes are set dynamically via properties. Properties correspond to
the standard Google Data API query parameters with YouTube Data API
extensions. Please refer to the API documentation for details.
Attributes:
vq: The vq parameter, which is only supported for video feeds, specifies a
search query term. Refer to API documentation for further details.
orderby: The orderby parameter, which is only supported for video feeds,
specifies the value that will be used to sort videos in the search
result set. Valid values for this parameter are relevance, published,
viewCount and rating.
time: The time parameter, which is only available for the top_rated,
top_favorites, most_viewed, most_discussed, most_linked and
most_responded standard feeds, restricts the search to videos uploaded
within the specified time. Valid values for this parameter are today
(1 day), this_week (7 days), this_month (1 month) and all_time.
The default value for this parameter is all_time.
format: The format parameter specifies that videos must be available in a
particular video format. Refer to the API documentation for details.
racy: The racy parameter allows a search result set to include restricted
content as well as standard content. Valid values for this parameter
are include and exclude. By default, restricted content is excluded.
lr: The lr parameter restricts the search to videos that have a title,
description or keywords in a specific language. Valid values for the lr
parameter are ISO 639-1 two-letter language codes.
restriction: The restriction parameter identifies the IP address that
should be used to filter videos that can only be played in specific
countries.
"""
def __init__(self, video_id=None, feed_type=None, text_query=None,
params=None, categories=None):
if feed_type in YOUTUBE_STANDARDFEEDS:
feed = 'http://%s/feeds/standardfeeds/%s' % (YOUTUBE_SERVER, feed_type)
elif feed_type is 'responses' or feed_type is 'comments' and video_id:
feed = 'http://%s/feeds/videos/%s/%s' % (YOUTUBE_SERVER, video_id,
feed_type)
else:
feed = 'http://%s/feeds/videos' % (YOUTUBE_SERVER)
gdata.service.Query.__init__(self, feed, text_query=text_query,
params=params, categories=categories)
def _GetVideoQuery(self):
if 'vq' in self:
return self['vq']
else:
return None
def _SetVideoQuery(self, val):
self['vq'] = val
vq = property(_GetVideoQuery, _SetVideoQuery,
doc="""The video query (vq) query parameter""")
def _GetOrderBy(self):
if 'orderby' in self:
return self['orderby']
else:
return None
def _SetOrderBy(self, val):
if val not in YOUTUBE_QUERY_VALID_ORDERBY_PARAMETERS:
raise YouTubeError('OrderBy must be one of: %s ' %
' '.join(YOUTUBE_QUERY_VALID_ORDERBY_PARAMETERS))
self['orderby'] = val
orderby = property(_GetOrderBy, _SetOrderBy,
doc="""The orderby query parameter""")
def _GetTime(self):
if 'time' in self:
return self['time']
else:
return None
def _SetTime(self, val):
if val not in YOUTUBE_QUERY_VALID_TIME_PARAMETERS:
raise YouTubeError('Time must be one of: %s ' %
' '.join(YOUTUBE_QUERY_VALID_TIME_PARAMETERS))
self['time'] = val
time = property(_GetTime, _SetTime,
doc="""The time query parameter""")
def _GetFormat(self):
if 'format' in self:
return self['format']
else:
return None
def _SetFormat(self, val):
if val not in YOUTUBE_QUERY_VALID_FORMAT_PARAMETERS:
raise YouTubeError('Format must be one of: %s ' %
' '.join(YOUTUBE_QUERY_VALID_FORMAT_PARAMETERS))
self['format'] = val
format = property(_GetFormat, _SetFormat,
doc="""The format query parameter""")
def _GetRacy(self):
if 'racy' in self:
return self['racy']
else:
return None
def _SetRacy(self, val):
if val not in YOUTUBE_QUERY_VALID_RACY_PARAMETERS:
raise YouTubeError('Racy must be one of: %s ' %
' '.join(YOUTUBE_QUERY_VALID_RACY_PARAMETERS))
self['racy'] = val
racy = property(_GetRacy, _SetRacy,
doc="""The racy query parameter""")
def _GetLanguageRestriction(self):
if 'lr' in self:
return self['lr']
else:
return None
def _SetLanguageRestriction(self, val):
self['lr'] = val
lr = property(_GetLanguageRestriction, _SetLanguageRestriction,
doc="""The lr (language restriction) query parameter""")
def _GetIPRestriction(self):
if 'restriction' in self:
return self['restriction']
else:
return None
def _SetIPRestriction(self, val):
self['restriction'] = val
restriction = property(_GetIPRestriction, _SetIPRestriction,
doc="""The restriction query parameter""")
class YouTubeUserQuery(YouTubeVideoQuery):
"""Subclasses YouTubeVideoQuery to perform user-specific queries.
Attributes are set dynamically via properties. Properties correspond to
the standard Google Data API query parameters with YouTube Data API
extensions.
"""
def __init__(self, username=None, feed_type=None, subscription_id=None,
text_query=None, params=None, categories=None):
uploads_favorites_playlists = ('uploads', 'favorites', 'playlists')
if feed_type is 'subscriptions' and subscription_id and username:
feed = "http://%s/feeds/users/%s/%s/%s" % (YOUTUBE_SERVER, username,
feed_type, subscription_id)
elif feed_type is 'subscriptions' and not subscription_id and username:
feed = "http://%s/feeds/users/%s/%s" % (YOUTUBE_SERVER, username,
feed_type)
elif feed_type in uploads_favorites_playlists:
feed = "http://%s/feeds/users/%s/%s" % (YOUTUBE_SERVER, username,
feed_type)
else:
feed = "http://%s/feeds/users" % (YOUTUBE_SERVER)
YouTubeVideoQuery.__init__(self, feed, text_query=text_query,
params=params, categories=categories)
class YouTubePlaylistQuery(YouTubeVideoQuery):
"""Subclasses YouTubeVideoQuery to perform playlist-specific queries.
Attributes are set dynamically via properties. Properties correspond to
the standard Google Data API query parameters with YouTube Data API
extensions.
"""
def __init__(self, playlist_id, text_query=None, params=None,
categories=None):
if playlist_id:
feed = "http://%s/feeds/playlists/%s" % (YOUTUBE_SERVER, playlist_id)
else:
feed = "http://%s/feeds/playlists" % (YOUTUBE_SERVER)
YouTubeVideoQuery.__init__(self, feed, text_query=text_query,
params=params, categories=categories)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = ('api.stephaniel@gmail.com (Stephanie Liu)'
', api.jhartmann@gmail.com (Jochen Hartmann)')
import atom
import gdata
import gdata.media as Media
import gdata.geo as Geo
YOUTUBE_NAMESPACE = 'http://gdata.youtube.com/schemas/2007'
YOUTUBE_FORMAT = '{http://gdata.youtube.com/schemas/2007}format'
YOUTUBE_DEVELOPER_TAG_SCHEME = '%s/%s' % (YOUTUBE_NAMESPACE,
'developertags.cat')
YOUTUBE_SUBSCRIPTION_TYPE_SCHEME = '%s/%s' % (YOUTUBE_NAMESPACE,
'subscriptiontypes.cat')
class Username(atom.AtomBase):
"""The YouTube Username element"""
_tag = 'username'
_namespace = YOUTUBE_NAMESPACE
class QueryString(atom.AtomBase):
"""The YouTube QueryString element"""
_tag = 'queryString'
_namespace = YOUTUBE_NAMESPACE
class FirstName(atom.AtomBase):
"""The YouTube FirstName element"""
_tag = 'firstName'
_namespace = YOUTUBE_NAMESPACE
class LastName(atom.AtomBase):
"""The YouTube LastName element"""
_tag = 'lastName'
_namespace = YOUTUBE_NAMESPACE
class Age(atom.AtomBase):
"""The YouTube Age element"""
_tag = 'age'
_namespace = YOUTUBE_NAMESPACE
class Books(atom.AtomBase):
"""The YouTube Books element"""
_tag = 'books'
_namespace = YOUTUBE_NAMESPACE
class Gender(atom.AtomBase):
"""The YouTube Gender element"""
_tag = 'gender'
_namespace = YOUTUBE_NAMESPACE
class Company(atom.AtomBase):
"""The YouTube Company element"""
_tag = 'company'
_namespace = YOUTUBE_NAMESPACE
class Hobbies(atom.AtomBase):
"""The YouTube Hobbies element"""
_tag = 'hobbies'
_namespace = YOUTUBE_NAMESPACE
class Hometown(atom.AtomBase):
"""The YouTube Hometown element"""
_tag = 'hometown'
_namespace = YOUTUBE_NAMESPACE
class Location(atom.AtomBase):
"""The YouTube Location element"""
_tag = 'location'
_namespace = YOUTUBE_NAMESPACE
class Movies(atom.AtomBase):
"""The YouTube Movies element"""
_tag = 'movies'
_namespace = YOUTUBE_NAMESPACE
class Music(atom.AtomBase):
"""The YouTube Music element"""
_tag = 'music'
_namespace = YOUTUBE_NAMESPACE
class Occupation(atom.AtomBase):
"""The YouTube Occupation element"""
_tag = 'occupation'
_namespace = YOUTUBE_NAMESPACE
class School(atom.AtomBase):
"""The YouTube School element"""
_tag = 'school'
_namespace = YOUTUBE_NAMESPACE
class Relationship(atom.AtomBase):
"""The YouTube Relationship element"""
_tag = 'relationship'
_namespace = YOUTUBE_NAMESPACE
class Recorded(atom.AtomBase):
"""The YouTube Recorded element"""
_tag = 'recorded'
_namespace = YOUTUBE_NAMESPACE
class Statistics(atom.AtomBase):
"""The YouTube Statistics element."""
_tag = 'statistics'
_namespace = YOUTUBE_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['viewCount'] = 'view_count'
_attributes['videoWatchCount'] = 'video_watch_count'
_attributes['subscriberCount'] = 'subscriber_count'
_attributes['lastWebAccess'] = 'last_web_access'
_attributes['favoriteCount'] = 'favorite_count'
def __init__(self, view_count=None, video_watch_count=None,
favorite_count=None, subscriber_count=None, last_web_access=None,
extension_elements=None, extension_attributes=None, text=None):
self.view_count = view_count
self.video_watch_count = video_watch_count
self.subscriber_count = subscriber_count
self.last_web_access = last_web_access
self.favorite_count = favorite_count
atom.AtomBase.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes, text=text)
class Status(atom.AtomBase):
"""The YouTube Status element"""
_tag = 'status'
_namespace = YOUTUBE_NAMESPACE
class Position(atom.AtomBase):
"""The YouTube Position element. The position in a playlist feed."""
_tag = 'position'
_namespace = YOUTUBE_NAMESPACE
class Racy(atom.AtomBase):
"""The YouTube Racy element."""
_tag = 'racy'
_namespace = YOUTUBE_NAMESPACE
class Description(atom.AtomBase):
"""The YouTube Description element."""
_tag = 'description'
_namespace = YOUTUBE_NAMESPACE
class Private(atom.AtomBase):
"""The YouTube Private element."""
_tag = 'private'
_namespace = YOUTUBE_NAMESPACE
class NoEmbed(atom.AtomBase):
"""The YouTube VideoShare element. Whether a video can be embedded or not."""
_tag = 'noembed'
_namespace = YOUTUBE_NAMESPACE
class Comments(atom.AtomBase):
"""The GData Comments element"""
_tag = 'comments'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
[gdata.FeedLink])
def __init__(self, feed_link=None, extension_elements=None,
extension_attributes=None, text=None):
self.feed_link = feed_link
atom.AtomBase.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes, text=text)
class Rating(atom.AtomBase):
"""The GData Rating element"""
_tag = 'rating'
_namespace = gdata.GDATA_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['min'] = 'min'
_attributes['max'] = 'max'
_attributes['numRaters'] = 'num_raters'
_attributes['average'] = 'average'
def __init__(self, min=None, max=None,
num_raters=None, average=None, extension_elements=None,
extension_attributes=None, text=None):
self.min = min
self.max = max
self.num_raters = num_raters
self.average = average
atom.AtomBase.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes, text=text)
class YouTubePlaylistVideoEntry(gdata.GDataEntry):
"""Represents a YouTubeVideoEntry on a YouTubePlaylist."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
[gdata.FeedLink])
_children['{%s}description' % YOUTUBE_NAMESPACE] = ('description',
Description)
_children['{%s}rating' % gdata.GDATA_NAMESPACE] = ('rating', Rating)
_children['{%s}comments' % gdata.GDATA_NAMESPACE] = ('comments', Comments)
_children['{%s}statistics' % YOUTUBE_NAMESPACE] = ('statistics', Statistics)
_children['{%s}location' % YOUTUBE_NAMESPACE] = ('location', Location)
_children['{%s}position' % YOUTUBE_NAMESPACE] = ('position', Position)
_children['{%s}group' % gdata.media.MEDIA_NAMESPACE] = ('media', Media.Group)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None, title=None,
updated=None, feed_link=None, description=None,
rating=None, comments=None, statistics=None,
location=None, position=None, media=None,
extension_elements=None, extension_attributes=None):
self.feed_link = feed_link
self.description = description
self.rating = rating
self.comments = comments
self.statistics = statistics
self.location = location
self.position = position
self.media = media
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id,
link=link, published=published, title=title,
updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
class YouTubeVideoCommentEntry(gdata.GDataEntry):
"""Represents a comment on YouTube."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
class YouTubeSubscriptionEntry(gdata.GDataEntry):
"""Represents a subscription entry on YouTube."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}username' % YOUTUBE_NAMESPACE] = ('username', Username)
_children['{%s}queryString' % YOUTUBE_NAMESPACE] = (
'query_string', QueryString)
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
[gdata.FeedLink])
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None, title=None,
updated=None, username=None, query_string=None, feed_link=None,
extension_elements=None, extension_attributes=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title, updated=updated)
self.username = username
self.query_string = query_string
self.feed_link = feed_link
def GetSubscriptionType(self):
"""Retrieve the type of this subscription.
Returns:
A string that is either 'channel, 'query' or 'favorites'
"""
for category in self.category:
if category.scheme == YOUTUBE_SUBSCRIPTION_TYPE_SCHEME:
return category.term
class YouTubeVideoResponseEntry(gdata.GDataEntry):
"""Represents a video response. """
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}rating' % gdata.GDATA_NAMESPACE] = ('rating', Rating)
_children['{%s}noembed' % YOUTUBE_NAMESPACE] = ('noembed', NoEmbed)
_children['{%s}statistics' % YOUTUBE_NAMESPACE] = ('statistics', Statistics)
_children['{%s}racy' % YOUTUBE_NAMESPACE] = ('racy', Racy)
_children['{%s}group' % gdata.media.MEDIA_NAMESPACE] = ('media', Media.Group)
def __init__(self, author=None, category=None, content=None, atom_id=None,
link=None, published=None, title=None, updated=None, rating=None,
noembed=None, statistics=None, racy=None, media=None,
extension_elements=None, extension_attributes=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title, updated=updated)
self.rating = rating
self.noembed = noembed
self.statistics = statistics
self.racy = racy
self.media = media or Media.Group()
class YouTubeContactEntry(gdata.GDataEntry):
"""Represents a contact entry."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}username' % YOUTUBE_NAMESPACE] = ('username', Username)
_children['{%s}status' % YOUTUBE_NAMESPACE] = ('status', Status)
def __init__(self, author=None, category=None, content=None, atom_id=None,
link=None, published=None, title=None, updated=None,
username=None, status=None, extension_elements=None,
extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title, updated=updated)
self.username = username
self.status = status
class YouTubeVideoEntry(gdata.GDataEntry):
"""Represents a video on YouTube."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}rating' % gdata.GDATA_NAMESPACE] = ('rating', Rating)
_children['{%s}comments' % gdata.GDATA_NAMESPACE] = ('comments', Comments)
_children['{%s}noembed' % YOUTUBE_NAMESPACE] = ('noembed', NoEmbed)
_children['{%s}statistics' % YOUTUBE_NAMESPACE] = ('statistics', Statistics)
_children['{%s}recorded' % YOUTUBE_NAMESPACE] = ('recorded', Recorded)
_children['{%s}racy' % YOUTUBE_NAMESPACE] = ('racy', Racy)
_children['{%s}group' % gdata.media.MEDIA_NAMESPACE] = ('media', Media.Group)
_children['{%s}where' % gdata.geo.GEORSS_NAMESPACE] = ('geo', Geo.Where)
def __init__(self, author=None, category=None, content=None, atom_id=None,
link=None, published=None, title=None, updated=None, rating=None,
noembed=None, statistics=None, racy=None, media=None, geo=None,
recorded=None, comments=None, extension_elements=None,
extension_attributes=None):
self.rating = rating
self.noembed = noembed
self.statistics = statistics
self.racy = racy
self.comments = comments
self.media = media or Media.Group()
self.geo = geo
self.recorded = recorded
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title, updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
def GetSwfUrl(self):
"""Return the URL for the embeddable Video
Returns:
URL of the embeddable video
"""
if self.media.content:
for content in self.media.content:
if content.extension_attributes[YOUTUBE_FORMAT] == '5':
return content.url
else:
return None
def AddDeveloperTags(self, developer_tags):
"""Add a developer tag for this entry.
Developer tags can only be set during the initial upload.
Arguments:
developer_tags: A list of developer tags as strings.
Returns:
A list of all developer tags for this video entry.
"""
for tag_text in developer_tags:
self.media.category.append(gdata.media.Category(
text=tag_text, label=tag_text, scheme=YOUTUBE_DEVELOPER_TAG_SCHEME))
return self.GetDeveloperTags()
def GetDeveloperTags(self):
"""Retrieve developer tags for this video entry."""
developer_tags = []
for category in self.media.category:
if category.scheme == YOUTUBE_DEVELOPER_TAG_SCHEME:
developer_tags.append(category)
if len(developer_tags) > 0:
return developer_tags
def GetYouTubeCategoryAsString(self):
"""Convenience method to return the YouTube category as string.
YouTubeVideoEntries can contain multiple Category objects with differing
schemes. This method returns only the category with the correct
scheme, ignoring developer tags.
"""
for category in self.media.category:
if category.scheme != YOUTUBE_DEVELOPER_TAG_SCHEME:
return category.text
class YouTubeUserEntry(gdata.GDataEntry):
"""Represents a user on YouTube."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}username' % YOUTUBE_NAMESPACE] = ('username', Username)
_children['{%s}firstName' % YOUTUBE_NAMESPACE] = ('first_name', FirstName)
_children['{%s}lastName' % YOUTUBE_NAMESPACE] = ('last_name', LastName)
_children['{%s}age' % YOUTUBE_NAMESPACE] = ('age', Age)
_children['{%s}books' % YOUTUBE_NAMESPACE] = ('books', Books)
_children['{%s}gender' % YOUTUBE_NAMESPACE] = ('gender', Gender)
_children['{%s}company' % YOUTUBE_NAMESPACE] = ('company', Company)
_children['{%s}description' % YOUTUBE_NAMESPACE] = ('description',
Description)
_children['{%s}hobbies' % YOUTUBE_NAMESPACE] = ('hobbies', Hobbies)
_children['{%s}hometown' % YOUTUBE_NAMESPACE] = ('hometown', Hometown)
_children['{%s}location' % YOUTUBE_NAMESPACE] = ('location', Location)
_children['{%s}movies' % YOUTUBE_NAMESPACE] = ('movies', Movies)
_children['{%s}music' % YOUTUBE_NAMESPACE] = ('music', Music)
_children['{%s}occupation' % YOUTUBE_NAMESPACE] = ('occupation', Occupation)
_children['{%s}school' % YOUTUBE_NAMESPACE] = ('school', School)
_children['{%s}relationship' % YOUTUBE_NAMESPACE] = ('relationship',
Relationship)
_children['{%s}statistics' % YOUTUBE_NAMESPACE] = ('statistics', Statistics)
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
[gdata.FeedLink])
_children['{%s}thumbnail' % gdata.media.MEDIA_NAMESPACE] = ('thumbnail',
Media.Thumbnail)
def __init__(self, author=None, category=None, content=None, atom_id=None,
link=None, published=None, title=None, updated=None,
username=None, first_name=None, last_name=None, age=None,
books=None, gender=None, company=None, description=None,
hobbies=None, hometown=None, location=None, movies=None,
music=None, occupation=None, school=None, relationship=None,
statistics=None, feed_link=None, extension_elements=None,
extension_attributes=None, text=None):
self.username = username
self.first_name = first_name
self.last_name = last_name
self.age = age
self.books = books
self.gender = gender
self.company = company
self.description = description
self.hobbies = hobbies
self.hometown = hometown
self.location = location
self.movies = movies
self.music = music
self.occupation = occupation
self.school = school
self.relationship = relationship
self.statistics = statistics
self.feed_link = feed_link
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id,
link=link, published=published,
title=title, updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
class YouTubeVideoFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a video feed on YouTube."""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [YouTubeVideoEntry])
class YouTubePlaylistEntry(gdata.GDataEntry):
"""Represents a playlist in YouTube."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}description' % YOUTUBE_NAMESPACE] = ('description',
Description)
_children['{%s}private' % YOUTUBE_NAMESPACE] = ('private',
Private)
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
[gdata.FeedLink])
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None, title=None,
updated=None, private=None, feed_link=None,
description=None, extension_elements=None,
extension_attributes=None):
self.description = description
self.private = private
self.feed_link = feed_link
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id,
link=link, published=published, title=title,
updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
class YouTubePlaylistFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a feed of a user's playlists """
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[YouTubePlaylistEntry])
class YouTubePlaylistVideoFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a feed of video entry on a playlist."""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[YouTubePlaylistVideoEntry])
class YouTubeContactFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a feed of a users contacts."""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[YouTubeContactEntry])
class YouTubeSubscriptionFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a feed of a users subscriptions."""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[YouTubeSubscriptionEntry])
class YouTubeVideoCommentFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a feed of comments for a video."""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[YouTubeVideoCommentEntry])
class YouTubeVideoResponseFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a feed of video responses."""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[YouTubeVideoResponseEntry])
def YouTubeVideoFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoFeed, xml_string)
def YouTubeVideoEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoEntry, xml_string)
def YouTubeContactFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeContactFeed, xml_string)
def YouTubeContactEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeContactEntry, xml_string)
def YouTubeVideoCommentFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoCommentFeed, xml_string)
def YouTubeVideoCommentEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoCommentEntry, xml_string)
def YouTubeUserFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoFeed, xml_string)
def YouTubeUserEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeUserEntry, xml_string)
def YouTubePlaylistFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubePlaylistFeed, xml_string)
def YouTubePlaylistVideoFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubePlaylistVideoFeed, xml_string)
def YouTubePlaylistEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubePlaylistEntry, xml_string)
def YouTubePlaylistVideoEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubePlaylistVideoEntry, xml_string)
def YouTubeSubscriptionFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeSubscriptionFeed, xml_string)
def YouTubeSubscriptionEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeSubscriptionEntry, xml_string)
def YouTubeVideoResponseFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoResponseFeed, xml_string)
def YouTubeVideoResponseEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoResponseEntry, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Provides HttpRequest function for gdata.service to use on Google App Engine
HttpRequest: Function that wraps google.appengine.api.urlfetch.Fetch in a
common interface which is used by gdata.service.GDataService. In other
words, this module can be used as the gdata service request handler so
that all HTTP requests will be performed by the hosting Google App Engine
server.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
import StringIO
import atom.service
from google.appengine.api import urlfetch
def HttpRequest(service, operation, data, uri, extra_headers=None,
url_params=None, escape_params=True, content_type='application/atom+xml'):
"""Performs an HTTP call to the server, supports GET, POST, PUT, and DELETE.
To use this module with gdata.service, you can set this module to be the
http_request_handler so that HTTP requests use Google App Engine's urlfetch.
import gdata.service
import gdata.urlfetch
gdata.service.http_request_handler = gdata.urlfetch
Args:
service: atom.AtomService object which contains some of the parameters
needed to make the request. The following members are used to
construct the HTTP call: server (str), additional_headers (dict),
port (int), and ssl (bool).
operation: str The HTTP operation to be performed. This is usually one of
'GET', 'POST', 'PUT', or 'DELETE'
data: filestream, list of parts, or other object which can be
converted to a string.
Should be set to None when performing a GET or PUT.
If data is a file-like object which can be read, this method will read
a chunk of 100K bytes at a time and send them.
If the data is a list of parts to be sent, each part will be evaluated
and sent.
uri: The beginning of the URL to which the request should be sent.
Examples: '/', '/base/feeds/snippets',
'/m8/feeds/contacts/default/base'
extra_headers: dict of strings. HTTP headers which should be sent
in the request. These headers are in addition to those stored in
service.additional_headers.
url_params: dict of strings. Key value pairs to be added to the URL as
URL parameters. For example {'foo':'bar', 'test':'param'} will
become ?foo=bar&test=param.
escape_params: bool default True. If true, the keys and values in
url_params will be URL escaped when the form is constructed
(Special characters converted to %XX form.)
content_type: str The MIME type for the data being sent. Defaults to
'application/atom+xml', this is only used if data is set.
"""
full_uri = atom.service.BuildUri(uri, url_params, escape_params)
(server, port, ssl, partial_uri) = atom.service.ProcessUrl(service, full_uri)
# Construct the full URL for the request.
if ssl:
full_url = 'https://%s%s' % (server, partial_uri)
else:
full_url = 'http://%s%s' % (server, partial_uri)
# Construct the full payload.
# Assume that data is None or a string.
data_str = data
if data:
if isinstance(data, list):
# If data is a list of different objects, convert them all to strings
# and join them together.
converted_parts = [__ConvertDataPart(x) for x in data]
data_str = ''.join(converted_parts)
else:
data_str = __ConvertDataPart(data)
# Construct the dictionary of HTTP headers.
headers = {}
if isinstance(service.additional_headers, dict):
headers = service.additional_headers.copy()
if isinstance(extra_headers, dict):
for header, value in extra_headers.iteritems():
headers[header] = value
# Add the content type header (we don't need to calculate content length,
# since urlfetch.Fetch will calculate for us).
if content_type:
headers['Content-Type'] = content_type
# Lookup the urlfetch operation which corresponds to the desired HTTP verb.
if operation == 'GET':
method = urlfetch.GET
elif operation == 'POST':
method = urlfetch.POST
elif operation == 'PUT':
method = urlfetch.PUT
elif operation == 'DELETE':
method = urlfetch.DELETE
else:
method = None
return HttpResponse(urlfetch.Fetch(url=full_url, payload=data_str,
method=method, headers=headers))
def __ConvertDataPart(data):
if not data or isinstance(data, str):
return data
elif hasattr(data, 'read'):
# data is a file like object, so read it completely.
return data.read()
# The data object was not a file.
# Try to convert to a string and send the data.
return str(data)
class HttpResponse(object):
"""Translates a urlfetch resoinse to look like an hhtplib resoinse.
Used to allow the resoinse from HttpRequest to be usable by gdata.service
methods.
"""
def __init__(self, urlfetch_response):
self.body = StringIO.StringIO(urlfetch_response.content)
self.headers = urlfetch_response.headers
self.status = urlfetch_response.status_code
self.reason = ''
def read(self, length=None):
if not length:
return self.body.read()
else:
return self.body.read(length)
def getheader(self, name):
if not self.headers.has_key(name):
return self.headers[name.lower()]
return self.headers[name]
| Python |
#!/usr/bin/python
#
# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Provides HttpRequest function for gdata.service to use on Google App Engine
HttpRequest: Function that wraps google.appengine.api.urlfetch.Fetch in a
common interface which is used by gdata.service.GDataService. In other
words, this module can be used as the gdata service request handler so
that all HTTP requests will be performed by the hosting Google App Engine
server.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
import StringIO
import atom.service
from google.appengine.api import urlfetch
def HttpRequest(service, operation, data, uri, extra_headers=None,
url_params=None, escape_params=True, content_type='application/atom+xml'):
"""Performs an HTTP call to the server, supports GET, POST, PUT, and DELETE.
To use this module with gdata.service, you can set this module to be the
http_request_handler so that HTTP requests use Google App Engine's urlfetch.
import gdata.service
import gdata.urlfetch
gdata.service.http_request_handler = gdata.urlfetch
Args:
service: atom.AtomService object which contains some of the parameters
needed to make the request. The following members are used to
construct the HTTP call: server (str), additional_headers (dict),
port (int), and ssl (bool).
operation: str The HTTP operation to be performed. This is usually one of
'GET', 'POST', 'PUT', or 'DELETE'
data: filestream, list of parts, or other object which can be
converted to a string.
Should be set to None when performing a GET or PUT.
If data is a file-like object which can be read, this method will read
a chunk of 100K bytes at a time and send them.
If the data is a list of parts to be sent, each part will be evaluated
and sent.
uri: The beginning of the URL to which the request should be sent.
Examples: '/', '/base/feeds/snippets',
'/m8/feeds/contacts/default/base'
extra_headers: dict of strings. HTTP headers which should be sent
in the request. These headers are in addition to those stored in
service.additional_headers.
url_params: dict of strings. Key value pairs to be added to the URL as
URL parameters. For example {'foo':'bar', 'test':'param'} will
become ?foo=bar&test=param.
escape_params: bool default True. If true, the keys and values in
url_params will be URL escaped when the form is constructed
(Special characters converted to %XX form.)
content_type: str The MIME type for the data being sent. Defaults to
'application/atom+xml', this is only used if data is set.
"""
full_uri = atom.service.BuildUri(uri, url_params, escape_params)
(server, port, ssl, partial_uri) = atom.service.ProcessUrl(service, full_uri)
# Construct the full URL for the request.
if ssl:
full_url = 'https://%s%s' % (server, partial_uri)
else:
full_url = 'http://%s%s' % (server, partial_uri)
# Construct the full payload.
# Assume that data is None or a string.
data_str = data
if data:
if isinstance(data, list):
# If data is a list of different objects, convert them all to strings
# and join them together.
converted_parts = [__ConvertDataPart(x) for x in data]
data_str = ''.join(converted_parts)
else:
data_str = __ConvertDataPart(data)
# Construct the dictionary of HTTP headers.
headers = {}
if isinstance(service.additional_headers, dict):
headers = service.additional_headers.copy()
if isinstance(extra_headers, dict):
for header, value in extra_headers.iteritems():
headers[header] = value
# Add the content type header (we don't need to calculate content length,
# since urlfetch.Fetch will calculate for us).
if content_type:
headers['Content-Type'] = content_type
# Lookup the urlfetch operation which corresponds to the desired HTTP verb.
if operation == 'GET':
method = urlfetch.GET
elif operation == 'POST':
method = urlfetch.POST
elif operation == 'PUT':
method = urlfetch.PUT
elif operation == 'DELETE':
method = urlfetch.DELETE
else:
method = None
return HttpResponse(urlfetch.Fetch(url=full_url, payload=data_str,
method=method, headers=headers))
def __ConvertDataPart(data):
if not data or isinstance(data, str):
return data
elif hasattr(data, 'read'):
# data is a file like object, so read it completely.
return data.read()
# The data object was not a file.
# Try to convert to a string and send the data.
return str(data)
class HttpResponse(object):
"""Translates a urlfetch resoinse to look like an hhtplib resoinse.
Used to allow the resoinse from HttpRequest to be usable by gdata.service
methods.
"""
def __init__(self, urlfetch_response):
self.body = StringIO.StringIO(urlfetch_response.content)
self.headers = urlfetch_response.headers
self.status = urlfetch_response.status_code
self.reason = ''
def read(self, length=None):
if not length:
return self.body.read()
else:
return self.body.read(length)
def getheader(self, name):
if not self.headers.has_key(name):
return self.headers[name.lower()]
return self.headers[name]
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
XML_ENTRY_1 = """<?xml version='1.0'?>
<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:g='http://base.google.com/ns/1.0'>
<category scheme="http://base.google.com/categories/itemtypes"
term="products"/>
<id> http://www.google.com/test/id/url </id>
<title type='text'>Testing 2000 series laptop</title>
<content type='xhtml'>
<div xmlns='http://www.w3.org/1999/xhtml'>A Testing Laptop</div>
</content>
<link rel='alternate' type='text/html'
href='http://www.provider-host.com/123456789'/>
<link rel='license'
href='http://creativecommons.org/licenses/by-nc/2.5/rdf'/>
<g:label>Computer</g:label>
<g:label>Laptop</g:label>
<g:label>testing laptop</g:label>
<g:item_type>products</g:item_type>
</entry>"""
TEST_BASE_ENTRY = """<?xml version='1.0'?>
<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:g='http://base.google.com/ns/1.0'>
<category scheme="http://base.google.com/categories/itemtypes"
term="products"/>
<title type='text'>Testing 2000 series laptop</title>
<content type='xhtml'>
<div xmlns='http://www.w3.org/1999/xhtml'>A Testing Laptop</div>
</content>
<app:control xmlns:app='http://purl.org/atom/app#'>
<app:draft>yes</app:draft>
<gm:disapproved xmlns:gm='http://base.google.com/ns-metadata/1.0'/>
</app:control>
<link rel='alternate' type='text/html'
href='http://www.provider-host.com/123456789'/>
<g:label>Computer</g:label>
<g:label>Laptop</g:label>
<g:label>testing laptop</g:label>
<g:item_type>products</g:item_type>
</entry>"""
BIG_FEED = """<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title type="text">dive into mark</title>
<subtitle type="html">
A <em>lot</em> of effort
went into making this effortless
</subtitle>
<updated>2005-07-31T12:29:29Z</updated>
<id>tag:example.org,2003:3</id>
<link rel="alternate" type="text/html"
hreflang="en" href="http://example.org/"/>
<link rel="self" type="application/atom+xml"
href="http://example.org/feed.atom"/>
<rights>Copyright (c) 2003, Mark Pilgrim</rights>
<generator uri="http://www.example.com/" version="1.0">
Example Toolkit
</generator>
<entry>
<title>Atom draft-07 snapshot</title>
<link rel="alternate" type="text/html"
href="http://example.org/2005/04/02/atom"/>
<link rel="enclosure" type="audio/mpeg" length="1337"
href="http://example.org/audio/ph34r_my_podcast.mp3"/>
<id>tag:example.org,2003:3.2397</id>
<updated>2005-07-31T12:29:29Z</updated>
<published>2003-12-13T08:29:29-04:00</published>
<author>
<name>Mark Pilgrim</name>
<uri>http://example.org/</uri>
<email>f8dy@example.com</email>
</author>
<contributor>
<name>Sam Ruby</name>
</contributor>
<contributor>
<name>Joe Gregorio</name>
</contributor>
<content type="xhtml" xml:lang="en"
xml:base="http://diveintomark.org/">
<div xmlns="http://www.w3.org/1999/xhtml">
<p><i>[Update: The Atom draft is finished.]</i></p>
</div>
</content>
</entry>
</feed>
"""
SMALL_FEED = """<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Example Feed</title>
<link href="http://example.org/"/>
<updated>2003-12-13T18:30:02Z</updated>
<author>
<name>John Doe</name>
</author>
<id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
<entry>
<title>Atom-Powered Robots Run Amok</title>
<link href="http://example.org/2003/12/13/atom03"/>
<id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
<updated>2003-12-13T18:30:02Z</updated>
<summary>Some text.</summary>
</entry>
</feed>
"""
GBASE_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:g='http://base.google.com/ns/1.0' xmlns:batch='http://schemas.google.com/gdata/batch'>
<id>http://www.google.com/base/feeds/snippets</id>
<updated>2007-02-08T23:18:21.935Z</updated>
<title type='text'>Items matching query: digital camera</title>
<link rel='alternate' type='text/html' href='http://base.google.com'>
</link>
<link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://www.google.com/base/feeds/snippets'>
</link>
<link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/snippets?start-index=1&max-results=25&bq=digital+camera'>
</link>
<link rel='next' type='application/atom+xml' href='http://www.google.com/base/feeds/snippets?start-index=26&max-results=25&bq=digital+camera'>
</link>
<generator version='1.0' uri='http://base.google.com'>GoogleBase </generator>
<openSearch:totalResults>2171885</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>http://www.google.com/base/feeds/snippets/13246453826751927533</id>
<published>2007-02-08T13:23:27.000Z</published>
<updated>2007-02-08T16:40:57.000Z</updated>
<category scheme='http://base.google.com/categories/itemtypes' term='Products'>
</category>
<title type='text'>Digital Camera Battery Notebook Computer 12v DC Power Cable - 5.5mm x 2.5mm (Center +) Camera Connecting Cables</title>
<content type='html'>Notebook Computer 12v DC Power Cable - 5.5mm x 2.1mm (Center +) This connection cable will allow any Digital Pursuits battery pack to power portable computers that operate with 12v power and have a 2.1mm power connector (center +) Digital ...</content>
<link rel='alternate' type='text/html' href='http://www.bhphotovideo.com/bnh/controller/home?O=productlist&A=details&Q=&sku=305668&is=REG&kw=DIDCB5092&BI=583'>
</link>
<link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/snippets/13246453826751927533'>
</link>
<author>
<name>B&H Photo-Video</name>
<email>anon-szot0wdsq0at@base.google.com</email>
</author>
<g:payment_notes type='text'>PayPal & Bill Me Later credit available online only.</g:payment_notes>
<g:condition type='text'>new</g:condition>
<g:location type='location'>420 9th Ave. 10001</g:location>
<g:id type='text'>305668-REG</g:id>
<g:item_type type='text'>Products</g:item_type>
<g:brand type='text'>Digital Camera Battery</g:brand>
<g:expiration_date type='dateTime'>2007-03-10T13:23:27.000Z</g:expiration_date>
<g:customer_id type='int'>1172711</g:customer_id>
<g:price type='floatUnit'>34.95 usd</g:price>
<g:product_type type='text'>Digital Photography>Camera Connecting Cables</g:product_type>
<g:item_language type='text'>EN</g:item_language>
<g:manufacturer_id type='text'>DCB5092</g:manufacturer_id>
<g:target_country type='text'>US</g:target_country>
<g:weight type='float'>1.0</g:weight>
<g:image_link type='url'>http://base.google.com/base_image?q=http%3A%2F%2Fwww.bhphotovideo.com%2Fimages%2Fitems%2F305668.jpg&dhm=ffffffff84c9a95e&size=6</g:image_link>
</entry>
<entry>
<id>http://www.google.com/base/feeds/snippets/10145771037331858608</id>
<published>2007-02-08T13:23:27.000Z</published>
<updated>2007-02-08T16:40:57.000Z</updated>
<category scheme='http://base.google.com/categories/itemtypes' term='Products'>
</category>
<title type='text'>Digital Camera Battery Electronic Device 5v DC Power Cable - 5.5mm x 2.5mm (Center +) Camera Connecting Cables</title>
<content type='html'>Electronic Device 5v DC Power Cable - 5.5mm x 2.5mm (Center +) This connection cable will allow any Digital Pursuits battery pack to power any electronic device that operates with 5v power and has a 2.5mm power connector (center +) Digital ...</content>
<link rel='alternate' type='text/html' href='http://www.bhphotovideo.com/bnh/controller/home?O=productlist&A=details&Q=&sku=305656&is=REG&kw=DIDCB5108&BI=583'>
</link>
<link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/snippets/10145771037331858608'>
</link>
<author>
<name>B&H Photo-Video</name>
<email>anon-szot0wdsq0at@base.google.com</email>
</author>
<g:location type='location'>420 9th Ave. 10001</g:location>
<g:condition type='text'>new</g:condition>
<g:weight type='float'>0.18</g:weight>
<g:target_country type='text'>US</g:target_country>
<g:product_type type='text'>Digital Photography>Camera Connecting Cables</g:product_type>
<g:payment_notes type='text'>PayPal & Bill Me Later credit available online only.</g:payment_notes>
<g:id type='text'>305656-REG</g:id>
<g:image_link type='url'>http://base.google.com/base_image?q=http%3A%2F%2Fwww.bhphotovideo.com%2Fimages%2Fitems%2F305656.jpg&dhm=7315bdc8&size=6</g:image_link>
<g:manufacturer_id type='text'>DCB5108</g:manufacturer_id>
<g:upc type='text'>838098005108</g:upc>
<g:price type='floatUnit'>34.95 usd</g:price>
<g:item_language type='text'>EN</g:item_language>
<g:brand type='text'>Digital Camera Battery</g:brand>
<g:customer_id type='int'>1172711</g:customer_id>
<g:item_type type='text'>Products</g:item_type>
<g:expiration_date type='dateTime'>2007-03-10T13:23:27.000Z</g:expiration_date>
</entry>
<entry>
<id>http://www.google.com/base/feeds/snippets/3128608193804768644</id>
<published>2007-02-08T02:21:27.000Z</published>
<updated>2007-02-08T15:40:13.000Z</updated>
<category scheme='http://base.google.com/categories/itemtypes' term='Products'>
</category>
<title type='text'>Digital Camera Battery Power Cable for Kodak 645 Pro-Back ProBack & DCS-300 Series Camera Connecting Cables</title>
<content type='html'>Camera Connection Cable - to Power Kodak 645 Pro-Back DCS-300 Series Digital Cameras This connection cable will allow any Digital Pursuits battery pack to power the following digital cameras: Kodak DCS Pro Back 645 DCS-300 series Digital Photography ...</content>
<link rel='alternate' type='text/html' href='http://www.bhphotovideo.com/bnh/controller/home?O=productlist&A=details&Q=&sku=305685&is=REG&kw=DIDCB6006&BI=583'>
</link>
<link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/snippets/3128608193804768644'>
</link>
<author>
<name>B&H Photo-Video</name>
<email>anon-szot0wdsq0at@base.google.com</email>
</author>
<g:weight type='float'>0.3</g:weight>
<g:manufacturer_id type='text'>DCB6006</g:manufacturer_id>
<g:image_link type='url'>http://base.google.com/base_image?q=http%3A%2F%2Fwww.bhphotovideo.com%2Fimages%2Fitems%2F305685.jpg&dhm=72f0ca0a&size=6</g:image_link>
<g:location type='location'>420 9th Ave. 10001</g:location>
<g:payment_notes type='text'>PayPal & Bill Me Later credit available online only.</g:payment_notes>
<g:item_type type='text'>Products</g:item_type>
<g:target_country type='text'>US</g:target_country>
<g:accessory_for type='text'>digital kodak camera</g:accessory_for>
<g:brand type='text'>Digital Camera Battery</g:brand>
<g:expiration_date type='dateTime'>2007-03-10T02:21:27.000Z</g:expiration_date>
<g:item_language type='text'>EN</g:item_language>
<g:condition type='text'>new</g:condition>
<g:price type='floatUnit'>34.95 usd</g:price>
<g:customer_id type='int'>1172711</g:customer_id>
<g:product_type type='text'>Digital Photography>Camera Connecting Cables</g:product_type>
<g:id type='text'>305685-REG</g:id>
</entry>
</feed>"""
EXTENSION_TREE = """<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<g:author xmlns:g="http://www.google.com">
<g:name>John Doe
<g:foo yes="no" up="down">Bar</g:foo>
</g:name>
</g:author>
</feed>
"""
TEST_AUTHOR = """<?xml version="1.0" encoding="utf-8"?>
<author xmlns="http://www.w3.org/2005/Atom">
<name xmlns="http://www.w3.org/2005/Atom">John Doe</name>
<email xmlns="http://www.w3.org/2005/Atom">johndoes@someemailadress.com</email>
<uri xmlns="http://www.w3.org/2005/Atom">http://www.google.com</uri>
</author>
"""
TEST_LINK = """<?xml version="1.0" encoding="utf-8"?>
<link xmlns="http://www.w3.org/2005/Atom" href="http://www.google.com"
rel="test rel" foo1="bar" foo2="rab"/>
"""
TEST_GBASE_ATTRIBUTE = """<?xml version="1.0" encoding="utf-8"?>
<g:brand type='text' xmlns:g="http://base.google.com/ns/1.0">Digital Camera Battery</g:brand>
"""
CALENDAR_FEED = """<?xml version='1.0' encoding='utf-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:gd='http://schemas.google.com/g/2005'
xmlns:gCal='http://schemas.google.com/gCal/2005'>
<id>http://www.google.com/calendar/feeds/default</id>
<updated>2007-03-20T22:48:57.833Z</updated>
<title type='text'>GData Ops Demo's Calendar List</title>
<link rel='http://schemas.google.com/g/2005#feed'
type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default'></link>
<link rel='http://schemas.google.com/g/2005#post'
type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default'></link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<generator version='1.0' uri='http://www.google.com/calendar'>
Google Calendar</generator>
<openSearch:startIndex>1</openSearch:startIndex>
<entry>
<id>
http://www.google.com/calendar/feeds/default/gdata.ops.demo%40gmail.com</id>
<published>2007-03-20T22:48:57.837Z</published>
<updated>2007-03-20T22:48:52.000Z</updated>
<title type='text'>GData Ops Demo</title>
<link rel='alternate' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/gdata.ops.demo%40gmail.com/private/full'>
</link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/gdata.ops.demo%40gmail.com'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:color value='#2952A3'></gCal:color>
<gCal:accesslevel value='owner'></gCal:accesslevel>
<gCal:hidden value='false'></gCal:hidden>
<gCal:timezone value='America/Los_Angeles'></gCal:timezone>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/jnh21ovnjgfph21h32gvms2758%40group.calendar.google.com</id>
<published>2007-03-20T22:48:57.837Z</published>
<updated>2007-03-20T22:48:53.000Z</updated>
<title type='text'>GData Ops Demo Secondary Calendar</title>
<summary type='text'></summary>
<link rel='alternate' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/jnh21ovnjgfph21h32gvms2758%40group.calendar.google.com/private/full'>
</link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/jnh21ovnjgfph21h32gvms2758%40group.calendar.google.com'>
</link>
<author>
<name>GData Ops Demo Secondary Calendar</name>
</author>
<gCal:color value='#528800'></gCal:color>
<gCal:accesslevel value='owner'></gCal:accesslevel>
<gCal:hidden value='false'></gCal:hidden>
<gCal:timezone value='America/Los_Angeles'></gCal:timezone>
<gd:where valueString=''></gd:where>
</entry>
</feed>
"""
CALENDAR_FULL_EVENT_FEED = """<?xml version='1.0' encoding='utf-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:gd='http://schemas.google.com/g/2005'
xmlns:gCal='http://schemas.google.com/gCal/2005'>
<id>
http://www.google.com/calendar/feeds/default/private/full</id>
<updated>2007-03-20T21:29:57.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>GData Ops Demo</title>
<subtitle type='text'>GData Ops Demo</subtitle>
<link rel='http://schemas.google.com/g/2005#feed'
type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full'>
</link>
<link rel='http://schemas.google.com/g/2005#post'
type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full'>
</link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full?updated-min=2001-01-01&max-results=25'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<generator version='1.0' uri='http://www.google.com/calendar'>
Google Calendar</generator>
<openSearch:totalResults>10</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<gCal:timezone value='America/Los_Angeles'></gCal:timezone>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/o99flmgmkfkfrr8u745ghr3100</id>
<published>2007-03-20T21:29:52.000Z</published>
<updated>2007-03-20T21:29:57.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>test deleted</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=bzk5ZmxtZ21rZmtmcnI4dTc0NWdocjMxMDAgZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/o99flmgmkfkfrr8u745ghr3100'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/o99flmgmkfkfrr8u745ghr3100/63310109397'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.canceled'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/o99flmgmkfkfrr8u745ghr3100/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:when startTime='2007-03-23T12:00:00.000-07:00'
endTime='2007-03-23T13:00:00.000-07:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/2qt3ao5hbaq7m9igr5ak9esjo0</id>
<published>2007-03-20T21:26:04.000Z</published>
<updated>2007-03-20T21:28:46.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>Afternoon at Dolores Park with Kim</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=MnF0M2FvNWhiYXE3bTlpZ3I1YWs5ZXNqbzAgZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/2qt3ao5hbaq7m9igr5ak9esjo0'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/2qt3ao5hbaq7m9igr5ak9esjo0/63310109326'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/2qt3ao5hbaq7m9igr5ak9esjo0/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.private'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:who rel='http://schemas.google.com/g/2005#event.organizer'
valueString='GData Ops Demo' email='gdata.ops.demo@gmail.com'>
<gd:attendeeStatus value='http://schemas.google.com/g/2005#event.accepted'>
</gd:attendeeStatus>
</gd:who>
<gd:who rel='http://schemas.google.com/g/2005#event.attendee'
valueString='Ryan Boyd (API)' email='api.rboyd@gmail.com'>
<gd:attendeeStatus value='http://schemas.google.com/g/2005#event.invited'>
</gd:attendeeStatus>
</gd:who>
<gd:when startTime='2007-03-24T12:00:00.000-07:00'
endTime='2007-03-24T15:00:00.000-07:00'>
<gd:reminder minutes='20'></gd:reminder>
</gd:when>
<gd:where valueString='Dolores Park with Kim'></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/uvsqhg7klnae40v50vihr1pvos</id>
<published>2007-03-20T21:28:37.000Z</published>
<updated>2007-03-20T21:28:37.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>Team meeting</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=dXZzcWhnN2tsbmFlNDB2NTB2aWhyMXB2b3NfMjAwNzAzMjNUMTYwMDAwWiBnZGF0YS5vcHMuZGVtb0Bt'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/uvsqhg7klnae40v50vihr1pvos'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/uvsqhg7klnae40v50vihr1pvos/63310109317'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gd:recurrence>DTSTART;TZID=America/Los_Angeles:20070323T090000
DTEND;TZID=America/Los_Angeles:20070323T100000
RRULE:FREQ=WEEKLY;BYDAY=FR;UNTIL=20070817T160000Z;WKST=SU
BEGIN:VTIMEZONE TZID:America/Los_Angeles
X-LIC-LOCATION:America/Los_Angeles BEGIN:STANDARD
TZOFFSETFROM:-0700 TZOFFSETTO:-0800 TZNAME:PST
DTSTART:19701025T020000 RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
END:STANDARD BEGIN:DAYLIGHT TZOFFSETFROM:-0800 TZOFFSETTO:-0700
TZNAME:PDT DTSTART:19700405T020000
RRULE:FREQ=YEARLY;BYMONTH=4;BYDAY=1SU END:DAYLIGHT
END:VTIMEZONE</gd:recurrence>
<gCal:sendEventNotifications value='true'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:visibility value='http://schemas.google.com/g/2005#event.public'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:reminder minutes='10'></gd:reminder>
<gd:where valueString=''></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/st4vk9kiffs6rasrl32e4a7alo</id>
<published>2007-03-20T21:25:46.000Z</published>
<updated>2007-03-20T21:25:46.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>Movie with Kim and danah</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=c3Q0dms5a2lmZnM2cmFzcmwzMmU0YTdhbG8gZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/st4vk9kiffs6rasrl32e4a7alo'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/st4vk9kiffs6rasrl32e4a7alo/63310109146'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/st4vk9kiffs6rasrl32e4a7alo/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:when startTime='2007-03-24T20:00:00.000-07:00'
endTime='2007-03-24T21:00:00.000-07:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/ofl1e45ubtsoh6gtu127cls2oo</id>
<published>2007-03-20T21:24:43.000Z</published>
<updated>2007-03-20T21:25:08.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>Dinner with Kim and Sarah</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=b2ZsMWU0NXVidHNvaDZndHUxMjdjbHMyb28gZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/ofl1e45ubtsoh6gtu127cls2oo'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/ofl1e45ubtsoh6gtu127cls2oo/63310109108'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/ofl1e45ubtsoh6gtu127cls2oo/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:when startTime='2007-03-20T19:00:00.000-07:00'
endTime='2007-03-20T21:30:00.000-07:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/b69s2avfi2joigsclecvjlc91g</id>
<published>2007-03-20T21:24:19.000Z</published>
<updated>2007-03-20T21:25:05.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>Dinner with Jane and John</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=YjY5czJhdmZpMmpvaWdzY2xlY3ZqbGM5MWcgZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/b69s2avfi2joigsclecvjlc91g'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/b69s2avfi2joigsclecvjlc91g/63310109105'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/b69s2avfi2joigsclecvjlc91g/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:when startTime='2007-03-22T17:00:00.000-07:00'
endTime='2007-03-22T19:30:00.000-07:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/u9p66kkiotn8bqh9k7j4rcnjjc</id>
<published>2007-03-20T21:24:33.000Z</published>
<updated>2007-03-20T21:24:33.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>Tennis with Elizabeth</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=dTlwNjZra2lvdG44YnFoOWs3ajRyY25qamMgZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/u9p66kkiotn8bqh9k7j4rcnjjc'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/u9p66kkiotn8bqh9k7j4rcnjjc/63310109073'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/u9p66kkiotn8bqh9k7j4rcnjjc/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:when startTime='2007-03-24T10:00:00.000-07:00'
endTime='2007-03-24T11:00:00.000-07:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/76oj2kceidob3s708tvfnuaq3c</id>
<published>2007-03-20T21:24:00.000Z</published>
<updated>2007-03-20T21:24:00.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>Lunch with Jenn</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=NzZvajJrY2VpZG9iM3M3MDh0dmZudWFxM2MgZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/76oj2kceidob3s708tvfnuaq3c'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/76oj2kceidob3s708tvfnuaq3c/63310109040'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/76oj2kceidob3s708tvfnuaq3c/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:when startTime='2007-03-20T11:30:00.000-07:00'
endTime='2007-03-20T12:30:00.000-07:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/5np9ec8m7uoauk1vedh5mhodco</id>
<published>2007-03-20T07:50:02.000Z</published>
<updated>2007-03-20T20:39:26.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>test entry</title>
<content type='text'>test desc</content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=NW5wOWVjOG03dW9hdWsxdmVkaDVtaG9kY28gZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/5np9ec8m7uoauk1vedh5mhodco'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/5np9ec8m7uoauk1vedh5mhodco/63310106366'>
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/5np9ec8m7uoauk1vedh5mhodco/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.private'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:who rel='http://schemas.google.com/g/2005#event.attendee'
valueString='Vivian Li' email='vli@google.com'>
<gd:attendeeStatus value='http://schemas.google.com/g/2005#event.declined'>
</gd:attendeeStatus>
</gd:who>
<gd:who rel='http://schemas.google.com/g/2005#event.organizer'
valueString='GData Ops Demo' email='gdata.ops.demo@gmail.com'>
<gd:attendeeStatus value='http://schemas.google.com/g/2005#event.accepted'>
</gd:attendeeStatus>
</gd:who>
<gd:when startTime='2007-03-21T08:00:00.000-07:00'
endTime='2007-03-21T09:00:00.000-07:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where valueString='anywhere'></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/fu6sl0rqakf3o0a13oo1i1a1mg</id>
<published>2007-02-14T23:23:37.000Z</published>
<updated>2007-02-14T23:25:30.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>test</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=ZnU2c2wwcnFha2YzbzBhMTNvbzFpMWExbWcgZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/fu6sl0rqakf3o0a13oo1i1a1mg'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/fu6sl0rqakf3o0a13oo1i1a1mg/63307178730'>
</link>
<link rel="http://schemas.google.com/gCal/2005/webContent" title="World Cup" href="http://www.google.com/calendar/images/google-holiday.gif" type="image/gif">
<gCal:webContent width="276" height="120" url="http://www.google.com/logos/worldcup06.gif" />
</link>
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/fu6sl0rqakf3o0a13oo1i1a1mg/comments'>
</gd:feedLink>
</gd:comments>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:when startTime='2007-02-15T08:30:00.000-08:00'
endTime='2007-02-15T09:30:00.000-08:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where></gd:where>
</entry>
<entry>
<id>
http://www.google.com/calendar/feeds/default/private/full/h7a0haa4da8sil3rr19ia6luvc</id>
<published>2007-07-16T22:13:28.000Z</published>
<updated>2007-07-16T22:13:29.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event' />
<title type='text'></title>
<content type='text' />
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=aDdhMGhhYTRkYThzaWwzcnIxOWlhNmx1dmMgZ2RhdGEub3BzLmRlbW9AbQ'
title='alternate' />
<link rel='http://schemas.google.com/gCal/2005/webContent'
type='application/x-google-gadgets+xml'
href='http://gdata.ops.demo.googlepages.com/birthdayicon.gif'
title='Date and Time Gadget'>
<gCal:webContent width='300' height='136'
url='http://google.com/ig/modules/datetime.xml'>
<gCal:webContentGadgetPref name='color' value='green' />
</gCal:webContent>
</link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/h7a0haa4da8sil3rr19ia6luvc' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/h7a0haa4da8sil3rr19ia6luvc/63320307209' />
<author>
<name>GData Ops Demo</name>
<email>gdata.ops.demo@gmail.com</email>
</author>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/h7a0haa4da8sil3rr19ia6luvc/comments' />
</gd:comments>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed' />
<gd:visibility value='http://schemas.google.com/g/2005#event.default' />
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque' />
<gd:when startTime='2007-03-14' endTime='2007-03-15' />
<gd:where />
</entry>
</feed>
"""
CALENDAR_BATCH_REQUEST = """<?xml version='1.0' encoding='utf-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:batch='http://schemas.google.com/gdata/batch'
xmlns:gCal='http://schemas.google.com/gCal/2005'>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<entry>
<batch:id>1</batch:id>
<batch:operation type='insert' />
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<title type='text'>Event inserted via batch</title>
</entry>
<entry>
<batch:id>2</batch:id>
<batch:operation type='query' />
<id>http://www.google.com/calendar/feeds/default/private/full/glcs0kv2qqa0gf52qi1jo018gc</id>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<title type='text'>Event queried via batch</title>
</entry>
<entry>
<batch:id>3</batch:id>
<batch:operation type='update' />
<id>http://www.google.com/calendar/feeds/default/private/full/ujm0go5dtngdkr6u91dcqvj0qs</id>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<title type='text'>Event updated via batch</title>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=dWptMGdvNWR0bmdka3I2dTkxZGNxdmowcXMgaGFyaXNodi50ZXN0QG0' title='alternate' />
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/ujm0go5dtngdkr6u91dcqvj0qs' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/ujm0go5dtngdkr6u91dcqvj0qs/63326098791' />
</entry>
<entry>
<batch:id>4</batch:id>
<batch:operation type='delete' />
<id>http://www.google.com/calendar/feeds/default/private/full/d8qbg9egk1n6lhsgq1sjbqffqc</id>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<title type='text'>Event deleted via batch</title>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=ZDhxYmc5ZWdrMW42bGhzZ3Exc2picWZmcWMgaGFyaXNodi50ZXN0QG0' title='alternate' />
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/d8qbg9egk1n6lhsgq1sjbqffqc' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/d8qbg9egk1n6lhsgq1sjbqffqc/63326018324' />
</entry>
</feed>
"""
CALENDAR_BATCH_RESPONSE = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:batch='http://schemas.google.com/gdata/batch'
xmlns:gCal='http://schemas.google.com/gCal/2005'>
<id>http://www.google.com/calendar/feeds/default/private/full</id>
<updated>2007-09-21T23:01:00.380Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>Batch Feed</title>
<link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full' />
<link rel='http://schemas.google.com/g/2005#post' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full' />
<link rel='http://schemas.google.com/g/2005#batch' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/batch' />
<entry>
<batch:id>1</batch:id>
<batch:status code='201' reason='Created' />
<batch:operation type='insert' />
<id>http://www.google.com/calendar/feeds/default/private/full/n9ug78gd9tv53ppn4hdjvk68ek</id>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<title type='text'>Event inserted via batch</title>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=bjl1Zzc4Z2Q5dHY1M3BwbjRoZGp2azY4ZWsgaGFyaXNodi50ZXN0QG0' title='alternate' />
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/n9ug78gd9tv53ppn4hdjvk68ek' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/n9ug78gd9tv53ppn4hdjvk68ek/63326098860' />
</entry>
<entry>
<batch:id>2</batch:id>
<batch:status code='200' reason='Success' />
<batch:operation type='query' />
<id>http://www.google.com/calendar/feeds/default/private/full/glsc0kv2aqa0ff52qi1jo018gc</id>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<title type='text'>Event queried via batch</title>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=Z2xzYzBrdjJhcWEwZmY1MnFpMWpvMDE4Z2MgaGFyaXNodi50ZXN0QG0' title='alternate' />
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/glsc0kv2aqa0ff52qi1jo018gc' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/glsc0kv2aqa0ff52qi1jo018gc/63326098791' />
</entry>
<entry xmlns:gCal='http://schemas.google.com/gCal/2005'>
<batch:id>3</batch:id>
<batch:status code='200' reason='Success' />
<batch:operation type='update' />
<id>http://www.google.com/calendar/feeds/default/private/full/ujm0go5dtngdkr6u91dcqvj0qs</id>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<title type='text'>Event updated via batch</title>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=dWptMGdvNWR0bmdka3I2dTkxZGNxdmowcXMgaGFyaXNodi50ZXN0QG0' title='alternate' />
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/ujm0go5dtngdkr6u91dcqvj0qs' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/full/ujm0go5dtngdkr6u91dcqvj0qs/63326098860' />
<batch:id>3</batch:id>
<batch:status code='200' reason='Success' />
<batch:operation type='update' />
</entry>
<entry>
<batch:id>4</batch:id>
<batch:status code='200' reason='Success' />
<batch:operation type='delete' />
<id>http://www.google.com/calendar/feeds/default/private/full/d8qbg9egk1n6lhsgq1sjbqffqc</id>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event' />
<title type='text'>Event deleted via batch</title>
<content type='text'>Deleted</content>
</entry>
</feed>
"""
GBASE_ATTRIBUTE_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gm='http://base.google.com/ns-metadata/1.0'>
<id>http://www.google.com/base/feeds/attributes</id>
<updated>2006-11-01T20:35:59.578Z</updated>
<category scheme='http://base.google.com/categories/itemtypes' term='online jobs'></category>
<category scheme='http://base.google.com/categories/itemtypes' term='jobs'></category>
<title type='text'>Attribute histogram for query: [item type:jobs]</title>
<link rel='alternate' type='text/html' href='http://base.google.com'></link>
<link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://www.google.com/base/feeds
/attributes'></link>
<link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/attributes/-/jobs'></link>
<generator version='1.0' uri='http://base.google.com'>GoogleBase</generator>
<openSearch:totalResults>16</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>16</openSearch:itemsPerPage>
<entry>
<id>http://www.google.com/base/feeds/attributes/job+industry%28text%29N%5Bitem+type%3Ajobs%5D</id>
<updated>2006-11-01T20:36:00.100Z</updated>
<title type='text'>job industry(text)</title>
<content type='text'>Attribute"job industry" of type text.
</content>
<link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/attributes/job+industry%28text
%29N%5Bitem+type%3Ajobs%5D'></link>
<gm:attribute name='job industry' type='text' count='4416629'>
<gm:value count='380772'>it internet</gm:value>
<gm:value count='261565'>healthcare</gm:value>
<gm:value count='142018'>information technology</gm:value>
<gm:value count='124622'>accounting</gm:value>
<gm:value count='111311'>clerical and administrative</gm:value>
<gm:value count='82928'>other</gm:value>
<gm:value count='77620'>sales and sales management</gm:value>
<gm:value count='68764'>information systems</gm:value>
<gm:value count='65859'>engineering and architecture</gm:value>
<gm:value count='64757'>sales</gm:value>
</gm:attribute>
</entry>
</feed>
"""
GBASE_ATTRIBUTE_ENTRY = """<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gm='http://base.google.com/ns-metadata/1.0'>
<id>http://www.google.com/base/feeds/attributes/job+industry%28text%29N%5Bitem+type%3Ajobs%5D</id>
<updated>2006-11-01T20:36:00.100Z</updated>
<title type='text'>job industry(text)</title>
<content type='text'>Attribute"job industry" of type text.
</content>
<link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/attributes/job+industry%28text%29N%5Bitem+type%3Ajobs%5D'></link>
<gm:attribute name='job industry' type='text' count='4416629'>
<gm:value count='380772'>it internet</gm:value>
<gm:value count='261565'>healthcare</gm:value>
<gm:value count='142018'>information technology</gm:value>
<gm:value count='124622'>accounting</gm:value>
<gm:value count='111311'>clerical and administrative</gm:value>
<gm:value count='82928'>other</gm:value>
<gm:value count='77620'>sales and sales management</gm:value>
<gm:value count='68764'>information systems</gm:value>
<gm:value count='65859'>engineering and architecture</gm:value>
<gm:value count='64757'>sales</gm:value>
</gm:attribute>
</entry>
"""
GBASE_LOCALES_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:gm='http://base.google.com/ns-metadata/1.0'>
<id> http://www.google.com/base/feeds/locales/</id>
<updated>2006-06-13T18:11:40.120Z</updated>
<title type="text">Locales</title>
<link rel="alternate" type="text/html" href="http://base.google.com"/>
<link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"
href="http://www.google.com/base/feeds/locales/"/>
<link rel="self" type="application/atom+xml" href="http://www.google.com/base/feeds/locales/"/>
<author>
<name>Google Inc.</name>
<email>base@google.com</email>
</author>
<generator version="1.0" uri="http://base.google.com">GoogleBase</generator>
<openSearch:totalResults>3</openSearch:totalResults>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>http://www.google.com/base/feeds/locales/en_US</id>
<updated>2006-03-27T22:27:36.658Z</updated>
<category scheme="http://base.google.com/categories/locales" term="en_US"/>
<title type="text">en_US</title>
<content type="text">en_US</content>
<link rel="self" type="application/atom+xml"
href="http://www.google.com/base/feeds/locales/en_US"></link>
<link rel="related" type="application/atom+xml"
href="http://www.google.com/base/feeds/itemtypes/en_US" title="Item types in en_US"/>
</entry>
<entry>
<id>http://www.google.com/base/feeds/locales/en_GB</id>
<updated>2006-06-13T18:14:18.601Z</updated>
<category scheme="http://base.google.com/categories/locales" term="en_GB"/>
<title type="text">en_GB</title>
<content type="text">en_GB</content>
<link rel="related" type="application/atom+xml"
href="http://www.google.com/base/feeds/itemtypes/en_GB" title="Item types in en_GB"/>
<link rel="self" type="application/atom+xml"
href="http://www.google.com/base/feeds/locales/en_GB"/>
</entry>
<entry>
<id>http://www.google.com/base/feeds/locales/de_DE</id>
<updated>2006-06-13T18:14:18.601Z</updated>
<category scheme="http://base.google.com/categories/locales" term="de_DE"/>
<title type="text">de_DE</title>
<content type="text">de_DE</content>
<link rel="related" type="application/atom+xml"
href="http://www.google.com/base/feeds/itemtypes/de_DE" title="Item types in de_DE"/>
<link rel="self" type="application/atom+xml"
href="http://www.google.com/base/feeds/locales/de_DE"/>
</entry>
</feed>"""
GBASE_STRING_ENCODING_ENTRY = """<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns='http://www.w3.org/2005/Atom' xmlns:gm='http://base.google.com/ns-metadata/1.0'
xmlns:g='http://base.google.com/ns/1.0' xmlns:batch='http://schemas.google.com/gdata/batch'>
<id>http://www.google.com/base/feeds/snippets/17495780256183230088</id>
<published>2007-12-09T03:13:07.000Z</published>
<updated>2008-01-07T03:26:46.000Z</updated>
<category scheme='http://base.google.com/categories/itemtypes' term='Products'/>
<title type='text'>Digital Camera Cord Fits SONY Cybershot DSC-R1 S40</title>
<content type='html'>SONY \xC2\xB7 Cybershot Digital Camera Usb Cable DESCRIPTION
This is a 2.5 USB 2.0 A to Mini B (5 Pin) high quality digital camera
cable used for connecting your Sony Digital Cameras and Camcoders. Backward
Compatible with USB 2.0, 1.0 and 1.1. Fully ...</content>
<link rel='alternate' type='text/html'
href='http://adfarm.mediaplex.com/ad/ck/711-5256-8196-2?loc=http%3A%2F%2Fcgi.ebay.com%2FDigital-Camera-Cord-Fits-SONY-Cybershot-DSC-R1-S40_W0QQitemZ270195049057QQcmdZViewItem'/>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/base/feeds/snippets/17495780256183230088'/>
<author>
<name>eBay</name>
</author>
<g:item_type type='text'>Products</g:item_type>
<g:item_language type='text'>EN</g:item_language>
<g:target_country type='text'>US</g:target_country>
<g:price type='floatUnit'>0.99 usd</g:price>
<g:image_link type='url'>http://thumbs.ebaystatic.com/pict/270195049057_1.jpg</g:image_link>
<g:category type='text'>Cameras & Photo>Digital Camera Accessories>Cables</g:category>
<g:category type='text'>Cords & Connectors>USB Cables>For Other Brands</g:category>
<g:customer_id type='int'>11729</g:customer_id>
<g:id type='text'>270195049057</g:id>
<g:expiration_date type='dateTime'>2008-02-06T03:26:46Z</g:expiration_date>
</entry>"""
RECURRENCE_EXCEPTION_ENTRY = """<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:gd='http://schemas.google.com/g/2005'
xmlns:gCal='http://schemas.google.com/gCal/2005'>
<id>
http://www.google.com/calendar/feeds/default/private/composite/i7lgfj69mjqjgnodklif3vbm7g</id>
<published>2007-04-05T21:51:49.000Z</published>
<updated>2007-04-05T21:51:49.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>testDavid</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=aTdsZ2ZqNjltanFqZ25vZGtsaWYzdmJtN2dfMjAwNzA0MDNUMTgwMDAwWiBnZGF0YS5vcHMudGVzdEBt'
title='alternate'></link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/default/private/composite/i7lgfj69mjqjgnodklif3vbm7g'>
</link>
<author>
<name>gdata ops</name>
<email>gdata.ops.test@gmail.com</email>
</author>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gCal:sendEventNotifications value='true'>
</gCal:sendEventNotifications>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'>
</gd:eventStatus>
<gd:recurrence>DTSTART;TZID=America/Anchorage:20070403T100000
DTEND;TZID=America/Anchorage:20070403T110000
RRULE:FREQ=DAILY;UNTIL=20070408T180000Z;WKST=SU
EXDATE;TZID=America/Anchorage:20070407T100000
EXDATE;TZID=America/Anchorage:20070405T100000
EXDATE;TZID=America/Anchorage:20070404T100000 BEGIN:VTIMEZONE
TZID:America/Anchorage X-LIC-LOCATION:America/Anchorage
BEGIN:STANDARD TZOFFSETFROM:-0800 TZOFFSETTO:-0900 TZNAME:AKST
DTSTART:19701025T020000 RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
END:STANDARD BEGIN:DAYLIGHT TZOFFSETFROM:-0900 TZOFFSETTO:-0800
TZNAME:AKDT DTSTART:19700405T020000
RRULE:FREQ=YEARLY;BYMONTH=4;BYDAY=1SU END:DAYLIGHT
END:VTIMEZONE</gd:recurrence>
<gd:where valueString=''></gd:where>
<gd:reminder minutes='10'></gd:reminder>
<gd:recurrenceException specialized='true'>
<gd:entryLink>
<entry>
<id>i7lgfj69mjqjgnodklif3vbm7g_20070407T180000Z</id>
<published>2007-04-05T21:51:49.000Z</published>
<updated>2007-04-05T21:52:58.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#event'></category>
<title type='text'>testDavid</title>
<content type='text'></content>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/event?eid=aTdsZ2ZqNjltanFqZ25vZGtsaWYzdmJtN2dfMjAwNzA0MDdUMTgwMDAwWiBnZGF0YS5vcHMudGVzdEBt'
title='alternate'></link>
<author>
<name>gdata ops</name>
<email>gdata.ops.test@gmail.com</email>
</author>
<gd:visibility value='http://schemas.google.com/g/2005#event.default'>
</gd:visibility>
<gd:originalEvent id='i7lgfj69mjqjgnodklif3vbm7g'
href='http://www.google.com/calendar/feeds/default/private/composite/i7lgfj69mjqjgnodklif3vbm7g'>
<gd:when startTime='2007-04-07T13:00:00.000-05:00'>
</gd:when>
</gd:originalEvent>
<gCal:sendEventNotifications value='false'>
</gCal:sendEventNotifications>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'>
</gd:transparency>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.canceled'>
</gd:eventStatus>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/default/private/full/i7lgfj69mjqjgnodklif3vbm7g_20070407T180000Z/comments'>
<feed>
<updated>2007-04-05T21:54:09.285Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/g/2005#message'>
</category>
<title type='text'>Comments for: testDavid</title>
<link rel='alternate' type='text/html'
href='http://www.google.com/calendar/feeds/default/private/full/i7lgfj69mjqjgnodklif3vbm7g_20070407T180000Z/comments'
title='alternate'></link>
</feed>
</gd:feedLink>
</gd:comments>
<gd:when startTime='2007-04-07T13:00:00.000-05:00'
endTime='2007-04-07T14:00:00.000-05:00'>
<gd:reminder minutes='10'></gd:reminder>
</gd:when>
<gd:where valueString=''></gd:where>
</entry>
</gd:entryLink>
</gd:recurrenceException>
</entry>"""
NICK_ENTRY = """<?xml version="1.0" encoding="UTF-8"?>
<atom:entry xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:apps="http://schemas.google.com/apps/2006"
xmlns:gd="http://schemas.google.com/g/2005">
<atom:id>https://www.google.com/a/feeds/example.com/nickname/2.0/Foo</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#nickname'/>
<atom:title type="text">Foo</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="https://www.google.com/a/feeds/example.com/nickname/2.0/Foo"/>
<atom:link rel="edit" type="application/atom+xml"
href="https://www.google.com/a/feeds/example.com/nickname/2.0/Foo"/>
<apps:nickname name="Foo"/>
<apps:login userName="TestUser"/>
</atom:entry>"""
NICK_FEED = """<?xml version="1.0" encoding="UTF-8"?>
<atom:feed xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:apps="http://schemas.google.com/apps/2006">
<atom:id>
http://www.google.com/a/feeds/example.com/nickname/2.0
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#nickname'/>
<atom:title type="text">Nicknames for user SusanJones</atom:title>
<atom:link rel='http://schemas.google.com/g/2005#feed'
type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/nickname/2.0"/>
<atom:link rel='http://schemas.google.com/g/2005#post'
type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/nickname/2.0"/>
<atom:link rel="self" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/nickname/2.0?username=TestUser"/>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>2</openSearch:itemsPerPage>
<atom:entry>
<atom:id>
http://www.google.com/a/feeds/example.com/nickname/2.0/Foo
</atom:id>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#nickname'/>
<atom:title type="text">Foo</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/nickname/2.0/Foo"/>
<atom:link rel="edit" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/nickname/2.0/Foo"/>
<apps:nickname name="Foo"/>
<apps:login userName="TestUser"/>
</atom:entry>
<atom:entry>
<atom:id>
http://www.google.com/a/feeds/example.com/nickname/2.0/suse
</atom:id>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#nickname'/>
<atom:title type="text">suse</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/nickname/2.0/Bar"/>
<atom:link rel="edit" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/nickname/2.0/Bar"/>
<apps:nickname name="Bar"/>
<apps:login userName="TestUser"/>
</atom:entry>
</atom:feed>"""
USER_ENTRY = """<?xml version="1.0" encoding="UTF-8"?>
<atom:entry xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:apps="http://schemas.google.com/apps/2006"
xmlns:gd="http://schemas.google.com/g/2005">
<atom:id>https://www.google.com/a/feeds/example.com/user/2.0/TestUser</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#user'/>
<atom:title type="text">TestUser</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="https://www.google.com/a/feeds/example.com/user/2.0/TestUser"/>
<atom:link rel="edit" type="application/atom+xml"
href="https://www.google.com/a/feeds/example.com/user/2.0/TestUser"/>
<apps:login userName="TestUser" password="password" suspended="false"
ipWhitelisted='false' hashFunctionName="SHA-1"/>
<apps:name familyName="Test" givenName="User"/>
<apps:quota limit="1024"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#user.nicknames'
href="https://www.google.com/a/feeds/example.com/nickname/2.0?username=Test-3121"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#user.emailLists'
href="https://www.google.com/a/feeds/example.com/emailList/2.0?recipient=testlist@example.com"/>
</atom:entry>"""
USER_FEED = """<?xml version="1.0" encoding="UTF-8"?>
<atom:feed xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:apps="http://schemas.google.com/apps/2006"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:gd="http://schemas.google.com/g/2005">
<atom:id>
http://www.google.com/a/feeds/example.com/user/2.0
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#user'/>
<atom:title type="text">Users</atom:title>
<atom:link rel="next" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/user/2.0?startUsername=john"/>
<atom:link rel='http://schemas.google.com/g/2005#feed'
type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/user/2.0"/>
<atom:link rel='http://schemas.google.com/g/2005#post'
type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/user/2.0"/>
<atom:link rel="self" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/user/2.0"/>
<openSearch:startIndex>1</openSearch:startIndex>
<atom:entry>
<atom:id>
http://www.google.com/a/feeds/example.com/user/2.0/TestUser
</atom:id>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#user'/>
<atom:title type="text">TestUser</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/user/2.0/TestUser"/>
<atom:link rel="edit" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/user/2.0/TestUser"/>
<gd:who rel='http://schemas.google.com/apps/2006#user.recipient'
email="TestUser@example.com"/>
<apps:login userName="TestUser" suspended="false"/>
<apps:quota limit="2048"/>
<apps:name familyName="Test" givenName="User"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#user.nicknames'
href="http://www.google.com/a/feeds/example.com/nickname/2.0?username=TestUser"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#user.emailLists'
href="http://www.google.com/a/feeds/example.com/emailList/2.0?recipient=TestUser@example.com"/>
</atom:entry>
<atom:entry>
<atom:id>
http://www.google.com/a/feeds/example.com/user/2.0/JohnSmith
</atom:id>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#user'/>
<atom:title type="text">JohnSmith</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/user/2.0/JohnSmith"/>
<atom:link rel="edit" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/user/2.0/JohnSmith"/>
<gd:who rel='http://schemas.google.com/apps/2006#user.recipient'
email="JohnSmith@example.com"/>
<apps:login userName="JohnSmith" suspended="false"/>
<apps:quota limit="2048"/>
<apps:name familyName="Smith" givenName="John"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#user.nicknames'
href="http://www.google.com/a/feeds/example.com/nickname/2.0?username=JohnSmith"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#user.emailLists'
href="http://www.google.com/a/feeds/example.com/emailList/2.0?recipient=JohnSmith@example.com"/>
</atom:entry>
</atom:feed>"""
EMAIL_LIST_ENTRY = """<?xml version="1.0" encoding="UTF-8"?>
<atom:entry xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:apps="http://schemas.google.com/apps/2006"
xmlns:gd="http://schemas.google.com/g/2005">
<atom:id>
https://www.google.com/a/feeds/example.com/emailList/2.0/testlist
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#emailList'/>
<atom:title type="text">testlist</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="https://www.google.com/a/feeds/example.com/emailList/2.0/testlist"/>
<atom:link rel="edit" type="application/atom+xml"
href="https://www.google.com/a/feeds/example.com/emailList/2.0/testlist"/>
<apps:emailList name="testlist"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#emailList.recipients'
href="http://www.google.com/a/feeds/example.com/emailList/2.0/testlist/recipient/"/>
</atom:entry>"""
EMAIL_LIST_FEED = """<?xml version="1.0" encoding="UTF-8"?>
<atom:feed xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:apps="http://schemas.google.com/apps/2006"
xmlns:gd="http://schemas.google.com/g/2005">
<atom:id>
http://www.google.com/a/feeds/example.com/emailList/2.0
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#emailList'/>
<atom:title type="text">EmailLists</atom:title>
<atom:link rel="next" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0?startEmailListName=john"/>
<atom:link rel='http://schemas.google.com/g/2005#feed'
type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0"/>
<atom:link rel='http://schemas.google.com/g/2005#post'
type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0"/>
<atom:link rel="self" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0"/>
<openSearch:startIndex>1</openSearch:startIndex>
<atom:entry>
<atom:id>
http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#emailList'/>
<atom:title type="text">us-sales</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales"/>
<atom:link rel="edit" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales"/>
<apps:emailList name="us-sales"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#emailList.recipients'
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/"/>
</atom:entry>
<atom:entry>
<atom:id>
http://www.google.com/a/feeds/example.com/emailList/2.0/us-eng
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#emailList'/>
<atom:title type="text">us-eng</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-eng"/>
<atom:link rel="edit" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-eng"/>
<apps:emailList name="us-eng"/>
<gd:feedLink rel='http://schemas.google.com/apps/2006#emailList.recipients'
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-eng/recipient/"/>
</atom:entry>
</atom:feed>"""
EMAIL_LIST_RECIPIENT_ENTRY = """<?xml version="1.0" encoding="UTF-8"?>
<atom:entry xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:apps="http://schemas.google.com/apps/2006"
xmlns:gd="http://schemas.google.com/g/2005">
<atom:id>https://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/TestUser%40example.com</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#emailList.recipient'/>
<atom:title type="text">TestUser</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="https://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/TestUser%40example.com"/>
<atom:link rel="edit" type="application/atom+xml"
href="https://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/TestUser%40example.com"/>
<gd:who email="TestUser@example.com"/>
</atom:entry>"""
EMAIL_LIST_RECIPIENT_FEED = """<?xml version="1.0" encoding="UTF-8"?>
<atom:feed xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:gd="http://schemas.google.com/g/2005">
<atom:id>
http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#emailList.recipient'/>
<atom:title type="text">Recipients for email list us-sales</atom:title>
<atom:link rel="next" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/?startRecipient=terry@example.com"/>
<atom:link rel='http://schemas.google.com/g/2005#feed'
type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient"/>
<atom:link rel='http://schemas.google.com/g/2005#post'
type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient"/>
<atom:link rel="self" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient"/>
<openSearch:startIndex>1</openSearch:startIndex>
<atom:entry>
<atom:id>
http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/joe%40example.com
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#emailList.recipient'/>
<atom:title type="text">joe@example.com</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/joe%40example.com"/>
<atom:link rel="edit" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/joe%40example.com"/>
<gd:who email="joe@example.com"/>
</atom:entry>
<atom:entry>
<atom:id>
http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/susan%40example.com
</atom:id>
<atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
<atom:category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/apps/2006#emailList.recipient'/>
<atom:title type="text">susan@example.com</atom:title>
<atom:link rel="self" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/susan%40example.com"/>
<atom:link rel="edit" type="application/atom+xml"
href="http://www.google.com/a/feeds/example.com/emailList/2.0/us-sales/recipient/susan%40example.com"/>
<gd:who email="susan@example.com"/>
</atom:entry>
</atom:feed>"""
ACL_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:gAcl='http://schemas.google.com/acl/2007'>
<id>http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full</id>
<updated>2007-04-21T00:52:04.000Z</updated>
<title type='text'>Elizabeth Bennet's access control list</title>
<link rel='http://schemas.google.com/acl/2007#controlledObject'
type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/private/full'>
</link>
<link rel='http://schemas.google.com/g/2005#feed'
type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full'>
</link>
<link rel='http://schemas.google.com/g/2005#post'
type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full'>
</link>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full'>
</link>
<generator version='1.0'
uri='http://www.google.com/calendar'>Google Calendar</generator>
<openSearch:totalResults>2</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<entry>
<id>http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/user%3Aliz%40gmail.com</id>
<updated>2007-04-21T00:52:04.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/acl/2007#accessRule'>
</category>
<title type='text'>owner</title>
<content type='text'></content>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/user%3Aliz%40gmail.com'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/user%3Aliz%40gmail.com'>
</link>
<author>
<name>Elizabeth Bennet</name>
<email>liz@gmail.com</email>
</author>
<gAcl:scope type='user' value='liz@gmail.com'></gAcl:scope>
<gAcl:role value='http://schemas.google.com/gCal/2005#owner'>
</gAcl:role>
</entry>
<entry>
<id>http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/default</id>
<updated>2007-04-21T00:52:04.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/acl/2007#accessRule'>
</category>
<title type='text'>read</title>
<content type='text'></content>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/default'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/default'>
</link>
<author>
<name>Elizabeth Bennet</name>
<email>liz@gmail.com</email>
</author>
<gAcl:scope type='default'></gAcl:scope>
<gAcl:role value='http://schemas.google.com/gCal/2005#read'>
</gAcl:role>
</entry>
</feed>"""
ACL_ENTRY = """<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gd='http://schemas.google.com/g/2005' xmlns:gCal='http://schemas.google.com/gCal/2005' xmlns:gAcl='http://schemas.google.com/acl/2007'>
<id>http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/user%3Aliz%40gmail.com</id>
<updated>2007-04-21T00:52:04.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/acl/2007#accessRule'>
</category>
<title type='text'>owner</title>
<content type='text'></content>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/user%3Aliz%40gmail.com'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/user%3Aliz%40gmail.com'>
</link>
<author>
<name>Elizabeth Bennet</name>
<email>liz@gmail.com</email>
</author>
<gAcl:scope type='user' value='liz@gmail.com'></gAcl:scope>
<gAcl:role value='http://schemas.google.com/gCal/2005#owner'>
</gAcl:role>
</entry>"""
DOCUMENT_LIST_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<ns0:feed xmlns:ns0="http://www.w3.org/2005/Atom"><ns1:totalResults
xmlns:ns1="http://a9.com/-/spec/opensearchrss/1.0/">2</ns1:totalResults><ns1:startIndex
xmlns:ns1="http://a9.com/-/spec/opensearchrss/1.0/">1</ns1:startIndex><ns0:entry><ns0:content
src="http://foo.com/fm?fmcmd=102&key=supercalifragilisticexpeadocious"
type="text/html"
/><ns0:author><ns0:name>test.user</ns0:name><ns0:email>test.user@gmail.com</ns0:email></ns0:author><ns0:category
label="spreadsheet" scheme="http://schemas.google.com/g/2005#kind"
term="http://schemas.google.com/docs/2007#spreadsheet"
/><ns0:id>http://docs.google.com/feeds/documents/private/full/spreadsheet%3Asupercalifragilisticexpeadocious</ns0:id><ns0:link
href="http://foo.com/ccc?key=supercalifragilisticexpeadocious" rel="alternate"
type="text/html" /><ns0:link
href="http://foo.com/feeds/worksheets/supercalifragilisticexpeadocious/private/full"
rel="http://schemas.google.com/spreadsheets/2006#worksheetsfeed"
type="application/atom+xml" /><ns0:link
href="http://docs.google.com/feeds/documents/private/full/spreadsheet%3Asupercalifragilisticexpeadocious"
rel="self" type="application/atom+xml" /><ns0:title type="text">Test Spreadsheet</ns0:title><ns0:updated>2007-07-03T18:03:32.045Z</ns0:updated></ns0:entry><ns0:entry><ns0:content
src="http://docs.google.com/RawDocContents?action=fetch&docID=gr00vy"
type="text/html"
/><ns0:author><ns0:name>test.user</ns0:name><ns0:email>test.user@gmail.com</ns0:email></ns0:author><ns0:category
label="document" scheme="http://schemas.google.com/g/2005#kind"
term="http://schemas.google.com/docs/2007#document"
/><ns0:id>http://docs.google.com/feeds/documents/private/full/document%3Agr00vy</ns0:id><ns0:link
href="http://foobar.com/Doc?id=gr00vy" rel="alternate" type="text/html"
/><ns0:link
href="http://docs.google.com/feeds/documents/private/full/document%3Agr00vy"
rel="self" type="application/atom+xml" /><ns0:title type="text">Test Document</ns0:title><ns0:updated>2007-07-03T18:02:50.338Z</ns0:updated></ns0:entry><ns0:id>http://docs.google.com/feeds/documents/private/full</ns0:id><ns0:link
href="http://docs.google.com" rel="alternate" type="text/html" /><ns0:link
href="http://docs.google.com/feeds/documents/private/full"
rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"
/><ns0:link href="http://docs.google.com/feeds/documents/private/full"
rel="http://schemas.google.com/g/2005#post" type="application/atom+xml"
/><ns0:link href="http://docs.google.com/feeds/documents/private/full"
rel="self" type="application/atom+xml" /><ns0:title type="text">Available
Documents -
test.user@gmail.com</ns0:title><ns0:updated>2007-07-09T23:07:21.898Z</ns0:updated></ns0:feed>
"""
DOCUMENT_LIST_ENTRY = """<?xml version='1.0' encoding='UTF-8'?>
<ns0:entry xmlns:ns0="http://www.w3.org/2005/Atom"><ns0:content
src="http://foo.com/fm?fmcmd=102&key=supercalifragilisticexpealidocious"
type="text/html"
/><ns0:author><ns0:name>test.user</ns0:name><ns0:email>test.user@gmail.com</ns0:email></ns0:author><ns0:category
label="spreadsheet" scheme="http://schemas.google.com/g/2005#kind"
term="http://schemas.google.com/docs/2007#spreadsheet"
/><ns0:id>http://docs.google.com/feeds/documents/private/full/spreadsheet%3Asupercalifragilisticexpealidocious</ns0:id><ns0:link
href="http://foo.com/ccc?key=supercalifragilisticexpealidocious"
rel="alternate" type="text/html" /><ns0:link
href="http://foo.com/feeds/worksheets/supercalifragilisticexpealidocious/private/full"
rel="http://schemas.google.com/spreadsheets/2006#worksheetsfeed"
type="application/atom+xml" /><ns0:link
href="http://docs.google.com/feeds/documents/private/full/spreadsheet%3Asupercalifragilisticexpealidocious"
rel="self" type="application/atom+xml" /><ns0:title type="text">Test Spreadsheet</ns0:title><ns0:updated>2007-07-03T18:03:32.045Z</ns0:updated></ns0:entry>
"""
BATCH_ENTRY = """<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:batch="http://schemas.google.com/gdata/batch"
xmlns:g="http://base.google.com/ns/1.0">
<id>http://www.google.com/base/feeds/items/2173859253842813008</id>
<published>2006-07-11T14:51:43.560Z</published>
<updated>2006-07-11T14:51: 43.560Z</updated>
<title type="text">title</title>
<content type="html">content</content>
<link rel="self"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items/2173859253842813008"/>
<link rel="edit"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items/2173859253842813008"/>
<g:item_type>recipes</g:item_type>
<batch:operation type="insert"/>
<batch:id>itemB</batch:id>
<batch:status code="201" reason="Created"/>
</entry>"""
BATCH_FEED_REQUEST = """<?xml version="1.0" encoding="UTF-8"?>
<feed
xmlns="http://www.w3.org/2005/Atom"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:g="http://base.google.com/ns/1.0"
xmlns:batch="http://schemas.google.com/gdata/batch">
<title type="text">My Batch Feed</title>
<entry>
<id>http://www.google.com/base/feeds/items/13308004346459454600</id>
<batch:operation type="delete"/>
</entry>
<entry>
<id>http://www.google.com/base/feeds/items/17437536661927313949</id>
<batch:operation type="delete"/>
</entry>
<entry>
<title type="text">...</title>
<content type="html">...</content>
<batch:id>itemA</batch:id>
<batch:operation type="insert"/>
<g:item_type>recipes</g:item_type>
</entry>
<entry>
<title type="text">...</title>
<content type="html">...</content>
<batch:id>itemB</batch:id>
<batch:operation type="insert"/>
<g:item_type>recipes</g:item_type>
</entry>
</feed>"""
BATCH_FEED_RESULT = """<?xml version="1.0" encoding="UTF-8"?>
<feed
xmlns="http://www.w3.org/2005/Atom"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:g="http://base.google.com/ns/1.0"
xmlns:batch="http://schemas.google.com/gdata/batch">
<id>http://www.google.com/base/feeds/items</id>
<updated>2006-07-11T14:51:42.894Z</updated>
<title type="text">My Batch</title>
<link rel="http://schemas.google.com/g/2005#feed"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items"/>
<link rel="http://schemas.google.com/g/2005#post"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items"/>
<link rel=" http://schemas.google.com/g/2005#batch"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items/batch"/>
<entry>
<id>http://www.google.com/base/feeds/items/2173859253842813008</id>
<published>2006-07-11T14:51:43.560Z</published>
<updated>2006-07-11T14:51: 43.560Z</updated>
<title type="text">...</title>
<content type="html">...</content>
<link rel="self"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items/2173859253842813008"/>
<link rel="edit"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items/2173859253842813008"/>
<g:item_type>recipes</g:item_type>
<batch:operation type="insert"/>
<batch:id>itemB</batch:id>
<batch:status code="201" reason="Created"/>
</entry>
<entry>
<id>http://www.google.com/base/feeds/items/11974645606383737963</id>
<published>2006-07-11T14:51:43.247Z</published>
<updated>2006-07-11T14:51: 43.247Z</updated>
<title type="text">...</title>
<content type="html">...</content>
<link rel="self"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items/11974645606383737963"/>
<link rel="edit"
type="application/atom+xml"
href="http://www.google.com/base/feeds/items/11974645606383737963"/>
<g:item_type>recipes</g:item_type>
<batch:operation type="insert"/>
<batch:id>itemA</batch:id>
<batch:status code="201" reason="Created"/>
</entry>
<entry>
<id>http://www.google.com/base/feeds/items/13308004346459454600</id>
<updated>2006-07-11T14:51:42.894Z</updated>
<title type="text">Error</title>
<content type="text">Bad request</content>
<batch:status code="404"
reason="Bad request"
content-type="application/xml">
<errors>
<error type="request" reason="Cannot find item"/>
</errors>
</batch:status>
</entry>
<entry>
<id>http://www.google.com/base/feeds/items/17437536661927313949</id>
<updated>2006-07-11T14:51:43.246Z</updated>
<content type="text">Deleted</content>
<batch:operation type="delete"/>
<batch:status code="200" reason="Success"/>
</entry>
</feed>"""
ALBUM_FEED = """<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:exif="http://schemas.google.com/photos/exif/2007" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:gml="http://www.opengis.net/gml" xmlns:georss="http://www.georss.org/georss" xmlns:photo="http://www.pheed.com/pheed/" xmlns:media="http://search.yahoo.com/mrss/" xmlns:batch="http://schemas.google.com/gdata/batch" xmlns:gphoto="http://schemas.google.com/photos/2007">
<id>http://picasaweb.google.com/data/feed/api/user/sample.user/albumid/1</id>
<updated>2007-09-21T18:23:05.000Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/photos/2007#album"/>
<title type="text">Test</title>
<subtitle type="text"/>
<rights type="text">public</rights>
<icon>http://lh6.google.com/sample.user/Rt8WNoDZEJE/AAAAAAAAABk/HQGlDhpIgWo/s160-c/Test.jpg</icon>
<link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://picasaweb.google.com/data/feed/api/user/sample.user/albumid/1"/>
<link rel="alternate" type="text/html" href="http://picasaweb.google.com/sample.user/Test"/>
<link rel="http://schemas.google.com/photos/2007#slideshow" type="application/x-shockwave-flash" href="http://picasaweb.google.com/s/c/bin/slideshow.swf?host=picasaweb.google.com&RGB=0x000000&feed=http%3A%2F%2Fpicasaweb.google.com%2Fdata%2Ffeed%2Fapi%2Fuser%2Fsample.user%2Falbumid%2F1%3Falt%3Drss"/>
<link rel="self" type="application/atom+xml" href="http://picasaweb.google.com/data/feed/api/user/sample.user/albumid/1?start-index=1&max-results=500&kind=photo%2Ctag"/>
<author>
<name>sample</name>
<uri>http://picasaweb.google.com/sample.user</uri>
</author>
<generator version="1.00" uri="http://picasaweb.google.com/">Picasaweb</generator> <openSearch:totalResults>4</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>500</openSearch:itemsPerPage>
<gphoto:id>1</gphoto:id>
<gphoto:name>Test</gphoto:name>
<gphoto:location/>
<gphoto:access>public</gphoto:access> <gphoto:timestamp>1188975600000</gphoto:timestamp>
<gphoto:numphotos>2</gphoto:numphotos>
<gphoto:user>sample.user</gphoto:user>
<gphoto:nickname>sample</gphoto:nickname>
<gphoto:commentingEnabled>true</gphoto:commentingEnabled>
<gphoto:commentCount>0</gphoto:commentCount>
<entry> <id>http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/photoid/2</id>
<published>2007-09-05T20:49:23.000Z</published>
<updated>2007-09-21T18:23:05.000Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/photos/2007#photo"/>
<title type="text">Aqua Blue.jpg</title>
<summary type="text">Blue</summary>
<content type="image/jpeg" src="http://lh4.google.com/sample.user/Rt8WU4DZEKI/AAAAAAAAABY/IVgLqmnzJII/Aqua%20Blue.jpg"/> <link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://picasaweb.google.com/data/feed/api/user/sample.user/albumid/1/photoid/2"/>
<link rel="alternate" type="text/html" href="http://picasaweb.google.com/sample.user/Test/photo#2"/>
<link rel="self" type="application/atom+xml" href="http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/photoid/2"/>
<gphoto:id>2</gphoto:id>
<gphoto:version>1190398985145172</gphoto:version>
<gphoto:position>0.0</gphoto:position>
<gphoto:albumid>1</gphoto:albumid> <gphoto:width>2560</gphoto:width>
<gphoto:height>1600</gphoto:height>
<gphoto:size>883405</gphoto:size>
<gphoto:client/>
<gphoto:checksum/>
<gphoto:timestamp>1189025362000</gphoto:timestamp>
<exif:tags> <exif:flash>true</exif:flash>
<exif:imageUniqueID>c041ce17aaa637eb656c81d9cf526c24</exif:imageUniqueID>
</exif:tags>
<gphoto:commentingEnabled>true</gphoto:commentingEnabled>
<gphoto:commentCount>1</gphoto:commentCount>
<media:group>
<media:title type="plain">Aqua Blue.jpg</media:title> <media:description type="plain">Blue</media:description>
<media:keywords>tag, test</media:keywords>
<media:content url="http://lh4.google.com/sample.user/Rt8WU4DZEKI/AAAAAAAAABY/IVgLqmnzJII/Aqua%20Blue.jpg" height="1600" width="2560" type="image/jpeg" medium="image"/>
<media:thumbnail url="http://lh4.google.com/sample.user/Rt8WU4DZEKI/AAAAAAAAABY/IVgLqmnzJII/s72/Aqua%20Blue.jpg" height="45" width="72"/>
<media:thumbnail url="http://lh4.google.com/sample.user/Rt8WU4DZEKI/AAAAAAAAABY/IVgLqmnzJII/s144/Aqua%20Blue.jpg" height="90" width="144"/>
<media:thumbnail url="http://lh4.google.com/sample.user/Rt8WU4DZEKI/AAAAAAAAABY/IVgLqmnzJII/s288/Aqua%20Blue.jpg" height="180" width="288"/>
<media:credit>sample</media:credit>
</media:group>
</entry>
<entry>
<id>http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/photoid/3</id>
<published>2007-09-05T20:49:24.000Z</published>
<updated>2007-09-21T18:19:38.000Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/photos/2007#photo"/>
<title type="text">Aqua Graphite.jpg</title>
<summary type="text">Gray</summary>
<content type="image/jpeg" src="http://lh5.google.com/sample.user/Rt8WVIDZELI/AAAAAAAAABg/d7e0i7gvhNU/Aqua%20Graphite.jpg"/>
<link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://picasaweb.google.com/data/feed/api/user/sample.user/albumid/1/photoid/3"/>
<link rel="alternate" type="text/html" href="http://picasaweb.google.com/sample.user/Test/photo#3"/>
<link rel="self" type="application/atom+xml" href="http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/photoid/3"/>
<gphoto:id>3</gphoto:id>
<gphoto:version>1190398778006402</gphoto:version>
<gphoto:position>1.0</gphoto:position>
<gphoto:albumid>1</gphoto:albumid>
<gphoto:width>2560</gphoto:width>
<gphoto:height>1600</gphoto:height>
<gphoto:size>798334</gphoto:size>
<gphoto:client/>
<gphoto:checksum/>
<gphoto:timestamp>1189025363000</gphoto:timestamp>
<exif:tags>
<exif:flash>true</exif:flash>
<exif:imageUniqueID>a5ce2e36b9df7d3cb081511c72e73926</exif:imageUniqueID>
</exif:tags>
<gphoto:commentingEnabled>true</gphoto:commentingEnabled>
<gphoto:commentCount>0</gphoto:commentCount>
<media:group>
<media:title type="plain">Aqua Graphite.jpg</media:title>
<media:description type="plain">Gray</media:description>
<media:keywords/>
<media:content url="http://lh5.google.com/sample.user/Rt8WVIDZELI/AAAAAAAAABg/d7e0i7gvhNU/Aqua%20Graphite.jpg" height="1600" width="2560" type="image/jpeg" medium="image"/>
<media:thumbnail url="http://lh5.google.com/sample.user/Rt8WVIDZELI/AAAAAAAAABg/d7e0i7gvhNU/s72/Aqua%20Graphite.jpg" height="45" width="72"/>
<media:thumbnail url="http://lh5.google.com/sample.user/Rt8WVIDZELI/AAAAAAAAABg/d7e0i7gvhNU/s144/Aqua%20Graphite.jpg" height="90" width="144"/>
<media:thumbnail url="http://lh5.google.com/sample.user/Rt8WVIDZELI/AAAAAAAAABg/d7e0i7gvhNU/s288/Aqua%20Graphite.jpg" height="180" width="288"/>
<media:credit>sample</media:credit>
</media:group>
</entry>
<entry>
<id>http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/tag/tag</id>
<updated>2007-09-05T20:49:24.000Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/photos/2007#tag"/>
<title type="text">tag</title>
<summary type="text">tag</summary>
<link rel="alternate" type="text/html" href="http://picasaweb.google.com/lh/searchbrowse?q=tag&psc=G&uname=sample.user&filter=0"/>
<link rel="self" type="application/atom+xml" href="http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/tag/tag"/>
<author>
<name>sample</name>
<uri>http://picasaweb.google.com/sample.user</uri>
</author>
</entry>
<entry>
<id>http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/tag/test</id>
<updated>2007-09-05T20:49:24.000Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/photos/2007#tag"/>
<title type="text">test</title>
<summary type="text">test</summary>
<link rel="alternate" type="text/html" href="http://picasaweb.google.com/lh/searchbrowse?q=test&psc=G&uname=sample.user&filter=0"/>
<link rel="self" type="application/atom+xml" href="http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/tag/test"/>
<author>
<name>sample</name>
<uri>http://picasaweb.google.com/sample.user</uri>
</author>
</entry>
</feed>"""
CODE_SEARCH_FEED = """<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:opensearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:gcs="http://schemas.google.com/codesearch/2006" xml:base="http://www.google.com">
<id>http://www.google.com/codesearch/feeds/search?q=malloc</id>
<updated>2007-12-19T16:08:04Z</updated>
<title type="text">Google Code Search</title>
<generator version="1.0" uri="http://www.google.com/codesearch">Google Code Search</generator>
<opensearch:totalResults>2530000</opensearch:totalResults>
<opensearch:startIndex>1</opensearch:startIndex>
<author>
<name>Google Code Search</name>
<uri>http://www.google.com/codesearch</uri>
</author>
<link rel="http://schemas.google.com/g/2006#feed" type="application/atom+xml" href="http://schemas.google.com/codesearch/2006"/>
<link rel="self" type="application/atom+xml" href="http://www.google.com/codesearch/feeds/search?q=malloc"/>
<link rel="next" type="application/atom+xml" href="http://www.google.com/codesearch/feeds/search?q=malloc&start-index=11"/>
<link rel="alternate" type="text/html" href="http://www.google.com/codesearch?q=malloc"/>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:LDjwp-Iqc7U:84hEYaYsZk8:xDGReDhvNi0&sa=N&ct=rx&cd=1&cs_p=http://www.gnu.org&cs_f=software/autoconf/manual/autoconf-2.60/autoconf.html-002&cs_p=http://www.gnu.org&cs_f=software/autoconf/manual/autoconf-2.60/autoconf.html-002#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">software/autoconf/manual/autoconf-2.60/autoconf.html</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:LDjwp-Iqc7U:84hEYaYsZk8:xDGReDhvNi0&sa=N&ct=rx&cd=1&cs_p=http://www.gnu.org&cs_f=software/autoconf/manual/autoconf-2.60/autoconf.html-002&cs_p=http://www.gnu.org&cs_f=software/autoconf/manual/autoconf-2.60/autoconf.html-002#first"/><gcs:package name="http://www.gnu.org" uri="http://www.gnu.org"></gcs:package><gcs:file name="software/autoconf/manual/autoconf-2.60/autoconf.html-002"></gcs:file><content type="text/html"><pre> 8: void *<b>malloc</b> ();
</pre></content><gcs:match lineNumber="4" type="text/html"><pre> #undef <b>malloc</b>
</pre></gcs:match><gcs:match lineNumber="8" type="text/html"><pre> void *<b>malloc</b> ();
</pre></gcs:match><gcs:match lineNumber="14" type="text/html"><pre> rpl_<b>malloc</b> (size_t n)
</pre></gcs:match><gcs:match lineNumber="18" type="text/html"><pre> return <b>malloc</b> (n);
</pre></gcs:match></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:h4hfh-fV-jI:niBq_bwWZNs:H0OhClf0HWQ&sa=N&ct=rx&cd=2&cs_p=ftp://ftp.gnu.org/gnu/guile/guile-1.6.8.tar.gz&cs_f=guile-1.6.8/libguile/mallocs.c&cs_p=ftp://ftp.gnu.org/gnu/guile/guile-1.6.8.tar.gz&cs_f=guile-1.6.8/libguile/mallocs.c#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">guile-1.6.8/libguile/mallocs.c</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:h4hfh-fV-jI:niBq_bwWZNs:H0OhClf0HWQ&sa=N&ct=rx&cd=2&cs_p=ftp://ftp.gnu.org/gnu/guile/guile-1.6.8.tar.gz&cs_f=guile-1.6.8/libguile/mallocs.c&cs_p=ftp://ftp.gnu.org/gnu/guile/guile-1.6.8.tar.gz&cs_f=guile-1.6.8/libguile/mallocs.c#first"/><gcs:package name="ftp://ftp.gnu.org/gnu/guile/guile-1.6.8.tar.gz" uri="ftp://ftp.gnu.org/gnu/guile/guile-1.6.8.tar.gz"></gcs:package><gcs:file name="guile-1.6.8/libguile/mallocs.c"></gcs:file><content type="text/html"><pre> 86: {
scm_t_bits mem = n ? (scm_t_bits) <b>malloc</b> (n) : 0;
if (n &amp;&amp; !mem)
</pre></content><gcs:match lineNumber="54" type="text/html"><pre>#include &lt;<b>malloc</b>.h&gt;
</pre></gcs:match><gcs:match lineNumber="62" type="text/html"><pre>scm_t_bits scm_tc16_<b>malloc</b>;
</pre></gcs:match><gcs:match lineNumber="66" type="text/html"><pre><b>malloc</b>_free (SCM ptr)
</pre></gcs:match><gcs:match lineNumber="75" type="text/html"><pre><b>malloc</b>_print (SCM exp, SCM port, scm_print_state *pstate SCM_UNUSED)
</pre></gcs:match><gcs:match lineNumber="77" type="text/html"><pre> scm_puts(&quot;#&lt;<b>malloc</b> &quot;, port);
</pre></gcs:match><gcs:match lineNumber="87" type="text/html"><pre> scm_t_bits mem = n ? (scm_t_bits) <b>malloc</b> (n) : 0;
</pre></gcs:match><gcs:match lineNumber="90" type="text/html"><pre> SCM_RETURN_NEWSMOB (scm_tc16_<b>malloc</b>, mem);
</pre></gcs:match><gcs:match lineNumber="98" type="text/html"><pre> scm_tc16_<b>malloc</b> = scm_make_smob_type (&quot;<b>malloc</b>&quot;, 0);
</pre></gcs:match><gcs:match lineNumber="99" type="text/html"><pre> scm_set_smob_free (scm_tc16_<b>malloc</b>, <b>malloc</b>_free);
</pre></gcs:match><rights>GPL</rights></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:9wyZUG-N_30:7_dFxoC1ZrY:C0_iYbFj90M&sa=N&ct=rx&cd=3&cs_p=http://ftp.gnu.org/gnu/bash/bash-3.0.tar.gz&cs_f=bash-3.0/lib/malloc/alloca.c&cs_p=http://ftp.gnu.org/gnu/bash/bash-3.0.tar.gz&cs_f=bash-3.0/lib/malloc/alloca.c#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">bash-3.0/lib/malloc/alloca.c</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:9wyZUG-N_30:7_dFxoC1ZrY:C0_iYbFj90M&sa=N&ct=rx&cd=3&cs_p=http://ftp.gnu.org/gnu/bash/bash-3.0.tar.gz&cs_f=bash-3.0/lib/malloc/alloca.c&cs_p=http://ftp.gnu.org/gnu/bash/bash-3.0.tar.gz&cs_f=bash-3.0/lib/malloc/alloca.c#first"/><gcs:package name="http://ftp.gnu.org/gnu/bash/bash-3.0.tar.gz" uri="http://ftp.gnu.org/gnu/bash/bash-3.0.tar.gz"></gcs:package><gcs:file name="bash-3.0/lib/malloc/alloca.c"></gcs:file><content type="text/html"><pre> 78: #ifndef emacs
#define <b>malloc</b> x<b>malloc</b>
extern pointer x<b>malloc</b> ();
</pre></content><gcs:match lineNumber="69" type="text/html"><pre> <b>malloc</b>. The Emacs executable needs alloca to call x<b>malloc</b>, because
</pre></gcs:match><gcs:match lineNumber="70" type="text/html"><pre> ordinary <b>malloc</b> isn&#39;t protected from input signals. On the other
</pre></gcs:match><gcs:match lineNumber="71" type="text/html"><pre> hand, the utilities in lib-src need alloca to call <b>malloc</b>; some of
</pre></gcs:match><gcs:match lineNumber="72" type="text/html"><pre> them are very simple, and don&#39;t have an x<b>malloc</b> routine.
</pre></gcs:match><gcs:match lineNumber="76" type="text/html"><pre> Callers below should use <b>malloc</b>. */
</pre></gcs:match><gcs:match lineNumber="79" type="text/html"><pre>#define <b>malloc</b> x<b>malloc</b>
</pre></gcs:match><gcs:match lineNumber="80" type="text/html"><pre>extern pointer x<b>malloc</b> ();
</pre></gcs:match><gcs:match lineNumber="132" type="text/html"><pre> It is very important that sizeof(header) agree with <b>malloc</b>
</pre></gcs:match><gcs:match lineNumber="198" type="text/html"><pre> register pointer new = <b>malloc</b> (sizeof (header) + size);
</pre></gcs:match><rights>GPL</rights></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:uhVCKyPcT6k:8juMxxzmUJw:H7_IDsTB2L4&sa=N&ct=rx&cd=4&cs_p=http://ftp.mozilla.org/pub/mozilla.org/mozilla/releases/mozilla1.7b/src/mozilla-source-1.7b-source.tar.bz2&cs_f=mozilla/xpcom/build/malloc.c&cs_p=http://ftp.mozilla.org/pub/mozilla.org/mozilla/releases/mozilla1.7b/src/mozilla-source-1.7b-source.tar.bz2&cs_f=mozilla/xpcom/build/malloc.c#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">mozilla/xpcom/build/malloc.c</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:uhVCKyPcT6k:8juMxxzmUJw:H7_IDsTB2L4&sa=N&ct=rx&cd=4&cs_p=http://ftp.mozilla.org/pub/mozilla.org/mozilla/releases/mozilla1.7b/src/mozilla-source-1.7b-source.tar.bz2&cs_f=mozilla/xpcom/build/malloc.c&cs_p=http://ftp.mozilla.org/pub/mozilla.org/mozilla/releases/mozilla1.7b/src/mozilla-source-1.7b-source.tar.bz2&cs_f=mozilla/xpcom/build/malloc.c#first"/><gcs:package name="http://ftp.mozilla.org/pub/mozilla.org/mozilla/releases/mozilla1.7b/src/mozilla-source-1.7b-source.tar.bz2" uri="http://ftp.mozilla.org/pub/mozilla.org/mozilla/releases/mozilla1.7b/src/mozilla-source-1.7b-source.tar.bz2"></gcs:package><gcs:file name="mozilla/xpcom/build/malloc.c"></gcs:file><content type="text/html"><pre> 54: http://gee.cs.oswego.edu/dl/html/<b>malloc</b>.html
You may already by default be using a c library containing a <b>malloc</b>
</pre></content><gcs:match lineNumber="4" type="text/html"><pre>/* ---------- To make a <b>malloc</b>.h, start cutting here ------------ */
</pre></gcs:match><gcs:match lineNumber="22" type="text/html"><pre> Note: There may be an updated version of this <b>malloc</b> obtainable at
</pre></gcs:match><gcs:match lineNumber="23" type="text/html"><pre> ftp://gee.cs.oswego.edu/pub/misc/<b>malloc</b>.c
</pre></gcs:match><gcs:match lineNumber="34" type="text/html"><pre>* Why use this <b>malloc</b>?
</pre></gcs:match><gcs:match lineNumber="37" type="text/html"><pre> most tunable <b>malloc</b> ever written. However it is among the fastest
</pre></gcs:match><gcs:match lineNumber="40" type="text/html"><pre> allocator for <b>malloc</b>-intensive programs.
</pre></gcs:match><gcs:match lineNumber="54" type="text/html"><pre> http://gee.cs.oswego.edu/dl/html/<b>malloc</b>.html
</pre></gcs:match><gcs:match lineNumber="56" type="text/html"><pre> You may already by default be using a c library containing a <b>malloc</b>
</pre></gcs:match><gcs:match lineNumber="57" type="text/html"><pre> that is somehow based on some version of this <b>malloc</b> (for example in
</pre></gcs:match><rights>Mozilla</rights></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:4n1P2HVOISs:Ybbpph0wR2M:OhIN_sDrG0U&sa=N&ct=rx&cd=5&cs_p=http://regexps.srparish.net/src/hackerlab/hackerlab-1.0pre2.tar.gz&cs_f=hackerlab-1.0pre2/src/hackerlab/tests/mem-tests/unit-must-malloc.sh&cs_p=http://regexps.srparish.net/src/hackerlab/hackerlab-1.0pre2.tar.gz&cs_f=hackerlab-1.0pre2/src/hackerlab/tests/mem-tests/unit-must-malloc.sh#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">hackerlab-1.0pre2/src/hackerlab/tests/mem-tests/unit-must-malloc.sh</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:4n1P2HVOISs:Ybbpph0wR2M:OhIN_sDrG0U&sa=N&ct=rx&cd=5&cs_p=http://regexps.srparish.net/src/hackerlab/hackerlab-1.0pre2.tar.gz&cs_f=hackerlab-1.0pre2/src/hackerlab/tests/mem-tests/unit-must-malloc.sh&cs_p=http://regexps.srparish.net/src/hackerlab/hackerlab-1.0pre2.tar.gz&cs_f=hackerlab-1.0pre2/src/hackerlab/tests/mem-tests/unit-must-malloc.sh#first"/><gcs:package name="http://regexps.srparish.net/src/hackerlab/hackerlab-1.0pre2.tar.gz" uri="http://regexps.srparish.net/src/hackerlab/hackerlab-1.0pre2.tar.gz"></gcs:package><gcs:file name="hackerlab-1.0pre2/src/hackerlab/tests/mem-tests/unit-must-malloc.sh"></gcs:file><content type="text/html"><pre> 11: echo ================ unit-must-<b>malloc</b> tests ================
./unit-must-<b>malloc</b>
echo ...passed
</pre></content><gcs:match lineNumber="2" type="text/html"><pre># tag: Tom Lord Tue Dec 4 14:54:29 2001 (mem-tests/unit-must-<b>malloc</b>.sh)
</pre></gcs:match><gcs:match lineNumber="11" type="text/html"><pre>echo ================ unit-must-<b>malloc</b> tests ================
</pre></gcs:match><gcs:match lineNumber="12" type="text/html"><pre>./unit-must-<b>malloc</b>
</pre></gcs:match><rights>GPL</rights></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:GzkwiWG266M:ykuz3bG00ws:2sTvVSif08g&sa=N&ct=rx&cd=6&cs_p=http://ftp.gnu.org/gnu/tar/tar-1.14.tar.bz2&cs_f=tar-1.14/lib/malloc.c&cs_p=http://ftp.gnu.org/gnu/tar/tar-1.14.tar.bz2&cs_f=tar-1.14/lib/malloc.c#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">tar-1.14/lib/malloc.c</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:GzkwiWG266M:ykuz3bG00ws:2sTvVSif08g&sa=N&ct=rx&cd=6&cs_p=http://ftp.gnu.org/gnu/tar/tar-1.14.tar.bz2&cs_f=tar-1.14/lib/malloc.c&cs_p=http://ftp.gnu.org/gnu/tar/tar-1.14.tar.bz2&cs_f=tar-1.14/lib/malloc.c#first"/><gcs:package name="http://ftp.gnu.org/gnu/tar/tar-1.14.tar.bz2" uri="http://ftp.gnu.org/gnu/tar/tar-1.14.tar.bz2"></gcs:package><gcs:file name="tar-1.14/lib/malloc.c"></gcs:file><content type="text/html"><pre> 22: #endif
#undef <b>malloc</b>
</pre></content><gcs:match lineNumber="1" type="text/html"><pre>/* Work around bug on some systems where <b>malloc</b> (0) fails.
</pre></gcs:match><gcs:match lineNumber="23" type="text/html"><pre>#undef <b>malloc</b>
</pre></gcs:match><gcs:match lineNumber="31" type="text/html"><pre>rpl_<b>malloc</b> (size_t n)
</pre></gcs:match><gcs:match lineNumber="35" type="text/html"><pre> return <b>malloc</b> (n);
</pre></gcs:match><rights>GPL</rights></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:o_TFIeBY6dY:ktI_dt8wPao:AI03BD1Dz0Y&sa=N&ct=rx&cd=7&cs_p=http://ftp.gnu.org/gnu/tar/tar-1.16.1.tar.gz&cs_f=tar-1.16.1/lib/malloc.c&cs_p=http://ftp.gnu.org/gnu/tar/tar-1.16.1.tar.gz&cs_f=tar-1.16.1/lib/malloc.c#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">tar-1.16.1/lib/malloc.c</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:o_TFIeBY6dY:ktI_dt8wPao:AI03BD1Dz0Y&sa=N&ct=rx&cd=7&cs_p=http://ftp.gnu.org/gnu/tar/tar-1.16.1.tar.gz&cs_f=tar-1.16.1/lib/malloc.c&cs_p=http://ftp.gnu.org/gnu/tar/tar-1.16.1.tar.gz&cs_f=tar-1.16.1/lib/malloc.c#first"/><gcs:package name="http://ftp.gnu.org/gnu/tar/tar-1.16.1.tar.gz" uri="http://ftp.gnu.org/gnu/tar/tar-1.16.1.tar.gz"></gcs:package><gcs:file name="tar-1.16.1/lib/malloc.c"></gcs:file><content type="text/html"><pre> 21: #include &lt;config.h&gt;
#undef <b>malloc</b>
</pre></content><gcs:match lineNumber="1" type="text/html"><pre>/* <b>malloc</b>() function that is glibc compatible.
</pre></gcs:match><gcs:match lineNumber="22" type="text/html"><pre>#undef <b>malloc</b>
</pre></gcs:match><gcs:match lineNumber="30" type="text/html"><pre>rpl_<b>malloc</b> (size_t n)
</pre></gcs:match><gcs:match lineNumber="34" type="text/html"><pre> return <b>malloc</b> (n);
</pre></gcs:match><rights>GPL</rights></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:_ibw-VLkMoI:jBOtIJSmFd4:-0NUEVeCwfY&sa=N&ct=rx&cd=8&cs_p=http://freshmeat.net/redir/uclibc/20616/url_bz2/uClibc-0.9.28.1.tar.bz2&cs_f=uClibc-0.9.29/include/malloc.h&cs_p=http://freshmeat.net/redir/uclibc/20616/url_bz2/uClibc-0.9.28.1.tar.bz2&cs_f=uClibc-0.9.29/include/malloc.h#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">uClibc-0.9.29/include/malloc.h</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:_ibw-VLkMoI:jBOtIJSmFd4:-0NUEVeCwfY&sa=N&ct=rx&cd=8&cs_p=http://freshmeat.net/redir/uclibc/20616/url_bz2/uClibc-0.9.28.1.tar.bz2&cs_f=uClibc-0.9.29/include/malloc.h&cs_p=http://freshmeat.net/redir/uclibc/20616/url_bz2/uClibc-0.9.28.1.tar.bz2&cs_f=uClibc-0.9.29/include/malloc.h#first"/><gcs:package name="http://freshmeat.net/redir/uclibc/20616/url_bz2/uClibc-0.9.28.1.tar.bz2" uri="http://freshmeat.net/redir/uclibc/20616/url_bz2/uClibc-0.9.28.1.tar.bz2"></gcs:package><gcs:file name="uClibc-0.9.29/include/malloc.h"></gcs:file><content type="text/html"><pre> 1: /* Prototypes and definition for <b>malloc</b> implementation.
Copyright (C) 1996, 1997, 1999, 2000 Free Software Foundation, Inc.
</pre></content><gcs:match lineNumber="1" type="text/html"><pre>/* Prototypes and definition for <b>malloc</b> implementation.
</pre></gcs:match><gcs:match lineNumber="26" type="text/html"><pre> `pt<b>malloc</b>&#39;, a <b>malloc</b> implementation for multiple threads without
</pre></gcs:match><gcs:match lineNumber="28" type="text/html"><pre> See the files `pt<b>malloc</b>.c&#39; or `COPYRIGHT&#39; for copying conditions.
</pre></gcs:match><gcs:match lineNumber="32" type="text/html"><pre> This work is mainly derived from <b>malloc</b>-2.6.4 by Doug Lea
</pre></gcs:match><gcs:match lineNumber="35" type="text/html"><pre> ftp://g.oswego.edu/pub/misc/<b>malloc</b>.c
</pre></gcs:match><gcs:match lineNumber="40" type="text/html"><pre> `pt<b>malloc</b>.c&#39;.
</pre></gcs:match><gcs:match lineNumber="45" type="text/html"><pre># define __<b>malloc</b>_ptr_t void *
</pre></gcs:match><gcs:match lineNumber="51" type="text/html"><pre># define __<b>malloc</b>_ptr_t char *
</pre></gcs:match><gcs:match lineNumber="56" type="text/html"><pre># define __<b>malloc</b>_size_t size_t
</pre></gcs:match><rights>LGPL</rights></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:F6qHcZ9vefo:bTX7o9gKfks:hECF4r_eKC0&sa=N&ct=rx&cd=9&cs_p=http://ftp.gnu.org/gnu/glibc/glibc-2.0.1.tar.gz&cs_f=glibc-2.0.1/hurd/hurdmalloc.h&cs_p=http://ftp.gnu.org/gnu/glibc/glibc-2.0.1.tar.gz&cs_f=glibc-2.0.1/hurd/hurdmalloc.h#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">glibc-2.0.1/hurd/hurdmalloc.h</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:F6qHcZ9vefo:bTX7o9gKfks:hECF4r_eKC0&sa=N&ct=rx&cd=9&cs_p=http://ftp.gnu.org/gnu/glibc/glibc-2.0.1.tar.gz&cs_f=glibc-2.0.1/hurd/hurdmalloc.h&cs_p=http://ftp.gnu.org/gnu/glibc/glibc-2.0.1.tar.gz&cs_f=glibc-2.0.1/hurd/hurdmalloc.h#first"/><gcs:package name="http://ftp.gnu.org/gnu/glibc/glibc-2.0.1.tar.gz" uri="http://ftp.gnu.org/gnu/glibc/glibc-2.0.1.tar.gz"></gcs:package><gcs:file name="glibc-2.0.1/hurd/hurdmalloc.h"></gcs:file><content type="text/html"><pre> 15: #define <b>malloc</b> _hurd_<b>malloc</b>
#define realloc _hurd_realloc
</pre></content><gcs:match lineNumber="3" type="text/html"><pre> All hurd-internal code which uses <b>malloc</b> et al includes this file so it
</pre></gcs:match><gcs:match lineNumber="4" type="text/html"><pre> will use the internal <b>malloc</b> routines _hurd_{<b>malloc</b>,realloc,free}
</pre></gcs:match><gcs:match lineNumber="7" type="text/html"><pre> of <b>malloc</b> et al is the unixoid one using sbrk.
</pre></gcs:match><gcs:match lineNumber="11" type="text/html"><pre>extern void *_hurd_<b>malloc</b> (size_t);
</pre></gcs:match><gcs:match lineNumber="15" type="text/html"><pre>#define <b>malloc</b> _hurd_<b>malloc</b>
</pre></gcs:match><rights>GPL</rights></entry>
<entry><id>http://www.google.com/codesearch?hl=en&q=+malloc+show:CHUvHYzyLc8:pdcAfzDA6lY:wjofHuNLTHg&sa=N&ct=rx&cd=10&cs_p=ftp://apache.mirrors.pair.com/httpd/httpd-2.2.4.tar.bz2&cs_f=httpd-2.2.4/srclib/apr/include/arch/netware/apr_private.h&cs_p=ftp://apache.mirrors.pair.com/httpd/httpd-2.2.4.tar.bz2&cs_f=httpd-2.2.4/srclib/apr/include/arch/netware/apr_private.h#first</id><updated>2007-12-19T16:08:04Z</updated><author><name>Code owned by external author.</name></author><title type="text">httpd-2.2.4/srclib/apr/include/arch/netware/apr_private.h</title><link rel="alternate" type="text/html" href="http://www.google.com/codesearch?hl=en&q=+malloc+show:CHUvHYzyLc8:pdcAfzDA6lY:wjofHuNLTHg&sa=N&ct=rx&cd=10&cs_p=ftp://apache.mirrors.pair.com/httpd/httpd-2.2.4.tar.bz2&cs_f=httpd-2.2.4/srclib/apr/include/arch/netware/apr_private.h&cs_p=ftp://apache.mirrors.pair.com/httpd/httpd-2.2.4.tar.bz2&cs_f=httpd-2.2.4/srclib/apr/include/arch/netware/apr_private.h#first"/><gcs:package name="ftp://apache.mirrors.pair.com/httpd/httpd-2.2.4.tar.bz2" uri="ftp://apache.mirrors.pair.com/httpd/httpd-2.2.4.tar.bz2"></gcs:package><gcs:file name="httpd-2.2.4/srclib/apr/include/arch/netware/apr_private.h"></gcs:file><content type="text/html"><pre> 173: #undef <b>malloc</b>
#define <b>malloc</b>(x) library_<b>malloc</b>(gLibHandle,x)
</pre></content><gcs:match lineNumber="170" type="text/html"><pre>/* Redefine <b>malloc</b> to use the library <b>malloc</b> call so
</pre></gcs:match><gcs:match lineNumber="173" type="text/html"><pre>#undef <b>malloc</b>
</pre></gcs:match><gcs:match lineNumber="174" type="text/html"><pre>#define <b>malloc</b>(x) library_<b>malloc</b>(gLibHandle,x)
</pre></gcs:match><rights>Apache</rights></entry>
</feed>"""
YOUTUBE_VIDEO_FEED = """<?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gml='http://www.opengis.net/gml' xmlns:georss='http://www.georss.org/georss' xmlns:media='http://search.yahoo.com/mrss/' xmlns:yt='http://gdata.youtube.com/schemas/2007' xmlns:gd='http://schemas.google.com/g/2005'><id>http://gdata.youtube.com/feeds/api/standardfeeds/top_rated</id><updated>2008-05-14T02:24:07.000-07:00</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#video'/><title type='text'>Top Rated</title><logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo><link rel='alternate' type='text/html' href='http://www.youtube.com/browse?s=tr'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/standardfeeds/top_rated'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?start-index=1&max-results=25'/><link rel='next' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?start-index=26&max-results=25'/><author><name>YouTube</name><uri>http://www.youtube.com/</uri></author><generator version='beta' uri='http://gdata.youtube.com/'>YouTube data API</generator><openSearch:totalResults>100</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry><id>http://gdata.youtube.com/feeds/api/videos/C71ypXYGho8</id><published>2008-03-20T10:17:27.000-07:00</published><updated>2008-05-14T04:26:37.000-07:00</updated><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='karyn'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='garcia'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='me'/><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#video'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='boyfriend'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='por'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='te'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='odeio'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='amar'/><category scheme='http://gdata.youtube.com/schemas/2007/categories.cat' term='Music' label='Music'/><title type='text'>Me odeio por te amar - KARYN GARCIA</title><content type='text'>http://www.karyngarcia.com.br</content><link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=C71ypXYGho8'/><link rel='http://gdata.youtube.com/schemas/2007#video.related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/C71ypXYGho8/related'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/standardfeeds/top_rated/C71ypXYGho8'/><author><name>TvKarynGarcia</name><uri>http://gdata.youtube.com/feeds/api/users/tvkaryngarcia</uri></author><media:group><media:title type='plain'>Me odeio por te amar - KARYN GARCIA</media:title><media:description type='plain'>http://www.karyngarcia.com.br</media:description><media:keywords>amar, boyfriend, garcia, karyn, me, odeio, por, te</media:keywords><yt:duration seconds='203'/><media:category label='Music' scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>Music</media:category><media:category label='test111' scheme='http://gdata.youtube.com/schemas/2007/developertags.cat'>test111</media:category><media:category label='test222' scheme='http://gdata.youtube.com/schemas/2007/developertags.cat'>test222</media:category><media:content url='http://www.youtube.com/v/C71ypXYGho8' type='application/x-shockwave-flash' medium='video' isDefault='true' expression='full' duration='203' yt:format='5'/><media:content url='rtsp://rtsp2.youtube.com/ChoLENy73wIaEQmPhgZ2pXK9CxMYDSANFEgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='203' yt:format='1'/><media:content url='rtsp://rtsp2.youtube.com/ChoLENy73wIaEQmPhgZ2pXK9CxMYESARFEgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='203' yt:format='6'/><media:player url='http://www.youtube.com/watch?v=C71ypXYGho8'/><media:thumbnail url='http://img.youtube.com/vi/C71ypXYGho8/2.jpg' height='97' width='130' time='00:01:41.500'/><media:thumbnail url='http://img.youtube.com/vi/C71ypXYGho8/1.jpg' height='97' width='130' time='00:00:50.750'/><media:thumbnail url='http://img.youtube.com/vi/C71ypXYGho8/3.jpg' height='97' width='130' time='00:02:32.250'/><media:thumbnail url='http://img.youtube.com/vi/C71ypXYGho8/0.jpg' height='240' width='320' time='00:01:41.500'/></media:group><yt:statistics viewCount='138864' favoriteCount='2474'/><gd:rating min='1' max='5' numRaters='4626' average='4.95'/><gd:comments><gd:feedLink href='http://gdata.youtube.com/feeds/api/videos/C71ypXYGho8/comments' countHint='27'/></gd:comments></entry>
<entry><id>http://gdata.youtube.com/feeds/api/videos/gsVaTyb1tBw</id><published>2008-02-15T04:31:45.000-08:00</published><updated>2008-05-14T05:09:42.000-07:00</updated><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='extreme'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='cam'/><category scheme='http://gdata.youtube.com/schemas/2007/categories.cat' term='Sports' label='Sports'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='alcala'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='kani'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='helmet'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='campillo'/><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#video'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='pato'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='dirt'/><title type='text'>extreme helmet cam Kani, Keil and Pato</title><content type='text'>trimmed</content><link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=gsVaTyb1tBw'/><link rel='http://gdata.youtube.com/schemas/2007#video.responses' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/gsVaTyb1tBw/responses'/><link rel='http://gdata.youtube.com/schemas/2007#video.related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/gsVaTyb1tBw/related'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/standardfeeds/recently_featured/gsVaTyb1tBw'/><author><name>peraltamagic</name><uri>http://gdata.youtube.com/feeds/api/users/peraltamagic</uri></author><media:group><media:title type='plain'>extreme helmet cam Kani, Keil and Pato</media:title><media:description type='plain'>trimmed</media:description><media:keywords>alcala, cam, campillo, dirt, extreme, helmet, kani, pato</media:keywords><yt:duration seconds='31'/><media:category label='Sports' scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>Sports</media:category><media:content url='http://www.youtube.com/v/gsVaTyb1tBw' type='application/x-shockwave-flash' medium='video' isDefault='true' expression='full' duration='31' yt:format='5'/><media:content url='rtsp://rtsp2.youtube.com/ChoLENy73wIaEQkctPUmT1rFghMYDSANFEgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='31' yt:format='1'/><media:content url='rtsp://rtsp2.youtube.com/ChoLENy73wIaEQkctPUmT1rFghMYESARFEgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='31' yt:format='6'/><media:player url='http://www.youtube.com/watch?v=gsVaTyb1tBw'/><media:thumbnail url='http://img.youtube.com/vi/gsVaTyb1tBw/2.jpg' height='97' width='130' time='00:00:15.500'/><media:thumbnail url='http://img.youtube.com/vi/gsVaTyb1tBw/1.jpg' height='97' width='130' time='00:00:07.750'/><media:thumbnail url='http://img.youtube.com/vi/gsVaTyb1tBw/3.jpg' height='97' width='130' time='00:00:23.250'/><media:thumbnail url='http://img.youtube.com/vi/gsVaTyb1tBw/0.jpg' height='240' width='320' time='00:00:15.500'/></media:group><yt:statistics viewCount='489941' favoriteCount='561'/><gd:rating min='1' max='5' numRaters='1255' average='4.11'/><gd:comments><gd:feedLink href='http://gdata.youtube.com/feeds/api/videos/gsVaTyb1tBw/comments' countHint='1116'/></gd:comments></entry>
</feed>"""
YOUTUBE_ENTRY_PRIVATE = """<?xml version='1.0' encoding='utf-8'?>
<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:media='http://search.yahoo.com/mrss/'
xmlns:gd='http://schemas.google.com/g/2005'
xmlns:yt='http://gdata.youtube.com/schemas/2007'
xmlns:gml='http://www.opengis.net/gml'
xmlns:georss='http://www.georss.org/georss'
xmlns:app='http://purl.org/atom/app#'>
<id>http://gdata.youtube.com/feeds/videos/UMFI1hdm96E</id>
<published>2007-01-07T01:50:15.000Z</published>
<updated>2007-01-07T01:50:15.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://gdata.youtube.com/schemas/2007#video' />
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat'
term='barkley' />
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat'
term='singing' />
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat'
term='acoustic' />
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat'
term='cover' />
<category scheme='http://gdata.youtube.com/schemas/2007/categories.cat'
term='Music' label='Music' />
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat'
term='gnarls' />
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat'
term='music' />
<title type='text'>"Crazy (Gnarles Barkley)" - Acoustic Cover</title>
<content type='html'><div style="color: #000000;font-family:
Arial, Helvetica, sans-serif; font-size:12px; font-size: 12px;
width: 555px;"><table cellspacing="0" cellpadding="0"
border="0"><tbody><tr><td width="140"
valign="top" rowspan="2"><div style="border: 1px solid
#999999; margin: 0px 10px 5px 0px;"><a
href="http://www.youtube.com/watch?v=UMFI1hdm96E"><img
alt=""
src="http://img.youtube.com/vi/UMFI1hdm96E/2.jpg"></a></div></td>
<td width="256" valign="top"><div style="font-size:
12px; font-weight: bold;"><a style="font-size: 15px;
font-weight: bold; font-decoration: none;"
href="http://www.youtube.com/watch?v=UMFI1hdm96E">&quot;Crazy
(Gnarles Barkley)&quot; - Acoustic Cover</a>
<br></div> <div style="font-size: 12px; margin:
3px 0px;"><span>Gnarles Barkley acoustic cover
http://www.myspace.com/davidchoimusic</span></div></td>
<td style="font-size: 11px; line-height: 1.4em; padding-left:
20px; padding-top: 1px;" width="146"
valign="top"><div><span style="color: #666666;
font-size: 11px;">From:</span> <a
href="http://www.youtube.com/profile?user=davidchoimusic">davidchoimusic</a></div>
<div><span style="color: #666666; font-size:
11px;">Views:</span> 113321</div> <div
style="white-space: nowrap;text-align: left"><img
style="border: 0px none; margin: 0px; padding: 0px;
vertical-align: middle; font-size: 11px;" align="top" alt=""
src="http://gdata.youtube.com/static/images/icn_star_full_11x11.gif">
<img style="border: 0px none; margin: 0px; padding: 0px;
vertical-align: middle; font-size: 11px;" align="top" alt=""
src="http://gdata.youtube.com/static/images/icn_star_full_11x11.gif">
<img style="border: 0px none; margin: 0px; padding: 0px;
vertical-align: middle; font-size: 11px;" align="top" alt=""
src="http://gdata.youtube.com/static/images/icn_star_full_11x11.gif">
<img style="border: 0px none; margin: 0px; padding: 0px;
vertical-align: middle; font-size: 11px;" align="top" alt=""
src="http://gdata.youtube.com/static/images/icn_star_full_11x11.gif">
<img style="border: 0px none; margin: 0px; padding: 0px;
vertical-align: middle; font-size: 11px;" align="top" alt=""
src="http://gdata.youtube.com/static/images/icn_star_half_11x11.gif"></div>
<div style="font-size: 11px;">1005 <span style="color:
#666666; font-size:
11px;">ratings</span></div></td></tr>
<tr><td><span style="color: #666666; font-size:
11px;">Time:</span> <span style="color: #000000;
font-size: 11px; font-weight:
bold;">04:15</span></td> <td style="font-size:
11px; padding-left: 20px;"><span style="color: #666666;
font-size: 11px;">More in</span> <a
href="http://www.youtube.com/categories_portal?c=10">Music</a></td></tr></tbody></table></div></content>
<link rel='self' type='application/atom+xml'
href='http://gdata.youtube.com/feeds/videos/UMFI1hdm96E' />
<link rel='alternate' type='text/html'
href='http://www.youtube.com/watch?v=UMFI1hdm96E' />
<link rel='http://gdata.youtube.com/schemas/2007#video.responses'
type='application/atom+xml'
href='http://gdata.youtube.com/feeds/videos/UMFI1hdm96E/responses' />
<link rel='http://gdata.youtube.com/schemas/2007#video.related'
type='application/atom+xml'
href='http://gdata.youtube.com/feeds/videos/UMFI1hdm96E/related' />
<author>
<name>davidchoimusic</name>
<uri>http://gdata.youtube.com/feeds/users/davidchoimusic</uri>
</author>
<media:group>
<media:title type='plain'>"Crazy (Gnarles Barkley)" - Acoustic Cover</media:title>
<media:description type='plain'>Gnarles Barkley acoustic cover http://www.myspace.com/davidchoimusic</media:description>
<media:keywords>music, singing, gnarls, barkley, acoustic, cover</media:keywords>
<yt:duration seconds='255' />
<media:category label='Music'
scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>
Music</media:category>
<media:category
scheme='http://gdata.youtube.com/schemas/2007/developertags.cat'>
DeveloperTag1</media:category>
<media:content url='http://www.youtube.com/v/UMFI1hdm96E'
type='application/x-shockwave-flash' medium='video'
isDefault='true' expression='full' duration='255'
yt:format='5' />
<media:player url='http://www.youtube.com/watch?v=UMFI1hdm96E' />
<media:thumbnail url='http://img.youtube.com/vi/UMFI1hdm96E/2.jpg'
height='97' width='130' time='00:02:07.500' />
<media:thumbnail url='http://img.youtube.com/vi/UMFI1hdm96E/1.jpg'
height='97' width='130' time='00:01:03.750' />
<media:thumbnail url='http://img.youtube.com/vi/UMFI1hdm96E/3.jpg'
height='97' width='130' time='00:03:11.250' />
<media:thumbnail url='http://img.youtube.com/vi/UMFI1hdm96E/0.jpg'
height='240' width='320' time='00:02:07.500' />
<yt:private />
</media:group>
<yt:statistics viewCount='113321' />
<gd:rating min='1' max='5' numRaters='1005' average='4.77' />
<georss:where>
<gml:Point>
<gml:pos>37.398529052734375 -122.0635986328125</gml:pos>
</gml:Point>
</georss:where>
<gd:comments>
<gd:feedLink href='http://gdata.youtube.com/feeds/videos/UMFI1hdm96E/comments' />
</gd:comments>
<yt:noembed />
<app:control>
<app:draft>yes</app:draft>
<yt:state
name="rejected"
reasonCode="inappropriate"
helpUrl="http://www.youtube.com/t/community_guidelines">
The content of this video may violate the terms of use.</yt:state>
</app:control>
</entry>"""
YOUTUBE_COMMENT_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'><id>http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments</id><updated>2008-05-19T21:45:45.261Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#comment'/><title type='text'>Comments</title><logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo><link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU'/><link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=2Idhz9ef5oU'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments?start-index=1&max-results=25'/><author><name>YouTube</name><uri>http://www.youtube.com/</uri></author><generator version='beta' uri='http://gdata.youtube.com/'>YouTube data API</generator><openSearch:totalResults>0</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments/91F809A3DE2EB81B</id>
<published>2008-02-22T15:27:15.000-08:00</published><updated>2008-02-22T15:27:15.000-08:00</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#comment'/>
<title type='text'>test66</title>
<content type='text'>test66</content>
<link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU'/>
<link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=2Idhz9ef5oU'/>
<link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments/91F809A3DE2EB81B'/>
<author><name>apitestjhartmann</name><uri>http://gdata.youtube.com/feeds/users/apitestjhartmann</uri></author>
</entry>
<entry>
<id>http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments/A261AEEFD23674AA</id>
<published>2008-02-22T15:27:01.000-08:00</published><updated>2008-02-22T15:27:01.000-08:00</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#comment'/>
<title type='text'>test333</title>
<content type='text'>test333</content>
<link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU'/>
<link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=2Idhz9ef5oU'/>
<link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments/A261AEEFD23674AA'/>
<author><name>apitestjhartmann</name><uri>http://gdata.youtube.com/feeds/users/apitestjhartmann</uri></author>
</entry>
<entry>
<id>http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments/0DCF1E3531B3FF85</id>
<published>2008-02-22T15:11:06.000-08:00</published><updated>2008-02-22T15:11:06.000-08:00</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#comment'/>
<title type='text'>test2</title>
<content type='text'>test2</content>
<link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU'/>
<link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=2Idhz9ef5oU'/>
<link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments/0DCF1E3531B3FF85'/>
<author><name>apitestjhartmann</name><uri>http://gdata.youtube.com/feeds/users/apitestjhartmann</uri></author>
</entry>
</feed>"""
YOUTUBE_PLAYLIST_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:media='http://search.yahoo.com/mrss/'
xmlns:yt='http://gdata.youtube.com/schemas/2007'
xmlns:gd='http://schemas.google.com/g/2005'>
<id>http://gdata.youtube.com/feeds/users/andyland74/playlists?start-index=1&max-results=25</id>
<updated>2008-02-26T00:26:15.635Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#playlistLink'/>
<title type='text'>andyland74's Playlists</title>
<logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo>
<link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/andyland74'/>
<link rel='alternate' type='text/html' href='http://www.youtube.com/profile_play_list?user=andyland74'/>
<link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/andyland74/playlists'/>
<link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/andyland74/playlists?start-index=1&max-results=25'/>
<author>
<name>andyland74</name>
<uri>http://gdata.youtube.com/feeds/users/andyland74</uri>
</author>
<generator version='beta' uri='http://gdata.youtube.com/'>YouTube data API</generator>
<openSearch:totalResults>1</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<yt:description>My new playlist Description</yt:description>
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#playlist' href='http://gdata.youtube.com/feeds/playlists/8BCDD04DE8F771B2'/>
<id>http://gdata.youtube.com/feeds/users/andyland74/playlists/8BCDD04DE8F771B2</id>
<published>2007-11-04T17:30:27.000-08:00</published>
<updated>2008-02-22T09:55:14.000-08:00</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#playlistLink'/>
<title type='text'>My New Playlist Title</title>
<content type='text'>My new playlist Description</content>
<link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/andyland74'/>
<link rel='alternate' type='text/html' href='http://www.youtube.com/view_play_list?p=8BCDD04DE8F771B2'/>
<link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/andyland74/playlists/8BCDD04DE8F771B2'/>
<author>
<name>andyland74</name>
<uri>http://gdata.youtube.com/feeds/users/andyland74</uri>
</author>
</entry>
</feed>"""
YOUTUBE_PLAYLIST_VIDEO_FEED = """<?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gml='http://www.opengis.net/gml' xmlns:georss='http://www.georss.org/georss' xmlns:media='http://search.yahoo.com/mrss/' xmlns:yt='http://gdata.youtube.com/schemas/2007' xmlns:gd='http://schemas.google.com/g/2005'><id>http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505</id><updated>2008-05-16T12:03:17.000-07:00</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#playlist'/><category scheme='http://gdata.youtube.com/schemas/2007/tags.cat' term='videos'/><category scheme='http://gdata.youtube.com/schemas/2007/tags.cat' term='python'/><title type='text'>Test Playlist</title><subtitle type='text'>Test playlist 1</subtitle><logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo><link rel='alternate' type='text/html' href='http://www.youtube.com/view_play_list?p=BCB3BB96DF51B505'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505?start-index=1&max-results=25'/><author><name>gdpython</name><uri>http://gdata.youtube.com/feeds/api/users/gdpython</uri></author><generator version='beta' uri='http://gdata.youtube.com/'>YouTube data API</generator><openSearch:totalResults>1</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><media:group><media:title type='plain'>Test Playlist</media:title><media:description type='plain'>Test playlist 1</media:description><media:content url='http://www.youtube.com/ep.swf?id=BCB3BB96DF51B505' type='application/x-shockwave-flash' yt:format='5'/></media:group><entry><id>http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505/B0F29389E537F888</id><updated>2008-05-16T20:54:08.520Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#playlist'/><title type='text'>Uploading YouTube Videos with the PHP Client Library</title><content type='text'>Jochen Hartmann demonstrates the basics of how to use the PHP Client Library with the YouTube Data API.
PHP Developer's Guide:
http://code.google.com/apis/youtube/developers_guide_php.html
Other documentation:
http://code.google.com/apis/youtube/</content><link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=iIp7OnHXBlo'/><link rel='http://gdata.youtube.com/schemas/2007#video.responses' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/iIp7OnHXBlo/responses'/><link rel='http://gdata.youtube.com/schemas/2007#video.related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/iIp7OnHXBlo/related'/><link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/iIp7OnHXBlo'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505/B0F29389E537F888'/><author><name>GoogleDevelopers</name><uri>http://gdata.youtube.com/feeds/api/users/googledevelopers</uri></author><media:group><media:title type='plain'>Uploading YouTube Videos with the PHP Client Library</media:title><media:description type='plain'>Jochen Hartmann demonstrates the basics of how to use the PHP Client Library with the YouTube Data API.
PHP Developer's Guide:
http://code.google.com/apis/youtube/developers_guide_php.html
Other documentation:
http://code.google.com/apis/youtube/</media:description><media:keywords>api, data, demo, php, screencast, tutorial, uploading, walkthrough, youtube</media:keywords><yt:duration seconds='466'/><media:category label='Education' scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>Education</media:category><media:content url='http://www.youtube.com/v/iIp7OnHXBlo' type='application/x-shockwave-flash' medium='video' isDefault='true' expression='full' duration='466' yt:format='5'/><media:content url='rtsp://rtsp2.youtube.com/ChoLENy73wIaEQlaBtdxOnuKiBMYDSANFEgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='466' yt:format='1'/><media:content url='rtsp://rtsp2.youtube.com/ChoLENy73wIaEQlaBtdxOnuKiBMYESARFEgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='466' yt:format='6'/><media:player url='http://www.youtube.com/watch?v=iIp7OnHXBlo'/><media:thumbnail url='http://img.youtube.com/vi/iIp7OnHXBlo/2.jpg' height='97' width='130' time='00:03:53'/><media:thumbnail url='http://img.youtube.com/vi/iIp7OnHXBlo/1.jpg' height='97' width='130' time='00:01:56.500'/><media:thumbnail url='http://img.youtube.com/vi/iIp7OnHXBlo/3.jpg' height='97' width='130' time='00:05:49.500'/><media:thumbnail url='http://img.youtube.com/vi/iIp7OnHXBlo/0.jpg' height='240' width='320' time='00:03:53'/></media:group><yt:statistics viewCount='1550' favoriteCount='5'/><gd:rating min='1' max='5' numRaters='3' average='4.67'/><yt:location>undefined</yt:location><gd:comments><gd:feedLink href='http://gdata.youtube.com/feeds/api/videos/iIp7OnHXBlo/comments' countHint='2'/></gd:comments><yt:position>1</yt:position></entry></feed>"""
YOUTUBE_SUBSCRIPTION_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:media='http://search.yahoo.com/mrss/'
xmlns:yt='http://gdata.youtube.com/schemas/2007'
xmlns:gd='http://schemas.google.com/g/2005'>
<id>http://gdata.youtube.com/feeds/users/andyland74/subscriptions?start-index=1&max-results=25</id>
<updated>2008-02-26T00:26:15.635Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://gdata.youtube.com/schemas/2007#subscription'/>
<title type='text'>andyland74's Subscriptions</title>
<logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo>
<link rel='related' type='application/atom+xml'
href='http://gdata.youtube.com/feeds/users/andyland74'/>
<link rel='alternate' type='text/html'
href='http://www.youtube.com/profile_subscriptions?user=andyland74'/>
<link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml'
href='http://gdata.youtube.com/feeds/users/andyland74/subscriptions'/>
<link rel='self' type='application/atom+xml'
href='http://gdata.youtube.com/feeds/users/andyland74/subscriptions?start-index=1&max-results=25'/>
<author>
<name>andyland74</name>
<uri>http://gdata.youtube.com/feeds/users/andyland74</uri>
</author>
<generator version='beta' uri='http://gdata.youtube.com/'>YouTube data API</generator>
<openSearch:totalResults>1</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>http://gdata.youtube.com/feeds/users/andyland74/subscriptions/d411759045e2ad8c</id>
<published>2007-11-04T17:30:27.000-08:00</published>
<updated>2008-02-22T09:55:14.000-08:00</updated>
<category scheme='http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat'
term='channel'/>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://gdata.youtube.com/schemas/2007#subscription'/>
<title type='text'>Videos published by : NBC</title>
<link rel='related' type='application/atom+xml'
href='http://gdata.youtube.com/feeds/users/andyland74'/>
<link rel='alternate' type='text/html'
href='http://www.youtube.com/profile_videos?user=NBC'/>
<link rel='self' type='application/atom+xml'
href='http://gdata.youtube.com/feeds/users/andyland74/subscriptions/d411759045e2ad8c'/>
<author>
<name>andyland74</name>
<uri>http://gdata.youtube.com/feeds/users/andyland74</uri>
</author>
<yt:username>NBC</yt:username>
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#user.uploads'
href='http://gdata.youtube.com/feeds/api/users/nbc/uploads'/>
</entry>
</feed>"""
YOUTUBE_VIDEO_RESPONSE_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gml='http://www.opengis.net/gml' xmlns:georss='http://www.georss.org/georss' xmlns:media='http://search.yahoo.com/mrss/' xmlns:yt='http://gdata.youtube.com/schemas/2007' xmlns:gd='http://schemas.google.com/g/2005'>
<id>http://gdata.youtube.com/feeds/videos/2c3q9K4cHzY/responses</id><updated>2008-05-19T22:37:34.076Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#video'/><title type='text'>Videos responses to 'Giant NES controller coffee table'</title><logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo><link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2c3q9K4cHzY'/><link rel='alternate' type='text/html' href='http://www.youtube.com/video_response_view_all?v=2c3q9K4cHzY'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2c3q9K4cHzY/responses'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2c3q9K4cHzY/responses?start-index=1&max-results=25'/><author><name>YouTube</name><uri>http://www.youtube.com/</uri></author><generator version='beta' uri='http://gdata.youtube.com/'>YouTube data API</generator><openSearch:totalResults>8</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>http://gdata.youtube.com/feeds/videos/7b9EnRI9VbY</id><published>2008-03-11T19:08:53.000-07:00</published><updated>2008-05-18T21:33:10.000-07:00</updated>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='OD'/><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#video'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='chat'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='Uncle'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='sex'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='catmint'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='kato'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='kissa'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='katt'/>
<category scheme='http://gdata.youtube.com/schemas/2007/categories.cat' term='Animals' label='Pets & Animals'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='kat'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='cat'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='cats'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='kedi'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='gato'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='Brattman'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='drug'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='overdose'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='catnip'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='party'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='Katze'/><category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='gatto'/>
<title type='text'>Catnip Party</title><content type='html'>snipped</content>
<link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=7b9EnRI9VbY'/>
<link rel='http://gdata.youtube.com/schemas/2007#video.responses' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/7b9EnRI9VbY/responses'/>
<link rel='http://gdata.youtube.com/schemas/2007#video.related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/7b9EnRI9VbY/related'/>
<link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/videos/2c3q9K4cHzY/responses/7b9EnRI9VbY'/>
<author><name>PismoBeach</name><uri>http://gdata.youtube.com/feeds/users/pismobeach</uri></author>
<media:group>
<media:title type='plain'>Catnip Party</media:title>
<media:description type='plain'>Uncle, Hillary, Hankette, and B4 all but overdose on the patio</media:description><media:keywords>Brattman, cat, catmint, catnip, cats, chat, drug, gato, gatto, kat, kato, katt, Katze, kedi, kissa, OD, overdose, party, sex, Uncle</media:keywords>
<yt:duration seconds='139'/>
<media:category label='Pets & Animals' scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>Animals</media:category>
<media:content url='http://www.youtube.com/v/7b9EnRI9VbY' type='application/x-shockwave-flash' medium='video' isDefault='true' expression='full' duration='139' yt:format='5'/>
<media:content url='rtsp://rtsp2.youtube.com/ChoLENy73wIaEQm2VT0SnUS_7RMYDSANFEgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='139' yt:format='1'/>
<media:content url='rtsp://rtsp2.youtube.com/ChoLENy73wIaEQm2VT0SnUS_7RMYESARFEgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='139' yt:format='6'/>
<media:player url='http://www.youtube.com/watch?v=7b9EnRI9VbY'/>
<media:thumbnail url='http://img.youtube.com/vi/7b9EnRI9VbY/2.jpg' height='97' width='130' time='00:01:09.500'/>
<media:thumbnail url='http://img.youtube.com/vi/7b9EnRI9VbY/1.jpg' height='97' width='130' time='00:00:34.750'/>
<media:thumbnail url='http://img.youtube.com/vi/7b9EnRI9VbY/3.jpg' height='97' width='130' time='00:01:44.250'/>
<media:thumbnail url='http://img.youtube.com/vi/7b9EnRI9VbY/0.jpg' height='240' width='320' time='00:01:09.500'/>
</media:group>
<yt:statistics viewCount='4235' favoriteCount='3'/>
<gd:rating min='1' max='5' numRaters='24' average='3.54'/>
<gd:comments>
<gd:feedLink href='http://gdata.youtube.com/feeds/videos/7b9EnRI9VbY/comments' countHint='14'/>
</gd:comments>
</entry>
</feed>
"""
YOUTUBE_PROFILE = """<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:media='http://search.yahoo.com/mrss/'
xmlns:yt='http://gdata.youtube.com/schemas/2007'
xmlns:gd='http://schemas.google.com/g/2005'>
<id>http://gdata.youtube.com/feeds/users/andyland74</id>
<published>2006-10-16T00:09:45.000-07:00</published>
<updated>2008-02-26T11:48:21.000-08:00</updated>
<category scheme='http://gdata.youtube.com/schemas/2007/channeltypes.cat'
term='Standard'/>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://gdata.youtube.com/schemas/2007#userProfile'/>
<title type='text'>andyland74 Channel</title>
<link rel='alternate' type='text/html'
href='http://www.youtube.com/profile?user=andyland74'/>
<link rel='self' type='application/atom+xml'
href='http://gdata.youtube.com/feeds/users/andyland74'/>
<author>
<name>andyland74</name>
<uri>http://gdata.youtube.com/feeds/users/andyland74</uri>
</author>
<yt:age>33</yt:age>
<yt:username>andyland74</yt:username>
<yt:firstName>andy</yt:firstName>
<yt:lastName>example</yt:lastName>
<yt:books>Catch-22</yt:books>
<yt:gender>m</yt:gender>
<yt:company>Google</yt:company>
<yt:hobbies>Testing YouTube APIs</yt:hobbies>
<yt:hometown>Somewhere</yt:hometown>
<yt:location>US</yt:location>
<yt:movies>Aqua Teen Hungerforce</yt:movies>
<yt:music>Elliott Smith</yt:music>
<yt:occupation>Technical Writer</yt:occupation>
<yt:school>University of North Carolina</yt:school>
<media:thumbnail url='http://i.ytimg.com/vi/YFbSxcdOL-w/default.jpg'/>
<yt:statistics viewCount='9' videoWatchCount='21' subscriberCount='1'
lastWebAccess='2008-02-25T16:03:38.000-08:00'/>
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#user.favorites'
href='http://gdata.youtube.com/feeds/users/andyland74/favorites' countHint='4'/>
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#user.contacts'
href='http://gdata.youtube.com/feeds/users/andyland74/contacts' countHint='1'/>
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#user.inbox'
href='http://gdata.youtube.com/feeds/users/andyland74/inbox' countHint='0'/>
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#user.playlists'
href='http://gdata.youtube.com/feeds/users/andyland74/playlists'/>
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#user.subscriptions'
href='http://gdata.youtube.com/feeds/users/andyland74/subscriptions' countHint='4'/>
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#user.uploads'
href='http://gdata.youtube.com/feeds/users/andyland74/uploads' countHint='1'/>
</entry>"""
YOUTUBE_CONTACTS_FEED = """<?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:yt='http://gdata.youtube.com/schemas/2007' xmlns:gd='http://schemas.google.com/g/2005'>
<id>http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts</id><updated>2008-05-16T19:24:34.916Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#friend'/><title type='text'>apitestjhartmann's Contacts</title><logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo><link rel='alternate' type='text/html' href='http://www.youtube.com/profile_friends?user=apitestjhartmann'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts'/><link rel='http://schemas.google.com/g/2005#post' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts?start-index=1&max-results=25'/><author><name>apitestjhartmann</name><uri>http://gdata.youtube.com/feeds/users/apitestjhartmann</uri></author><generator version='beta' uri='http://gdata.youtube.com/'>YouTube data API</generator><openSearch:totalResults>2</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts/test89899090</id><published>2008-02-04T11:27:54.000-08:00</published><updated>2008-05-16T19:24:34.916Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#friend'/><title type='text'>test89899090</title><link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/test89899090'/><link rel='alternate' type='text/html' href='http://www.youtube.com/profile?user=test89899090'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts/test89899090'/><link rel='edit' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts/test89899090'/><author><name>apitestjhartmann</name><uri>http://gdata.youtube.com/feeds/users/apitestjhartmann</uri></author><yt:username>test89899090</yt:username><yt:status>requested</yt:status></entry>
<entry>
<id>http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts/testjfisher</id><published>2008-02-26T14:13:03.000-08:00</published><updated>2008-05-16T19:24:34.916Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#friend'/><title type='text'>testjfisher</title><link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/testjfisher'/><link rel='alternate' type='text/html' href='http://www.youtube.com/profile?user=testjfisher'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts/testjfisher'/><link rel='edit' type='application/atom+xml' href='http://gdata.youtube.com/feeds/users/apitestjhartmann/contacts/testjfisher'/><author><name>apitestjhartmann</name><uri>http://gdata.youtube.com/feeds/users/apitestjhartmann</uri></author><yt:username>testjfisher</yt:username><yt:status>pending</yt:status></entry>
</feed>"""
NEW_CONTACT = """<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:gd='http://schemas.google.com/g/2005'
xmlns:gContact='http://schemas.google.com/contact/2008'>
<id>http://www.google.com/m8/feeds/contacts/liz%40gmail.com/base/8411573</id>
<updated>2008-02-28T18:47:02.303Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/contact/2008#contact' />
<title type='text'>Fitzgerald</title>
<content type='text'>Notes</content>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full/8411573' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full/8411573/1204224422303000' />
<gd:email rel='http://schemas.google.com/g/2005#work'
address='liz@gmail.com' />
<gd:email rel='http://schemas.google.com/g/2005#home'
address='liz@example.org' />
<gd:phoneNumber rel='http://schemas.google.com/g/2005#work'
primary='true'>(206)555-1212</gd:phoneNumber>
<gd:phoneNumber rel='http://schemas.google.com/g/2005#other'
primary='true'>456-123-2133</gd:phoneNumber>
<gd:phoneNumber rel='http://schemas.google.com/g/2005#home'>(206)555-1213</gd:phoneNumber>
<gd:extendedProperty name="pet" value="hamster" />
<gd:extendedProperty name="cousine">
<italian />
</gd:extendedProperty>
<gContact:groupMembershipInfo deleted="false" href="http://google.com/m8/feeds/groups/liz%40gmail.com/base/270f" />
<gd:im address='liz@gmail.com'
protocol='http://schemas.google.com/g/2005#GOOGLE_TALK'
rel='http://schemas.google.com/g/2005#home' />
<gd:postalAddress rel='http://schemas.google.com/g/2005#work'
primary='true'>1600 Amphitheatre Pkwy Mountain View</gd:postalAddress>
</entry>"""
CONTACTS_FEED = """<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:gd='http://schemas.google.com/g/2005'
xmlns:gContact='http://schemas.google.com/contact/2008'
xmlns:batch='http://schemas.google.com/gdata/batch'>
<id>http://www.google.com/m8/feeds/contacts/liz%40gmail.com/base</id>
<updated>2008-03-05T12:36:38.836Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/contact/2008#contact' />
<title type='text'>Contacts</title>
<link rel='http://schemas.google.com/g/2005#feed'
type='application/atom+xml'
href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full' />
<link rel='http://schemas.google.com/g/2005#post'
type='application/atom+xml'
href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full' />
<link rel='http://schemas.google.com/g/2005#batch'
type='application/atom+xml'
href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full/batch' />
<link rel='self' type='application/atom+xml'
href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full?max-results=25' />
<author>
<name>Elizabeth Bennet</name>
<email>liz@gmail.com</email>
</author>
<generator version='1.0' uri='http://www.google.com/m8/feeds/contacts'>
Contacts
</generator>
<openSearch:totalResults>1</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>
http://www.google.com/m8/feeds/contacts/liz%40gmail.com/base/c9012de
</id>
<updated>2008-03-05T12:36:38.835Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/contact/2008#contact' />
<title type='text'>Fitzgerald</title>
<link rel="http://schemas.google.com/contacts/2008/rel#photo" type="image/*"
href="http://google.com/m8/feeds/photos/media/liz%40gmail.com/c9012de"/>
<link rel="http://schemas.google.com/contacts/2008/rel#edit-photo" type="image/*"
href="http://www.google.com/m8/feeds/photos/media/liz%40gmail.com/c9012de/photo4524"/>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full/c9012de' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full/c9012de/1204720598835000' />
<gd:phoneNumber rel='http://schemas.google.com/g/2005#home'
primary='true'>
456
</gd:phoneNumber>
<gd:extendedProperty name="pet" value="hamster" />
<gContact:groupMembershipInfo deleted="false" href="http://google.com/m8/feeds/groups/liz%40gmail.com/base/270f" />
</entry>
</feed>"""
CONTACT_GROUPS_FEED = """<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:gContact="http://schemas.google.com/contact/2008"
xmlns:batch="http://schemas.google.com/gdata/batch"
xmlns:gd="http://schemas.google.com/g/2005">
<id>jo@gmail.com</id>
<updated>2008-05-21T21:11:25.237Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/contact/2008#group"/>
<title type="text">Jo's Contact Groups</title>
<link rel="alternate" type="text/html" href="http://www.google.com/"/>
<link rel="http://schemas.google.com/g/2005#feed"
type="application/atom+xml"
href="http://google.m/m8/feeds/groups/jo%40gmail.com/thin"/>
<link rel="http://schemas.google.com/g/2005#post"
type="application/atom+xml"
href="http://google.m/m8/feeds/groups/jo%40gmail.com/thin"/>
<link rel="http://schemas.google.com/g/2005#batch"
type="application/atom+xml"
href="http://googleom/m8/feeds/groups/jo%40gmail.com/thin/batch"/>
<link rel="self"
type="application/atom+xml"
href="http://google.com/m8/feeds/groups/jo%40gmail.com/thin?max-results=25"/>
<author>
<name>Jo Brown</name>
<email>jo@gmail.com</email>
</author>
<generator version="1.0" uri="http://google.com/m8/feeds">Contacts</generator>
<openSearch:totalResults>3</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>http://google.com/m8/feeds/groups/jo%40gmail.com/base/270f</id>
<updated>2008-05-14T13:10:19.070Z</updated>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/contact/2008#group"/>
<title type="text">joggers</title>
<content type="text">joggers</content>
<link rel="self" type="application/atom+xml"
href="http://google.com/m8/feeds/groups/jo%40gmail.com/thin/270f"/>
<link rel="edit" type="application/atom+xml"
href="http://google.com/m8/feeds/groups/jo%40gmail.com/thin/270f/1210770619070000"/>
</entry>
</feed>"""
CONTACT_GROUP_ENTRY = """<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:gd="http://schemas.google.com/g/2005">
<category scheme="http://schemas.google.com/g/2005#kind"
term="http://schemas.google.com/g/2005#group"/>
<id>http://www.google.com/feeds/groups/jo%40gmail.com/base/1234</id>
<published>2005-01-18T21:00:00Z</published>
<updated>2006-01-01T00:00:00Z</updated>
<title type="text">Salsa group</title>
<content type="text">Salsa group</content>
<link rel='self' type='application/atom+xml'
href= 'http://www.google.com/m8/feeds/groups/jo%40gmail.com/full/2' />
<link rel='edit' type='application/atom+xml'
href='http://www.google.com/m8/feeds/groups/jo%40gmail.com/full/2/0'/>
<gd:extendedProperty name="more info about the group">
<info>Very nice people.</info>
</gd:extendedProperty>
</entry>"""
BLOG_ENTRY = """<entry xmlns='http://www.w3.org/2005/Atom'>
<id>tag:blogger.com,1999:blog-blogID.post-postID</id>
<published>2006-08-02T18:44:43.089-07:00</published>
<updated>2006-11-08T18:10:23.020-08:00</updated>
<title type='text'>Lizzy's Diary</title>
<summary type='html'>Being the journal of Elizabeth Bennet</summary>
<link rel='alternate' type='text/html'
href='http://blogName.blogspot.com/'>
</link>
<link rel='http://schemas.google.com/g/2005#feed'
type='application/atom+xml'
href='http://blogName.blogspot.com/feeds/posts/default'>
</link>
<link rel='http://schemas.google.com/g/2005#post'
type='application/atom+xml'
href='http://www.blogger.com/feeds/blogID/posts/default'>
</link>
<link rel='self' type='application/atom+xml'
href='http://www.blogger.com/feeds/userID/blogs/blogID'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.blogger.com/feeds/userID/blogs/blogID'>
</link>
<author>
<name>Elizabeth Bennet</name>
<email>liz@gmail.com</email>
</author>
</entry>"""
BLOG_POST = """<entry xmlns='http://www.w3.org/2005/Atom'>
<title type='text'>Marriage!</title>
<content type='xhtml'>
<div xmlns="http://www.w3.org/1999/xhtml">
<p>Mr. Darcy has <em>proposed marriage</em> to me!</p>
<p>He is the last man on earth I would ever desire to marry.</p>
<p>Whatever shall I do?</p>
</div>
</content>
<author>
<name>Elizabeth Bennet</name>
<email>liz@gmail.com</email>
</author>
</entry>"""
BLOG_POSTS_FEED = """<feed xmlns='http://www.w3.org/2005/Atom'>
<id>tag:blogger.com,1999:blog-blogID</id>
<updated>2006-11-08T18:10:23.020-08:00</updated>
<title type='text'>Lizzy's Diary</title>
<link rel='alternate' type='text/html'
href='http://blogName.blogspot.com/index.html'>
</link>
<link rel='http://schemas.google.com/g/2005#feed'
type='application/atom+xml'
href='http://blogName.blogspot.com/feeds/posts/default'>
</link>
<link rel='self' type='application/atom+xml'
href='http://blogName.blogspot.com/feeds/posts/default'>
</link>
<author>
<name>Elizabeth Bennet</name>
<email>liz@gmail.com</email>
</author>
<generator version='7.00' uri='http://www2.blogger.com'>Blogger</generator>
<entry>
<id>tag:blogger.com,1999:blog-blogID.post-postID</id>
<published>2006-11-08T18:10:00.000-08:00</published>
<updated>2006-11-08T18:10:14.954-08:00</updated>
<title type='text'>Quite disagreeable</title>
<content type='html'><p>I met Mr. Bingley's friend Mr. Darcy
this evening. I found him quite disagreeable.</p></content>
<link rel='alternate' type='text/html'
href='http://blogName.blogspot.com/2006/11/quite-disagreeable.html'>
</link>
<link rel='self' type='application/atom+xml'
href='http://blogName.blogspot.com/feeds/posts/default/postID'>
</link>
<link rel='edit' type='application/atom+xml'
href='http://www.blogger.com/feeds/blogID/posts/default/postID'>
</link>
<author>
<name>Elizabeth Bennet</name>
<email>liz@gmail.com</email>
</author>
</entry>
</feed>"""
BLOG_COMMENTS_FEED = """<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/">
<id>tag:blogger.com,1999:blog-blogID.postpostID..comments</id>
<updated>2007-04-04T21:56:29.803-07:00</updated>
<title type="text">My Blog : Time to relax</title>
<link rel="alternate" type="text/html" href="http://blogName.blogspot.com/2007/04/first-post.html"/>
<link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://blogName.blogspot.com/feeds/postID/comments/default"/>
<link rel="self" type="application/atom+xml" href="http://blogName.blogspot.com/feeds/postID/comments/default"/>
<author>
<name>Blog Author name</name>
</author>
<generator version="7.00" uri="http://www2.blogger.com">Blogger</generator>
<openSearch:totalResults>1</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<entry>
<id>tag:blogger.com,1999:blog-blogID.post-commentID</id>
<published>2007-04-04T21:56:00.000-07:00</published>
<updated>2007-04-04T21:56:29.803-07:00</updated>
<title type="text">This is my first comment</title>
<content type="html">This is my first comment</content>
<link rel="alternate" type="text/html" href="http://blogName.blogspot.com/2007/04/first-post.html#commentID"/>
<link rel="self" type="application/atom+xml" href="http://blogName.blogspot.com/feeds/postID/comments/default/commentID"/>
<link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/blogID/postID/comments/default/commentID"/>
<author>
<name>Blog Author name</name>
</author>
<thr:in-reply-to xmlns:thr='http://purl.org/syndication/thread/1.0'
href='http://blogName.blogspot.com/2007/04/first-post.html'
ref='tag:blogger.com,1999:blog-blogID.post-postID'
source='http://blogName.blogspot.com/feeds/posts/default/postID'
type='text/html' />
</entry>
</feed>"""
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains classes representing Google Data elements.
Extends Atom classes to add Google Data specific elements.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
import os
import atom
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
# XML namespaces which are often used in GData entities.
GDATA_NAMESPACE = 'http://schemas.google.com/g/2005'
GDATA_TEMPLATE = '{http://schemas.google.com/g/2005}%s'
OPENSEARCH_NAMESPACE = 'http://a9.com/-/spec/opensearchrss/1.0/'
OPENSEARCH_TEMPLATE = '{http://a9.com/-/spec/opensearchrss/1.0/}%s'
BATCH_NAMESPACE = 'http://schemas.google.com/gdata/batch'
GACL_NAMESPACE = 'http://schemas.google.com/acl/2007'
GACL_TEMPLATE = '{http://schemas.google.com/acl/2007}%s'
# Labels used in batch request entries to specify the desired CRUD operation.
BATCH_INSERT = 'insert'
BATCH_UPDATE = 'update'
BATCH_DELETE = 'delete'
BATCH_QUERY = 'query'
class Error(Exception):
pass
class MissingRequiredParameters(Error):
pass
class MediaSource(object):
"""GData Entries can refer to media sources, so this class provides a
place to store references to these objects along with some metadata.
"""
def __init__(self, file_handle=None, content_type=None, content_length=None,
file_path=None, file_name=None):
"""Creates an object of type MediaSource.
Args:
file_handle: A file handle pointing to the file to be encapsulated in the
MediaSource
content_type: string The MIME type of the file. Required if a file_handle
is given.
content_length: int The size of the file. Required if a file_handle is
given.
file_path: string (optional) A full path name to the file. Used in
place of a file_handle.
file_name: string The name of the file without any path information.
Required if a file_handle is given.
"""
self.file_handle = file_handle
self.content_type = content_type
self.content_length = content_length
self.file_name = file_name
if (file_handle is None and content_type is not None and
file_path is not None):
self.setFile(file_path, content_type)
def setFile(self, file_name, content_type):
"""A helper function which can create a file handle from a given filename
and set the content type and length all at once.
Args:
file_name: string The path and file name to the file containing the media
content_type: string A MIME type representing the type of the media
"""
self.file_handle = open(file_name, 'rb')
self.content_type = content_type
self.content_length = os.path.getsize(file_name)
self.file_name = os.path.basename(file_name)
class LinkFinder(atom.LinkFinder):
"""An "interface" providing methods to find link elements
GData Entry elements often contain multiple links which differ in the rel
attribute or content type. Often, developers are interested in a specific
type of link so this class provides methods to find specific classes of
links.
This class is used as a mixin in GData entries.
"""
def GetSelfLink(self):
"""Find the first link with rel set to 'self'
Returns:
An atom.Link or none if none of the links had rel equal to 'self'
"""
for a_link in self.link:
if a_link.rel == 'self':
return a_link
return None
def GetEditLink(self):
for a_link in self.link:
if a_link.rel == 'edit':
return a_link
return None
def GetEditMediaLink(self):
"""The Picasa API mistakenly returns media-edit rather than edit-media, but
this may change soon.
"""
for a_link in self.link:
if a_link.rel == 'edit-media':
return a_link
if a_link.rel == 'media-edit':
return a_link
return None
def GetHtmlLink(self):
"""Find the first link with rel of alternate and type of text/html
Returns:
An atom.Link or None if no links matched
"""
for a_link in self.link:
if a_link.rel == 'alternate' and a_link.type == 'text/html':
return a_link
return None
def GetPostLink(self):
"""Get a link containing the POST target URL.
The POST target URL is used to insert new entries.
Returns:
A link object with a rel matching the POST type.
"""
for a_link in self.link:
if a_link.rel == 'http://schemas.google.com/g/2005#post':
return a_link
return None
def GetAclLink(self):
for a_link in self.link:
if a_link.rel == 'http://schemas.google.com/acl/2007#accessControlList':
return a_link
return None
def GetFeedLink(self):
for a_link in self.link:
if a_link.rel == 'http://schemas.google.com/g/2005#feed':
return a_link
return None
def GetNextLink(self):
for a_link in self.link:
if a_link.rel == 'next':
return a_link
return None
class TotalResults(atom.AtomBase):
"""opensearch:TotalResults for a GData feed"""
_tag = 'totalResults'
_namespace = OPENSEARCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def TotalResultsFromString(xml_string):
return atom.CreateClassFromXMLString(TotalResults, xml_string)
class StartIndex(atom.AtomBase):
"""The opensearch:startIndex element in GData feed"""
_tag = 'startIndex'
_namespace = OPENSEARCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def StartIndexFromString(xml_string):
return atom.CreateClassFromXMLString(StartIndex, xml_string)
class ItemsPerPage(atom.AtomBase):
"""The opensearch:itemsPerPage element in GData feed"""
_tag = 'itemsPerPage'
_namespace = OPENSEARCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ItemsPerPageFromString(xml_string):
return atom.CreateClassFromXMLString(ItemsPerPage, xml_string)
class ExtendedProperty(atom.AtomBase):
"""The Google Data extendedProperty element.
Used to store arbitrary key-value information specific to your
application. The value can either be a text string stored as an XML
attribute (.value), or an XML node (XmlBlob) as a child element.
This element is used in the Google Calendar data API and the Google
Contacts data API.
"""
_tag = 'extendedProperty'
_namespace = GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['name'] = 'name'
_attributes['value'] = 'value'
def __init__(self, name=None, value=None, extension_elements=None,
extension_attributes=None, text=None):
self.name = name
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GetXmlBlobExtensionElement(self):
"""Returns the XML blob as an atom.ExtensionElement.
Returns:
An atom.ExtensionElement representing the blob's XML, or None if no
blob was set.
"""
if len(self.extension_elements) < 1:
return None
else:
return self.extension_elements[0]
def GetXmlBlobString(self):
"""Returns the XML blob as a string.
Returns:
A string containing the blob's XML, or None if no blob was set.
"""
blob = self.GetXmlBlobExtensionElement()
if blob:
return blob.ToString()
return None
def SetXmlBlob(self, blob):
"""Sets the contents of the extendedProperty to XML as a child node.
Since the extendedProperty is only allowed one child element as an XML
blob, setting the XML blob will erase any preexisting extension elements
in this object.
Args:
blob: str, ElementTree Element or atom.ExtensionElement representing
the XML blob stored in the extendedProperty.
"""
# Erase any existing extension_elements, clears the child nodes from the
# extendedProperty.
self.extension_elements = []
if isinstance(blob, atom.ExtensionElement):
self.extension_elements.append(blob)
elif ElementTree.iselement(blob):
self.extension_elements.append(atom._ExtensionElementFromElementTree(
blob))
else:
self.extension_elements.append(atom.ExtensionElementFromString(blob))
def ExtendedPropertyFromString(xml_string):
return atom.CreateClassFromXMLString(ExtendedProperty, xml_string)
class GDataEntry(atom.Entry, LinkFinder):
"""Extends Atom Entry to provide data processing"""
_tag = atom.Entry._tag
_namespace = atom.Entry._namespace
_children = atom.Entry._children.copy()
_attributes = atom.Entry._attributes.copy()
def __GetId(self):
return self.__id
# This method was created to strip the unwanted whitespace from the id's
# text node.
def __SetId(self, id):
self.__id = id
if id is not None and id.text is not None:
self.__id.text = id.text.strip()
id = property(__GetId, __SetId)
def IsMedia(self):
"""Determines whether or not an entry is a GData Media entry.
"""
if (self.GetEditMediaLink()):
return True
else:
return False
def GetMediaURL(self):
"""Returns the URL to the media content, if the entry is a media entry.
Otherwise returns None.
"""
if not self.IsMedia():
return None
else:
return self.content.src
def GDataEntryFromString(xml_string):
"""Creates a new GDataEntry instance given a string of XML."""
return atom.CreateClassFromXMLString(GDataEntry, xml_string)
class GDataFeed(atom.Feed, LinkFinder):
"""A Feed from a GData service"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = atom.Feed._children.copy()
_attributes = atom.Feed._attributes.copy()
_children['{%s}totalResults' % OPENSEARCH_NAMESPACE] = ('total_results',
TotalResults)
_children['{%s}startIndex' % OPENSEARCH_NAMESPACE] = ('start_index',
StartIndex)
_children['{%s}itemsPerPage' % OPENSEARCH_NAMESPACE] = ('items_per_page',
ItemsPerPage)
# Add a conversion rule for atom:entry to make it into a GData
# Entry.
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GDataEntry])
def __GetId(self):
return self.__id
def __SetId(self, id):
self.__id = id
if id is not None and id.text is not None:
self.__id.text = id.text.strip()
id = property(__GetId, __SetId)
def __GetGenerator(self):
return self.__generator
def __SetGenerator(self, generator):
self.__generator = generator
if generator is not None:
self.__generator.text = generator.text.strip()
generator = property(__GetGenerator, __SetGenerator)
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None, entry=None,
total_results=None, start_index=None, items_per_page=None,
extension_elements=None, extension_attributes=None, text=None):
"""Constructor for Source
Args:
author: list (optional) A list of Author instances which belong to this
class.
category: list (optional) A list of Category instances
contributor: list (optional) A list on Contributor instances
generator: Generator (optional)
icon: Icon (optional)
id: Id (optional) The entry's Id element
link: list (optional) A list of Link instances
logo: Logo (optional)
rights: Rights (optional) The entry's Rights element
subtitle: Subtitle (optional) The entry's subtitle element
title: Title (optional) the entry's title element
updated: Updated (optional) the entry's updated element
entry: list (optional) A list of the Entry instances contained in the
feed.
text: String (optional) The text contents of the element. This is the
contents of the Entry's XML text node.
(Example: <foo>This is the text</foo>)
extension_elements: list (optional) A list of ExtensionElement instances
which are children of this element.
extension_attributes: dict (optional) A dictionary of strings which are
the values for additional XML attributes of this element.
"""
self.author = author or []
self.category = category or []
self.contributor = contributor or []
self.generator = generator
self.icon = icon
self.id = atom_id
self.link = link or []
self.logo = logo
self.rights = rights
self.subtitle = subtitle
self.title = title
self.updated = updated
self.entry = entry or []
self.total_results = total_results
self.start_index = start_index
self.items_per_page = items_per_page
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GDataFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GDataFeed, xml_string)
class BatchId(atom.AtomBase):
_tag = 'id'
_namespace = BATCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def BatchIdFromString(xml_string):
return atom.CreateClassFromXMLString(BatchId, xml_string)
class BatchOperation(atom.AtomBase):
_tag = 'operation'
_namespace = BATCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['type'] = 'type'
def __init__(self, op_type=None, extension_elements=None,
extension_attributes=None,
text=None):
self.type = op_type
atom.AtomBase.__init__(self,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def BatchOperationFromString(xml_string):
return atom.CreateClassFromXMLString(BatchOperation, xml_string)
class BatchStatus(atom.AtomBase):
"""The batch:status element present in a batch response entry.
A status element contains the code (HTTP response code) and
reason as elements. In a single request these fields would
be part of the HTTP response, but in a batch request each
Entry operation has a corresponding Entry in the response
feed which includes status information.
See http://code.google.com/apis/gdata/batch.html#Handling_Errors
"""
_tag = 'status'
_namespace = BATCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['code'] = 'code'
_attributes['reason'] = 'reason'
_attributes['content-type'] = 'content_type'
def __init__(self, code=None, reason=None, content_type=None,
extension_elements=None, extension_attributes=None, text=None):
self.code = code
self.reason = reason
self.content_type = content_type
atom.AtomBase.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def BatchStatusFromString(xml_string):
return atom.CreateClassFromXMLString(BatchStatus, xml_string)
class BatchEntry(GDataEntry):
"""An atom:entry for use in batch requests.
The BatchEntry contains additional members to specify the operation to be
performed on this entry and a batch ID so that the server can reference
individual operations in the response feed. For more information, see:
http://code.google.com/apis/gdata/batch.html
"""
_tag = GDataEntry._tag
_namespace = GDataEntry._namespace
_children = GDataEntry._children.copy()
_children['{%s}operation' % BATCH_NAMESPACE] = ('batch_operation', BatchOperation)
_children['{%s}id' % BATCH_NAMESPACE] = ('batch_id', BatchId)
_children['{%s}status' % BATCH_NAMESPACE] = ('batch_status', BatchStatus)
_attributes = GDataEntry._attributes.copy()
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, control=None, title=None, updated=None,
batch_operation=None, batch_id=None, batch_status=None,
extension_elements=None, extension_attributes=None, text=None):
self.batch_operation = batch_operation
self.batch_id = batch_id
self.batch_status = batch_status
GDataEntry.__init__(self, author=author, category=category,
content=content, contributor=contributor, atom_id=atom_id, link=link,
published=published, rights=rights, source=source, summary=summary,
control=control, title=title, updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes, text=text)
def BatchEntryFromString(xml_string):
return atom.CreateClassFromXMLString(BatchEntry, xml_string)
class BatchInterrupted(atom.AtomBase):
"""The batch:interrupted element sent if batch request was interrupted.
Only appears in a feed if some of the batch entries could not be processed.
See: http://code.google.com/apis/gdata/batch.html#Handling_Errors
"""
_tag = 'interrupted'
_namespace = BATCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['reason'] = 'reason'
_attributes['success'] = 'success'
_attributes['failures'] = 'failures'
_attributes['parsed'] = 'parsed'
def __init__(self, reason=None, success=None, failures=None, parsed=None,
extension_elements=None, extension_attributes=None, text=None):
self.reason = reason
self.success = success
self.failures = failures
self.parsed = parsed
atom.AtomBase.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def BatchInterruptedFromString(xml_string):
return atom.CreateClassFromXMLString(BatchInterrupted, xml_string)
class BatchFeed(GDataFeed):
"""A feed containing a list of batch request entries."""
_tag = GDataFeed._tag
_namespace = GDataFeed._namespace
_children = GDataFeed._children.copy()
_attributes = GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [BatchEntry])
_children['{%s}interrupted' % BATCH_NAMESPACE] = ('interrupted', BatchInterrupted)
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None, entry=None,
total_results=None, start_index=None, items_per_page=None,
interrupted=None,
extension_elements=None, extension_attributes=None, text=None):
self.interrupted = interrupted
GDataFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results, start_index=start_index,
items_per_page=items_per_page,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def AddBatchEntry(self, entry=None, id_url_string=None,
batch_id_string=None, operation_string=None):
"""Logic for populating members of a BatchEntry and adding to the feed.
If the entry is not a BatchEntry, it is converted to a BatchEntry so
that the batch specific members will be present.
The id_url_string can be used in place of an entry if the batch operation
applies to a URL. For example query and delete operations require just
the URL of an entry, no body is sent in the HTTP request. If an
id_url_string is sent instead of an entry, a BatchEntry is created and
added to the feed.
This method also assigns the desired batch id to the entry so that it
can be referenced in the server's response. If the batch_id_string is
None, this method will assign a batch_id to be the index at which this
entry will be in the feed's entry list.
Args:
entry: BatchEntry, atom.Entry, or another Entry flavor (optional) The
entry which will be sent to the server as part of the batch request.
The item must have a valid atom id so that the server knows which
entry this request references.
id_url_string: str (optional) The URL of the entry to be acted on. You
can find this URL in the text member of the atom id for an entry.
If an entry is not sent, this id will be used to construct a new
BatchEntry which will be added to the request feed.
batch_id_string: str (optional) The batch ID to be used to reference
this batch operation in the results feed. If this parameter is None,
the current length of the feed's entry array will be used as a
count. Note that batch_ids should either always be specified or
never, mixing could potentially result in duplicate batch ids.
operation_string: str (optional) The desired batch operation which will
set the batch_operation.type member of the entry. Options are
'insert', 'update', 'delete', and 'query'
Raises:
MissingRequiredParameters: Raised if neither an id_ url_string nor an
entry are provided in the request.
Returns:
The added entry.
"""
if entry is None and id_url_string is None:
raise MissingRequiredParameters('supply either an entry or URL string')
if entry is None and id_url_string is not None:
entry = BatchEntry(atom_id=atom.Id(text=id_url_string))
# TODO: handle cases in which the entry lacks batch_... members.
#if not isinstance(entry, BatchEntry):
# Convert the entry to a batch entry.
if batch_id_string is not None:
entry.batch_id = BatchId(text=batch_id_string)
elif entry.batch_id is None or entry.batch_id.text is None:
entry.batch_id = BatchId(text=str(len(self.entry)))
if operation_string is not None:
entry.batch_operation = BatchOperation(op_type=operation_string)
self.entry.append(entry)
return entry
def AddInsert(self, entry, batch_id_string=None):
"""Add an insert request to the operations in this batch request feed.
If the entry doesn't yet have an operation or a batch id, these will
be set to the insert operation and a batch_id specified as a parameter.
Args:
entry: BatchEntry The entry which will be sent in the batch feed as an
insert request.
batch_id_string: str (optional) The batch ID to be used to reference
this batch operation in the results feed. If this parameter is None,
the current length of the feed's entry array will be used as a
count. Note that batch_ids should either always be specified or
never, mixing could potentially result in duplicate batch ids.
"""
entry = self.AddBatchEntry(entry=entry, batch_id_string=batch_id_string,
operation_string=BATCH_INSERT)
def AddUpdate(self, entry, batch_id_string=None):
"""Add an update request to the list of batch operations in this feed.
Sets the operation type of the entry to insert if it is not already set
and assigns the desired batch id to the entry so that it can be
referenced in the server's response.
Args:
entry: BatchEntry The entry which will be sent to the server as an
update (HTTP PUT) request. The item must have a valid atom id
so that the server knows which entry to replace.
batch_id_string: str (optional) The batch ID to be used to reference
this batch operation in the results feed. If this parameter is None,
the current length of the feed's entry array will be used as a
count. See also comments for AddInsert.
"""
entry = self.AddBatchEntry(entry=entry, batch_id_string=batch_id_string,
operation_string=BATCH_UPDATE)
def AddDelete(self, url_string=None, entry=None, batch_id_string=None):
"""Adds a delete request to the batch request feed.
This method takes either the url_string which is the atom id of the item
to be deleted, or the entry itself. The atom id of the entry must be
present so that the server knows which entry should be deleted.
Args:
url_string: str (optional) The URL of the entry to be deleted. You can
find this URL in the text member of the atom id for an entry.
entry: BatchEntry (optional) The entry to be deleted.
batch_id_string: str (optional)
Raises:
MissingRequiredParameters: Raised if neither a url_string nor an entry
are provided in the request.
"""
entry = self.AddBatchEntry(entry=entry, id_url_string=url_string,
batch_id_string=batch_id_string,
operation_string=BATCH_DELETE)
def AddQuery(self, url_string=None, entry=None, batch_id_string=None):
"""Adds a query request to the batch request feed.
This method takes either the url_string which is the query URL
whose results will be added to the result feed. The query URL will
be encapsulated in a BatchEntry, and you may pass in the BatchEntry
with a query URL instead of sending a url_string.
Args:
url_string: str (optional)
entry: BatchEntry (optional)
batch_id_string: str (optional)
Raises:
MissingRequiredParameters
"""
entry = self.AddBatchEntry(entry=entry, id_url_string=url_string,
batch_id_string=batch_id_string,
operation_string=BATCH_QUERY)
def GetBatchLink(self):
for link in self.link:
if link.rel == 'http://schemas.google.com/g/2005#batch':
return link
return None
def BatchFeedFromString(xml_string):
return atom.CreateClassFromXMLString(BatchFeed, xml_string)
class EntryLink(atom.AtomBase):
"""The gd:entryLink element"""
_tag = 'entryLink'
_namespace = GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
# The entry used to be an atom.Entry, now it is a GDataEntry.
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', GDataEntry)
_attributes['rel'] = 'rel',
_attributes['readOnly'] = 'read_only'
_attributes['href'] = 'href'
def __init__(self, href=None, read_only=None, rel=None,
entry=None, extension_elements=None,
extension_attributes=None, text=None):
self.href = href
self.read_only = read_only
self.rel = rel
self.entry = entry
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def EntryLinkFromString(xml_string):
return atom.CreateClassFromXMLString(EntryLink, xml_string)
class FeedLink(atom.AtomBase):
"""The gd:feedLink element"""
_tag = 'feedLink'
_namespace = GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}feed' % atom.ATOM_NAMESPACE] = ('feed', GDataFeed)
_attributes['rel'] = 'rel'
_attributes['readOnly'] = 'read_only'
_attributes['countHint'] = 'count_hint'
_attributes['href'] = 'href'
def __init__(self, count_hint=None, href=None, read_only=None, rel=None,
feed=None, extension_elements=None, extension_attributes=None,
text=None):
self.count_hint = count_hint
self.href = href
self.read_only = read_only
self.rel = rel
self.feed = feed
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def FeedLinkFromString(xml_string):
return atom.CreateClassFromXMLString(EntryLink, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""GDataService provides CRUD ops. and programmatic login for GData services.
Error: A base exception class for all exceptions in the gdata_client
module.
CaptchaRequired: This exception is thrown when a login attempt results in a
captcha challenge from the ClientLogin service. When this
exception is thrown, the captcha_token and captcha_url are
set to the values provided in the server's response.
BadAuthentication: Raised when a login attempt is made with an incorrect
username or password.
NotAuthenticated: Raised if an operation requiring authentication is called
before a user has authenticated.
NonAuthSubToken: Raised if a method to modify an AuthSub token is used when
the user is either not authenticated or is authenticated
through programmatic login.
RequestError: Raised if a CRUD request returned a non-success code.
UnexpectedReturnType: Raised if the response from the server was not of the
desired type. For example, this would be raised if the
server sent a feed when the client requested an entry.
GDataService: Encapsulates user credentials needed to perform insert, update
and delete operations with the GData API. An instance can
perform user authentication, query, insertion, deletion, and
update.
Query: Eases query URI creation by allowing URI parameters to be set as
dictionary attributes. For example a query with a feed of
'/base/feeds/snippets' and ['bq'] set to 'digital camera' will
produce '/base/feeds/snippets?bq=digital+camera' when .ToUri() is
called on it.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
import re
import httplib
import urllib
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import atom.service
import gdata
import atom
import gdata.auth
PROGRAMMATIC_AUTH_LABEL = 'GoogleLogin auth'
AUTHSUB_AUTH_LABEL = 'AuthSub token'
AUTH_SERVER_HOST = 'https://www.google.com'
# Module level variable specifies which module should be used by GDataService
# objects to make HttpRequests. This setting can be overridden on each
# instance of GDataService.
http_request_handler = atom.service
class Error(Exception):
pass
class CaptchaRequired(Error):
pass
class BadAuthentication(Error):
pass
class NotAuthenticated(Error):
pass
class NonAuthSubToken(Error):
pass
class RequestError(Error):
pass
class UnexpectedReturnType(Error):
pass
class BadAuthenticationServiceURL(Error):
pass
class GDataService(atom.service.AtomService):
"""Contains elements needed for GData login and CRUD request headers.
Maintains additional headers (tokens for example) needed for the GData
services to allow a user to perform inserts, updates, and deletes.
"""
def __init__(self, email=None, password=None, account_type='HOSTED_OR_GOOGLE',
service=None, auth_service_url=None, source=None, server=None,
additional_headers=None, handler=None):
"""Creates an object of type GDataService.
Args:
email: string (optional) The user's email address, used for
authentication.
password: string (optional) The user's password.
account_type: string (optional) The type of account to use. Use
'GOOGLE' for regular Google accounts or 'HOSTED' for Google
Apps accounts, or 'HOSTED_OR_GOOGLE' to try finding a HOSTED
account first and, if it doesn't exist, try finding a regular
GOOGLE account. Default value: 'HOSTED_OR_GOOGLE'.
service: string (optional) The desired service for which credentials
will be obtained.
auth_service_url: string (optional) User-defined auth token request URL
allows users to explicitly specify where to send auth token requests.
source: string (optional) The name of the user's application.
server: string (optional) The name of the server to which a connection
will be opened. Default value: 'base.google.com'.
additional_headers: dictionary (optional) Any additional headers which
should be included with CRUD operations.
handler: module (optional) The module whose HttpRequest function
should be used when making requests to the server. The default
value is atom.service.
"""
self.email = email
self.password = password
self.account_type = account_type
self.service = service
self.auth_service_url = auth_service_url
self.server = server
self.additional_headers = additional_headers or {}
self.handler = handler or http_request_handler
self.__SetSource(source)
self.__auth_token = None
self.__captcha_token = None
self.__captcha_url = None
self.__gsessionid = None
# Define properties for GDataService
def _SetAuthSubToken(self, auth_token):
"""Sets the token sent in requests to an AuthSub token.
Only use this method if you have received a token from the AuthSub
service. The auth_token is set automatically when ProgrammaticLogin()
is used. See documentation for Google AuthSub here:
http://code.google.com/apis/accounts/AuthForWebApps.html .
Args:
auth_token: string The token returned by the AuthSub service.
"""
self.__auth_token = '%s=%s' % (AUTHSUB_AUTH_LABEL, auth_token)
# The auth token is only set externally when using AuthSub authentication,
# so set the auth_type to indicate AuthSub.
def __SetAuthSubToken(self, auth_token):
self._SetAuthSubToken(auth_token)
def _GetAuthToken(self):
"""Returns the auth token used for authenticating requests.
Returns:
string
"""
return self.__auth_token
def __GetAuthToken(self):
return self._GetAuthToken()
auth_token = property(__GetAuthToken, __SetAuthSubToken,
doc="""Get or set the token used for authentication.""")
def _GetCaptchaToken(self):
"""Returns a captcha token if the most recent login attempt generated one.
The captcha token is only set if the Programmatic Login attempt failed
because the Google service issued a captcha challenge.
Returns:
string
"""
return self.__captcha_token
def __GetCaptchaToken(self):
return self._GetCaptchaToken()
captcha_token = property(__GetCaptchaToken,
doc="""Get the captcha token for a login request.""")
def _GetCaptchaURL(self):
"""Returns the URL of the captcha image if a login attempt generated one.
The captcha URL is only set if the Programmatic Login attempt failed
because the Google service issued a captcha challenge.
Returns:
string
"""
return self.__captcha_url
def __GetCaptchaURL(self):
return self._GetCaptchaURL()
captcha_url = property(__GetCaptchaURL,
doc="""Get the captcha URL for a login request.""")
def GetAuthSubToken(self):
"""Returns the AuthSub Token after removing the AuthSub Authorization
Label.
The AuthSub Authorization Label reads: "AuthSub token"
Returns:
If the AuthSub Token is set AND it begins with the AuthSub
Authorization Label, the AuthSub Token is returned minus the AuthSub
Label. If the AuthSub Token does not start with the AuthSub
Authorization Label or it is not set, None is returned.
"""
if self.__auth_token.startswith(AUTHSUB_AUTH_LABEL):
# Strip off the leading 'AUTHSUB_AUTH_LABEL=' and just return the
# token value.
return self.__auth_token[len(AUTHSUB_AUTH_LABEL)+1:]
else:
return None
def SetAuthSubToken(self, token):
self.__auth_token = '%s=%s' % (AUTHSUB_AUTH_LABEL, token)
def GetClientLoginToken(self):
if self.__auth_token.startswith(PROGRAMMATIC_AUTH_LABEL):
# Strip off the leading 'PROGRAMMATIC_AUTH_LABEL=' and just return the
# token value.
return self.__auth_token[len(PROGRAMMATIC_AUTH_LABEL)+1:]
else:
return None
def SetClientLoginToken(self, token):
self.__auth_token = '%s=%s' % (PROGRAMMATIC_AUTH_LABEL, token)
# Private methods to create the source property.
def __GetSource(self):
return self.__source
def __SetSource(self, new_source):
self.__source = new_source
# Update the UserAgent header to include the new application name.
self.additional_headers['User-Agent'] = '%s GData-Python/1.1.1' % (
self.__source)
source = property(__GetSource, __SetSource,
doc="""The source is the name of the application making the request.
It should be in the form company_id-app_name-app_version""")
# Authentication operations
def 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
"""
request_body = gdata.auth.GenerateClientLoginRequestBody(self.email,
self.password, self.service, self.source, self.account_type,
captcha_token, captcha_response)
# If the user has defined their own authentication service URL,
# send the ClientLogin requests to this URL:
if not self.auth_service_url:
auth_request_url = AUTH_SERVER_HOST + '/accounts/ClientLogin'
else:
auth_request_url = self.auth_service_url
auth_response = self.handler.HttpRequest(self, 'POST', request_body,
auth_request_url,
extra_headers={'Content-Length':str(len(request_body))},
content_type='application/x-www-form-urlencoded')
response_body = auth_response.read()
if auth_response.status == 200:
self.__auth_token = gdata.auth.GenerateClientLoginAuthToken(
response_body)
self.__captcha_token = None
self.__captcha_url = None
elif auth_response.status == 403:
# Examine each line to find the error type and the captcha token and
# captch URL if they are present.
captcha_parameters = gdata.auth.GetCaptchChallenge(response_body,
captcha_base_url='%s/accounts/' % AUTH_SERVER_HOST)
if captcha_parameters:
self.__captcha_token = captcha_parameters['token']
self.__captcha_url = captcha_parameters['url']
raise CaptchaRequired, 'Captcha Required'
elif response_body.splitlines()[0] == 'Error=BadAuthentication':
self.__captcha_token = None
self.__captcha_url = None
raise BadAuthentication, 'Incorrect username or password'
else:
self.__captcha_token = None
self.__captcha_url = None
raise Error, 'Server responded with a 403 code'
elif auth_response.status == 302:
self.__captcha_token = None
self.__captcha_url = None
# Google tries to redirect all bad URLs back to
# http://www.google.<locale>. If a redirect
# attempt is made, assume the user has supplied an incorrect authentication URL
raise BadAuthenticationServiceURL, 'Server responded with a 302 code.'
def ClientLogin(self, username, password, account_type=None, service=None,
auth_service_url=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)
auth_service_url: string (optional)
captcha_token: string (optional)
captcha_response: string (optional)
"""
self.email = username
self.password = password
if account_type:
self.account_type = account_type
if service:
self.service = service
if source:
self.source = source
if auth_service_url:
self.auth_service_url = auth_service_url
self.ProgrammaticLogin(captcha_token, captcha_response)
def 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.
"""
# Translate True/False values for parameters into numeric values acceoted
# by the AuthSub service.
if secure:
secure = 1
else:
secure = 0
if session:
session = 1
else:
session = 0
request_params = urllib.urlencode({'next': next, 'scope': scope,
'secure': secure, 'session': session})
return '%s/accounts/AuthSubRequest?%s' % (AUTH_SERVER_HOST, request_params)
def 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
"""
if not self.__auth_token.startswith(AUTHSUB_AUTH_LABEL):
raise NonAuthSubToken
response = self.handler.HttpRequest(self, 'GET', None,
AUTH_SERVER_HOST + '/accounts/AuthSubSessionToken',
extra_headers={'Authorization':self.__auth_token},
content_type='application/x-www-form-urlencoded')
response_body = response.read()
if response.status == 200:
for response_line in response_body.splitlines():
if response_line.startswith('Token='):
self.SetAuthSubToken(response_line.lstrip('Token='))
def RevokeAuthSubToken(self):
"""Revokes an existing AuthSub token.
Raises:
NonAuthSubToken if the user's auth token is not an AuthSub token
"""
if not self.__auth_token.startswith(AUTHSUB_AUTH_LABEL):
raise NonAuthSubToken
response = self.handler.HttpRequest(self, 'GET', None,
AUTH_SERVER_HOST + '/accounts/AuthSubRevokeToken',
extra_headers={'Authorization':self.__auth_token},
content_type='application/x-www-form-urlencoded')
if response.status == 200:
self.__auth_token = None
# CRUD operations
def 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.
"""
if extra_headers is None:
extra_headers = {}
# Add the authentication header to the Get request
if self.__auth_token:
extra_headers['Authorization'] = self.__auth_token
if self.__gsessionid is not None:
if uri.find('gsessionid=') < 0:
if uri.find('?') > -1:
uri += '&gsessionid=%s' % (self.__gsessionid,)
else:
uri += '?gsessionid=%s' % (self.__gsessionid,)
server_response = self.handler.HttpRequest(self, 'GET', None, uri,
extra_headers=extra_headers)
result_body = server_response.read()
if server_response.status == 200:
if converter:
return converter(result_body)
# There was no ResultsTransformer specified, so try to convert the
# server's response into a GDataFeed.
feed = gdata.GDataFeedFromString(result_body)
if not feed:
# If conversion to a GDataFeed failed, try to convert the server's
# response to a GDataEntry.
entry = gdata.GDataEntryFromString(result_body)
if not entry:
# The server's response wasn't a feed, or an entry, so return the
# response body as a string.
return result_body
return entry
return feed
elif server_response.status == 302:
if redirects_remaining > 0:
location = server_response.getheader('Location')
if location is not None:
m = re.compile('[\?\&]gsessionid=(\w*)').search(location)
if m is not None:
self.__gsessionid = m.group(1)
return self.Get(location, extra_headers, redirects_remaining - 1,
encoding=encoding, converter=converter)
else:
raise RequestError, {'status': server_response.status,
'reason': '302 received without Location header',
'body': result_body}
else:
raise RequestError, {'status': server_response.status,
'reason': 'Redirect received, but redirects_remaining <= 0',
'body': result_body}
else:
raise RequestError, {'status': server_response.status,
'reason': server_response.reason, 'body': result_body}
def GetMedia(self, uri, extra_headers=None):
"""Returns a MediaSource containing media and its metadata from the given
URI string.
"""
response_handle = self.handler.HttpRequest(self, 'GET', None, uri,
extra_headers=extra_headers)
return gdata.MediaSource(response_handle, response_handle.getheader(
'Content-Type'),
response_handle.getheader('Content-Length'))
def GetEntry(self, uri, extra_headers=None):
"""Query the GData API with the given URI and receive an Entry.
See also documentation for gdata.service.Get
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.
Returns:
A GDataEntry built from the XML in the server's response.
"""
result = self.Get(uri, extra_headers, converter=atom.EntryFromString)
if isinstance(result, atom.Entry):
return result
else:
raise UnexpectedReturnType, 'Server did not send an entry'
def GetFeed(self, uri, extra_headers=None,
converter=gdata.GDataFeedFromString):
"""Query the GData API with the given URI and receive a Feed.
See also documentation for gdata.service.Get
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.
Returns:
A GDataFeed built from the XML in the server's response.
"""
result = self.Get(uri, extra_headers, converter=converter)
if isinstance(result, atom.Feed):
return result
else:
raise UnexpectedReturnType, 'Server did not send a feed'
def 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.
"""
next_link = feed.GetNextLink()
# Create a closure which will convert an XML string to the class of
# the feed object passed in.
def ConvertToFeedClass(xml_string):
return atom.CreateClassFromXMLString(feed.__class__, xml_string)
# Make a GET request on the next link and use the above closure for the
# converted which processes the XML string from the server.
if next_link and next_link.href:
return self.Get(next_link.href, converter=ConvertToFeedClass)
else:
return None
def Post(self, data, uri, extra_headers=None, url_params=None,
escape_params=True, redirects_remaining=4, media_source=None,
converter=None):
"""Insert or update 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).
"""
return self.PostOrPut('POST', data, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params,
redirects_remaining=redirects_remaining,
media_source=media_source, converter=converter)
def PostOrPut(self, verb, 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:
verb: string, either 'POST' or 'PUT'
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).
"""
if extra_headers is None:
extra_headers = {}
# Add the authentication header to the Get request
if self.__auth_token:
extra_headers['Authorization'] = self.__auth_token
if self.__gsessionid is not None:
if uri.find('gsessionid=') < 0:
if uri.find('?') > -1:
uri += '&gsessionid=%s' % (self.__gsessionid,)
else:
uri += '?gsessionid=%s' % (self.__gsessionid,)
if data and media_source:
if ElementTree.iselement(data):
data_str = ElementTree.tostring(data)
else:
data_str = str(data)
multipart = []
multipart.append('Media multipart posting\r\n--END_OF_PART\r\n' + \
'Content-Type: application/atom+xml\r\n\r\n')
multipart.append('\r\n--END_OF_PART\r\nContent-Type: ' + \
media_source.content_type+'\r\n\r\n')
multipart.append('\r\n--END_OF_PART--\r\n')
extra_headers['MIME-version'] = '1.0'
extra_headers['Content-Length'] = str(len(multipart[0]) +
len(multipart[1]) + len(multipart[2]) +
len(data_str) + media_source.content_length)
server_response = self.handler.HttpRequest(self, verb,
[multipart[0], data_str, multipart[1], media_source.file_handle,
multipart[2]], uri,
extra_headers=extra_headers, url_params=url_params,
escape_params=escape_params,
content_type='multipart/related; boundary=END_OF_PART')
result_body = server_response.read()
elif media_source or isinstance(data, gdata.MediaSource):
if isinstance(data, gdata.MediaSource):
media_source = data
extra_headers['Content-Length'] = str(media_source.content_length)
server_response = self.handler.HttpRequest(self, verb,
media_source.file_handle, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params,
content_type=media_source.content_type)
result_body = server_response.read()
else:
http_data = data
content_type = 'application/atom+xml'
server_response = self.handler.HttpRequest(self, verb,
http_data, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params,
content_type=content_type)
result_body = server_response.read()
# Server returns 201 for most post requests, but when performing a batch
# request the server responds with a 200 on success.
if server_response.status == 201 or server_response.status == 200:
if converter:
return converter(result_body)
feed = gdata.GDataFeedFromString(result_body)
if not feed:
entry = gdata.GDataEntryFromString(result_body)
if not entry:
return result_body
return entry
return feed
elif server_response.status == 302:
if redirects_remaining > 0:
location = server_response.getheader('Location')
if location is not None:
m = re.compile('[\?\&]gsessionid=(\w*)').search(location)
if m is not None:
self.__gsessionid = m.group(1)
return self.Post(data, location, extra_headers, url_params,
escape_params, redirects_remaining - 1, media_source,
converter=converter)
else:
raise RequestError, {'status': server_response.status,
'reason': '302 received without Location header',
'body': result_body}
else:
raise RequestError, {'status': server_response.status,
'reason': 'Redirect received, but redirects_remaining <= 0',
'body': result_body}
else:
raise RequestError, {'status': server_response.status,
'reason': server_response.reason, 'body': result_body}
def 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).
"""
return self.PostOrPut('PUT', data, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params,
redirects_remaining=redirects_remaining,
media_source=media_source, converter=converter)
def Delete(self, uri, extra_headers=None, url_params=None,
escape_params=True, redirects_remaining=4):
"""Deletes the entry at the given URI.
Args:
uri: string The URI of the entry to be deleted. Example:
'/base/feeds/items/ITEM-ID'
extra_headers: dict (optional) HTTP headers which are to be included.
The client automatically sets the Content-Type and
Authorization 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.
Returns:
True if the entry was deleted.
"""
if extra_headers is None:
extra_headers = {}
# Add the authentication header to the Get request
if self.__auth_token:
extra_headers['Authorization'] = self.__auth_token
if self.__gsessionid is not None:
if uri.find('gsessionid=') < 0:
if uri.find('?') > -1:
uri += '&gsessionid=%s' % (self.__gsessionid,)
else:
uri += '?gsessionid=%s' % (self.__gsessionid,)
server_response = self.handler.HttpRequest(self, 'DELETE', None, uri,
extra_headers=extra_headers, url_params=url_params,
escape_params=escape_params)
result_body = server_response.read()
if server_response.status == 200:
return True
elif server_response.status == 302:
if redirects_remaining > 0:
location = server_response.getheader('Location')
if location is not None:
m = re.compile('[\?\&]gsessionid=(\w*)').search(location)
if m is not None:
self.__gsessionid = m.group(1)
return self.Delete(location, extra_headers, url_params,
escape_params, redirects_remaining - 1)
else:
raise RequestError, {'status': server_response.status,
'reason': '302 received without Location header',
'body': result_body}
else:
raise RequestError, {'status': server_response.status,
'reason': 'Redirect received, but redirects_remaining <= 0',
'body': result_body}
else:
raise RequestError, {'status': server_response.status,
'reason': server_response.reason, 'body': result_body}
class Query(dict):
"""Constructs a query URL to be used in GET requests
Url parameters are created by adding key-value pairs to this object as a
dict. For example, to add &max-results=25 to the URL do
my_query['max-results'] = 25
Category queries are created by adding category strings to the categories
member. All items in the categories list will be concatenated with the /
symbol (symbolizing a category x AND y restriction). If you would like to OR
2 categories, append them as one string with a | between the categories.
For example, do query.categories.append('Fritz|Laurie') to create a query
like this feed/-/Fritz%7CLaurie . This query will look for results in both
categories.
"""
def __init__(self, feed=None, text_query=None, params=None,
categories=None):
"""Constructor for Query
Args:
feed: str (optional) The path for the feed (Examples:
'/base/feeds/snippets' or 'calendar/feeds/jo@gmail.com/private/full'
text_query: str (optional) The contents of the q query parameter. The
contents of the text_query are URL escaped upon conversion to a URI.
params: dict (optional) Parameter value string pairs which become URL
params when translated to a URI. These parameters are added to the
query's items (key-value pairs).
categories: list (optional) List of category strings which should be
included as query categories. See
http://code.google.com/apis/gdata/reference.html#Queries for
details. If you want to get results from category A or B (both
categories), specify a single list item 'A|B'.
"""
self.feed = feed
self.categories = []
if text_query:
self.text_query = text_query
if isinstance(params, dict):
for param in params:
self[param] = params[param]
if isinstance(categories, list):
for category in categories:
self.categories.append(category)
def _GetTextQuery(self):
if 'q' in self.keys():
return self['q']
else:
return None
def _SetTextQuery(self, query):
self['q'] = query
text_query = property(_GetTextQuery, _SetTextQuery,
doc="""The feed query's q parameter""")
def _GetAuthor(self):
if 'author' in self.keys():
return self['author']
else:
return None
def _SetAuthor(self, query):
self['author'] = query
author = property(_GetAuthor, _SetAuthor,
doc="""The feed query's author parameter""")
def _GetAlt(self):
if 'alt' in self.keys():
return self['alt']
else:
return None
def _SetAlt(self, query):
self['alt'] = query
alt = property(_GetAlt, _SetAlt,
doc="""The feed query's alt parameter""")
def _GetUpdatedMin(self):
if 'updated-min' in self.keys():
return self['updated-min']
else:
return None
def _SetUpdatedMin(self, query):
self['updated-min'] = query
updated_min = property(_GetUpdatedMin, _SetUpdatedMin,
doc="""The feed query's updated-min parameter""")
def _GetUpdatedMax(self):
if 'updated-max' in self.keys():
return self['updated-max']
else:
return None
def _SetUpdatedMax(self, query):
self['updated-max'] = query
updated_max = property(_GetUpdatedMax, _SetUpdatedMax,
doc="""The feed query's updated-max parameter""")
def _GetPublishedMin(self):
if 'published-min' in self.keys():
return self['published-min']
else:
return None
def _SetPublishedMin(self, query):
self['published-min'] = query
published_min = property(_GetPublishedMin, _SetPublishedMin,
doc="""The feed query's published-min parameter""")
def _GetPublishedMax(self):
if 'published-max' in self.keys():
return self['published-max']
else:
return None
def _SetPublishedMax(self, query):
self['published-max'] = query
published_max = property(_GetPublishedMax, _SetPublishedMax,
doc="""The feed query's published-max parameter""")
def _GetStartIndex(self):
if 'start-index' in self.keys():
return self['start-index']
else:
return None
def _SetStartIndex(self, query):
if not isinstance(query, str):
query = str(query)
self['start-index'] = query
start_index = property(_GetStartIndex, _SetStartIndex,
doc="""The feed query's start-index parameter""")
def _GetMaxResults(self):
if 'max-results' in self.keys():
return self['max-results']
else:
return None
def _SetMaxResults(self, query):
if not isinstance(query, str):
query = str(query)
self['max-results'] = query
max_results = property(_GetMaxResults, _SetMaxResults,
doc="""The feed query's max-results parameter""")
def _GetOrderBy(self):
if 'orderby' in self.keys():
return self['orderby']
else:
return None
def _SetOrderBy(self, query):
self['orderby'] = query
orderby = property(_GetOrderBy, _SetOrderBy,
doc="""The feed query's orderby parameter""")
def ToUri(self):
q_feed = self.feed or ''
category_string = '/'.join(
[urllib.quote_plus(c) for c in self.categories])
# Add categories to the feed if there are any.
if len(self.categories) > 0:
q_feed = q_feed + '/-/' + category_string
return atom.service.BuildUri(q_feed, self)
def __str__(self):
return self.ToUri()
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""GDataService provides CRUD ops. and programmatic login for GData services.
Error: A base exception class for all exceptions in the gdata_client
module.
CaptchaRequired: This exception is thrown when a login attempt results in a
captcha challenge from the ClientLogin service. When this
exception is thrown, the captcha_token and captcha_url are
set to the values provided in the server's response.
BadAuthentication: Raised when a login attempt is made with an incorrect
username or password.
NotAuthenticated: Raised if an operation requiring authentication is called
before a user has authenticated.
NonAuthSubToken: Raised if a method to modify an AuthSub token is used when
the user is either not authenticated or is authenticated
through programmatic login.
RequestError: Raised if a CRUD request returned a non-success code.
UnexpectedReturnType: Raised if the response from the server was not of the
desired type. For example, this would be raised if the
server sent a feed when the client requested an entry.
GDataService: Encapsulates user credentials needed to perform insert, update
and delete operations with the GData API. An instance can
perform user authentication, query, insertion, deletion, and
update.
Query: Eases query URI creation by allowing URI parameters to be set as
dictionary attributes. For example a query with a feed of
'/base/feeds/snippets' and ['bq'] set to 'digital camera' will
produce '/base/feeds/snippets?bq=digital+camera' when .ToUri() is
called on it.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
import re
import httplib
import urllib
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import atom.service
import gdata
import atom
import gdata.auth
PROGRAMMATIC_AUTH_LABEL = 'GoogleLogin auth'
AUTHSUB_AUTH_LABEL = 'AuthSub token'
AUTH_SERVER_HOST = 'https://www.google.com'
# Module level variable specifies which module should be used by GDataService
# objects to make HttpRequests. This setting can be overridden on each
# instance of GDataService.
http_request_handler = atom.service
class Error(Exception):
pass
class CaptchaRequired(Error):
pass
class BadAuthentication(Error):
pass
class NotAuthenticated(Error):
pass
class NonAuthSubToken(Error):
pass
class RequestError(Error):
pass
class UnexpectedReturnType(Error):
pass
class BadAuthenticationServiceURL(Error):
pass
class GDataService(atom.service.AtomService):
"""Contains elements needed for GData login and CRUD request headers.
Maintains additional headers (tokens for example) needed for the GData
services to allow a user to perform inserts, updates, and deletes.
"""
def __init__(self, email=None, password=None, account_type='HOSTED_OR_GOOGLE',
service=None, auth_service_url=None, source=None, server=None,
additional_headers=None, handler=None):
"""Creates an object of type GDataService.
Args:
email: string (optional) The user's email address, used for
authentication.
password: string (optional) The user's password.
account_type: string (optional) The type of account to use. Use
'GOOGLE' for regular Google accounts or 'HOSTED' for Google
Apps accounts, or 'HOSTED_OR_GOOGLE' to try finding a HOSTED
account first and, if it doesn't exist, try finding a regular
GOOGLE account. Default value: 'HOSTED_OR_GOOGLE'.
service: string (optional) The desired service for which credentials
will be obtained.
auth_service_url: string (optional) User-defined auth token request URL
allows users to explicitly specify where to send auth token requests.
source: string (optional) The name of the user's application.
server: string (optional) The name of the server to which a connection
will be opened. Default value: 'base.google.com'.
additional_headers: dictionary (optional) Any additional headers which
should be included with CRUD operations.
handler: module (optional) The module whose HttpRequest function
should be used when making requests to the server. The default
value is atom.service.
"""
self.email = email
self.password = password
self.account_type = account_type
self.service = service
self.auth_service_url = auth_service_url
self.server = server
self.additional_headers = additional_headers or {}
self.handler = handler or http_request_handler
self.__SetSource(source)
self.__auth_token = None
self.__captcha_token = None
self.__captcha_url = None
self.__gsessionid = None
# Define properties for GDataService
def _SetAuthSubToken(self, auth_token):
"""Sets the token sent in requests to an AuthSub token.
Only use this method if you have received a token from the AuthSub
service. The auth_token is set automatically when ProgrammaticLogin()
is used. See documentation for Google AuthSub here:
http://code.google.com/apis/accounts/AuthForWebApps.html .
Args:
auth_token: string The token returned by the AuthSub service.
"""
self.__auth_token = '%s=%s' % (AUTHSUB_AUTH_LABEL, auth_token)
# The auth token is only set externally when using AuthSub authentication,
# so set the auth_type to indicate AuthSub.
def __SetAuthSubToken(self, auth_token):
self._SetAuthSubToken(auth_token)
def _GetAuthToken(self):
"""Returns the auth token used for authenticating requests.
Returns:
string
"""
return self.__auth_token
def __GetAuthToken(self):
return self._GetAuthToken()
auth_token = property(__GetAuthToken, __SetAuthSubToken,
doc="""Get or set the token used for authentication.""")
def _GetCaptchaToken(self):
"""Returns a captcha token if the most recent login attempt generated one.
The captcha token is only set if the Programmatic Login attempt failed
because the Google service issued a captcha challenge.
Returns:
string
"""
return self.__captcha_token
def __GetCaptchaToken(self):
return self._GetCaptchaToken()
captcha_token = property(__GetCaptchaToken,
doc="""Get the captcha token for a login request.""")
def _GetCaptchaURL(self):
"""Returns the URL of the captcha image if a login attempt generated one.
The captcha URL is only set if the Programmatic Login attempt failed
because the Google service issued a captcha challenge.
Returns:
string
"""
return self.__captcha_url
def __GetCaptchaURL(self):
return self._GetCaptchaURL()
captcha_url = property(__GetCaptchaURL,
doc="""Get the captcha URL for a login request.""")
def GetAuthSubToken(self):
"""Returns the AuthSub Token after removing the AuthSub Authorization
Label.
The AuthSub Authorization Label reads: "AuthSub token"
Returns:
If the AuthSub Token is set AND it begins with the AuthSub
Authorization Label, the AuthSub Token is returned minus the AuthSub
Label. If the AuthSub Token does not start with the AuthSub
Authorization Label or it is not set, None is returned.
"""
if self.__auth_token.startswith(AUTHSUB_AUTH_LABEL):
# Strip off the leading 'AUTHSUB_AUTH_LABEL=' and just return the
# token value.
return self.__auth_token[len(AUTHSUB_AUTH_LABEL)+1:]
else:
return None
def SetAuthSubToken(self, token):
self.__auth_token = '%s=%s' % (AUTHSUB_AUTH_LABEL, token)
def GetClientLoginToken(self):
if self.__auth_token.startswith(PROGRAMMATIC_AUTH_LABEL):
# Strip off the leading 'PROGRAMMATIC_AUTH_LABEL=' and just return the
# token value.
return self.__auth_token[len(PROGRAMMATIC_AUTH_LABEL)+1:]
else:
return None
def SetClientLoginToken(self, token):
self.__auth_token = '%s=%s' % (PROGRAMMATIC_AUTH_LABEL, token)
# Private methods to create the source property.
def __GetSource(self):
return self.__source
def __SetSource(self, new_source):
self.__source = new_source
# Update the UserAgent header to include the new application name.
self.additional_headers['User-Agent'] = '%s GData-Python/1.1.1' % (
self.__source)
source = property(__GetSource, __SetSource,
doc="""The source is the name of the application making the request.
It should be in the form company_id-app_name-app_version""")
# Authentication operations
def 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
"""
request_body = gdata.auth.GenerateClientLoginRequestBody(self.email,
self.password, self.service, self.source, self.account_type,
captcha_token, captcha_response)
# If the user has defined their own authentication service URL,
# send the ClientLogin requests to this URL:
if not self.auth_service_url:
auth_request_url = AUTH_SERVER_HOST + '/accounts/ClientLogin'
else:
auth_request_url = self.auth_service_url
auth_response = self.handler.HttpRequest(self, 'POST', request_body,
auth_request_url,
extra_headers={'Content-Length':str(len(request_body))},
content_type='application/x-www-form-urlencoded')
response_body = auth_response.read()
if auth_response.status == 200:
self.__auth_token = gdata.auth.GenerateClientLoginAuthToken(
response_body)
self.__captcha_token = None
self.__captcha_url = None
elif auth_response.status == 403:
# Examine each line to find the error type and the captcha token and
# captch URL if they are present.
captcha_parameters = gdata.auth.GetCaptchChallenge(response_body,
captcha_base_url='%s/accounts/' % AUTH_SERVER_HOST)
if captcha_parameters:
self.__captcha_token = captcha_parameters['token']
self.__captcha_url = captcha_parameters['url']
raise CaptchaRequired, 'Captcha Required'
elif response_body.splitlines()[0] == 'Error=BadAuthentication':
self.__captcha_token = None
self.__captcha_url = None
raise BadAuthentication, 'Incorrect username or password'
else:
self.__captcha_token = None
self.__captcha_url = None
raise Error, 'Server responded with a 403 code'
elif auth_response.status == 302:
self.__captcha_token = None
self.__captcha_url = None
# Google tries to redirect all bad URLs back to
# http://www.google.<locale>. If a redirect
# attempt is made, assume the user has supplied an incorrect authentication URL
raise BadAuthenticationServiceURL, 'Server responded with a 302 code.'
def ClientLogin(self, username, password, account_type=None, service=None,
auth_service_url=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)
auth_service_url: string (optional)
captcha_token: string (optional)
captcha_response: string (optional)
"""
self.email = username
self.password = password
if account_type:
self.account_type = account_type
if service:
self.service = service
if source:
self.source = source
if auth_service_url:
self.auth_service_url = auth_service_url
self.ProgrammaticLogin(captcha_token, captcha_response)
def 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.
"""
# Translate True/False values for parameters into numeric values acceoted
# by the AuthSub service.
if secure:
secure = 1
else:
secure = 0
if session:
session = 1
else:
session = 0
request_params = urllib.urlencode({'next': next, 'scope': scope,
'secure': secure, 'session': session})
return '%s/accounts/AuthSubRequest?%s' % (AUTH_SERVER_HOST, request_params)
def 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
"""
if not self.__auth_token.startswith(AUTHSUB_AUTH_LABEL):
raise NonAuthSubToken
response = self.handler.HttpRequest(self, 'GET', None,
AUTH_SERVER_HOST + '/accounts/AuthSubSessionToken',
extra_headers={'Authorization':self.__auth_token},
content_type='application/x-www-form-urlencoded')
response_body = response.read()
if response.status == 200:
for response_line in response_body.splitlines():
if response_line.startswith('Token='):
self.SetAuthSubToken(response_line.lstrip('Token='))
def RevokeAuthSubToken(self):
"""Revokes an existing AuthSub token.
Raises:
NonAuthSubToken if the user's auth token is not an AuthSub token
"""
if not self.__auth_token.startswith(AUTHSUB_AUTH_LABEL):
raise NonAuthSubToken
response = self.handler.HttpRequest(self, 'GET', None,
AUTH_SERVER_HOST + '/accounts/AuthSubRevokeToken',
extra_headers={'Authorization':self.__auth_token},
content_type='application/x-www-form-urlencoded')
if response.status == 200:
self.__auth_token = None
# CRUD operations
def 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.
"""
if extra_headers is None:
extra_headers = {}
# Add the authentication header to the Get request
if self.__auth_token:
extra_headers['Authorization'] = self.__auth_token
if self.__gsessionid is not None:
if uri.find('gsessionid=') < 0:
if uri.find('?') > -1:
uri += '&gsessionid=%s' % (self.__gsessionid,)
else:
uri += '?gsessionid=%s' % (self.__gsessionid,)
server_response = self.handler.HttpRequest(self, 'GET', None, uri,
extra_headers=extra_headers)
result_body = server_response.read()
if server_response.status == 200:
if converter:
return converter(result_body)
# There was no ResultsTransformer specified, so try to convert the
# server's response into a GDataFeed.
feed = gdata.GDataFeedFromString(result_body)
if not feed:
# If conversion to a GDataFeed failed, try to convert the server's
# response to a GDataEntry.
entry = gdata.GDataEntryFromString(result_body)
if not entry:
# The server's response wasn't a feed, or an entry, so return the
# response body as a string.
return result_body
return entry
return feed
elif server_response.status == 302:
if redirects_remaining > 0:
location = server_response.getheader('Location')
if location is not None:
m = re.compile('[\?\&]gsessionid=(\w*)').search(location)
if m is not None:
self.__gsessionid = m.group(1)
return self.Get(location, extra_headers, redirects_remaining - 1,
encoding=encoding, converter=converter)
else:
raise RequestError, {'status': server_response.status,
'reason': '302 received without Location header',
'body': result_body}
else:
raise RequestError, {'status': server_response.status,
'reason': 'Redirect received, but redirects_remaining <= 0',
'body': result_body}
else:
raise RequestError, {'status': server_response.status,
'reason': server_response.reason, 'body': result_body}
def GetMedia(self, uri, extra_headers=None):
"""Returns a MediaSource containing media and its metadata from the given
URI string.
"""
response_handle = self.handler.HttpRequest(self, 'GET', None, uri,
extra_headers=extra_headers)
return gdata.MediaSource(response_handle, response_handle.getheader(
'Content-Type'),
response_handle.getheader('Content-Length'))
def GetEntry(self, uri, extra_headers=None):
"""Query the GData API with the given URI and receive an Entry.
See also documentation for gdata.service.Get
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.
Returns:
A GDataEntry built from the XML in the server's response.
"""
result = self.Get(uri, extra_headers, converter=atom.EntryFromString)
if isinstance(result, atom.Entry):
return result
else:
raise UnexpectedReturnType, 'Server did not send an entry'
def GetFeed(self, uri, extra_headers=None,
converter=gdata.GDataFeedFromString):
"""Query the GData API with the given URI and receive a Feed.
See also documentation for gdata.service.Get
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.
Returns:
A GDataFeed built from the XML in the server's response.
"""
result = self.Get(uri, extra_headers, converter=converter)
if isinstance(result, atom.Feed):
return result
else:
raise UnexpectedReturnType, 'Server did not send a feed'
def 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.
"""
next_link = feed.GetNextLink()
# Create a closure which will convert an XML string to the class of
# the feed object passed in.
def ConvertToFeedClass(xml_string):
return atom.CreateClassFromXMLString(feed.__class__, xml_string)
# Make a GET request on the next link and use the above closure for the
# converted which processes the XML string from the server.
if next_link and next_link.href:
return self.Get(next_link.href, converter=ConvertToFeedClass)
else:
return None
def Post(self, data, uri, extra_headers=None, url_params=None,
escape_params=True, redirects_remaining=4, media_source=None,
converter=None):
"""Insert or update 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).
"""
return self.PostOrPut('POST', data, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params,
redirects_remaining=redirects_remaining,
media_source=media_source, converter=converter)
def PostOrPut(self, verb, 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:
verb: string, either 'POST' or 'PUT'
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).
"""
if extra_headers is None:
extra_headers = {}
# Add the authentication header to the Get request
if self.__auth_token:
extra_headers['Authorization'] = self.__auth_token
if self.__gsessionid is not None:
if uri.find('gsessionid=') < 0:
if uri.find('?') > -1:
uri += '&gsessionid=%s' % (self.__gsessionid,)
else:
uri += '?gsessionid=%s' % (self.__gsessionid,)
if data and media_source:
if ElementTree.iselement(data):
data_str = ElementTree.tostring(data)
else:
data_str = str(data)
multipart = []
multipart.append('Media multipart posting\r\n--END_OF_PART\r\n' + \
'Content-Type: application/atom+xml\r\n\r\n')
multipart.append('\r\n--END_OF_PART\r\nContent-Type: ' + \
media_source.content_type+'\r\n\r\n')
multipart.append('\r\n--END_OF_PART--\r\n')
extra_headers['MIME-version'] = '1.0'
extra_headers['Content-Length'] = str(len(multipart[0]) +
len(multipart[1]) + len(multipart[2]) +
len(data_str) + media_source.content_length)
server_response = self.handler.HttpRequest(self, verb,
[multipart[0], data_str, multipart[1], media_source.file_handle,
multipart[2]], uri,
extra_headers=extra_headers, url_params=url_params,
escape_params=escape_params,
content_type='multipart/related; boundary=END_OF_PART')
result_body = server_response.read()
elif media_source or isinstance(data, gdata.MediaSource):
if isinstance(data, gdata.MediaSource):
media_source = data
extra_headers['Content-Length'] = str(media_source.content_length)
server_response = self.handler.HttpRequest(self, verb,
media_source.file_handle, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params,
content_type=media_source.content_type)
result_body = server_response.read()
else:
http_data = data
content_type = 'application/atom+xml'
server_response = self.handler.HttpRequest(self, verb,
http_data, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params,
content_type=content_type)
result_body = server_response.read()
# Server returns 201 for most post requests, but when performing a batch
# request the server responds with a 200 on success.
if server_response.status == 201 or server_response.status == 200:
if converter:
return converter(result_body)
feed = gdata.GDataFeedFromString(result_body)
if not feed:
entry = gdata.GDataEntryFromString(result_body)
if not entry:
return result_body
return entry
return feed
elif server_response.status == 302:
if redirects_remaining > 0:
location = server_response.getheader('Location')
if location is not None:
m = re.compile('[\?\&]gsessionid=(\w*)').search(location)
if m is not None:
self.__gsessionid = m.group(1)
return self.Post(data, location, extra_headers, url_params,
escape_params, redirects_remaining - 1, media_source,
converter=converter)
else:
raise RequestError, {'status': server_response.status,
'reason': '302 received without Location header',
'body': result_body}
else:
raise RequestError, {'status': server_response.status,
'reason': 'Redirect received, but redirects_remaining <= 0',
'body': result_body}
else:
raise RequestError, {'status': server_response.status,
'reason': server_response.reason, 'body': result_body}
def 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).
"""
return self.PostOrPut('PUT', data, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params,
redirects_remaining=redirects_remaining,
media_source=media_source, converter=converter)
def Delete(self, uri, extra_headers=None, url_params=None,
escape_params=True, redirects_remaining=4):
"""Deletes the entry at the given URI.
Args:
uri: string The URI of the entry to be deleted. Example:
'/base/feeds/items/ITEM-ID'
extra_headers: dict (optional) HTTP headers which are to be included.
The client automatically sets the Content-Type and
Authorization 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.
Returns:
True if the entry was deleted.
"""
if extra_headers is None:
extra_headers = {}
# Add the authentication header to the Get request
if self.__auth_token:
extra_headers['Authorization'] = self.__auth_token
if self.__gsessionid is not None:
if uri.find('gsessionid=') < 0:
if uri.find('?') > -1:
uri += '&gsessionid=%s' % (self.__gsessionid,)
else:
uri += '?gsessionid=%s' % (self.__gsessionid,)
server_response = self.handler.HttpRequest(self, 'DELETE', None, uri,
extra_headers=extra_headers, url_params=url_params,
escape_params=escape_params)
result_body = server_response.read()
if server_response.status == 200:
return True
elif server_response.status == 302:
if redirects_remaining > 0:
location = server_response.getheader('Location')
if location is not None:
m = re.compile('[\?\&]gsessionid=(\w*)').search(location)
if m is not None:
self.__gsessionid = m.group(1)
return self.Delete(location, extra_headers, url_params,
escape_params, redirects_remaining - 1)
else:
raise RequestError, {'status': server_response.status,
'reason': '302 received without Location header',
'body': result_body}
else:
raise RequestError, {'status': server_response.status,
'reason': 'Redirect received, but redirects_remaining <= 0',
'body': result_body}
else:
raise RequestError, {'status': server_response.status,
'reason': server_response.reason, 'body': result_body}
class Query(dict):
"""Constructs a query URL to be used in GET requests
Url parameters are created by adding key-value pairs to this object as a
dict. For example, to add &max-results=25 to the URL do
my_query['max-results'] = 25
Category queries are created by adding category strings to the categories
member. All items in the categories list will be concatenated with the /
symbol (symbolizing a category x AND y restriction). If you would like to OR
2 categories, append them as one string with a | between the categories.
For example, do query.categories.append('Fritz|Laurie') to create a query
like this feed/-/Fritz%7CLaurie . This query will look for results in both
categories.
"""
def __init__(self, feed=None, text_query=None, params=None,
categories=None):
"""Constructor for Query
Args:
feed: str (optional) The path for the feed (Examples:
'/base/feeds/snippets' or 'calendar/feeds/jo@gmail.com/private/full'
text_query: str (optional) The contents of the q query parameter. The
contents of the text_query are URL escaped upon conversion to a URI.
params: dict (optional) Parameter value string pairs which become URL
params when translated to a URI. These parameters are added to the
query's items (key-value pairs).
categories: list (optional) List of category strings which should be
included as query categories. See
http://code.google.com/apis/gdata/reference.html#Queries for
details. If you want to get results from category A or B (both
categories), specify a single list item 'A|B'.
"""
self.feed = feed
self.categories = []
if text_query:
self.text_query = text_query
if isinstance(params, dict):
for param in params:
self[param] = params[param]
if isinstance(categories, list):
for category in categories:
self.categories.append(category)
def _GetTextQuery(self):
if 'q' in self.keys():
return self['q']
else:
return None
def _SetTextQuery(self, query):
self['q'] = query
text_query = property(_GetTextQuery, _SetTextQuery,
doc="""The feed query's q parameter""")
def _GetAuthor(self):
if 'author' in self.keys():
return self['author']
else:
return None
def _SetAuthor(self, query):
self['author'] = query
author = property(_GetAuthor, _SetAuthor,
doc="""The feed query's author parameter""")
def _GetAlt(self):
if 'alt' in self.keys():
return self['alt']
else:
return None
def _SetAlt(self, query):
self['alt'] = query
alt = property(_GetAlt, _SetAlt,
doc="""The feed query's alt parameter""")
def _GetUpdatedMin(self):
if 'updated-min' in self.keys():
return self['updated-min']
else:
return None
def _SetUpdatedMin(self, query):
self['updated-min'] = query
updated_min = property(_GetUpdatedMin, _SetUpdatedMin,
doc="""The feed query's updated-min parameter""")
def _GetUpdatedMax(self):
if 'updated-max' in self.keys():
return self['updated-max']
else:
return None
def _SetUpdatedMax(self, query):
self['updated-max'] = query
updated_max = property(_GetUpdatedMax, _SetUpdatedMax,
doc="""The feed query's updated-max parameter""")
def _GetPublishedMin(self):
if 'published-min' in self.keys():
return self['published-min']
else:
return None
def _SetPublishedMin(self, query):
self['published-min'] = query
published_min = property(_GetPublishedMin, _SetPublishedMin,
doc="""The feed query's published-min parameter""")
def _GetPublishedMax(self):
if 'published-max' in self.keys():
return self['published-max']
else:
return None
def _SetPublishedMax(self, query):
self['published-max'] = query
published_max = property(_GetPublishedMax, _SetPublishedMax,
doc="""The feed query's published-max parameter""")
def _GetStartIndex(self):
if 'start-index' in self.keys():
return self['start-index']
else:
return None
def _SetStartIndex(self, query):
if not isinstance(query, str):
query = str(query)
self['start-index'] = query
start_index = property(_GetStartIndex, _SetStartIndex,
doc="""The feed query's start-index parameter""")
def _GetMaxResults(self):
if 'max-results' in self.keys():
return self['max-results']
else:
return None
def _SetMaxResults(self, query):
if not isinstance(query, str):
query = str(query)
self['max-results'] = query
max_results = property(_GetMaxResults, _SetMaxResults,
doc="""The feed query's max-results parameter""")
def _GetOrderBy(self):
if 'orderby' in self.keys():
return self['orderby']
else:
return None
def _SetOrderBy(self, query):
self['orderby'] = query
orderby = property(_GetOrderBy, _SetOrderBy,
doc="""The feed query's orderby parameter""")
def ToUri(self):
q_feed = self.feed or ''
category_string = '/'.join(
[urllib.quote_plus(c) for c in self.categories])
# Add categories to the feed if there are any.
if len(self.categories) > 0:
q_feed = q_feed + '/-/' + category_string
return atom.service.BuildUri(q_feed, self)
def __str__(self):
return self.ToUri()
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to Atom objects used with Google Documents."""
__author__ = 'api.jfisher (Jeff Fisher)'
import atom
import gdata
class DocumentListEntry(gdata.GDataEntry):
"""The Google Documents version of an Atom Entry"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
def DocumentListEntryFromString(xml_string):
"""Converts an XML string into a DocumentListEntry object.
Args:
xml_string: string The XML describing a Document List feed entry.
Returns:
A DocumentListEntry object corresponding to the given XML.
"""
return atom.CreateClassFromXMLString(DocumentListEntry, xml_string)
class DocumentListFeed(gdata.GDataFeed):
"""A feed containing a list of Google Documents Items"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[DocumentListEntry])
def DocumentListFeedFromString(xml_string):
"""Converts an XML string into a DocumentListFeed object.
Args:
xml_string: string The XML describing a DocumentList feed.
Returns:
A DocumentListFeed object corresponding to the given XML.
"""
return atom.CreateClassFromXMLString(DocumentListFeed, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""DocsService extends the GDataService to streamline Google Documents
operations.
DocsService: Provides methods to query feeds and manipulate items.
Extends GDataService.
DocumentQuery: Queries a Google Document list feed.
"""
__author__ = 'api.jfisher (Jeff Fisher)'
import urllib
import atom
import gdata.service
import gdata.docs
# XML Namespaces used in Google Documents entities.
DATA_KIND_SCHEME = 'http://schemas.google.com/g/2005#kind'
DOCUMENT_KIND_TERM = 'http://schemas.google.com/docs/2007#document'
SPREADSHEET_KIND_TERM = 'http://schemas.google.com/docs/2007#spreadsheet'
PRESENTATION_KIND_TERM = 'http://schemas.google.com/docs/2007#presentation'
# File extensions of documents that are permitted to be uploaded.
SUPPORTED_FILETYPES = {
'CSV': 'text/csv',
'TSV': 'text/tab-separated-values',
'TAB': 'text/tab-separated-values',
'DOC': 'application/msword',
'ODS': 'application/x-vnd.oasis.opendocument.spreadsheet',
'ODT': 'application/vnd.oasis.opendocument.text',
'RTF': 'application/rtf',
'SXW': 'application/vnd.sun.xml.writer',
'TXT': 'text/plain',
'XLS': 'application/vnd.ms-excel',
'PPT': 'application/vnd.ms-powerpoint',
'PPS': 'application/vnd.ms-powerpoint',
'HTM': 'text/html',
'HTML' : 'text/html'}
class DocsService(gdata.service.GDataService):
"""Client extension for the Google Documents service Document List feed."""
def __init__(self, email=None, password=None, source=None,
server='docs.google.com', additional_headers=None):
"""Constructor for the DocsService.
Args:
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.
Yields:
A DocsService object used to communicate with the Google Documents
service.
"""
gdata.service.GDataService.__init__(self, email=email, password=password,
service='writely', source=source,
server=server,
additional_headers=additional_headers)
def Query(self, uri, converter=gdata.docs.DocumentListFeedFromString):
"""Queries the Document List feed and returns the resulting feed of
entries.
Args:
uri: string The full URI to be queried. This can contain query
parameters, a hostname, or simply the relative path to a Document
List feed. The DocumentQuery object is useful when constructing
query parameters.
converter: func (optional) A function which will be executed on the
retrieved item, generally to render it into a Python object.
By default the DocumentListFeedFromString function is used to
return a DocumentListFeed object. This is because most feed
queries will result in a feed and not a single entry.
"""
return self.Get(uri, converter=converter)
def QueryDocumentListFeed(self, uri):
"""Retrieves a DocumentListFeed by retrieving a URI based off the Document
List feed, including any query parameters. A DocumentQuery object can
be used to construct these parameters.
Args:
uri: string The URI of the feed being retrieved possibly with query
parameters.
Returns:
A DocumentListFeed object representing the feed returned by the server.
"""
return self.Get(uri, converter=gdata.docs.DocumentListFeedFromString)
def GetDocumentListEntry(self, uri):
"""Retrieves a particular DocumentListEntry by its unique URI.
Args:
uri: string The unique URI of an entry in a Document List feed.
Returns:
A DocumentListEntry object representing the retrieved entry.
"""
return self.Get(uri, converter=gdata.docs.DocumentListEntryFromString)
def GetDocumentListFeed(self):
"""Retrieves a feed containing all of a user's documents."""
q = gdata.docs.service.DocumentQuery();
return self.QueryDocumentListFeed(q.ToUri())
def UploadPresentation(self, media_source, title):
"""Uploads a presentation inside of a MediaSource object to the Document
List feed with the given title.
Args:
media_source: MediaSource The MediaSource object containing a
presentation file to be uploaded.
title: string The title of the presentation on the server after being
uploaded.
Returns:
A GDataEntry containing information about the presentation created on the
Google Documents service.
"""
category = atom.Category(scheme=DATA_KIND_SCHEME,
term=PRESENTATION_KIND_TERM)
return self._UploadFile(media_source, title, category)
def UploadSpreadsheet(self, media_source, title):
"""Uploads a spreadsheet inside of a MediaSource object to the Document
List feed with the given title.
Args:
media_source: MediaSource The MediaSource object containing a spreadsheet
file to be uploaded.
title: string The title of the spreadsheet on the server after being
uploaded.
Returns:
A GDataEntry containing information about the spreadsheet created on the
Google Documents service.
"""
category = atom.Category(scheme=DATA_KIND_SCHEME,
term=SPREADSHEET_KIND_TERM)
return self._UploadFile(media_source, title, category)
def UploadDocument(self, media_source, title):
"""Uploads a document inside of a MediaSource object to the Document List
feed with the given title.
Args:
media_source: MediaSource The gdata.MediaSource object containing a
document file to be uploaded.
title: string The title of the document on the server after being
uploaded.
Returns:
A GDataEntry containing information about the document created on the
Google Documents service.
"""
category = atom.Category(scheme=DATA_KIND_SCHEME,
term=DOCUMENT_KIND_TERM)
return self._UploadFile(media_source, title, category)
def _UploadFile(self, media_source, title, category):
"""Uploads a file to the Document List feed.
Args:
media_source: A gdata.MediaSource object containing the file to be
uploaded.
title: string The title of the document on the server after being
uploaded.
category: An atom.Category object specifying the appropriate document
type
Returns:
A GDataEntry containing information about the document created on
the Google Documents service.
"""
media_entry = gdata.GDataEntry()
media_entry.title = atom.Title(text=title)
media_entry.category.append(category)
media_entry = self.Post(media_entry, '/feeds/documents/private/full',
media_source = media_source,
extra_headers = {'Slug' : media_source.file_name })
return media_entry
class DocumentQuery(gdata.service.Query):
"""Object used to construct a URI to query the Google Document List feed"""
def __init__(self, feed='/feeds/documents', visibility='private',
projection='full', text_query=None, params=None,
categories=None):
"""Constructor for Document List Query
Args:
feed: string (optional) The path for the feed. (e.g. '/feeds/documents')
visibility: string (optional) The visibility chosen for the current feed.
projection: string (optional) The projection chosen for the current feed.
text_query: string (optional) The contents of the q query parameter. This
string is URL escaped upon conversion to a URI.
params: dict (optional) Parameter value string pairs which become URL
params when translated to a URI. These parameters are added to
the query's items.
categories: list (optional) List of category strings which should be
included as query categories. See gdata.service.Query for
additional documentation.
Yields:
A DocumentQuery object used to construct a URI based on the Document
List feed.
"""
self.visibility = visibility
self.projection = projection
gdata.service.Query.__init__(self, feed, text_query, params, categories)
def ToUri(self):
"""Generates a URI from the query parameters set in the object.
Returns:
A string containing the URI used to retrieve entries from the Document
List feed.
"""
old_feed = self.feed
self.feed = '/'.join([old_feed, self.visibility, self.projection])
new_feed = gdata.service.Query.ToUri(self)
self.feed = old_feed
return new_feed
def AddNamedFolder(self, email, folder_name):
"""Adds a named folder category, qualified by a schema.
This function lets you query for documents that are contained inside a
named folder without fear of collision with other categories.
Args:
email: string The email of the user who owns the folder.
folder_name: string The name of the folder.
Returns:
The string of the category that was added to the object.
"""
category = '{http://schemas.google.com/docs/2007/folders/'
category += email + '}' + folder_name
self.categories.append(category)
return category
def RemoveNamedFolder(self, email, folder_name):
"""Removes a named folder category, qualified by a schema.
Args:
email: string The email of the user who owns the folder.
folder_name: string The name of the folder.
Returns:
The string of the category that was removed to the object.
"""
category = '{http://schemas.google.com/docs/2007/folders/'
category += email + '}' + folder_name
self.categories.remove(category)
return category
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""DocsService extends the GDataService to streamline Google Documents
operations.
DocsService: Provides methods to query feeds and manipulate items.
Extends GDataService.
DocumentQuery: Queries a Google Document list feed.
"""
__author__ = 'api.jfisher (Jeff Fisher)'
import urllib
import atom
import gdata.service
import gdata.docs
# XML Namespaces used in Google Documents entities.
DATA_KIND_SCHEME = 'http://schemas.google.com/g/2005#kind'
DOCUMENT_KIND_TERM = 'http://schemas.google.com/docs/2007#document'
SPREADSHEET_KIND_TERM = 'http://schemas.google.com/docs/2007#spreadsheet'
PRESENTATION_KIND_TERM = 'http://schemas.google.com/docs/2007#presentation'
# File extensions of documents that are permitted to be uploaded.
SUPPORTED_FILETYPES = {
'CSV': 'text/csv',
'TSV': 'text/tab-separated-values',
'TAB': 'text/tab-separated-values',
'DOC': 'application/msword',
'ODS': 'application/x-vnd.oasis.opendocument.spreadsheet',
'ODT': 'application/vnd.oasis.opendocument.text',
'RTF': 'application/rtf',
'SXW': 'application/vnd.sun.xml.writer',
'TXT': 'text/plain',
'XLS': 'application/vnd.ms-excel',
'PPT': 'application/vnd.ms-powerpoint',
'PPS': 'application/vnd.ms-powerpoint',
'HTM': 'text/html',
'HTML' : 'text/html'}
class DocsService(gdata.service.GDataService):
"""Client extension for the Google Documents service Document List feed."""
def __init__(self, email=None, password=None, source=None,
server='docs.google.com', additional_headers=None):
"""Constructor for the DocsService.
Args:
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.
Yields:
A DocsService object used to communicate with the Google Documents
service.
"""
gdata.service.GDataService.__init__(self, email=email, password=password,
service='writely', source=source,
server=server,
additional_headers=additional_headers)
def Query(self, uri, converter=gdata.docs.DocumentListFeedFromString):
"""Queries the Document List feed and returns the resulting feed of
entries.
Args:
uri: string The full URI to be queried. This can contain query
parameters, a hostname, or simply the relative path to a Document
List feed. The DocumentQuery object is useful when constructing
query parameters.
converter: func (optional) A function which will be executed on the
retrieved item, generally to render it into a Python object.
By default the DocumentListFeedFromString function is used to
return a DocumentListFeed object. This is because most feed
queries will result in a feed and not a single entry.
"""
return self.Get(uri, converter=converter)
def QueryDocumentListFeed(self, uri):
"""Retrieves a DocumentListFeed by retrieving a URI based off the Document
List feed, including any query parameters. A DocumentQuery object can
be used to construct these parameters.
Args:
uri: string The URI of the feed being retrieved possibly with query
parameters.
Returns:
A DocumentListFeed object representing the feed returned by the server.
"""
return self.Get(uri, converter=gdata.docs.DocumentListFeedFromString)
def GetDocumentListEntry(self, uri):
"""Retrieves a particular DocumentListEntry by its unique URI.
Args:
uri: string The unique URI of an entry in a Document List feed.
Returns:
A DocumentListEntry object representing the retrieved entry.
"""
return self.Get(uri, converter=gdata.docs.DocumentListEntryFromString)
def GetDocumentListFeed(self):
"""Retrieves a feed containing all of a user's documents."""
q = gdata.docs.service.DocumentQuery();
return self.QueryDocumentListFeed(q.ToUri())
def UploadPresentation(self, media_source, title):
"""Uploads a presentation inside of a MediaSource object to the Document
List feed with the given title.
Args:
media_source: MediaSource The MediaSource object containing a
presentation file to be uploaded.
title: string The title of the presentation on the server after being
uploaded.
Returns:
A GDataEntry containing information about the presentation created on the
Google Documents service.
"""
category = atom.Category(scheme=DATA_KIND_SCHEME,
term=PRESENTATION_KIND_TERM)
return self._UploadFile(media_source, title, category)
def UploadSpreadsheet(self, media_source, title):
"""Uploads a spreadsheet inside of a MediaSource object to the Document
List feed with the given title.
Args:
media_source: MediaSource The MediaSource object containing a spreadsheet
file to be uploaded.
title: string The title of the spreadsheet on the server after being
uploaded.
Returns:
A GDataEntry containing information about the spreadsheet created on the
Google Documents service.
"""
category = atom.Category(scheme=DATA_KIND_SCHEME,
term=SPREADSHEET_KIND_TERM)
return self._UploadFile(media_source, title, category)
def UploadDocument(self, media_source, title):
"""Uploads a document inside of a MediaSource object to the Document List
feed with the given title.
Args:
media_source: MediaSource The gdata.MediaSource object containing a
document file to be uploaded.
title: string The title of the document on the server after being
uploaded.
Returns:
A GDataEntry containing information about the document created on the
Google Documents service.
"""
category = atom.Category(scheme=DATA_KIND_SCHEME,
term=DOCUMENT_KIND_TERM)
return self._UploadFile(media_source, title, category)
def _UploadFile(self, media_source, title, category):
"""Uploads a file to the Document List feed.
Args:
media_source: A gdata.MediaSource object containing the file to be
uploaded.
title: string The title of the document on the server after being
uploaded.
category: An atom.Category object specifying the appropriate document
type
Returns:
A GDataEntry containing information about the document created on
the Google Documents service.
"""
media_entry = gdata.GDataEntry()
media_entry.title = atom.Title(text=title)
media_entry.category.append(category)
media_entry = self.Post(media_entry, '/feeds/documents/private/full',
media_source = media_source,
extra_headers = {'Slug' : media_source.file_name })
return media_entry
class DocumentQuery(gdata.service.Query):
"""Object used to construct a URI to query the Google Document List feed"""
def __init__(self, feed='/feeds/documents', visibility='private',
projection='full', text_query=None, params=None,
categories=None):
"""Constructor for Document List Query
Args:
feed: string (optional) The path for the feed. (e.g. '/feeds/documents')
visibility: string (optional) The visibility chosen for the current feed.
projection: string (optional) The projection chosen for the current feed.
text_query: string (optional) The contents of the q query parameter. This
string is URL escaped upon conversion to a URI.
params: dict (optional) Parameter value string pairs which become URL
params when translated to a URI. These parameters are added to
the query's items.
categories: list (optional) List of category strings which should be
included as query categories. See gdata.service.Query for
additional documentation.
Yields:
A DocumentQuery object used to construct a URI based on the Document
List feed.
"""
self.visibility = visibility
self.projection = projection
gdata.service.Query.__init__(self, feed, text_query, params, categories)
def ToUri(self):
"""Generates a URI from the query parameters set in the object.
Returns:
A string containing the URI used to retrieve entries from the Document
List feed.
"""
old_feed = self.feed
self.feed = '/'.join([old_feed, self.visibility, self.projection])
new_feed = gdata.service.Query.ToUri(self)
self.feed = old_feed
return new_feed
def AddNamedFolder(self, email, folder_name):
"""Adds a named folder category, qualified by a schema.
This function lets you query for documents that are contained inside a
named folder without fear of collision with other categories.
Args:
email: string The email of the user who owns the folder.
folder_name: string The name of the folder.
Returns:
The string of the category that was added to the object.
"""
category = '{http://schemas.google.com/docs/2007/folders/'
category += email + '}' + folder_name
self.categories.append(category)
return category
def RemoveNamedFolder(self, email, folder_name):
"""Removes a named folder category, qualified by a schema.
Args:
email: string The email of the user who owns the folder.
folder_name: string The name of the folder.
Returns:
The string of the category that was removed to the object.
"""
category = '{http://schemas.google.com/docs/2007/folders/'
category += email + '}' + folder_name
self.categories.remove(category)
return category
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to Atom objects used with Google Documents."""
__author__ = 'api.jfisher (Jeff Fisher)'
import atom
import gdata
class DocumentListEntry(gdata.GDataEntry):
"""The Google Documents version of an Atom Entry"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
def DocumentListEntryFromString(xml_string):
"""Converts an XML string into a DocumentListEntry object.
Args:
xml_string: string The XML describing a Document List feed entry.
Returns:
A DocumentListEntry object corresponding to the given XML.
"""
return atom.CreateClassFromXMLString(DocumentListEntry, xml_string)
class DocumentListFeed(gdata.GDataFeed):
"""A feed containing a list of Google Documents Items"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[DocumentListEntry])
def DocumentListFeedFromString(xml_string):
"""Converts an XML string into a DocumentListFeed object.
Args:
xml_string: string The XML describing a DocumentList feed.
Returns:
A DocumentListFeed object corresponding to the given XML.
"""
return atom.CreateClassFromXMLString(DocumentListFeed, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to ElementWrapper objects used with Google Contacts."""
__author__ = 'dbrattli (Dag Brattli)'
import atom
import gdata
## Constants from http://code.google.com/apis/gdata/elements.html ##
REL_HOME = 'http://schemas.google.com/g/2005#home'
REL_WORK = 'http://schemas.google.com/g/2005#work'
REL_OTHER = 'http://schemas.google.com/g/2005#other'
IM_AIM = 'http://schemas.google.com/g/2005#AIM' # AOL Instant Messenger protocol
IM_MSN = 'http://schemas.google.com/g/2005#MSN' # MSN Messenger protocol
IM_YAHOO = 'http://schemas.google.com/g/2005#YAHOO' # Yahoo Messenger protocol
IM_SKYPE = 'http://schemas.google.com/g/2005#SKYPE' # Skype protocol
IM_QQ = 'http://schemas.google.com/g/2005#QQ' # QQ protocol
IM_GOOGLE_TALK = 'http://schemas.google.com/g/2005#GOOGLE_TALK' # Google Talk protocol
IM_ICQ = 'http://schemas.google.com/g/2005#ICQ' # ICQ protocol
IM_JABBER = 'http://schemas.google.com/g/2005#JABBER' # Jabber protocol
PHOTO_LINK_REL = 'http://schemas.google.com/contacts/2008/rel#photo'
PHOTO_EDIT_LINK_REL = 'http://schemas.google.com/contacts/2008/rel#edit-photo'
CONTACTS_NAMESPACE = 'http://schemas.google.com/contact/2008'
class OrgName(atom.AtomBase):
_tag = 'orgName'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, text=None,
extension_elements=None, extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class OrgTitle(atom.AtomBase):
_tag = 'orgTitle'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, text=None,
extension_elements=None, extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Organization(atom.AtomBase):
_tag = 'organization'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['rel'] = 'rel'
_attributes['label'] = 'label'
_attributes['primary'] = 'primary'
_children['{%s}orgName' % gdata.GDATA_NAMESPACE] = ('org_name', OrgName)
_children['{%s}orgTitle' % gdata.GDATA_NAMESPACE] = ('org_title', OrgTitle)
def __init__(self, rel=None, primary='false', org_name=None, org_title=None,
label=None, text=None, extension_elements=None,
extension_attributes=None):
self.rel = rel or REL_OTHER
self.primary = primary
self.org_name = org_name
self.org_title = org_title
self.label = label
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class PostalAddress(atom.AtomBase):
_tag = 'postalAddress'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['primary'] = 'primary'
_attributes['rel'] = 'rel'
def __init__(self, primary=None, rel=None, text=None,
extension_elements=None, extension_attributes=None):
self.primary = primary
self.rel = rel or REL_OTHER
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class IM(atom.AtomBase):
_tag = 'im'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['address'] = 'address'
_attributes['primary'] = 'primary'
_attributes['protocol'] = 'protocol'
_attributes['label'] = 'label'
_attributes['rel'] = 'rel'
def __init__(self, primary=None, rel=None, address=None, protocol=None,
label=None, text=None, extension_elements=None,
extension_attributes=None):
self.protocol = protocol
self.address = address
self.primary = primary
self.rel = rel or REL_OTHER
self.label = label
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Email(atom.AtomBase):
_tag = 'email'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['address'] = 'address'
_attributes['primary'] = 'primary'
_attributes['rel'] = 'rel'
_attributes['label'] = 'label'
def __init__(self, primary=None, rel=None, address=None, text=None,
label=None, extension_elements=None, extension_attributes=None):
self.address = address
self.primary = primary
self.rel = rel or REL_OTHER
self.label = label
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class PhoneNumber(atom.AtomBase):
_tag = 'phoneNumber'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['primary'] = 'primary'
_attributes['rel'] = 'rel'
def __init__(self, primary=None, rel=None, text=None,
extension_elements=None, extension_attributes=None):
self.primary = primary
self.rel = rel or REL_OTHER
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Deleted(atom.AtomBase):
_tag = 'deleted'
_namespace = gdata.GDATA_NAMESPACE
def __init__(self, text=None,
extension_elements=None, extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class GroupMembershipInfo(atom.AtomBase):
_tag = 'groupMembershipInfo'
_namespace = CONTACTS_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['deleted'] = 'deleted'
_attributes['href'] = 'href'
def __init__(self, deleted=None, href=None, text=None,
extension_elements=None, extension_attributes=None):
self.deleted = deleted
self.href = href
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class ContactEntry(gdata.BatchEntry):
"""A Google Contact flavor of an Atom Entry """
_children = gdata.BatchEntry._children.copy()
_children['{%s}postalAddress' % gdata.GDATA_NAMESPACE] = ('postal_address',
[PostalAddress])
_children['{%s}phoneNumber' % gdata.GDATA_NAMESPACE] = ('phone_number',
[PhoneNumber])
_children['{%s}organization' % gdata.GDATA_NAMESPACE] = ('organization',
Organization)
_children['{%s}email' % gdata.GDATA_NAMESPACE] = ('email', [Email])
_children['{%s}im' % gdata.GDATA_NAMESPACE] = ('im', [IM])
_children['{%s}deleted' % gdata.GDATA_NAMESPACE] = ('deleted', Deleted)
_children['{%s}groupMembershipInfo' % CONTACTS_NAMESPACE] = (
'group_membership_info', [GroupMembershipInfo])
_children['{%s}extendedProperty' % gdata.GDATA_NAMESPACE] = (
'extended_property', [gdata.ExtendedProperty])
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None, email=None, postal_address=None,
deleted=None, organization=None, phone_number=None, im=None,
extended_property=None, group_membership_info=None,
batch_operation=None, batch_id=None, batch_status=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.BatchEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link, published=published,
batch_operation=batch_operation, batch_id=batch_id,
batch_status=batch_status, title=title, updated=updated)
self.organization = organization
self.deleted = deleted
self.phone_number = phone_number or []
self.postal_address = postal_address or []
self.im = im or []
self.extended_property = extended_property or []
self.email = email or []
self.group_membership_info = group_membership_info or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GetPhotoLink(self):
for a_link in self.link:
if a_link.rel == PHOTO_LINK_REL:
return a_link
return None
def GetPhotoEditLink(self):
for a_link in self.link:
if a_link.rel == PHOTO_EDIT_LINK_REL:
return a_link
return None
def ContactEntryFromString(xml_string):
return atom.CreateClassFromXMLString(ContactEntry, xml_string)
class ContactsFeed(gdata.BatchFeed, gdata.LinkFinder):
"""A Google Contacts feed flavor of an Atom Feed"""
_children = gdata.BatchFeed._children.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [ContactEntry])
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None,
entry=None, total_results=None, start_index=None,
items_per_page=None, extension_elements=None,
extension_attributes=None, text=None):
gdata.BatchFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def ContactsFeedFromString(xml_string):
return atom.CreateClassFromXMLString(ContactsFeed, xml_string)
class GroupEntry(gdata.BatchEntry):
"""Represents a contact group."""
_children = gdata.BatchEntry._children.copy()
_children['{%s}extendedProperty' % gdata.GDATA_NAMESPACE] = (
'extended_property', [gdata.ExtendedProperty])
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, control=None, title=None, updated=None,
extended_property=None, batch_operation=None, batch_id=None,
batch_status=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.BatchEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
batch_operation=batch_operation, batch_id=batch_id,
batch_status=batch_status,
title=title, updated=updated)
self.extended_property = extended_property or []
def GroupEntryFromString(xml_string):
return atom.CreateClassFromXMLString(GroupEntry, xml_string)
class GroupsFeed(gdata.BatchFeed):
"""A Google contact groups feed flavor of an Atom Feed"""
_children = gdata.BatchFeed._children.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GroupEntry])
def GroupsFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GroupsFeed, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""ContactsService extends the GDataService to streamline Google Contacts operations.
ContactsService: Provides methods to query feeds and manipulate items. Extends
GDataService.
DictionaryToParamList: Function which converts a dictionary into a list of
URL arguments (represented as strings). This is a
utility function used in CRUD operations.
"""
__author__ = 'dbrattli (Dag Brattli)'
import gdata
import atom.service
import gdata.service
import gdata.calendar
import atom
class Error(Exception):
pass
class RequestError(Error):
pass
class ContactsService(gdata.service.GDataService):
"""Client for the Google Contats service."""
def __init__(self, email=None, password=None, source=None,
server='www.google.com',
additional_headers=None):
gdata.service.GDataService.__init__(self, email=email, password=password,
service='cp', source=source,
server=server,
additional_headers=additional_headers)
def GetContactsFeed(self,
uri='http://www.google.com/m8/feeds/contacts/default/full'):
return self.Get(uri, converter=gdata.contacts.ContactsFeedFromString)
def GetContact(self, uri):
return self.Get(uri, converter=gdata.contacts.ContactEntryFromString)
def CreateContact(self, new_contact,
insert_uri='/m8/feeds/contacts/default/full', url_params=None,
escape_params=True):
"""Adds an event to Google Contacts.
Args:
new_contact: atom.Entry or subclass A new event which is to be added to
Google Contacts.
insert_uri: the URL to post new contacts to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the contact created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Post(new_contact, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.contacts.ContactEntryFromString)
def UpdateContact(self, edit_uri, updated_contact, url_params=None,
escape_params=True):
"""Updates an existing contact.
Args:
edit_uri: string The edit link URI for the element being updated
updated_contact: string, atom.Entry or subclass containing
the Atom Entry which will replace the event which is
stored at the edit_url
url_params: dict (optional) Additional URL parameters to be included
in the update request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful update, a httplib.HTTPResponse containing the server's
response to the PUT request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Put(updated_contact, '/%s' % edit_uri,
url_params=url_params,
escape_params=escape_params,
converter=gdata.contacts.ContactEntryFromString)
def DeleteContact(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
"""Removes an event with the specified ID from Google Contacts.
Args:
edit_uri: string The edit URL of the entry to be deleted. Example:
'http://www.google.com/m8/feeds/contacts/default/full/xxx/yyy'
url_params: dict (optional) Additional URL parameters to be included
in the deletion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful delete, a httplib.HTTPResponse containing the server's
response to the DELETE request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Delete('/%s' % edit_uri,
url_params=url_params, escape_params=escape_params)
def GetGroupsFeed(self,
uri='http://www.google.com/m8/feeds/groups/default/full'):
return self.Get(uri, converter=gdata.contacts.GroupsFeedFromString)
def CreateGroup(self, new_group,
insert_uri='/m8/feeds/groups/default/full', url_params=None,
escape_params=True):
return self.Post(new_group, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.contacts.GroupEntryFromString)
def UpdateGroup(self, edit_uri, updated_group, url_params=None,
escape_params=True):
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Put(updated_group, '/%s' % edit_uri,
url_params=url_params,
escape_params=escape_params,
converter=gdata.contacts.GroupEntryFromString)
def DeleteGroup(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Delete('/%s' % edit_uri,
url_params=url_params, escape_params=escape_params)
def ChangePhoto(self, media, contact_entry_or_url, content_type=None,
content_length=None):
"""Change the photo for the contact by uploading a new photo.
Performs a PUT against the photo edit URL to send the binary data for the
photo.
Args:
media: filename, file-like-object, or a gdata.MediaSource object to send.
contact_entry_or_url: ContactEntry or str If it is a ContactEntry, this
method will search for an edit photo link URL and
perform a PUT to the URL.
content_type: str (optional) the mime type for the photo data. This is
necessary if media is a file or file name, but if media
is a MediaSource object then the media object can contain
the mime type. If media_type is set, it will override the
mime type in the media object.
content_length: int or str (optional) Specifying the content length is
only required if media is a file-like object. If media
is a filename, the length is determined using
os.path.getsize. If media is a MediaSource object, it is
assumed that it already contains the content length.
"""
if isinstance(contact_entry_or_url, gdata.contacts.ContactEntry):
url = contact_entry_or_url.GetPhotoEditLink().href
else:
url = contact_entry_or_url
if isinstance(media, gdata.MediaSource):
payload = media
# If the media object is a file-like object, then use it as the file
# handle in the in the MediaSource.
elif hasattr(media, 'read'):
payload = gdata.MediaSource(file_handle=media,
content_type=content_type, content_length=content_length)
# Assume that the media object is a file name.
else:
payload = gdata.MediaSource(content_type=content_type,
content_length=content_length, file_path=media)
return self.Put(payload, url)
def GetPhoto(self, contact_entry_or_url):
"""Retrives the binary data for the contact's profile photo as a string.
Args:
contact_entry_or_url: a gdata.contacts.ContactEntry objecr or a string
containing the photo link's URL. If the contact entry does not
contain a photo link, the image will not be fetched and this method
will return None.
"""
# TODO: add the ability to write out the binary image data to a file,
# reading and writing a chunk at a time to avoid potentially using up
# large amounts of memory.
url = None
if isinstance(contact_entry_or_url, gdata.contacts.ContactEntry):
photo_link = contact_entry_or_url.GetPhotoLink()
if photo_link:
url = photo_link.href
else:
url = contact_entry_or_url
if url:
return self.Get(url, converter=str)
else:
return None
def DeletePhoto(self, contact_entry_or_url):
url = None
if isinstance(contact_entry_or_url, gdata.contacts.ContactEntry):
url = contact_entry_or_url.GetPhotoEditLink().href
else:
url = contact_entry_or_url
if url:
self.Delete(url)
class ContactsQuery(gdata.service.Query):
def __init__(self, feed=None, text_query=None, params=None,
categories=None):
self.feed = feed or '/m8/feeds/contacts/default/full'
gdata.service.Query.__init__(self, feed=self.feed, text_query=text_query,
params=params, categories=categories)
def _GetGroup(self):
if 'group' in self:
return self['group']
else:
return None
def _SetGroup(self, group_id):
self['group'] = group_id
group = property(_GetGroup, _SetGroup,
doc='The group query parameter to find only contacts in this group')
| Python |
#!/usr/bin/python
#
# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""ContactsService extends the GDataService to streamline Google Contacts operations.
ContactsService: Provides methods to query feeds and manipulate items. Extends
GDataService.
DictionaryToParamList: Function which converts a dictionary into a list of
URL arguments (represented as strings). This is a
utility function used in CRUD operations.
"""
__author__ = 'dbrattli (Dag Brattli)'
import gdata
import atom.service
import gdata.service
import gdata.calendar
import atom
class Error(Exception):
pass
class RequestError(Error):
pass
class ContactsService(gdata.service.GDataService):
"""Client for the Google Contats service."""
def __init__(self, email=None, password=None, source=None,
server='www.google.com',
additional_headers=None):
gdata.service.GDataService.__init__(self, email=email, password=password,
service='cp', source=source,
server=server,
additional_headers=additional_headers)
def GetContactsFeed(self,
uri='http://www.google.com/m8/feeds/contacts/default/full'):
return self.Get(uri, converter=gdata.contacts.ContactsFeedFromString)
def GetContact(self, uri):
return self.Get(uri, converter=gdata.contacts.ContactEntryFromString)
def CreateContact(self, new_contact,
insert_uri='/m8/feeds/contacts/default/full', url_params=None,
escape_params=True):
"""Adds an event to Google Contacts.
Args:
new_contact: atom.Entry or subclass A new event which is to be added to
Google Contacts.
insert_uri: the URL to post new contacts to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the contact created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Post(new_contact, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.contacts.ContactEntryFromString)
def UpdateContact(self, edit_uri, updated_contact, url_params=None,
escape_params=True):
"""Updates an existing contact.
Args:
edit_uri: string The edit link URI for the element being updated
updated_contact: string, atom.Entry or subclass containing
the Atom Entry which will replace the event which is
stored at the edit_url
url_params: dict (optional) Additional URL parameters to be included
in the update request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful update, a httplib.HTTPResponse containing the server's
response to the PUT request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Put(updated_contact, '/%s' % edit_uri,
url_params=url_params,
escape_params=escape_params,
converter=gdata.contacts.ContactEntryFromString)
def DeleteContact(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
"""Removes an event with the specified ID from Google Contacts.
Args:
edit_uri: string The edit URL of the entry to be deleted. Example:
'http://www.google.com/m8/feeds/contacts/default/full/xxx/yyy'
url_params: dict (optional) Additional URL parameters to be included
in the deletion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful delete, a httplib.HTTPResponse containing the server's
response to the DELETE request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Delete('/%s' % edit_uri,
url_params=url_params, escape_params=escape_params)
def GetGroupsFeed(self,
uri='http://www.google.com/m8/feeds/groups/default/full'):
return self.Get(uri, converter=gdata.contacts.GroupsFeedFromString)
def CreateGroup(self, new_group,
insert_uri='/m8/feeds/groups/default/full', url_params=None,
escape_params=True):
return self.Post(new_group, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.contacts.GroupEntryFromString)
def UpdateGroup(self, edit_uri, updated_group, url_params=None,
escape_params=True):
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Put(updated_group, '/%s' % edit_uri,
url_params=url_params,
escape_params=escape_params,
converter=gdata.contacts.GroupEntryFromString)
def DeleteGroup(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Delete('/%s' % edit_uri,
url_params=url_params, escape_params=escape_params)
def ChangePhoto(self, media, contact_entry_or_url, content_type=None,
content_length=None):
"""Change the photo for the contact by uploading a new photo.
Performs a PUT against the photo edit URL to send the binary data for the
photo.
Args:
media: filename, file-like-object, or a gdata.MediaSource object to send.
contact_entry_or_url: ContactEntry or str If it is a ContactEntry, this
method will search for an edit photo link URL and
perform a PUT to the URL.
content_type: str (optional) the mime type for the photo data. This is
necessary if media is a file or file name, but if media
is a MediaSource object then the media object can contain
the mime type. If media_type is set, it will override the
mime type in the media object.
content_length: int or str (optional) Specifying the content length is
only required if media is a file-like object. If media
is a filename, the length is determined using
os.path.getsize. If media is a MediaSource object, it is
assumed that it already contains the content length.
"""
if isinstance(contact_entry_or_url, gdata.contacts.ContactEntry):
url = contact_entry_or_url.GetPhotoEditLink().href
else:
url = contact_entry_or_url
if isinstance(media, gdata.MediaSource):
payload = media
# If the media object is a file-like object, then use it as the file
# handle in the in the MediaSource.
elif hasattr(media, 'read'):
payload = gdata.MediaSource(file_handle=media,
content_type=content_type, content_length=content_length)
# Assume that the media object is a file name.
else:
payload = gdata.MediaSource(content_type=content_type,
content_length=content_length, file_path=media)
return self.Put(payload, url)
def GetPhoto(self, contact_entry_or_url):
"""Retrives the binary data for the contact's profile photo as a string.
Args:
contact_entry_or_url: a gdata.contacts.ContactEntry objecr or a string
containing the photo link's URL. If the contact entry does not
contain a photo link, the image will not be fetched and this method
will return None.
"""
# TODO: add the ability to write out the binary image data to a file,
# reading and writing a chunk at a time to avoid potentially using up
# large amounts of memory.
url = None
if isinstance(contact_entry_or_url, gdata.contacts.ContactEntry):
photo_link = contact_entry_or_url.GetPhotoLink()
if photo_link:
url = photo_link.href
else:
url = contact_entry_or_url
if url:
return self.Get(url, converter=str)
else:
return None
def DeletePhoto(self, contact_entry_or_url):
url = None
if isinstance(contact_entry_or_url, gdata.contacts.ContactEntry):
url = contact_entry_or_url.GetPhotoEditLink().href
else:
url = contact_entry_or_url
if url:
self.Delete(url)
class ContactsQuery(gdata.service.Query):
def __init__(self, feed=None, text_query=None, params=None,
categories=None):
self.feed = feed or '/m8/feeds/contacts/default/full'
gdata.service.Query.__init__(self, feed=self.feed, text_query=text_query,
params=params, categories=categories)
def _GetGroup(self):
if 'group' in self:
return self['group']
else:
return None
def _SetGroup(self, group_id):
self['group'] = group_id
group = property(_GetGroup, _SetGroup,
doc='The group query parameter to find only contacts in this group')
| Python |
#!/usr/bin/python
#
# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to ElementWrapper objects used with Google Contacts."""
__author__ = 'dbrattli (Dag Brattli)'
import atom
import gdata
## Constants from http://code.google.com/apis/gdata/elements.html ##
REL_HOME = 'http://schemas.google.com/g/2005#home'
REL_WORK = 'http://schemas.google.com/g/2005#work'
REL_OTHER = 'http://schemas.google.com/g/2005#other'
IM_AIM = 'http://schemas.google.com/g/2005#AIM' # AOL Instant Messenger protocol
IM_MSN = 'http://schemas.google.com/g/2005#MSN' # MSN Messenger protocol
IM_YAHOO = 'http://schemas.google.com/g/2005#YAHOO' # Yahoo Messenger protocol
IM_SKYPE = 'http://schemas.google.com/g/2005#SKYPE' # Skype protocol
IM_QQ = 'http://schemas.google.com/g/2005#QQ' # QQ protocol
IM_GOOGLE_TALK = 'http://schemas.google.com/g/2005#GOOGLE_TALK' # Google Talk protocol
IM_ICQ = 'http://schemas.google.com/g/2005#ICQ' # ICQ protocol
IM_JABBER = 'http://schemas.google.com/g/2005#JABBER' # Jabber protocol
PHOTO_LINK_REL = 'http://schemas.google.com/contacts/2008/rel#photo'
PHOTO_EDIT_LINK_REL = 'http://schemas.google.com/contacts/2008/rel#edit-photo'
CONTACTS_NAMESPACE = 'http://schemas.google.com/contact/2008'
class OrgName(atom.AtomBase):
_tag = 'orgName'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, text=None,
extension_elements=None, extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class OrgTitle(atom.AtomBase):
_tag = 'orgTitle'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, text=None,
extension_elements=None, extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Organization(atom.AtomBase):
_tag = 'organization'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['rel'] = 'rel'
_attributes['label'] = 'label'
_attributes['primary'] = 'primary'
_children['{%s}orgName' % gdata.GDATA_NAMESPACE] = ('org_name', OrgName)
_children['{%s}orgTitle' % gdata.GDATA_NAMESPACE] = ('org_title', OrgTitle)
def __init__(self, rel=None, primary='false', org_name=None, org_title=None,
label=None, text=None, extension_elements=None,
extension_attributes=None):
self.rel = rel or REL_OTHER
self.primary = primary
self.org_name = org_name
self.org_title = org_title
self.label = label
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class PostalAddress(atom.AtomBase):
_tag = 'postalAddress'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['primary'] = 'primary'
_attributes['rel'] = 'rel'
def __init__(self, primary=None, rel=None, text=None,
extension_elements=None, extension_attributes=None):
self.primary = primary
self.rel = rel or REL_OTHER
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class IM(atom.AtomBase):
_tag = 'im'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['address'] = 'address'
_attributes['primary'] = 'primary'
_attributes['protocol'] = 'protocol'
_attributes['label'] = 'label'
_attributes['rel'] = 'rel'
def __init__(self, primary=None, rel=None, address=None, protocol=None,
label=None, text=None, extension_elements=None,
extension_attributes=None):
self.protocol = protocol
self.address = address
self.primary = primary
self.rel = rel or REL_OTHER
self.label = label
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Email(atom.AtomBase):
_tag = 'email'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['address'] = 'address'
_attributes['primary'] = 'primary'
_attributes['rel'] = 'rel'
_attributes['label'] = 'label'
def __init__(self, primary=None, rel=None, address=None, text=None,
label=None, extension_elements=None, extension_attributes=None):
self.address = address
self.primary = primary
self.rel = rel or REL_OTHER
self.label = label
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class PhoneNumber(atom.AtomBase):
_tag = 'phoneNumber'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['primary'] = 'primary'
_attributes['rel'] = 'rel'
def __init__(self, primary=None, rel=None, text=None,
extension_elements=None, extension_attributes=None):
self.primary = primary
self.rel = rel or REL_OTHER
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Deleted(atom.AtomBase):
_tag = 'deleted'
_namespace = gdata.GDATA_NAMESPACE
def __init__(self, text=None,
extension_elements=None, extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class GroupMembershipInfo(atom.AtomBase):
_tag = 'groupMembershipInfo'
_namespace = CONTACTS_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['deleted'] = 'deleted'
_attributes['href'] = 'href'
def __init__(self, deleted=None, href=None, text=None,
extension_elements=None, extension_attributes=None):
self.deleted = deleted
self.href = href
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class ContactEntry(gdata.BatchEntry):
"""A Google Contact flavor of an Atom Entry """
_children = gdata.BatchEntry._children.copy()
_children['{%s}postalAddress' % gdata.GDATA_NAMESPACE] = ('postal_address',
[PostalAddress])
_children['{%s}phoneNumber' % gdata.GDATA_NAMESPACE] = ('phone_number',
[PhoneNumber])
_children['{%s}organization' % gdata.GDATA_NAMESPACE] = ('organization',
Organization)
_children['{%s}email' % gdata.GDATA_NAMESPACE] = ('email', [Email])
_children['{%s}im' % gdata.GDATA_NAMESPACE] = ('im', [IM])
_children['{%s}deleted' % gdata.GDATA_NAMESPACE] = ('deleted', Deleted)
_children['{%s}groupMembershipInfo' % CONTACTS_NAMESPACE] = (
'group_membership_info', [GroupMembershipInfo])
_children['{%s}extendedProperty' % gdata.GDATA_NAMESPACE] = (
'extended_property', [gdata.ExtendedProperty])
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None, email=None, postal_address=None,
deleted=None, organization=None, phone_number=None, im=None,
extended_property=None, group_membership_info=None,
batch_operation=None, batch_id=None, batch_status=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.BatchEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link, published=published,
batch_operation=batch_operation, batch_id=batch_id,
batch_status=batch_status, title=title, updated=updated)
self.organization = organization
self.deleted = deleted
self.phone_number = phone_number or []
self.postal_address = postal_address or []
self.im = im or []
self.extended_property = extended_property or []
self.email = email or []
self.group_membership_info = group_membership_info or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GetPhotoLink(self):
for a_link in self.link:
if a_link.rel == PHOTO_LINK_REL:
return a_link
return None
def GetPhotoEditLink(self):
for a_link in self.link:
if a_link.rel == PHOTO_EDIT_LINK_REL:
return a_link
return None
def ContactEntryFromString(xml_string):
return atom.CreateClassFromXMLString(ContactEntry, xml_string)
class ContactsFeed(gdata.BatchFeed, gdata.LinkFinder):
"""A Google Contacts feed flavor of an Atom Feed"""
_children = gdata.BatchFeed._children.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [ContactEntry])
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None,
entry=None, total_results=None, start_index=None,
items_per_page=None, extension_elements=None,
extension_attributes=None, text=None):
gdata.BatchFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def ContactsFeedFromString(xml_string):
return atom.CreateClassFromXMLString(ContactsFeed, xml_string)
class GroupEntry(gdata.BatchEntry):
"""Represents a contact group."""
_children = gdata.BatchEntry._children.copy()
_children['{%s}extendedProperty' % gdata.GDATA_NAMESPACE] = (
'extended_property', [gdata.ExtendedProperty])
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, control=None, title=None, updated=None,
extended_property=None, batch_operation=None, batch_id=None,
batch_status=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.BatchEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
batch_operation=batch_operation, batch_id=batch_id,
batch_status=batch_status,
title=title, updated=updated)
self.extended_property = extended_property or []
def GroupEntryFromString(xml_string):
return atom.CreateClassFromXMLString(GroupEntry, xml_string)
class GroupsFeed(gdata.BatchFeed):
"""A Google contact groups feed flavor of an Atom Feed"""
_children = gdata.BatchFeed._children.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GroupEntry])
def GroupsFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GroupsFeed, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to ElementWrapper objects used with Google Calendar."""
__author__ = 'api.vli (Vivian Li), api.rboyd (Ryan Boyd)'
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import atom
import gdata
# XML namespaces which are often used in Google Calendar entities.
GCAL_NAMESPACE = 'http://schemas.google.com/gCal/2005'
GCAL_TEMPLATE = '{http://schemas.google.com/gCal/2005}%s'
WEB_CONTENT_LINK_REL = '%s/%s' % (GCAL_NAMESPACE, 'webContent')
GACL_NAMESPACE = gdata.GACL_NAMESPACE
GACL_TEMPLATE = gdata.GACL_TEMPLATE
class ValueAttributeContainer(atom.AtomBase):
"""A parent class for all Calendar classes which have a value attribute.
Children include Color, AccessLevel, Hidden
"""
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, value=None, extension_elements=None,
extension_attributes=None, text=None):
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Color(ValueAttributeContainer):
"""The Google Calendar color element"""
_tag = 'color'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class AccessLevel(ValueAttributeContainer):
"""The Google Calendar accesslevel element"""
_tag = 'accesslevel'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class Hidden(ValueAttributeContainer):
"""The Google Calendar hidden element"""
_tag = 'hidden'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class Selected(ValueAttributeContainer):
"""The Google Calendar selected element"""
_tag = 'selected'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class Timezone(ValueAttributeContainer):
"""The Google Calendar timezone element"""
_tag = 'timezone'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class Where(atom.AtomBase):
"""The Google Calendar Where element"""
_tag = 'where'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['valueString'] = 'value_string'
def __init__(self, value_string=None, extension_elements=None,
extension_attributes=None, text=None):
self.value_string = value_string
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class CalendarListEntry(gdata.GDataEntry, gdata.LinkFinder):
"""A Google Calendar meta Entry flavor of an Atom Entry """
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}color' % GCAL_NAMESPACE] = ('color', Color)
_children['{%s}accesslevel' % GCAL_NAMESPACE] = ('access_level',
AccessLevel)
_children['{%s}hidden' % GCAL_NAMESPACE] = ('hidden', Hidden)
_children['{%s}selected' % GCAL_NAMESPACE] = ('selected', Selected)
_children['{%s}timezone' % GCAL_NAMESPACE] = ('timezone', Timezone)
_children['{%s}where' % gdata.GDATA_NAMESPACE] = ('where', Where)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
color=None, access_level=None, hidden=None, timezone=None,
selected=None,
where=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title,
updated=updated, text=None)
self.color = color
self.access_level = access_level
self.hidden = hidden
self.selected = selected
self.timezone = timezone
self.where = where
class CalendarListFeed(gdata.GDataFeed, gdata.LinkFinder):
"""A Google Calendar meta feed flavor of an Atom Feed"""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CalendarListEntry])
class Scope(atom.AtomBase):
"""The Google ACL scope element"""
_tag = 'scope'
_namespace = GACL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
_attributes['type'] = 'type'
def __init__(self, extension_elements=None, value=None, scope_type=None,
extension_attributes=None, text=None):
self.value = value
self.type = scope_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Role(ValueAttributeContainer):
"""The Google Calendar timezone element"""
_tag = 'role'
_namespace = GACL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class CalendarAclEntry(gdata.GDataEntry, gdata.LinkFinder):
"""A Google Calendar ACL Entry flavor of an Atom Entry """
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}scope' % GACL_NAMESPACE] = ('scope', Scope)
_children['{%s}role' % GACL_NAMESPACE] = ('role', Role)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
scope=None, role=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title,
updated=updated, text=None)
self.scope = scope
self.role = role
class CalendarAclFeed(gdata.GDataFeed, gdata.LinkFinder):
"""A Google Calendar ACL feed flavor of an Atom Feed"""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CalendarAclEntry])
class CalendarEventCommentEntry(gdata.GDataEntry, gdata.LinkFinder):
"""A Google Calendar event comments entry flavor of an Atom Entry"""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
class CalendarEventCommentFeed(gdata.GDataFeed, gdata.LinkFinder):
"""A Google Calendar event comments feed flavor of an Atom Feed"""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[CalendarEventCommentEntry])
class ExtendedProperty(gdata.ExtendedProperty):
"""A transparent subclass of gdata.ExtendedProperty added to this module
for backwards compatibility."""
class Reminder(atom.AtomBase):
"""The Google Calendar reminder element"""
_tag = 'reminder'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['absoluteTime'] = 'absolute_time'
_attributes['days'] = 'days'
_attributes['hours'] = 'hours'
_attributes['minutes'] = 'minutes'
def __init__(self, absolute_time=None,
days=None, hours=None, minutes=None,
extension_elements=None,
extension_attributes=None, text=None):
self.absolute_time = absolute_time
if days is not None:
self.days = str(days)
else:
self.days = None
if hours is not None:
self.hours = str(hours)
else:
self.hours = None
if minutes is not None:
self.minutes = str(minutes)
else:
self.minutes = None
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class When(atom.AtomBase):
"""The Google Calendar When element"""
_tag = 'when'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}reminder' % gdata.GDATA_NAMESPACE] = ('reminder', [Reminder])
_attributes['startTime'] = 'start_time'
_attributes['endTime'] = 'end_time'
def __init__(self, start_time=None, end_time=None, reminder=None,
extension_elements=None, extension_attributes=None, text=None):
self.start_time = start_time
self.end_time = end_time
self.reminder = reminder or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Recurrence(atom.AtomBase):
"""The Google Calendar Recurrence element"""
_tag = 'recurrence'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
class UriEnumElement(atom.AtomBase):
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, tag, enum_map, attrib_name='value',
extension_elements=None, extension_attributes=None, text=None):
self.tag=tag
self.enum_map=enum_map
self.attrib_name=attrib_name
self.value=None
self.text=text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def findKey(self, value):
res=[item[0] for item in self.enum_map.items() if item[1] == value]
if res is None or len(res) == 0:
return None
return res[0]
def _ConvertElementAttributeToMember(self, attribute, value):
# Special logic to use the enum_map to set the value of the object's value member.
if attribute == self.attrib_name and value != '':
self.value = self.enum_map[value]
return
# Find the attribute in this class's list of attributes.
if self.__class__._attributes.has_key(attribute):
# Find the member of this class which corresponds to the XML attribute
# (lookup in current_class._attributes) and set this member to the
# desired value (using self.__dict__).
setattr(self, self.__class__._attributes[attribute], value)
else:
# The current class doesn't map this attribute, so try to parent class.
atom.ExtensionContainer._ConvertElementAttributeToMember(self,
attribute,
value)
def _AddMembersToElementTree(self, tree):
# Convert the members of this class which are XML child nodes.
# This uses the class's _children dictionary to find the members which
# should become XML child nodes.
member_node_names = [values[0] for tag, values in
self.__class__._children.iteritems()]
for member_name in member_node_names:
member = getattr(self, member_name)
if member is None:
pass
elif isinstance(member, list):
for instance in member:
instance._BecomeChildElement(tree)
else:
member._BecomeChildElement(tree)
# Special logic to set the desired XML attribute.
key = self.findKey(self.value)
if key is not None:
tree.attrib[self.attrib_name]=key
# Convert the members of this class which are XML attributes.
for xml_attribute, member_name in self.__class__._attributes.iteritems():
member = getattr(self, member_name)
if member is not None:
tree.attrib[xml_attribute] = member
# Lastly, call the parent's _AddMembersToElementTree to get any
# extension elements.
atom.ExtensionContainer._AddMembersToElementTree(self, tree)
class AttendeeStatus(UriEnumElement):
"""The Google Calendar attendeeStatus element"""
_tag = 'attendeeStatus'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
attendee_enum = {
'http://schemas.google.com/g/2005#event.accepted' : 'ACCEPTED',
'http://schemas.google.com/g/2005#event.declined' : 'DECLINED',
'http://schemas.google.com/g/2005#event.invited' : 'INVITED',
'http://schemas.google.com/g/2005#event.tentative' : 'TENTATIVE'}
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, 'attendeeStatus', AttendeeStatus.attendee_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
class AttendeeType(UriEnumElement):
"""The Google Calendar attendeeType element"""
_tag = 'attendeeType'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
attendee_type_enum = {
'http://schemas.google.com/g/2005#event.optional' : 'OPTIONAL',
'http://schemas.google.com/g/2005#event.required' : 'REQUIRED' }
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, 'attendeeType',
AttendeeType.attendee_type_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,text=text)
class Visibility(UriEnumElement):
"""The Google Calendar Visibility element"""
_tag = 'visibility'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
visibility_enum = {
'http://schemas.google.com/g/2005#event.confidential' : 'CONFIDENTIAL',
'http://schemas.google.com/g/2005#event.default' : 'DEFAULT',
'http://schemas.google.com/g/2005#event.private' : 'PRIVATE',
'http://schemas.google.com/g/2005#event.public' : 'PUBLIC' }
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, 'visibility', Visibility.visibility_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
class Transparency(UriEnumElement):
"""The Google Calendar Transparency element"""
_tag = 'transparency'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
transparency_enum = {
'http://schemas.google.com/g/2005#event.opaque' : 'OPAQUE',
'http://schemas.google.com/g/2005#event.transparent' : 'TRANSPARENT' }
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, tag='transparency',
enum_map=Transparency.transparency_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
class Comments(atom.AtomBase):
"""The Google Calendar comments element"""
_tag = 'comments'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
gdata.FeedLink)
_attributes['rel'] = 'rel'
def __init__(self, rel=None, feed_link=None, extension_elements=None,
extension_attributes=None, text=None):
self.rel = rel
self.feed_link = feed_link
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class EventStatus(UriEnumElement):
"""The Google Calendar eventStatus element"""
_tag = 'eventStatus'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
status_enum = { 'http://schemas.google.com/g/2005#event.canceled' : 'CANCELED',
'http://schemas.google.com/g/2005#event.confirmed' : 'CONFIRMED',
'http://schemas.google.com/g/2005#event.tentative' : 'TENTATIVE'}
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, tag='eventStatus',
enum_map=EventStatus.status_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
class Who(UriEnumElement):
"""The Google Calendar Who element"""
_tag = 'who'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
_children['{%s}attendeeStatus' % gdata.GDATA_NAMESPACE] = (
'attendee_status', AttendeeStatus)
_children['{%s}attendeeType' % gdata.GDATA_NAMESPACE] = ('attendee_type',
AttendeeType)
_attributes['valueString'] = 'name'
_attributes['email'] = 'email'
relEnum = { 'http://schemas.google.com/g/2005#event.attendee' : 'ATTENDEE',
'http://schemas.google.com/g/2005#event.organizer' : 'ORGANIZER',
'http://schemas.google.com/g/2005#event.performer' : 'PERFORMER',
'http://schemas.google.com/g/2005#event.speaker' : 'SPEAKER',
'http://schemas.google.com/g/2005#message.bcc' : 'BCC',
'http://schemas.google.com/g/2005#message.cc' : 'CC',
'http://schemas.google.com/g/2005#message.from' : 'FROM',
'http://schemas.google.com/g/2005#message.reply-to' : 'REPLY_TO',
'http://schemas.google.com/g/2005#message.to' : 'TO' }
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, 'who', Who.relEnum, attrib_name='rel',
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.name=None
self.email=None
self.attendee_status=None
self.attendee_type=None
self.rel=None
class OriginalEvent(atom.AtomBase):
"""The Google Calendar OriginalEvent element"""
_tag = 'originalEvent'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
# TODO: The when tag used to map to a EntryLink, make sure it should really be a When.
_children['{%s}when' % gdata.GDATA_NAMESPACE] = ('when', When)
_attributes['id'] = 'id'
_attributes['href'] = 'href'
def __init__(self, id=None, href=None, when=None,
extension_elements=None, extension_attributes=None, text=None):
self.id = id
self.href = href
self.when = when
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GetCalendarEventEntryClass():
return CalendarEventEntry
# This class is not completely defined here, because of a circular reference
# in which CalendarEventEntryLink and CalendarEventEntry refer to one another.
class CalendarEventEntryLink(gdata.EntryLink):
"""An entryLink which contains a calendar event entry
Within an event's recurranceExceptions, an entry link
points to a calendar event entry. This class exists
to capture the calendar specific extensions in the entry.
"""
_tag = 'entryLink'
_namespace = gdata.GDATA_NAMESPACE
_children = gdata.EntryLink._children.copy()
_attributes = gdata.EntryLink._attributes.copy()
# The CalendarEventEntryLink should like CalendarEventEntry as a child but
# that class hasn't been defined yet, so we will wait until after defining
# CalendarEventEntry to list it in _children.
class RecurrenceException(atom.AtomBase):
"""The Google Calendar RecurrenceException element"""
_tag = 'recurrenceException'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}entryLink' % gdata.GDATA_NAMESPACE] = ('entry_link',
CalendarEventEntryLink)
_children['{%s}originalEvent' % gdata.GDATA_NAMESPACE] = ('original_event',
OriginalEvent)
_attributes['specialized'] = 'specialized'
def __init__(self, specialized=None, entry_link=None,
original_event=None, extension_elements=None,
extension_attributes=None, text=None):
self.specialized = specialized
self.entry_link = entry_link
self.original_event = original_event
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class SendEventNotifications(atom.AtomBase):
"""The Google Calendar sendEventNotifications element"""
_tag = 'sendEventNotifications'
_namespace = GCAL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, extension_elements=None,
value=None, extension_attributes=None, text=None):
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class QuickAdd(atom.AtomBase):
"""The Google Calendar quickadd element"""
_tag = 'quickadd'
_namespace = GCAL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, extension_elements=None,
value=None, extension_attributes=None, text=None):
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def _TransferToElementTree(self, element_tree):
if self.value:
element_tree.attrib['value'] = self.value
element_tree.tag = GCAL_TEMPLATE % 'quickadd'
atom.AtomBase._TransferToElementTree(self, element_tree)
return element_tree
def _TakeAttributeFromElementTree(self, attribute, element_tree):
if attribute == 'value':
self.value = element_tree.attrib[attribute]
del element_tree.attrib[attribute]
else:
atom.AtomBase._TakeAttributeFromElementTree(self, attribute,
element_tree)
class WebContentGadgetPref(atom.AtomBase):
_tag = 'webContentGadgetPref'
_namespace = GCAL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['name'] = 'name'
_attributes['value'] = 'value'
"""The Google Calendar Web Content Gadget Preferences element"""
def __init__(self, name=None, value=None, extension_elements=None,
extension_attributes=None, text=None):
self.name = name
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class WebContent(atom.AtomBase):
_tag = 'webContent'
_namespace = GCAL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}webContentGadgetPref' % GCAL_NAMESPACE] = ('gadget_pref',
[WebContentGadgetPref])
_attributes['url'] = 'url'
_attributes['width'] = 'width'
_attributes['height'] = 'height'
def __init__(self, url=None, width=None, height=None, text=None,
gadget_pref=None, extension_elements=None, extension_attributes=None):
self.url = url
self.width = width
self.height = height
self.text = text
self.gadget_pref = gadget_pref or []
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class WebContentLink(atom.Link):
_tag = 'link'
_namespace = atom.ATOM_NAMESPACE
_children = atom.Link._children.copy()
_attributes = atom.Link._attributes.copy()
_children['{%s}webContent' % GCAL_NAMESPACE] = ('web_content', WebContent)
def __init__(self, title=None, href=None, link_type=None,
web_content=None):
atom.Link.__init__(self, rel=WEB_CONTENT_LINK_REL, title=title, href=href,
link_type=link_type)
self.web_content = web_content
class CalendarEventEntry(gdata.BatchEntry):
"""A Google Calendar flavor of an Atom Entry """
_tag = gdata.BatchEntry._tag
_namespace = gdata.BatchEntry._namespace
_children = gdata.BatchEntry._children.copy()
_attributes = gdata.BatchEntry._attributes.copy()
# This class also contains WebContentLinks but converting those members
# is handled in a special version of _ConvertElementTreeToMember.
_children['{%s}where' % gdata.GDATA_NAMESPACE] = ('where', [Where])
_children['{%s}when' % gdata.GDATA_NAMESPACE] = ('when', [When])
_children['{%s}who' % gdata.GDATA_NAMESPACE] = ('who', [Who])
_children['{%s}extendedProperty' % gdata.GDATA_NAMESPACE] = (
'extended_property', [ExtendedProperty])
_children['{%s}visibility' % gdata.GDATA_NAMESPACE] = ('visibility',
Visibility)
_children['{%s}transparency' % gdata.GDATA_NAMESPACE] = ('transparency',
Transparency)
_children['{%s}eventStatus' % gdata.GDATA_NAMESPACE] = ('event_status',
EventStatus)
_children['{%s}recurrence' % gdata.GDATA_NAMESPACE] = ('recurrence',
Recurrence)
_children['{%s}recurrenceException' % gdata.GDATA_NAMESPACE] = (
'recurrence_exception', [RecurrenceException])
_children['{%s}sendEventNotifications' % GCAL_NAMESPACE] = (
'send_event_notifications', SendEventNotifications)
_children['{%s}quickadd' % GCAL_NAMESPACE] = ('quick_add', QuickAdd)
_children['{%s}comments' % gdata.GDATA_NAMESPACE] = ('comments', Comments)
_children['{%s}originalEvent' % gdata.GDATA_NAMESPACE] = ('original_event',
OriginalEvent)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
transparency=None, comments=None, event_status=None,
send_event_notifications=None, visibility=None,
recurrence=None, recurrence_exception=None,
where=None, when=None, who=None, quick_add=None,
extended_property=None, original_event=None,
batch_operation=None, batch_id=None, batch_status=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.BatchEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
batch_operation=batch_operation, batch_id=batch_id,
batch_status=batch_status,
title=title, updated=updated)
self.transparency = transparency
self.comments = comments
self.event_status = event_status
self.send_event_notifications = send_event_notifications
self.visibility = visibility
self.recurrence = recurrence
self.recurrence_exception = recurrence_exception or []
self.where = where or []
self.when = when or []
self.who = who or []
self.quick_add = quick_add
self.extended_property = extended_property or []
self.original_event = original_event
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
# We needed to add special logic to _ConvertElementTreeToMember because we
# want to make links with a rel of WEB_CONTENT_LINK_REL into a
# WebContentLink
def _ConvertElementTreeToMember(self, child_tree):
# Special logic to handle Web Content links
if (child_tree.tag == '{%s}link' % atom.ATOM_NAMESPACE and
child_tree.attrib['rel'] == WEB_CONTENT_LINK_REL):
if self.link is None:
self.link = []
self.link.append(atom._CreateClassFromElementTree(WebContentLink,
child_tree))
return
# Find the element's tag in this class's list of child members
if self.__class__._children.has_key(child_tree.tag):
member_name = self.__class__._children[child_tree.tag][0]
member_class = self.__class__._children[child_tree.tag][1]
# If the class member is supposed to contain a list, make sure the
# matching member is set to a list, then append the new member
# instance to the list.
if isinstance(member_class, list):
if getattr(self, member_name) is None:
setattr(self, member_name, [])
getattr(self, member_name).append(atom._CreateClassFromElementTree(
member_class[0], child_tree))
else:
setattr(self, member_name,
atom._CreateClassFromElementTree(member_class, child_tree))
else:
atom.ExtensionContainer._ConvertElementTreeToMember(self, child_tree)
def GetWebContentLink(self):
"""Finds the first link with rel set to WEB_CONTENT_REL
Returns:
A gdata.calendar.WebContentLink or none if none of the links had rel
equal to WEB_CONTENT_REL
"""
for a_link in self.link:
if a_link.rel == WEB_CONTENT_LINK_REL:
return a_link
return None
def CalendarEventEntryFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventEntry, xml_string)
def CalendarEventCommentEntryFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventCommentEntry, xml_string)
CalendarEventEntryLink._children = {'{%s}entry' % atom.ATOM_NAMESPACE:
('entry', CalendarEventEntry)}
def CalendarEventEntryLinkFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventEntryLink, xml_string)
class CalendarEventFeed(gdata.BatchFeed, gdata.LinkFinder):
"""A Google Calendar event feed flavor of an Atom Feed"""
_tag = gdata.BatchFeed._tag
_namespace = gdata.BatchFeed._namespace
_children = gdata.BatchFeed._children.copy()
_attributes = gdata.BatchFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[CalendarEventEntry])
_children['{%s}timezone' % GCAL_NAMESPACE] = ('timezone', Timezone)
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None, entry=None,
total_results=None, start_index=None, items_per_page=None,
interrupted=None, timezone=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.BatchFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
interrupted=interrupted,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.timezone = timezone
def CalendarListEntryFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarListEntry, xml_string)
def CalendarAclEntryFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarAclEntry, xml_string)
def CalendarListFeedFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarListFeed, xml_string)
def CalendarAclFeedFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarAclFeed, xml_string)
def CalendarEventFeedFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventFeed, xml_string)
def CalendarEventCommentFeedFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventCommentFeed, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""CalendarService extends the GDataService to streamline Google Calendar operations.
CalendarService: Provides methods to query feeds and manipulate items. Extends
GDataService.
DictionaryToParamList: Function which converts a dictionary into a list of
URL arguments (represented as strings). This is a
utility function used in CRUD operations.
"""
__author__ = 'api.vli (Vivian Li)'
import urllib
import gdata
import atom.service
import gdata.service
import gdata.calendar
import atom
DEFAULT_BATCH_URL = ('http://www.google.com/calendar/feeds/default/private'
'/full/batch')
class Error(Exception):
pass
class RequestError(Error):
pass
class CalendarService(gdata.service.GDataService):
"""Client for the Google Calendar service."""
def __init__(self, email=None, password=None, source=None,
server='www.google.com',
additional_headers=None):
gdata.service.GDataService.__init__(self, email=email, password=password,
service='cl', source=source,
server=server,
additional_headers=additional_headers)
def GetCalendarEventFeed(self, uri='/calendar/feeds/default/private/full'):
return self.Get(uri, converter=gdata.calendar.CalendarEventFeedFromString)
def GetCalendarEventEntry(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarEventEntryFromString)
def GetCalendarListFeed(self, uri='/calendar/feeds/default/allcalendars/full'):
return self.Get(uri, converter=gdata.calendar.CalendarListFeedFromString)
def GetAllCalendarsFeed(self, uri='/calendar/feeds/default/allcalendars/full'):
return self.Get(uri, converter=gdata.calendar.CalendarListFeedFromString)
def GetOwnCalendarsFeed(self, uri='/calendar/feeds/default/owncalendars/full'):
return self.Get(uri, converter=gdata.calendar.CalendarListFeedFromString)
def GetCalendarListEntry(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarListEntryFromString)
def GetCalendarAclFeed(self, uri='/calendar/feeds/default/acl/full'):
return self.Get(uri, converter=gdata.calendar.CalendarAclFeedFromString)
def GetCalendarAclEntry(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarAclEntryFromString)
def GetCalendarEventCommentFeed(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarEventCommentFeedFromString)
def GetCalendarEventCommentEntry(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarEventCommentEntryFromString)
def Query(self, uri, converter=None):
"""Performs a query and returns a resulting feed or entry.
Args:
feed: string The feed which is to be queried
Returns:
On success, a GDataFeed or Entry depending on which is sent from the
server.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
if converter:
result = self.Get(uri, converter=converter)
else:
result = self.Get(uri)
return result
def CalendarQuery(self, query):
if isinstance(query, CalendarEventQuery):
return self.Query(query.ToUri(),
converter=gdata.calendar.CalendarEventFeedFromString)
elif isinstance(query, CalendarListQuery):
return self.Query(query.ToUri(),
converter=gdata.calendar.CalendarListFeedFromString)
elif isinstance(query, CalendarEventCommentQuery):
return self.Query(query.ToUri(),
converter=gdata.calendar.CalendarEventCommentFeedFromString)
else:
return self.Query(query.ToUri())
def InsertEvent(self, new_event, insert_uri, url_params=None,
escape_params=True):
"""Adds an event to Google Calendar.
Args:
new_event: atom.Entry or subclass A new event which is to be added to
Google Calendar.
insert_uri: the URL to post new events to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the event created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Post(new_event, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarEventEntryFromString)
def InsertCalendarSubscription(self, calendar, url_params=None,
escape_params=True):
"""Subscribes the authenticated user to the provided calendar.
Args:
calendar: The calendar to which the user should be subscribed.
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the subscription created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
insert_uri = '/calendar/feeds/default/allcalendars/full'
return self.Post(calendar, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarListEntryFromString)
def InsertCalendar(self, new_calendar, url_params=None,
escape_params=True):
"""Creates a new calendar.
Args:
new_calendar: The calendar to be created
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the calendar created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
insert_uri = '/calendar/feeds/default/owncalendars/full'
response = self.Post(new_calendar, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarListEntryFromString)
return response
def UpdateCalendar(self, calendar, url_params=None,
escape_params=True):
"""Updates a calendar.
Args:
calendar: The calendar which should be updated
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the calendar created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
update_uri = calendar.GetEditLink().href
response = self.Put(data=calendar, uri=update_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarListEntryFromString)
return response
def InsertAclEntry(self, new_entry, insert_uri, url_params=None,
escape_params=True):
"""Adds an ACL entry (rule) to Google Calendar.
Args:
new_entry: atom.Entry or subclass A new ACL entry which is to be added to
Google Calendar.
insert_uri: the URL to post new entries to the ACL feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the ACL entry created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Post(new_entry, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarAclEntryFromString)
def InsertEventComment(self, new_entry, insert_uri, url_params=None,
escape_params=True):
"""Adds an entry to Google Calendar.
Args:
new_entry: atom.Entry or subclass A new entry which is to be added to
Google Calendar.
insert_uri: the URL to post new entrys to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the comment created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Post(new_entry, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarEventCommentEntryFromString)
def DeleteEvent(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
"""Removes an event with the specified ID from Google Calendar.
Args:
edit_uri: string The edit URL of the entry to be deleted. Example:
'http://www.google.com/calendar/feeds/default/private/full/abx'
url_params: dict (optional) Additional URL parameters to be included
in the deletion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful delete, a httplib.HTTPResponse containing the server's
response to the DELETE request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Delete('/%s' % edit_uri,
url_params=url_params, escape_params=escape_params)
def DeleteAclEntry(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
"""Removes an ACL entry at the given edit_uri from Google Calendar.
Args:
edit_uri: string The edit URL of the entry to be deleted. Example:
'http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/default'
url_params: dict (optional) Additional URL parameters to be included
in the deletion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful delete, a httplib.HTTPResponse containing the server's
response to the DELETE request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Delete('/%s' % edit_uri,
url_params=url_params, escape_params=escape_params)
def DeleteCalendarEntry(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
"""Removes a calendar entry at the given edit_uri from Google Calendar.
Args:
edit_uri: string The edit URL of the entry to be deleted. Example:
'http://www.google.com/calendar/feeds/default/allcalendars/abcdef@group.calendar.google.com'
url_params: dict (optional) Additional URL parameters to be included
in the deletion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful delete, True is returned
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Delete(edit_uri, url_params=url_params,
escape_params=escape_params)
def UpdateEvent(self, edit_uri, updated_event, url_params=None,
escape_params=True):
"""Updates an existing event.
Args:
edit_uri: string The edit link URI for the element being updated
updated_event: string, atom.Entry, or subclass containing
the Atom Entry which will replace the event which is
stored at the edit_url
url_params: dict (optional) Additional URL parameters to be included
in the update request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful update, a httplib.HTTPResponse containing the server's
response to the PUT request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Put(updated_event, '/%s' % edit_uri,
url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarEventEntryFromString)
def UpdateAclEntry(self, edit_uri, updated_rule, url_params=None,
escape_params=True):
"""Updates an existing ACL rule.
Args:
edit_uri: string The edit link URI for the element being updated
updated_rule: string, atom.Entry, or subclass containing
the Atom Entry which will replace the event which is
stored at the edit_url
url_params: dict (optional) Additional URL parameters to be included
in the update request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful update, a httplib.HTTPResponse containing the server's
response to the PUT request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Put(updated_rule, '/%s' % edit_uri,
url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarAclEntryFromString)
def ExecuteBatch(self, batch_feed, url,
converter=gdata.calendar.CalendarEventFeedFromString):
"""Sends a batch request feed to the server.
The batch request needs to be sent to the batch URL for a particular
calendar. You can find the URL by calling GetBatchLink().href on the
CalendarEventFeed.
Args:
batch_feed: gdata.calendar.CalendarEventFeed A feed containing batch
request entries. Each entry contains the operation to be performed
on the data contained in the entry. For example an entry with an
operation type of insert will be used as if the individual entry
had been inserted.
url: str The batch URL for the Calendar to which these operations should
be applied.
converter: Function (optional) The function used to convert the server's
response to an object. The default value is
CalendarEventFeedFromString.
Returns:
The results of the batch request's execution on the server. If the
default converter is used, this is stored in a CalendarEventFeed.
"""
return self.Post(batch_feed, url, converter=converter)
class CalendarEventQuery(gdata.service.Query):
def __init__(self, user='default', visibility='private', projection='full',
text_query=None, params=None, categories=None):
gdata.service.Query.__init__(self,
feed='http://www.google.com/calendar/feeds/%s/%s/%s' % (
urllib.quote(user),
urllib.quote(visibility),
urllib.quote(projection)),
text_query=text_query, params=params, categories=categories)
def _GetStartMin(self):
if 'start-min' in self.keys():
return self['start-min']
else:
return None
def _SetStartMin(self, val):
self['start-min'] = val
start_min = property(_GetStartMin, _SetStartMin,
doc="""The start-min query parameter""")
def _GetStartMax(self):
if 'start-max' in self.keys():
return self['start-max']
else:
return None
def _SetStartMax(self, val):
self['start-max'] = val
start_max = property(_GetStartMax, _SetStartMax,
doc="""The start-max query parameter""")
def _GetOrderBy(self):
if 'orderby' in self.keys():
return self['orderby']
else:
return None
def _SetOrderBy(self, val):
if val is not 'lastmodified' and val is not 'starttime':
raise Error, "Order By must be either 'lastmodified' or 'starttime'"
self['orderby'] = val
orderby = property(_GetOrderBy, _SetOrderBy,
doc="""The orderby query parameter""")
def _GetSortOrder(self):
if 'sortorder' in self.keys():
return self['sortorder']
else:
return None
def _SetSortOrder(self, val):
if (val is not 'ascending' and val is not 'descending'
and val is not 'a' and val is not 'd' and val is not 'ascend'
and val is not 'descend'):
raise Error, "Sort order must be either ascending, ascend, " + (
"a or descending, descend, or d")
self['sortorder'] = val
sortorder = property(_GetSortOrder, _SetSortOrder,
doc="""The sortorder query parameter""")
def _GetSingleEvents(self):
if 'singleevents' in self.keys():
return self['singleevents']
else:
return None
def _SetSingleEvents(self, val):
self['singleevents'] = val
singleevents = property(_GetSingleEvents, _SetSingleEvents,
doc="""The singleevents query parameter""")
def _GetFutureEvents(self):
if 'futureevents' in self.keys():
return self['futureevents']
else:
return None
def _SetFutureEvents(self, val):
self['futureevents'] = val
futureevents = property(_GetFutureEvents, _SetFutureEvents,
doc="""The futureevents query parameter""")
def _GetRecurrenceExpansionStart(self):
if 'recurrence-expansion-start' in self.keys():
return self['recurrence-expansion-start']
else:
return None
def _SetRecurrenceExpansionStart(self, val):
self['recurrence-expansion-start'] = val
recurrence_expansion_start = property(_GetRecurrenceExpansionStart,
_SetRecurrenceExpansionStart,
doc="""The recurrence-expansion-start query parameter""")
def _GetRecurrenceExpansionEnd(self):
if 'recurrence-expansion-end' in self.keys():
return self['recurrence-expansion-end']
else:
return None
def _SetRecurrenceExpansionEnd(self, val):
self['recurrence-expansion-end'] = val
recurrence_expansion_end = property(_GetRecurrenceExpansionEnd,
_SetRecurrenceExpansionEnd,
doc="""The recurrence-expansion-end query parameter""")
def _SetTimezone(self, val):
self['ctz'] = val
def _GetTimezone(self):
if 'ctz' in self.keys():
return self['ctz']
else:
return None
ctz = property(_GetTimezone, _SetTimezone,
doc="""The ctz query parameter which sets report time on the server.""")
class CalendarListQuery(gdata.service.Query):
"""Queries the Google Calendar meta feed"""
def __init__(self, userId=None, text_query=None,
params=None, categories=None):
if userId is None:
userId = 'default'
gdata.service.Query.__init__(self, feed='http://www.google.com/calendar/feeds/'
+userId,
text_query=text_query, params=params,
categories=categories)
class CalendarEventCommentQuery(gdata.service.Query):
"""Queries the Google Calendar event comments feed"""
def __init__(self, feed=None):
gdata.service.Query.__init__(self, feed=feed)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""CalendarService extends the GDataService to streamline Google Calendar operations.
CalendarService: Provides methods to query feeds and manipulate items. Extends
GDataService.
DictionaryToParamList: Function which converts a dictionary into a list of
URL arguments (represented as strings). This is a
utility function used in CRUD operations.
"""
__author__ = 'api.vli (Vivian Li)'
import urllib
import gdata
import atom.service
import gdata.service
import gdata.calendar
import atom
DEFAULT_BATCH_URL = ('http://www.google.com/calendar/feeds/default/private'
'/full/batch')
class Error(Exception):
pass
class RequestError(Error):
pass
class CalendarService(gdata.service.GDataService):
"""Client for the Google Calendar service."""
def __init__(self, email=None, password=None, source=None,
server='www.google.com',
additional_headers=None):
gdata.service.GDataService.__init__(self, email=email, password=password,
service='cl', source=source,
server=server,
additional_headers=additional_headers)
def GetCalendarEventFeed(self, uri='/calendar/feeds/default/private/full'):
return self.Get(uri, converter=gdata.calendar.CalendarEventFeedFromString)
def GetCalendarEventEntry(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarEventEntryFromString)
def GetCalendarListFeed(self, uri='/calendar/feeds/default/allcalendars/full'):
return self.Get(uri, converter=gdata.calendar.CalendarListFeedFromString)
def GetAllCalendarsFeed(self, uri='/calendar/feeds/default/allcalendars/full'):
return self.Get(uri, converter=gdata.calendar.CalendarListFeedFromString)
def GetOwnCalendarsFeed(self, uri='/calendar/feeds/default/owncalendars/full'):
return self.Get(uri, converter=gdata.calendar.CalendarListFeedFromString)
def GetCalendarListEntry(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarListEntryFromString)
def GetCalendarAclFeed(self, uri='/calendar/feeds/default/acl/full'):
return self.Get(uri, converter=gdata.calendar.CalendarAclFeedFromString)
def GetCalendarAclEntry(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarAclEntryFromString)
def GetCalendarEventCommentFeed(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarEventCommentFeedFromString)
def GetCalendarEventCommentEntry(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarEventCommentEntryFromString)
def Query(self, uri, converter=None):
"""Performs a query and returns a resulting feed or entry.
Args:
feed: string The feed which is to be queried
Returns:
On success, a GDataFeed or Entry depending on which is sent from the
server.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
if converter:
result = self.Get(uri, converter=converter)
else:
result = self.Get(uri)
return result
def CalendarQuery(self, query):
if isinstance(query, CalendarEventQuery):
return self.Query(query.ToUri(),
converter=gdata.calendar.CalendarEventFeedFromString)
elif isinstance(query, CalendarListQuery):
return self.Query(query.ToUri(),
converter=gdata.calendar.CalendarListFeedFromString)
elif isinstance(query, CalendarEventCommentQuery):
return self.Query(query.ToUri(),
converter=gdata.calendar.CalendarEventCommentFeedFromString)
else:
return self.Query(query.ToUri())
def InsertEvent(self, new_event, insert_uri, url_params=None,
escape_params=True):
"""Adds an event to Google Calendar.
Args:
new_event: atom.Entry or subclass A new event which is to be added to
Google Calendar.
insert_uri: the URL to post new events to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the event created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Post(new_event, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarEventEntryFromString)
def InsertCalendarSubscription(self, calendar, url_params=None,
escape_params=True):
"""Subscribes the authenticated user to the provided calendar.
Args:
calendar: The calendar to which the user should be subscribed.
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the subscription created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
insert_uri = '/calendar/feeds/default/allcalendars/full'
return self.Post(calendar, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarListEntryFromString)
def InsertCalendar(self, new_calendar, url_params=None,
escape_params=True):
"""Creates a new calendar.
Args:
new_calendar: The calendar to be created
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the calendar created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
insert_uri = '/calendar/feeds/default/owncalendars/full'
response = self.Post(new_calendar, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarListEntryFromString)
return response
def UpdateCalendar(self, calendar, url_params=None,
escape_params=True):
"""Updates a calendar.
Args:
calendar: The calendar which should be updated
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the calendar created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
update_uri = calendar.GetEditLink().href
response = self.Put(data=calendar, uri=update_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarListEntryFromString)
return response
def InsertAclEntry(self, new_entry, insert_uri, url_params=None,
escape_params=True):
"""Adds an ACL entry (rule) to Google Calendar.
Args:
new_entry: atom.Entry or subclass A new ACL entry which is to be added to
Google Calendar.
insert_uri: the URL to post new entries to the ACL feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the ACL entry created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Post(new_entry, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarAclEntryFromString)
def InsertEventComment(self, new_entry, insert_uri, url_params=None,
escape_params=True):
"""Adds an entry to Google Calendar.
Args:
new_entry: atom.Entry or subclass A new entry which is to be added to
Google Calendar.
insert_uri: the URL to post new entrys to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the comment created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Post(new_entry, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarEventCommentEntryFromString)
def DeleteEvent(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
"""Removes an event with the specified ID from Google Calendar.
Args:
edit_uri: string The edit URL of the entry to be deleted. Example:
'http://www.google.com/calendar/feeds/default/private/full/abx'
url_params: dict (optional) Additional URL parameters to be included
in the deletion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful delete, a httplib.HTTPResponse containing the server's
response to the DELETE request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Delete('/%s' % edit_uri,
url_params=url_params, escape_params=escape_params)
def DeleteAclEntry(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
"""Removes an ACL entry at the given edit_uri from Google Calendar.
Args:
edit_uri: string The edit URL of the entry to be deleted. Example:
'http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/default'
url_params: dict (optional) Additional URL parameters to be included
in the deletion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful delete, a httplib.HTTPResponse containing the server's
response to the DELETE request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Delete('/%s' % edit_uri,
url_params=url_params, escape_params=escape_params)
def DeleteCalendarEntry(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
"""Removes a calendar entry at the given edit_uri from Google Calendar.
Args:
edit_uri: string The edit URL of the entry to be deleted. Example:
'http://www.google.com/calendar/feeds/default/allcalendars/abcdef@group.calendar.google.com'
url_params: dict (optional) Additional URL parameters to be included
in the deletion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful delete, True is returned
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Delete(edit_uri, url_params=url_params,
escape_params=escape_params)
def UpdateEvent(self, edit_uri, updated_event, url_params=None,
escape_params=True):
"""Updates an existing event.
Args:
edit_uri: string The edit link URI for the element being updated
updated_event: string, atom.Entry, or subclass containing
the Atom Entry which will replace the event which is
stored at the edit_url
url_params: dict (optional) Additional URL parameters to be included
in the update request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful update, a httplib.HTTPResponse containing the server's
response to the PUT request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Put(updated_event, '/%s' % edit_uri,
url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarEventEntryFromString)
def UpdateAclEntry(self, edit_uri, updated_rule, url_params=None,
escape_params=True):
"""Updates an existing ACL rule.
Args:
edit_uri: string The edit link URI for the element being updated
updated_rule: string, atom.Entry, or subclass containing
the Atom Entry which will replace the event which is
stored at the edit_url
url_params: dict (optional) Additional URL parameters to be included
in the update request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful update, a httplib.HTTPResponse containing the server's
response to the PUT request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
url_prefix = 'http://%s/' % self.server
if edit_uri.startswith(url_prefix):
edit_uri = edit_uri[len(url_prefix):]
return self.Put(updated_rule, '/%s' % edit_uri,
url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarAclEntryFromString)
def ExecuteBatch(self, batch_feed, url,
converter=gdata.calendar.CalendarEventFeedFromString):
"""Sends a batch request feed to the server.
The batch request needs to be sent to the batch URL for a particular
calendar. You can find the URL by calling GetBatchLink().href on the
CalendarEventFeed.
Args:
batch_feed: gdata.calendar.CalendarEventFeed A feed containing batch
request entries. Each entry contains the operation to be performed
on the data contained in the entry. For example an entry with an
operation type of insert will be used as if the individual entry
had been inserted.
url: str The batch URL for the Calendar to which these operations should
be applied.
converter: Function (optional) The function used to convert the server's
response to an object. The default value is
CalendarEventFeedFromString.
Returns:
The results of the batch request's execution on the server. If the
default converter is used, this is stored in a CalendarEventFeed.
"""
return self.Post(batch_feed, url, converter=converter)
class CalendarEventQuery(gdata.service.Query):
def __init__(self, user='default', visibility='private', projection='full',
text_query=None, params=None, categories=None):
gdata.service.Query.__init__(self,
feed='http://www.google.com/calendar/feeds/%s/%s/%s' % (
urllib.quote(user),
urllib.quote(visibility),
urllib.quote(projection)),
text_query=text_query, params=params, categories=categories)
def _GetStartMin(self):
if 'start-min' in self.keys():
return self['start-min']
else:
return None
def _SetStartMin(self, val):
self['start-min'] = val
start_min = property(_GetStartMin, _SetStartMin,
doc="""The start-min query parameter""")
def _GetStartMax(self):
if 'start-max' in self.keys():
return self['start-max']
else:
return None
def _SetStartMax(self, val):
self['start-max'] = val
start_max = property(_GetStartMax, _SetStartMax,
doc="""The start-max query parameter""")
def _GetOrderBy(self):
if 'orderby' in self.keys():
return self['orderby']
else:
return None
def _SetOrderBy(self, val):
if val is not 'lastmodified' and val is not 'starttime':
raise Error, "Order By must be either 'lastmodified' or 'starttime'"
self['orderby'] = val
orderby = property(_GetOrderBy, _SetOrderBy,
doc="""The orderby query parameter""")
def _GetSortOrder(self):
if 'sortorder' in self.keys():
return self['sortorder']
else:
return None
def _SetSortOrder(self, val):
if (val is not 'ascending' and val is not 'descending'
and val is not 'a' and val is not 'd' and val is not 'ascend'
and val is not 'descend'):
raise Error, "Sort order must be either ascending, ascend, " + (
"a or descending, descend, or d")
self['sortorder'] = val
sortorder = property(_GetSortOrder, _SetSortOrder,
doc="""The sortorder query parameter""")
def _GetSingleEvents(self):
if 'singleevents' in self.keys():
return self['singleevents']
else:
return None
def _SetSingleEvents(self, val):
self['singleevents'] = val
singleevents = property(_GetSingleEvents, _SetSingleEvents,
doc="""The singleevents query parameter""")
def _GetFutureEvents(self):
if 'futureevents' in self.keys():
return self['futureevents']
else:
return None
def _SetFutureEvents(self, val):
self['futureevents'] = val
futureevents = property(_GetFutureEvents, _SetFutureEvents,
doc="""The futureevents query parameter""")
def _GetRecurrenceExpansionStart(self):
if 'recurrence-expansion-start' in self.keys():
return self['recurrence-expansion-start']
else:
return None
def _SetRecurrenceExpansionStart(self, val):
self['recurrence-expansion-start'] = val
recurrence_expansion_start = property(_GetRecurrenceExpansionStart,
_SetRecurrenceExpansionStart,
doc="""The recurrence-expansion-start query parameter""")
def _GetRecurrenceExpansionEnd(self):
if 'recurrence-expansion-end' in self.keys():
return self['recurrence-expansion-end']
else:
return None
def _SetRecurrenceExpansionEnd(self, val):
self['recurrence-expansion-end'] = val
recurrence_expansion_end = property(_GetRecurrenceExpansionEnd,
_SetRecurrenceExpansionEnd,
doc="""The recurrence-expansion-end query parameter""")
def _SetTimezone(self, val):
self['ctz'] = val
def _GetTimezone(self):
if 'ctz' in self.keys():
return self['ctz']
else:
return None
ctz = property(_GetTimezone, _SetTimezone,
doc="""The ctz query parameter which sets report time on the server.""")
class CalendarListQuery(gdata.service.Query):
"""Queries the Google Calendar meta feed"""
def __init__(self, userId=None, text_query=None,
params=None, categories=None):
if userId is None:
userId = 'default'
gdata.service.Query.__init__(self, feed='http://www.google.com/calendar/feeds/'
+userId,
text_query=text_query, params=params,
categories=categories)
class CalendarEventCommentQuery(gdata.service.Query):
"""Queries the Google Calendar event comments feed"""
def __init__(self, feed=None):
gdata.service.Query.__init__(self, feed=feed)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to ElementWrapper objects used with Google Calendar."""
__author__ = 'api.vli (Vivian Li), api.rboyd (Ryan Boyd)'
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import atom
import gdata
# XML namespaces which are often used in Google Calendar entities.
GCAL_NAMESPACE = 'http://schemas.google.com/gCal/2005'
GCAL_TEMPLATE = '{http://schemas.google.com/gCal/2005}%s'
WEB_CONTENT_LINK_REL = '%s/%s' % (GCAL_NAMESPACE, 'webContent')
GACL_NAMESPACE = gdata.GACL_NAMESPACE
GACL_TEMPLATE = gdata.GACL_TEMPLATE
class ValueAttributeContainer(atom.AtomBase):
"""A parent class for all Calendar classes which have a value attribute.
Children include Color, AccessLevel, Hidden
"""
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, value=None, extension_elements=None,
extension_attributes=None, text=None):
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Color(ValueAttributeContainer):
"""The Google Calendar color element"""
_tag = 'color'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class AccessLevel(ValueAttributeContainer):
"""The Google Calendar accesslevel element"""
_tag = 'accesslevel'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class Hidden(ValueAttributeContainer):
"""The Google Calendar hidden element"""
_tag = 'hidden'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class Selected(ValueAttributeContainer):
"""The Google Calendar selected element"""
_tag = 'selected'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class Timezone(ValueAttributeContainer):
"""The Google Calendar timezone element"""
_tag = 'timezone'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class Where(atom.AtomBase):
"""The Google Calendar Where element"""
_tag = 'where'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['valueString'] = 'value_string'
def __init__(self, value_string=None, extension_elements=None,
extension_attributes=None, text=None):
self.value_string = value_string
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class CalendarListEntry(gdata.GDataEntry, gdata.LinkFinder):
"""A Google Calendar meta Entry flavor of an Atom Entry """
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}color' % GCAL_NAMESPACE] = ('color', Color)
_children['{%s}accesslevel' % GCAL_NAMESPACE] = ('access_level',
AccessLevel)
_children['{%s}hidden' % GCAL_NAMESPACE] = ('hidden', Hidden)
_children['{%s}selected' % GCAL_NAMESPACE] = ('selected', Selected)
_children['{%s}timezone' % GCAL_NAMESPACE] = ('timezone', Timezone)
_children['{%s}where' % gdata.GDATA_NAMESPACE] = ('where', Where)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
color=None, access_level=None, hidden=None, timezone=None,
selected=None,
where=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title,
updated=updated, text=None)
self.color = color
self.access_level = access_level
self.hidden = hidden
self.selected = selected
self.timezone = timezone
self.where = where
class CalendarListFeed(gdata.GDataFeed, gdata.LinkFinder):
"""A Google Calendar meta feed flavor of an Atom Feed"""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CalendarListEntry])
class Scope(atom.AtomBase):
"""The Google ACL scope element"""
_tag = 'scope'
_namespace = GACL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
_attributes['type'] = 'type'
def __init__(self, extension_elements=None, value=None, scope_type=None,
extension_attributes=None, text=None):
self.value = value
self.type = scope_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Role(ValueAttributeContainer):
"""The Google Calendar timezone element"""
_tag = 'role'
_namespace = GACL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class CalendarAclEntry(gdata.GDataEntry, gdata.LinkFinder):
"""A Google Calendar ACL Entry flavor of an Atom Entry """
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}scope' % GACL_NAMESPACE] = ('scope', Scope)
_children['{%s}role' % GACL_NAMESPACE] = ('role', Role)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
scope=None, role=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title,
updated=updated, text=None)
self.scope = scope
self.role = role
class CalendarAclFeed(gdata.GDataFeed, gdata.LinkFinder):
"""A Google Calendar ACL feed flavor of an Atom Feed"""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CalendarAclEntry])
class CalendarEventCommentEntry(gdata.GDataEntry, gdata.LinkFinder):
"""A Google Calendar event comments entry flavor of an Atom Entry"""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
class CalendarEventCommentFeed(gdata.GDataFeed, gdata.LinkFinder):
"""A Google Calendar event comments feed flavor of an Atom Feed"""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[CalendarEventCommentEntry])
class ExtendedProperty(gdata.ExtendedProperty):
"""A transparent subclass of gdata.ExtendedProperty added to this module
for backwards compatibility."""
class Reminder(atom.AtomBase):
"""The Google Calendar reminder element"""
_tag = 'reminder'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['absoluteTime'] = 'absolute_time'
_attributes['days'] = 'days'
_attributes['hours'] = 'hours'
_attributes['minutes'] = 'minutes'
def __init__(self, absolute_time=None,
days=None, hours=None, minutes=None,
extension_elements=None,
extension_attributes=None, text=None):
self.absolute_time = absolute_time
if days is not None:
self.days = str(days)
else:
self.days = None
if hours is not None:
self.hours = str(hours)
else:
self.hours = None
if minutes is not None:
self.minutes = str(minutes)
else:
self.minutes = None
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class When(atom.AtomBase):
"""The Google Calendar When element"""
_tag = 'when'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}reminder' % gdata.GDATA_NAMESPACE] = ('reminder', [Reminder])
_attributes['startTime'] = 'start_time'
_attributes['endTime'] = 'end_time'
def __init__(self, start_time=None, end_time=None, reminder=None,
extension_elements=None, extension_attributes=None, text=None):
self.start_time = start_time
self.end_time = end_time
self.reminder = reminder or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Recurrence(atom.AtomBase):
"""The Google Calendar Recurrence element"""
_tag = 'recurrence'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
class UriEnumElement(atom.AtomBase):
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, tag, enum_map, attrib_name='value',
extension_elements=None, extension_attributes=None, text=None):
self.tag=tag
self.enum_map=enum_map
self.attrib_name=attrib_name
self.value=None
self.text=text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def findKey(self, value):
res=[item[0] for item in self.enum_map.items() if item[1] == value]
if res is None or len(res) == 0:
return None
return res[0]
def _ConvertElementAttributeToMember(self, attribute, value):
# Special logic to use the enum_map to set the value of the object's value member.
if attribute == self.attrib_name and value != '':
self.value = self.enum_map[value]
return
# Find the attribute in this class's list of attributes.
if self.__class__._attributes.has_key(attribute):
# Find the member of this class which corresponds to the XML attribute
# (lookup in current_class._attributes) and set this member to the
# desired value (using self.__dict__).
setattr(self, self.__class__._attributes[attribute], value)
else:
# The current class doesn't map this attribute, so try to parent class.
atom.ExtensionContainer._ConvertElementAttributeToMember(self,
attribute,
value)
def _AddMembersToElementTree(self, tree):
# Convert the members of this class which are XML child nodes.
# This uses the class's _children dictionary to find the members which
# should become XML child nodes.
member_node_names = [values[0] for tag, values in
self.__class__._children.iteritems()]
for member_name in member_node_names:
member = getattr(self, member_name)
if member is None:
pass
elif isinstance(member, list):
for instance in member:
instance._BecomeChildElement(tree)
else:
member._BecomeChildElement(tree)
# Special logic to set the desired XML attribute.
key = self.findKey(self.value)
if key is not None:
tree.attrib[self.attrib_name]=key
# Convert the members of this class which are XML attributes.
for xml_attribute, member_name in self.__class__._attributes.iteritems():
member = getattr(self, member_name)
if member is not None:
tree.attrib[xml_attribute] = member
# Lastly, call the parent's _AddMembersToElementTree to get any
# extension elements.
atom.ExtensionContainer._AddMembersToElementTree(self, tree)
class AttendeeStatus(UriEnumElement):
"""The Google Calendar attendeeStatus element"""
_tag = 'attendeeStatus'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
attendee_enum = {
'http://schemas.google.com/g/2005#event.accepted' : 'ACCEPTED',
'http://schemas.google.com/g/2005#event.declined' : 'DECLINED',
'http://schemas.google.com/g/2005#event.invited' : 'INVITED',
'http://schemas.google.com/g/2005#event.tentative' : 'TENTATIVE'}
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, 'attendeeStatus', AttendeeStatus.attendee_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
class AttendeeType(UriEnumElement):
"""The Google Calendar attendeeType element"""
_tag = 'attendeeType'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
attendee_type_enum = {
'http://schemas.google.com/g/2005#event.optional' : 'OPTIONAL',
'http://schemas.google.com/g/2005#event.required' : 'REQUIRED' }
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, 'attendeeType',
AttendeeType.attendee_type_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,text=text)
class Visibility(UriEnumElement):
"""The Google Calendar Visibility element"""
_tag = 'visibility'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
visibility_enum = {
'http://schemas.google.com/g/2005#event.confidential' : 'CONFIDENTIAL',
'http://schemas.google.com/g/2005#event.default' : 'DEFAULT',
'http://schemas.google.com/g/2005#event.private' : 'PRIVATE',
'http://schemas.google.com/g/2005#event.public' : 'PUBLIC' }
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, 'visibility', Visibility.visibility_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
class Transparency(UriEnumElement):
"""The Google Calendar Transparency element"""
_tag = 'transparency'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
transparency_enum = {
'http://schemas.google.com/g/2005#event.opaque' : 'OPAQUE',
'http://schemas.google.com/g/2005#event.transparent' : 'TRANSPARENT' }
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, tag='transparency',
enum_map=Transparency.transparency_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
class Comments(atom.AtomBase):
"""The Google Calendar comments element"""
_tag = 'comments'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
gdata.FeedLink)
_attributes['rel'] = 'rel'
def __init__(self, rel=None, feed_link=None, extension_elements=None,
extension_attributes=None, text=None):
self.rel = rel
self.feed_link = feed_link
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class EventStatus(UriEnumElement):
"""The Google Calendar eventStatus element"""
_tag = 'eventStatus'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
status_enum = { 'http://schemas.google.com/g/2005#event.canceled' : 'CANCELED',
'http://schemas.google.com/g/2005#event.confirmed' : 'CONFIRMED',
'http://schemas.google.com/g/2005#event.tentative' : 'TENTATIVE'}
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, tag='eventStatus',
enum_map=EventStatus.status_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
class Who(UriEnumElement):
"""The Google Calendar Who element"""
_tag = 'who'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
_children['{%s}attendeeStatus' % gdata.GDATA_NAMESPACE] = (
'attendee_status', AttendeeStatus)
_children['{%s}attendeeType' % gdata.GDATA_NAMESPACE] = ('attendee_type',
AttendeeType)
_attributes['valueString'] = 'name'
_attributes['email'] = 'email'
relEnum = { 'http://schemas.google.com/g/2005#event.attendee' : 'ATTENDEE',
'http://schemas.google.com/g/2005#event.organizer' : 'ORGANIZER',
'http://schemas.google.com/g/2005#event.performer' : 'PERFORMER',
'http://schemas.google.com/g/2005#event.speaker' : 'SPEAKER',
'http://schemas.google.com/g/2005#message.bcc' : 'BCC',
'http://schemas.google.com/g/2005#message.cc' : 'CC',
'http://schemas.google.com/g/2005#message.from' : 'FROM',
'http://schemas.google.com/g/2005#message.reply-to' : 'REPLY_TO',
'http://schemas.google.com/g/2005#message.to' : 'TO' }
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, 'who', Who.relEnum, attrib_name='rel',
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.name=None
self.email=None
self.attendee_status=None
self.attendee_type=None
self.rel=None
class OriginalEvent(atom.AtomBase):
"""The Google Calendar OriginalEvent element"""
_tag = 'originalEvent'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
# TODO: The when tag used to map to a EntryLink, make sure it should really be a When.
_children['{%s}when' % gdata.GDATA_NAMESPACE] = ('when', When)
_attributes['id'] = 'id'
_attributes['href'] = 'href'
def __init__(self, id=None, href=None, when=None,
extension_elements=None, extension_attributes=None, text=None):
self.id = id
self.href = href
self.when = when
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GetCalendarEventEntryClass():
return CalendarEventEntry
# This class is not completely defined here, because of a circular reference
# in which CalendarEventEntryLink and CalendarEventEntry refer to one another.
class CalendarEventEntryLink(gdata.EntryLink):
"""An entryLink which contains a calendar event entry
Within an event's recurranceExceptions, an entry link
points to a calendar event entry. This class exists
to capture the calendar specific extensions in the entry.
"""
_tag = 'entryLink'
_namespace = gdata.GDATA_NAMESPACE
_children = gdata.EntryLink._children.copy()
_attributes = gdata.EntryLink._attributes.copy()
# The CalendarEventEntryLink should like CalendarEventEntry as a child but
# that class hasn't been defined yet, so we will wait until after defining
# CalendarEventEntry to list it in _children.
class RecurrenceException(atom.AtomBase):
"""The Google Calendar RecurrenceException element"""
_tag = 'recurrenceException'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}entryLink' % gdata.GDATA_NAMESPACE] = ('entry_link',
CalendarEventEntryLink)
_children['{%s}originalEvent' % gdata.GDATA_NAMESPACE] = ('original_event',
OriginalEvent)
_attributes['specialized'] = 'specialized'
def __init__(self, specialized=None, entry_link=None,
original_event=None, extension_elements=None,
extension_attributes=None, text=None):
self.specialized = specialized
self.entry_link = entry_link
self.original_event = original_event
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class SendEventNotifications(atom.AtomBase):
"""The Google Calendar sendEventNotifications element"""
_tag = 'sendEventNotifications'
_namespace = GCAL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, extension_elements=None,
value=None, extension_attributes=None, text=None):
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class QuickAdd(atom.AtomBase):
"""The Google Calendar quickadd element"""
_tag = 'quickadd'
_namespace = GCAL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, extension_elements=None,
value=None, extension_attributes=None, text=None):
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def _TransferToElementTree(self, element_tree):
if self.value:
element_tree.attrib['value'] = self.value
element_tree.tag = GCAL_TEMPLATE % 'quickadd'
atom.AtomBase._TransferToElementTree(self, element_tree)
return element_tree
def _TakeAttributeFromElementTree(self, attribute, element_tree):
if attribute == 'value':
self.value = element_tree.attrib[attribute]
del element_tree.attrib[attribute]
else:
atom.AtomBase._TakeAttributeFromElementTree(self, attribute,
element_tree)
class WebContentGadgetPref(atom.AtomBase):
_tag = 'webContentGadgetPref'
_namespace = GCAL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['name'] = 'name'
_attributes['value'] = 'value'
"""The Google Calendar Web Content Gadget Preferences element"""
def __init__(self, name=None, value=None, extension_elements=None,
extension_attributes=None, text=None):
self.name = name
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class WebContent(atom.AtomBase):
_tag = 'webContent'
_namespace = GCAL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}webContentGadgetPref' % GCAL_NAMESPACE] = ('gadget_pref',
[WebContentGadgetPref])
_attributes['url'] = 'url'
_attributes['width'] = 'width'
_attributes['height'] = 'height'
def __init__(self, url=None, width=None, height=None, text=None,
gadget_pref=None, extension_elements=None, extension_attributes=None):
self.url = url
self.width = width
self.height = height
self.text = text
self.gadget_pref = gadget_pref or []
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class WebContentLink(atom.Link):
_tag = 'link'
_namespace = atom.ATOM_NAMESPACE
_children = atom.Link._children.copy()
_attributes = atom.Link._attributes.copy()
_children['{%s}webContent' % GCAL_NAMESPACE] = ('web_content', WebContent)
def __init__(self, title=None, href=None, link_type=None,
web_content=None):
atom.Link.__init__(self, rel=WEB_CONTENT_LINK_REL, title=title, href=href,
link_type=link_type)
self.web_content = web_content
class CalendarEventEntry(gdata.BatchEntry):
"""A Google Calendar flavor of an Atom Entry """
_tag = gdata.BatchEntry._tag
_namespace = gdata.BatchEntry._namespace
_children = gdata.BatchEntry._children.copy()
_attributes = gdata.BatchEntry._attributes.copy()
# This class also contains WebContentLinks but converting those members
# is handled in a special version of _ConvertElementTreeToMember.
_children['{%s}where' % gdata.GDATA_NAMESPACE] = ('where', [Where])
_children['{%s}when' % gdata.GDATA_NAMESPACE] = ('when', [When])
_children['{%s}who' % gdata.GDATA_NAMESPACE] = ('who', [Who])
_children['{%s}extendedProperty' % gdata.GDATA_NAMESPACE] = (
'extended_property', [ExtendedProperty])
_children['{%s}visibility' % gdata.GDATA_NAMESPACE] = ('visibility',
Visibility)
_children['{%s}transparency' % gdata.GDATA_NAMESPACE] = ('transparency',
Transparency)
_children['{%s}eventStatus' % gdata.GDATA_NAMESPACE] = ('event_status',
EventStatus)
_children['{%s}recurrence' % gdata.GDATA_NAMESPACE] = ('recurrence',
Recurrence)
_children['{%s}recurrenceException' % gdata.GDATA_NAMESPACE] = (
'recurrence_exception', [RecurrenceException])
_children['{%s}sendEventNotifications' % GCAL_NAMESPACE] = (
'send_event_notifications', SendEventNotifications)
_children['{%s}quickadd' % GCAL_NAMESPACE] = ('quick_add', QuickAdd)
_children['{%s}comments' % gdata.GDATA_NAMESPACE] = ('comments', Comments)
_children['{%s}originalEvent' % gdata.GDATA_NAMESPACE] = ('original_event',
OriginalEvent)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
transparency=None, comments=None, event_status=None,
send_event_notifications=None, visibility=None,
recurrence=None, recurrence_exception=None,
where=None, when=None, who=None, quick_add=None,
extended_property=None, original_event=None,
batch_operation=None, batch_id=None, batch_status=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.BatchEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
batch_operation=batch_operation, batch_id=batch_id,
batch_status=batch_status,
title=title, updated=updated)
self.transparency = transparency
self.comments = comments
self.event_status = event_status
self.send_event_notifications = send_event_notifications
self.visibility = visibility
self.recurrence = recurrence
self.recurrence_exception = recurrence_exception or []
self.where = where or []
self.when = when or []
self.who = who or []
self.quick_add = quick_add
self.extended_property = extended_property or []
self.original_event = original_event
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
# We needed to add special logic to _ConvertElementTreeToMember because we
# want to make links with a rel of WEB_CONTENT_LINK_REL into a
# WebContentLink
def _ConvertElementTreeToMember(self, child_tree):
# Special logic to handle Web Content links
if (child_tree.tag == '{%s}link' % atom.ATOM_NAMESPACE and
child_tree.attrib['rel'] == WEB_CONTENT_LINK_REL):
if self.link is None:
self.link = []
self.link.append(atom._CreateClassFromElementTree(WebContentLink,
child_tree))
return
# Find the element's tag in this class's list of child members
if self.__class__._children.has_key(child_tree.tag):
member_name = self.__class__._children[child_tree.tag][0]
member_class = self.__class__._children[child_tree.tag][1]
# If the class member is supposed to contain a list, make sure the
# matching member is set to a list, then append the new member
# instance to the list.
if isinstance(member_class, list):
if getattr(self, member_name) is None:
setattr(self, member_name, [])
getattr(self, member_name).append(atom._CreateClassFromElementTree(
member_class[0], child_tree))
else:
setattr(self, member_name,
atom._CreateClassFromElementTree(member_class, child_tree))
else:
atom.ExtensionContainer._ConvertElementTreeToMember(self, child_tree)
def GetWebContentLink(self):
"""Finds the first link with rel set to WEB_CONTENT_REL
Returns:
A gdata.calendar.WebContentLink or none if none of the links had rel
equal to WEB_CONTENT_REL
"""
for a_link in self.link:
if a_link.rel == WEB_CONTENT_LINK_REL:
return a_link
return None
def CalendarEventEntryFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventEntry, xml_string)
def CalendarEventCommentEntryFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventCommentEntry, xml_string)
CalendarEventEntryLink._children = {'{%s}entry' % atom.ATOM_NAMESPACE:
('entry', CalendarEventEntry)}
def CalendarEventEntryLinkFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventEntryLink, xml_string)
class CalendarEventFeed(gdata.BatchFeed, gdata.LinkFinder):
"""A Google Calendar event feed flavor of an Atom Feed"""
_tag = gdata.BatchFeed._tag
_namespace = gdata.BatchFeed._namespace
_children = gdata.BatchFeed._children.copy()
_attributes = gdata.BatchFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[CalendarEventEntry])
_children['{%s}timezone' % GCAL_NAMESPACE] = ('timezone', Timezone)
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None, entry=None,
total_results=None, start_index=None, items_per_page=None,
interrupted=None, timezone=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.BatchFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
interrupted=interrupted,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.timezone = timezone
def CalendarListEntryFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarListEntry, xml_string)
def CalendarAclEntryFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarAclEntry, xml_string)
def CalendarListFeedFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarListFeed, xml_string)
def CalendarAclFeedFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarAclFeed, xml_string)
def CalendarEventFeedFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventFeed, xml_string)
def CalendarEventCommentFeedFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventCommentFeed, xml_string)
| Python |
# -*-*- encoding: utf-8 -*-*-
#
# This is gdata.photos.media, implementing parts of the MediaRSS spec in gdata structures
#
# $Id: __init__.py 81 2007-10-03 14:41:42Z havard.gulldahl $
#
# Copyright 2007 Håvard Gulldahl
# Portions copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Essential attributes of photos in Google Photos/Picasa Web Albums are
expressed using elements from the `media' namespace, defined in the
MediaRSS specification[1].
Due to copyright issues, the elements herein are documented sparingly, please
consult with the Google Photos API Reference Guide[2], alternatively the
official MediaRSS specification[1] for details.
(If there is a version conflict between the two sources, stick to the
Google Photos API).
[1]: http://search.yahoo.com/mrss (version 1.1.1)
[2]: http://code.google.com/apis/picasaweb/reference.html#media_reference
Keep in mind that Google Photos only uses a subset of the MediaRSS elements
(and some of the attributes are trimmed down, too):
media:content
media:credit
media:description
media:group
media:keywords
media:thumbnail
media:title
"""
__author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: api chokes on non-ascii chars in __author__
__license__ = 'Apache License v2'
import atom
import gdata
MEDIA_NAMESPACE = 'http://search.yahoo.com/mrss/'
YOUTUBE_NAMESPACE = 'http://gdata.youtube.com/schemas/2007'
class MediaBaseElement(atom.AtomBase):
"""Base class for elements in the MEDIA_NAMESPACE.
To add new elements, you only need to add the element tag name to self._tag
"""
_tag = ''
_namespace = MEDIA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, name=None, extension_elements=None,
extension_attributes=None, text=None):
self.name = name
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Content(MediaBaseElement):
"""(attribute container) This element describes the original content,
e.g. an image or a video. There may be multiple Content elements
in a media:Group.
For example, a video may have a
<media:content medium="image"> element that specifies a JPEG
representation of the video, and a <media:content medium="video">
element that specifies the URL of the video itself.
Attributes:
url: non-ambigous reference to online object
width: width of the object frame, in pixels
height: width of the object frame, in pixels
medium: one of `image' or `video', allowing the api user to quickly
determine the object's type
type: Internet media Type[1] (a.k.a. mime type) of the object -- a more
verbose way of determining the media type
(optional) fileSize: the size of the object, in bytes
[1]: http://en.wikipedia.org/wiki/Internet_media_type
"""
_tag = 'content'
_attributes = atom.AtomBase._attributes.copy()
_attributes['url'] = 'url'
_attributes['width'] = 'width'
_attributes['height'] = 'height'
_attributes['medium'] = 'medium'
_attributes['type'] = 'type'
_attributes['fileSize'] = 'fileSize'
def __init__(self, url=None, width=None, height=None,
medium=None, content_type=None, fileSize=None, format=None,
extension_elements=None, extension_attributes=None, text=None):
MediaBaseElement.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.url = url
self.width = width
self.height = height
self.medium = medium
self.type = content_type
self.fileSize = fileSize
def ContentFromString(xml_string):
return atom.CreateClassFromXMLString(Content, xml_string)
class Credit(MediaBaseElement):
"""(string) Contains the nickname of the user who created the content,
e.g. `Liz Bennet'.
This is a user-specified value that should be used when referring to
the user by name.
Note that none of the attributes from the MediaRSS spec are supported.
"""
_tag = 'credit'
def CreditFromString(xml_string):
return atom.CreateClassFromXMLString(Credit, xml_string)
class Description(MediaBaseElement):
"""(string) A description of the media object.
Either plain unicode text, or entity-encoded html (look at the `type'
attribute).
E.g `A set of photographs I took while vacationing in Italy.'
For `api' projections, the description is in plain text;
for `base' projections, the description is in HTML.
Attributes:
type: either `text' or `html'.
"""
_tag = 'description'
_attributes = atom.AtomBase._attributes.copy()
_attributes['type'] = 'type'
def __init__(self, description_type=None,
extension_elements=None, extension_attributes=None, text=None):
MediaBaseElement.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.type = description_type
def DescriptionFromString(xml_string):
return atom.CreateClassFromXMLString(Description, xml_string)
class Keywords(MediaBaseElement):
"""(string) Lists the tags associated with the entry,
e.g `italy, vacation, sunset'.
Contains a comma-separated list of tags that have been added to the photo, or
all tags that have been added to photos in the album.
"""
_tag = 'keywords'
def KeywordsFromString(xml_string):
return atom.CreateClassFromXMLString(Keywords, xml_string)
class Thumbnail(MediaBaseElement):
"""(attributes) Contains the URL of a thumbnail of a photo or album cover.
There can be multiple <media:thumbnail> elements for a given <media:group>;
for example, a given item may have multiple thumbnails at different sizes.
Photos generally have two thumbnails at different sizes;
albums generally have one cropped thumbnail.
If the thumbsize parameter is set to the initial query, this element points
to thumbnails of the requested sizes; otherwise the thumbnails are the
default thumbnail size.
This element must not be confused with the <gphoto:thumbnail> element.
Attributes:
url: The URL of the thumbnail image.
height: The height of the thumbnail image, in pixels.
width: The width of the thumbnail image, in pixels.
"""
_tag = 'thumbnail'
_attributes = atom.AtomBase._attributes.copy()
_attributes['url'] = 'url'
_attributes['width'] = 'width'
_attributes['height'] = 'height'
def __init__(self, url=None, width=None, height=None,
extension_attributes=None, text=None, extension_elements=None):
MediaBaseElement.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.url = url
self.width = width
self.height = height
def ThumbnailFromString(xml_string):
return atom.CreateClassFromXMLString(Thumbnail, xml_string)
class Title(MediaBaseElement):
"""(string) Contains the title of the entry's media content, in plain text.
Attributes:
type: Always set to plain
"""
_tag = 'title'
_attributes = atom.AtomBase._attributes.copy()
_attributes['type'] = 'type'
def __init__(self, title_type=None,
extension_attributes=None, text=None, extension_elements=None):
MediaBaseElement.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.type = title_type
def TitleFromString(xml_string):
return atom.CreateClassFromXMLString(Title, xml_string)
class Player(MediaBaseElement):
"""(string) Contains the embeddable player URL for the entry's media content
if the media is a video.
Attributes:
url: Always set to plain
"""
_tag = 'player'
_attributes = atom.AtomBase._attributes.copy()
_attributes['url'] = 'url'
def __init__(self, player_url=None,
extension_attributes=None, extension_elements=None):
MediaBaseElement.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes)
self.url= player_url
class Private(atom.AtomBase):
"""The YouTube Private element"""
_tag = 'private'
_namespace = YOUTUBE_NAMESPACE
class Duration(atom.AtomBase):
"""The YouTube Duration element"""
_tag = 'duration'
_namespace = YOUTUBE_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['seconds'] = 'seconds'
class Category(MediaBaseElement):
"""The mediagroup:category element"""
_tag = 'category'
_attributes = atom.AtomBase._attributes.copy()
_attributes['term'] = 'term'
_attributes['scheme'] = 'scheme'
_attributes['label'] = 'label'
def __init__(self, term=None, scheme=None, label=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for Category
Args:
term: str
scheme: str
label: str
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.term = term
self.scheme = scheme
self.label = label
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Group(MediaBaseElement):
"""Container element for all media elements.
The <media:group> element can appear as a child of an album, photo or
video entry."""
_tag = 'group'
_children = atom.AtomBase._children.copy()
_children['{%s}content' % MEDIA_NAMESPACE] = ('content', [Content,])
_children['{%s}credit' % MEDIA_NAMESPACE] = ('credit', Credit)
_children['{%s}description' % MEDIA_NAMESPACE] = ('description', Description)
_children['{%s}keywords' % MEDIA_NAMESPACE] = ('keywords', Keywords)
_children['{%s}thumbnail' % MEDIA_NAMESPACE] = ('thumbnail', [Thumbnail,])
_children['{%s}title' % MEDIA_NAMESPACE] = ('title', Title)
_children['{%s}category' % MEDIA_NAMESPACE] = ('category', [Category,])
_children['{%s}duration' % YOUTUBE_NAMESPACE] = ('duration', Duration)
_children['{%s}private' % YOUTUBE_NAMESPACE] = ('private', Private)
_children['{%s}player' % MEDIA_NAMESPACE] = ('player', Player)
def __init__(self, content=None, credit=None, description=None, keywords=None,
thumbnail=None, title=None, duration=None, private=None,
category=None, player=None, extension_elements=None,
extension_attributes=None, text=None):
MediaBaseElement.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.content=content
self.credit=credit
self.description=description
self.keywords=keywords
self.thumbnail=thumbnail or []
self.title=title
self.duration=duration
self.private=private
self.category=category or []
self.player=player
def GroupFromString(xml_string):
return atom.CreateClassFromXMLString(Group, xml_string)
| Python |
# -*-*- encoding: utf-8 -*-*-
#
# This is gdata.photos.geo, implementing geological positioning in gdata structures
#
# $Id: __init__.py 81 2007-10-03 14:41:42Z havard.gulldahl $
#
# Copyright 2007 Håvard Gulldahl
# Portions copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Picasa Web Albums uses the georss and gml namespaces for
elements defined in the GeoRSS and Geography Markup Language specifications.
Specifically, Picasa Web Albums uses the following elements:
georss:where
gml:Point
gml:pos
http://code.google.com/apis/picasaweb/reference.html#georss_reference
Picasa Web Albums also accepts geographic-location data in two other formats:
W3C format and plain-GeoRSS (without GML) format.
"""
#
#Over the wire, the Picasa Web Albums only accepts and sends the
#elements mentioned above, but this module will let you seamlessly convert
#between the different formats (TODO 2007-10-18 hg)
__author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: api chokes on non-ascii chars in __author__
__license__ = 'Apache License v2'
import atom
import gdata
GEO_NAMESPACE = 'http://www.w3.org/2003/01/geo/wgs84_pos#'
GML_NAMESPACE = 'http://www.opengis.net/gml'
GEORSS_NAMESPACE = 'http://www.georss.org/georss'
class GeoBaseElement(atom.AtomBase):
"""Base class for elements.
To add new elements, you only need to add the element tag name to self._tag
and the namespace to self._namespace
"""
_tag = ''
_namespace = GML_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, name=None, extension_elements=None,
extension_attributes=None, text=None):
self.name = name
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Pos(GeoBaseElement):
"""(string) Specifies a latitude and longitude, separated by a space,
e.g. `35.669998 139.770004'"""
_tag = 'pos'
def PosFromString(xml_string):
return atom.CreateClassFromXMLString(Pos, xml_string)
class Point(GeoBaseElement):
"""(container) Specifies a particular geographical point, by means of
a <gml:pos> element."""
_tag = 'Point'
_children = atom.AtomBase._children.copy()
_children['{%s}pos' % GML_NAMESPACE] = ('pos', Pos)
def __init__(self, pos=None, extension_elements=None, extension_attributes=None, text=None):
GeoBaseElement.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
if pos is None:
pos = Pos()
self.pos=pos
def PointFromString(xml_string):
return atom.CreateClassFromXMLString(Point, xml_string)
class Where(GeoBaseElement):
"""(container) Specifies a geographical location or region.
A container element, containing a single <gml:Point> element.
(Not to be confused with <gd:where>.)
Note that the (only) child attribute, .Point, is title-cased.
This reflects the names of elements in the xml stream
(principle of least surprise).
As a convenience, you can get a tuple of (lat, lon) with Where.location(),
and set the same data with Where.setLocation( (lat, lon) ).
Similarly, there are methods to set and get only latitude and longtitude.
"""
_tag = 'where'
_namespace = GEORSS_NAMESPACE
_children = atom.AtomBase._children.copy()
_children['{%s}Point' % GML_NAMESPACE] = ('Point', Point)
def __init__(self, point=None, extension_elements=None, extension_attributes=None, text=None):
GeoBaseElement.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
if point is None:
point = Point()
self.Point=point
def location(self):
"(float, float) Return Where.Point.pos.text as a (lat,lon) tuple"
try:
return tuple([float(z) for z in self.Point.pos.text.split(' ')])
except AttributeError:
return tuple()
def set_location(self, latlon):
"""(bool) Set Where.Point.pos.text from a (lat,lon) tuple.
Arguments:
lat (float): The latitude in degrees, from -90.0 to 90.0
lon (float): The longitude in degrees, from -180.0 to 180.0
Returns True on success.
"""
assert(isinstance(latlon[0], float))
assert(isinstance(latlon[1], float))
try:
self.Point.pos.text = "%s %s" % (latlon[0], latlon[1])
return True
except AttributeError:
return False
def latitude(self):
"(float) Get the latitude value of the geo-tag. See also .location()"
lat, lon = self.location()
return lat
def longtitude(self):
"(float) Get the longtitude value of the geo-tag. See also .location()"
lat, lon = self.location()
return lon
def set_latitude(self, lat):
"""(bool) Set the latitude value of the geo-tag.
Args:
lat (float): The new latitude value
See also .set_location()
"""
_lat, lon = self.location()
return self.set_location(lat, lon)
def set_longtitude(self, lon):
"""(bool) Set the longtitude value of the geo-tag.
Args:
lat (float): The new latitude value
See also .set_location()
"""
lat, _lon = self.location()
return self.set_location(lat, lon)
def WhereFromString(xml_string):
return atom.CreateClassFromXMLString(Where, xml_string)
| Python |
#!/usr/bin/env python
# -*-*- encoding: utf-8 -*-*-
#
# This is the service file for the Google Photo python client.
# It is used for higher level operations.
#
# $Id: service.py 144 2007-10-25 21:03:34Z havard.gulldahl $
#
# Copyright 2007 Håvard Gulldahl
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""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)
"""
__author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: pydoc chokes on non-ascii chars in __author__
__license__ = 'Apache License v2'
__version__ = '$Revision: 176 $'[11:-2]
import sys, os.path, StringIO
import time
import gdata.service
import gdata
import atom.service
import atom
import gdata.photos
SUPPORTED_UPLOAD_TYPES = ('bmp', 'jpeg', 'jpg', 'gif', 'png')
UNKOWN_ERROR=1000
GPHOTOS_BAD_REQUEST=400
GPHOTOS_CONFLICT=409
GPHOTOS_INTERNAL_SERVER_ERROR=500
GPHOTOS_INVALID_ARGUMENT=601
GPHOTOS_INVALID_CONTENT_TYPE=602
GPHOTOS_NOT_AN_IMAGE=603
GPHOTOS_INVALID_KIND=604
class GooglePhotosException(Exception):
def __init__(self, response):
self.error_code = response['status']
self.reason = response['reason'].strip()
if '<html>' in str(response['body']): #general html message, discard it
response['body'] = ""
self.body = response['body'].strip()
self.message = "(%(status)s) %(body)s -- %(reason)s" % response
#return explicit error codes
error_map = { '(12) Not an image':GPHOTOS_NOT_AN_IMAGE,
'kind: That is not one of the acceptable values':
GPHOTOS_INVALID_KIND,
}
for msg, code in error_map.iteritems():
if self.body == msg:
self.error_code = code
break
self.args = [self.error_code, self.reason, self.body]
class PhotosService(gdata.service.GDataService):
userUri = '/data/feed/api/user/%s'
def __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:
A PhotosService object used to communicate with the Google Photos
service.
"""
self.email = email
self.client = source
gdata.service.GDataService.__init__(self, email=self.email, password=password,
service='lh2', source=source,
server=server,
additional_headers=additional_headers)
def 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
"""
if limit is not None:
uri += '&max-results=%s' % limit
if start_index is not None:
uri += '&start-index=%s' % start_index
try:
return self.Get(uri, converter=gdata.photos.AnyFeedFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def 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
"""
if limit is not None:
uri += '&max-results=%s' % limit
if start_index is not None:
uri += '&start-index=%s' % start_index
try:
return self.Get(uri, converter=gdata.photos.AnyEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def 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
"""
if isinstance(kind, (list, tuple) ):
kind = ",".join(kind)
uri = '/data/feed/api/user/%s?kind=%s' % (user, kind)
return self.GetFeed(uri, limit=limit)
def 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
"""
# Lower-casing because of
# http://code.google.com/p/gdata-issues/issues/detail?id=194
uri = '/data/feed/api/user/%s?kind=photo&tag=%s' % (user, tag.lower())
return self.GetFeed(uri, limit)
def 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
"""
uri = '/data/feed/api/user/%s?kind=photo&q=%s' % (user, query)
return self.GetFeed(uri, limit=limit)
def 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
"""
uri='/data/feed/api/all?q=%s' % query
return self.GetFeed(uri, limit=limit)
def 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
"""
uri = '/data/feed/api/user/%s/contacts?kind=user' % user
return self.GetFeed(uri, limit=limit)
def 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
"""
uri = '/data/feed/api/user/%s/contacts?kind=photo&q=%s' % (user, search)
return self.GetFeed(uri, limit=limit)
def InsertAlbum(self, title, summary, location=None, access='public',
commenting_enabled='true', timestamp=None):
"""Add an album.
Needs authentication, see self.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
"""
album = gdata.photos.AlbumEntry()
album.title = atom.Title(text=title, title_type='text')
album.summary = atom.Summary(text=summary, summary_type='text')
if location is not None:
album.location = gdata.photos.Location(text=location)
album.access = gdata.photos.Access(text=access)
if commenting_enabled in ('true', 'false'):
album.commentingEnabled = gdata.photos.CommentingEnabled(text=commenting_enabled)
if timestamp is None:
timestamp = '%i' % int(time.time() * 1000)
album.timestamp = gdata.photos.Timestamp(text=timestamp)
try:
return self.Post(album, uri=self.userUri % self.email,
converter=gdata.photos.AlbumEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def InsertPhoto(self, album_or_uri, photo, filename_or_handle,
content_type='image/jpeg'):
"""Add a PhotoEntry
Needs authentication, see self.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'
"""
try:
assert(isinstance(photo, gdata.photos.PhotoEntry))
except AssertionError:
raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUMENT,
'body':'`photo` must be a gdata.photos.PhotoEntry instance',
'reason':'Found %s, not PhotoEntry' % type(photo)
})
try:
majtype, mintype = content_type.split('/')
assert(mintype in SUPPORTED_UPLOAD_TYPES)
except (ValueError, AssertionError):
raise GooglePhotosException({'status':GPHOTOS_INVALID_CONTENT_TYPE,
'body':'This is not a valid content type: %s' % content_type,
'reason':'Accepted content types: %s' % \
['image/'+t for t in SUPPORTED_UPLOAD_TYPES]
})
if isinstance(filename_or_handle, (str, unicode)) and \
os.path.exists(filename_or_handle): # it's a file name
mediasource = gdata.MediaSource()
mediasource.setFile(filename_or_handle, content_type)
elif hasattr(filename_or_handle, 'read'):# it's a file-like resource
if hasattr(filename_or_handle, 'seek'):
filename_or_handle.seek(0) # rewind pointer to the start of the file
# gdata.MediaSource needs the content length, so read the whole image
file_handle = StringIO.StringIO(filename_or_handle.read())
name = 'image'
if hasattr(filename_or_handle, 'name'):
name = filename_or_handle.name
mediasource = gdata.MediaSource(file_handle, content_type,
content_length=file_handle.len, file_name=name)
else: #filename_or_handle is not valid
raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUMENT,
'body':'`filename_or_handle` must be a path name or a file-like object',
'reason':'Found %s, not path name or object with a .read() method' % \
type(filename_or_handle)
})
if isinstance(album_or_uri, (str, unicode)): # it's a uri
feed_uri = album_or_uri
elif hasattr(album_or_uri, 'GetFeedLink'): # it's a AlbumFeed object
feed_uri = album_or_uri.GetFeedLink().href
try:
return self.Post(photo, uri=feed_uri, media_source=mediasource,
converter=gdata.photos.PhotoEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def 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 self.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
"""
metadata = gdata.photos.PhotoEntry()
metadata.title=atom.Title(text=title)
metadata.summary = atom.Summary(text=summary, summary_type='text')
if keywords is not None:
if isinstance(keywords, list):
keywords = ','.join(keywords)
metadata.media.keywords = gdata.media.Keywords(text=keywords)
return self.InsertPhoto(album_or_uri, metadata, filename_or_handle,
content_type)
def UpdatePhotoMetadata(self, photo):
"""Update a photo's metadata.
Needs authentication, see self.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
"""
try:
return self.Put(data=photo, uri=photo.GetEditLink().href,
converter=gdata.photos.PhotoEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def UpdatePhotoBlob(self, photo_or_uri, filename_or_handle,
content_type = 'image/jpeg'):
"""Update a photo's binary data.
Needs authentication, see self.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
"""
try:
majtype, mintype = content_type.split('/')
assert(mintype in SUPPORTED_UPLOAD_TYPES)
except (ValueError, AssertionError):
raise GooglePhotosException({'status':GPHOTOS_INVALID_CONTENT_TYPE,
'body':'This is not a valid content type: %s' % content_type,
'reason':'Accepted content types: %s' % \
['image/'+t for t in SUPPORTED_UPLOAD_TYPES]
})
if isinstance(filename_or_handle, (str, unicode)) and \
os.path.exists(filename_or_handle): # it's a file name
photoblob = gdata.MediaSource()
photoblob.setFile(filename_or_handle, content_type)
elif hasattr(filename_or_handle, 'read'):# it's a file-like resource
if hasattr(filename_or_handle, 'seek'):
filename_or_handle.seek(0) # rewind pointer to the start of the file
# gdata.MediaSource needs the content length, so read the whole image
file_handle = StringIO.StringIO(filename_or_handle.read())
name = 'image'
if hasattr(filename_or_handle, 'name'):
name = filename_or_handle.name
mediasource = gdata.MediaSource(file_handle, content_type,
content_length=file_handle.len, file_name=name)
else: #filename_or_handle is not valid
raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUMENT,
'body':'`filename_or_handle` must be a path name or a file-like object',
'reason':'Found %s, not path name or an object with .read() method' % \
type(filename_or_handle)
})
if isinstance(photo_or_uri, (str, unicode)):
entry_uri = photo_or_uri # it's a uri
elif hasattr(photo_or_uri, 'GetEditMediaLink'):
entry_uri = photo_or_uri.GetEditMediaLink().href
try:
return self.Put(photoblob, entry_uri,
converter=gdata.photos.PhotoEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def InsertTag(self, photo_or_uri, tag):
"""Add a tag (a.k.a. keyword) to a photo.
Needs authentication, see self.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')
"""
tag = gdata.photos.TagEntry(title=atom.Title(text=tag))
if isinstance(photo_or_uri, (str, unicode)):
post_uri = photo_or_uri # it's a uri
elif hasattr(photo_or_uri, 'GetEditMediaLink'):
post_uri = photo_or_uri.GetPostLink().href
try:
return self.Post(data=tag, uri=post_uri,
converter=gdata.photos.TagEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def InsertComment(self, photo_or_uri, comment):
"""Add a comment to a photo.
Needs authentication, see self.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?')
"""
comment = gdata.photos.CommentEntry(content=atom.Content(text=comment))
if isinstance(photo_or_uri, (str, unicode)):
post_uri = photo_or_uri # it's a uri
elif hasattr(photo_or_uri, 'GetEditMediaLink'):
post_uri = photo_or_uri.GetPostLink().href
try:
return self.Post(data=comment, uri=post_uri,
converter=gdata.photos.CommentEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def 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
"""
try:
uri = object_or_uri.GetEditLink().href
except AttributeError:
uri = object_or_uri
try:
return gdata.service.GDataService.Delete(self, uri, *args, **kwargs)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def GetSmallestThumbnail(media_thumbnail_list):
"""Helper function to get the smallest thumbnail of a list of
gdata.media.Thumbnail.
Returns gdata.media.Thumbnail """
r = {}
for thumb in media_thumbnail_list:
r[int(thumb.width)*int(thumb.height)] = thumb
keys = r.keys()
keys.sort()
return r[keys[0]]
def 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' -> """
return time.mktime(time.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.000Z'))
## TODO: Timezone aware
| Python |
#!/usr/bin/env python
# -*-*- encoding: utf-8 -*-*-
#
# This is the service file for the Google Photo python client.
# It is used for higher level operations.
#
# $Id: service.py 144 2007-10-25 21:03:34Z havard.gulldahl $
#
# Copyright 2007 Håvard Gulldahl
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""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)
"""
__author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: pydoc chokes on non-ascii chars in __author__
__license__ = 'Apache License v2'
__version__ = '$Revision: 176 $'[11:-2]
import sys, os.path, StringIO
import time
import gdata.service
import gdata
import atom.service
import atom
import gdata.photos
SUPPORTED_UPLOAD_TYPES = ('bmp', 'jpeg', 'jpg', 'gif', 'png')
UNKOWN_ERROR=1000
GPHOTOS_BAD_REQUEST=400
GPHOTOS_CONFLICT=409
GPHOTOS_INTERNAL_SERVER_ERROR=500
GPHOTOS_INVALID_ARGUMENT=601
GPHOTOS_INVALID_CONTENT_TYPE=602
GPHOTOS_NOT_AN_IMAGE=603
GPHOTOS_INVALID_KIND=604
class GooglePhotosException(Exception):
def __init__(self, response):
self.error_code = response['status']
self.reason = response['reason'].strip()
if '<html>' in str(response['body']): #general html message, discard it
response['body'] = ""
self.body = response['body'].strip()
self.message = "(%(status)s) %(body)s -- %(reason)s" % response
#return explicit error codes
error_map = { '(12) Not an image':GPHOTOS_NOT_AN_IMAGE,
'kind: That is not one of the acceptable values':
GPHOTOS_INVALID_KIND,
}
for msg, code in error_map.iteritems():
if self.body == msg:
self.error_code = code
break
self.args = [self.error_code, self.reason, self.body]
class PhotosService(gdata.service.GDataService):
userUri = '/data/feed/api/user/%s'
def __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:
A PhotosService object used to communicate with the Google Photos
service.
"""
self.email = email
self.client = source
gdata.service.GDataService.__init__(self, email=self.email, password=password,
service='lh2', source=source,
server=server,
additional_headers=additional_headers)
def 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
"""
if limit is not None:
uri += '&max-results=%s' % limit
if start_index is not None:
uri += '&start-index=%s' % start_index
try:
return self.Get(uri, converter=gdata.photos.AnyFeedFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def 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
"""
if limit is not None:
uri += '&max-results=%s' % limit
if start_index is not None:
uri += '&start-index=%s' % start_index
try:
return self.Get(uri, converter=gdata.photos.AnyEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def 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
"""
if isinstance(kind, (list, tuple) ):
kind = ",".join(kind)
uri = '/data/feed/api/user/%s?kind=%s' % (user, kind)
return self.GetFeed(uri, limit=limit)
def 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
"""
# Lower-casing because of
# http://code.google.com/p/gdata-issues/issues/detail?id=194
uri = '/data/feed/api/user/%s?kind=photo&tag=%s' % (user, tag.lower())
return self.GetFeed(uri, limit)
def 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
"""
uri = '/data/feed/api/user/%s?kind=photo&q=%s' % (user, query)
return self.GetFeed(uri, limit=limit)
def 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
"""
uri='/data/feed/api/all?q=%s' % query
return self.GetFeed(uri, limit=limit)
def 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
"""
uri = '/data/feed/api/user/%s/contacts?kind=user' % user
return self.GetFeed(uri, limit=limit)
def 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
"""
uri = '/data/feed/api/user/%s/contacts?kind=photo&q=%s' % (user, search)
return self.GetFeed(uri, limit=limit)
def InsertAlbum(self, title, summary, location=None, access='public',
commenting_enabled='true', timestamp=None):
"""Add an album.
Needs authentication, see self.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
"""
album = gdata.photos.AlbumEntry()
album.title = atom.Title(text=title, title_type='text')
album.summary = atom.Summary(text=summary, summary_type='text')
if location is not None:
album.location = gdata.photos.Location(text=location)
album.access = gdata.photos.Access(text=access)
if commenting_enabled in ('true', 'false'):
album.commentingEnabled = gdata.photos.CommentingEnabled(text=commenting_enabled)
if timestamp is None:
timestamp = '%i' % int(time.time() * 1000)
album.timestamp = gdata.photos.Timestamp(text=timestamp)
try:
return self.Post(album, uri=self.userUri % self.email,
converter=gdata.photos.AlbumEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def InsertPhoto(self, album_or_uri, photo, filename_or_handle,
content_type='image/jpeg'):
"""Add a PhotoEntry
Needs authentication, see self.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'
"""
try:
assert(isinstance(photo, gdata.photos.PhotoEntry))
except AssertionError:
raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUMENT,
'body':'`photo` must be a gdata.photos.PhotoEntry instance',
'reason':'Found %s, not PhotoEntry' % type(photo)
})
try:
majtype, mintype = content_type.split('/')
assert(mintype in SUPPORTED_UPLOAD_TYPES)
except (ValueError, AssertionError):
raise GooglePhotosException({'status':GPHOTOS_INVALID_CONTENT_TYPE,
'body':'This is not a valid content type: %s' % content_type,
'reason':'Accepted content types: %s' % \
['image/'+t for t in SUPPORTED_UPLOAD_TYPES]
})
if isinstance(filename_or_handle, (str, unicode)) and \
os.path.exists(filename_or_handle): # it's a file name
mediasource = gdata.MediaSource()
mediasource.setFile(filename_or_handle, content_type)
elif hasattr(filename_or_handle, 'read'):# it's a file-like resource
if hasattr(filename_or_handle, 'seek'):
filename_or_handle.seek(0) # rewind pointer to the start of the file
# gdata.MediaSource needs the content length, so read the whole image
file_handle = StringIO.StringIO(filename_or_handle.read())
name = 'image'
if hasattr(filename_or_handle, 'name'):
name = filename_or_handle.name
mediasource = gdata.MediaSource(file_handle, content_type,
content_length=file_handle.len, file_name=name)
else: #filename_or_handle is not valid
raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUMENT,
'body':'`filename_or_handle` must be a path name or a file-like object',
'reason':'Found %s, not path name or object with a .read() method' % \
type(filename_or_handle)
})
if isinstance(album_or_uri, (str, unicode)): # it's a uri
feed_uri = album_or_uri
elif hasattr(album_or_uri, 'GetFeedLink'): # it's a AlbumFeed object
feed_uri = album_or_uri.GetFeedLink().href
try:
return self.Post(photo, uri=feed_uri, media_source=mediasource,
converter=gdata.photos.PhotoEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def 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 self.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
"""
metadata = gdata.photos.PhotoEntry()
metadata.title=atom.Title(text=title)
metadata.summary = atom.Summary(text=summary, summary_type='text')
if keywords is not None:
if isinstance(keywords, list):
keywords = ','.join(keywords)
metadata.media.keywords = gdata.media.Keywords(text=keywords)
return self.InsertPhoto(album_or_uri, metadata, filename_or_handle,
content_type)
def UpdatePhotoMetadata(self, photo):
"""Update a photo's metadata.
Needs authentication, see self.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
"""
try:
return self.Put(data=photo, uri=photo.GetEditLink().href,
converter=gdata.photos.PhotoEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def UpdatePhotoBlob(self, photo_or_uri, filename_or_handle,
content_type = 'image/jpeg'):
"""Update a photo's binary data.
Needs authentication, see self.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
"""
try:
majtype, mintype = content_type.split('/')
assert(mintype in SUPPORTED_UPLOAD_TYPES)
except (ValueError, AssertionError):
raise GooglePhotosException({'status':GPHOTOS_INVALID_CONTENT_TYPE,
'body':'This is not a valid content type: %s' % content_type,
'reason':'Accepted content types: %s' % \
['image/'+t for t in SUPPORTED_UPLOAD_TYPES]
})
if isinstance(filename_or_handle, (str, unicode)) and \
os.path.exists(filename_or_handle): # it's a file name
photoblob = gdata.MediaSource()
photoblob.setFile(filename_or_handle, content_type)
elif hasattr(filename_or_handle, 'read'):# it's a file-like resource
if hasattr(filename_or_handle, 'seek'):
filename_or_handle.seek(0) # rewind pointer to the start of the file
# gdata.MediaSource needs the content length, so read the whole image
file_handle = StringIO.StringIO(filename_or_handle.read())
name = 'image'
if hasattr(filename_or_handle, 'name'):
name = filename_or_handle.name
mediasource = gdata.MediaSource(file_handle, content_type,
content_length=file_handle.len, file_name=name)
else: #filename_or_handle is not valid
raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUMENT,
'body':'`filename_or_handle` must be a path name or a file-like object',
'reason':'Found %s, not path name or an object with .read() method' % \
type(filename_or_handle)
})
if isinstance(photo_or_uri, (str, unicode)):
entry_uri = photo_or_uri # it's a uri
elif hasattr(photo_or_uri, 'GetEditMediaLink'):
entry_uri = photo_or_uri.GetEditMediaLink().href
try:
return self.Put(photoblob, entry_uri,
converter=gdata.photos.PhotoEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def InsertTag(self, photo_or_uri, tag):
"""Add a tag (a.k.a. keyword) to a photo.
Needs authentication, see self.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')
"""
tag = gdata.photos.TagEntry(title=atom.Title(text=tag))
if isinstance(photo_or_uri, (str, unicode)):
post_uri = photo_or_uri # it's a uri
elif hasattr(photo_or_uri, 'GetEditMediaLink'):
post_uri = photo_or_uri.GetPostLink().href
try:
return self.Post(data=tag, uri=post_uri,
converter=gdata.photos.TagEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def InsertComment(self, photo_or_uri, comment):
"""Add a comment to a photo.
Needs authentication, see self.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?')
"""
comment = gdata.photos.CommentEntry(content=atom.Content(text=comment))
if isinstance(photo_or_uri, (str, unicode)):
post_uri = photo_or_uri # it's a uri
elif hasattr(photo_or_uri, 'GetEditMediaLink'):
post_uri = photo_or_uri.GetPostLink().href
try:
return self.Post(data=comment, uri=post_uri,
converter=gdata.photos.CommentEntryFromString)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def 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
"""
try:
uri = object_or_uri.GetEditLink().href
except AttributeError:
uri = object_or_uri
try:
return gdata.service.GDataService.Delete(self, uri, *args, **kwargs)
except gdata.service.RequestError, e:
raise GooglePhotosException(e.args[0])
def GetSmallestThumbnail(media_thumbnail_list):
"""Helper function to get the smallest thumbnail of a list of
gdata.media.Thumbnail.
Returns gdata.media.Thumbnail """
r = {}
for thumb in media_thumbnail_list:
r[int(thumb.width)*int(thumb.height)] = thumb
keys = r.keys()
keys.sort()
return r[keys[0]]
def 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' -> """
return time.mktime(time.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.000Z'))
## TODO: Timezone aware
| Python |
# -*-*- encoding: utf-8 -*-*-
#
# This is the base file for the PicasaWeb python client.
# It is used for lower level operations.
#
# $Id: __init__.py 148 2007-10-28 15:09:19Z havard.gulldahl $
#
# Copyright 2007 Håvard Gulldahl
# Portions (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This module provides a pythonic, gdata-centric interface to Google Photos
(a.k.a. Picasa Web Services.
It is modelled after the gdata/* interfaces from the gdata-python-client
project[1] by Google.
You'll find the user-friendly api in photos.service. Please see the
documentation or live help() system for available methods.
[1]: http://gdata-python-client.googlecode.com/
"""
__author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: pydoc chokes on non-ascii chars in __author__
__license__ = 'Apache License v2'
__version__ = '$Revision: 164 $'[11:-2]
import re
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import atom
import gdata
# importing google photo submodules
import gdata.media as Media, gdata.exif as Exif, gdata.geo as Geo
# XML namespaces which are often used in Google Photo elements
PHOTOS_NAMESPACE = 'http://schemas.google.com/photos/2007'
MEDIA_NAMESPACE = 'http://search.yahoo.com/mrss/'
EXIF_NAMESPACE = 'http://schemas.google.com/photos/exif/2007'
OPENSEARCH_NAMESPACE = 'http://a9.com/-/spec/opensearchrss/1.0/'
GEO_NAMESPACE = 'http://www.w3.org/2003/01/geo/wgs84_pos#'
GML_NAMESPACE = 'http://www.opengis.net/gml'
GEORSS_NAMESPACE = 'http://www.georss.org/georss'
PHEED_NAMESPACE = 'http://www.pheed.com/pheed/'
BATCH_NAMESPACE = 'http://schemas.google.com/gdata/batch'
class PhotosBaseElement(atom.AtomBase):
"""Base class for elements in the PHOTO_NAMESPACE. To add new elements,
you only need to add the element tag name to self._tag
"""
_tag = ''
_namespace = PHOTOS_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, name=None, extension_elements=None,
extension_attributes=None, text=None):
self.name = name
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
#def __str__(self):
#return str(self.text)
#def __unicode__(self):
#return unicode(self.text)
def __int__(self):
return int(self.text)
def bool(self):
return self.text == 'true'
class GPhotosBaseFeed(gdata.GDataFeed, gdata.LinkFinder):
"Base class for all Feeds in gdata.photos"
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_attributes = gdata.GDataFeed._attributes.copy()
_children = gdata.GDataFeed._children.copy()
# We deal with Entry elements ourselves
del _children['{%s}entry' % atom.ATOM_NAMESPACE]
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None,
entry=None, total_results=None, start_index=None,
items_per_page=None, extension_elements=None,
extension_attributes=None, text=None):
gdata.GDataFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def kind(self):
"(string) Returns the kind"
try:
return self.category[0].term.split('#')[1]
except IndexError:
return None
def _feedUri(self, kind):
"Convenience method to return a uri to a feed of a special kind"
assert(kind in ('album', 'tag', 'photo', 'comment', 'user'))
here_href = self.GetSelfLink().href
if 'kind=%s' % kind in here_href:
return here_href
if not 'kind=' in here_href:
sep = '?'
if '?' in here_href: sep = '&'
return here_href + "%skind=%s" % (sep, kind)
rx = re.match('.*(kind=)(album|tag|photo|comment)', here_href)
return here_href[:rx.end(1)] + kind + here_href[rx.end(2):]
def _ConvertElementTreeToMember(self, child_tree):
"""Re-implementing the method from AtomBase, since we deal with
Entry elements specially"""
category = child_tree.find('{%s}category' % atom.ATOM_NAMESPACE)
if category is None:
return atom.AtomBase._ConvertElementTreeToMember(self, child_tree)
namespace, kind = category.get('term').split('#')
if namespace != PHOTOS_NAMESPACE:
return atom.AtomBase._ConvertElementTreeToMember(self, child_tree)
## TODO: is it safe to use getattr on gdata.photos?
entry_class = getattr(gdata.photos, '%sEntry' % kind.title())
if not hasattr(self, 'entry') or self.entry is None:
self.entry = []
self.entry.append(atom._CreateClassFromElementTree(
entry_class, child_tree))
class GPhotosBaseEntry(gdata.GDataEntry, gdata.LinkFinder):
"Base class for all Entry elements in gdata.photos"
_tag = 'entry'
_kind = ''
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
extended_property=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title,
updated=updated, text=text,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
self.category.append(
atom.Category(scheme='http://schemas.google.com/g/2005#kind',
term = 'http://schemas.google.com/photos/2007#%s' % self._kind))
def kind(self):
"(string) Returns the kind"
try:
return self.category[0].term.split('#')[1]
except IndexError:
return None
def _feedUri(self, kind):
"Convenience method to get the uri to this entry's feed of the some kind"
try:
href = self.GetFeedLink().href
except AttributeError:
return None
sep = '?'
if '?' in href: sep = '&'
return '%s%skind=%s' % (href, sep, kind)
class PhotosBaseEntry(GPhotosBaseEntry):
pass
class PhotosBaseFeed(GPhotosBaseFeed):
pass
class GPhotosBaseData(object):
pass
class Access(PhotosBaseElement):
"""The Google Photo `Access' element.
The album's access level. Valid values are `public' or `private'.
In documentation, access level is also referred to as `visibility.'"""
_tag = 'access'
def AccessFromString(xml_string):
return atom.CreateClassFromXMLString(Access, xml_string)
class Albumid(PhotosBaseElement):
"The Google Photo `Albumid' element"
_tag = 'albumid'
def AlbumidFromString(xml_string):
return atom.CreateClassFromXMLString(Albumid, xml_string)
class BytesUsed(PhotosBaseElement):
"The Google Photo `BytesUsed' element"
_tag = 'bytesUsed'
def BytesUsedFromString(xml_string):
return atom.CreateClassFromXMLString(BytesUsed, xml_string)
class Client(PhotosBaseElement):
"The Google Photo `Client' element"
_tag = 'client'
def ClientFromString(xml_string):
return atom.CreateClassFromXMLString(Client, xml_string)
class Checksum(PhotosBaseElement):
"The Google Photo `Checksum' element"
_tag = 'checksum'
def ChecksumFromString(xml_string):
return atom.CreateClassFromXMLString(Checksum, xml_string)
class CommentCount(PhotosBaseElement):
"The Google Photo `CommentCount' element"
_tag = 'commentCount'
def CommentCountFromString(xml_string):
return atom.CreateClassFromXMLString(CommentCount, xml_string)
class CommentingEnabled(PhotosBaseElement):
"The Google Photo `CommentingEnabled' element"
_tag = 'commentingEnabled'
def CommentingEnabledFromString(xml_string):
return atom.CreateClassFromXMLString(CommentingEnabled, xml_string)
class Height(PhotosBaseElement):
"The Google Photo `Height' element"
_tag = 'height'
def HeightFromString(xml_string):
return atom.CreateClassFromXMLString(Height, xml_string)
class Id(PhotosBaseElement):
"The Google Photo `Id' element"
_tag = 'id'
def IdFromString(xml_string):
return atom.CreateClassFromXMLString(Id, xml_string)
class Location(PhotosBaseElement):
"The Google Photo `Location' element"
_tag = 'location'
def LocationFromString(xml_string):
return atom.CreateClassFromXMLString(Location, xml_string)
class MaxPhotosPerAlbum(PhotosBaseElement):
"The Google Photo `MaxPhotosPerAlbum' element"
_tag = 'maxPhotosPerAlbum'
def MaxPhotosPerAlbumFromString(xml_string):
return atom.CreateClassFromXMLString(MaxPhotosPerAlbum, xml_string)
class Name(PhotosBaseElement):
"The Google Photo `Name' element"
_tag = 'name'
def NameFromString(xml_string):
return atom.CreateClassFromXMLString(Name, xml_string)
class Nickname(PhotosBaseElement):
"The Google Photo `Nickname' element"
_tag = 'nickname'
def NicknameFromString(xml_string):
return atom.CreateClassFromXMLString(Nickname, xml_string)
class Numphotos(PhotosBaseElement):
"The Google Photo `Numphotos' element"
_tag = 'numphotos'
def NumphotosFromString(xml_string):
return atom.CreateClassFromXMLString(Numphotos, xml_string)
class Numphotosremaining(PhotosBaseElement):
"The Google Photo `Numphotosremaining' element"
_tag = 'numphotosremaining'
def NumphotosremainingFromString(xml_string):
return atom.CreateClassFromXMLString(Numphotosremaining, xml_string)
class Position(PhotosBaseElement):
"The Google Photo `Position' element"
_tag = 'position'
def PositionFromString(xml_string):
return atom.CreateClassFromXMLString(Position, xml_string)
class Photoid(PhotosBaseElement):
"The Google Photo `Photoid' element"
_tag = 'photoid'
def PhotoidFromString(xml_string):
return atom.CreateClassFromXMLString(Photoid, xml_string)
class Quotacurrent(PhotosBaseElement):
"The Google Photo `Quotacurrent' element"
_tag = 'quotacurrent'
def QuotacurrentFromString(xml_string):
return atom.CreateClassFromXMLString(Quotacurrent, xml_string)
class Quotalimit(PhotosBaseElement):
"The Google Photo `Quotalimit' element"
_tag = 'quotalimit'
def QuotalimitFromString(xml_string):
return atom.CreateClassFromXMLString(Quotalimit, xml_string)
class Rotation(PhotosBaseElement):
"The Google Photo `Rotation' element"
_tag = 'rotation'
def RotationFromString(xml_string):
return atom.CreateClassFromXMLString(Rotation, xml_string)
class Size(PhotosBaseElement):
"The Google Photo `Size' element"
_tag = 'size'
def SizeFromString(xml_string):
return atom.CreateClassFromXMLString(Size, xml_string)
class Snippet(PhotosBaseElement):
"""The Google Photo `snippet' element.
When searching, the snippet element will contain a
string with the word you're looking for, highlighted in html markup
E.g. when your query is `hafjell', this element may contain:
`... here at <b>Hafjell</b>.'
You'll find this element in searches -- that is, feeds that combine the
`kind=photo' and `q=yoursearch' parameters in the request.
See also gphoto:truncated and gphoto:snippettype.
"""
_tag = 'snippet'
def SnippetFromString(xml_string):
return atom.CreateClassFromXMLString(Snippet, xml_string)
class Snippettype(PhotosBaseElement):
"""The Google Photo `Snippettype' element
When searching, this element will tell you the type of element that matches.
You'll find this element in searches -- that is, feeds that combine the
`kind=photo' and `q=yoursearch' parameters in the request.
See also gphoto:snippet and gphoto:truncated.
Possible values and their interpretation:
o ALBUM_TITLE - The album title matches
o PHOTO_TAGS - The match is a tag/keyword
o PHOTO_DESCRIPTION - The match is in the photo's description
If you discover a value not listed here, please submit a patch to update this docstring.
"""
_tag = 'snippettype'
def SnippettypeFromString(xml_string):
return atom.CreateClassFromXMLString(Snippettype, xml_string)
class Thumbnail(PhotosBaseElement):
"""The Google Photo `Thumbnail' element
Used to display user's photo thumbnail (hackergotchi).
(Not to be confused with the <media:thumbnail> element, which gives you
small versions of the photo object.)"""
_tag = 'thumbnail'
def ThumbnailFromString(xml_string):
return atom.CreateClassFromXMLString(Thumbnail, xml_string)
class Timestamp(PhotosBaseElement):
"""The Google Photo `Timestamp' element
Represented as the number of milliseconds since January 1st, 1970.
Take a look at the convenience methods .isoformat() and .datetime():
photo_epoch = Time.text # 1180294337000
photo_isostring = Time.isoformat() # '2007-05-27T19:32:17.000Z'
Alternatively:
photo_datetime = Time.datetime() # (requires python >= 2.3)
"""
_tag = 'timestamp'
def isoformat(self):
"""(string) Return the timestamp as a ISO 8601 formatted string,
e.g. '2007-05-27T19:32:17.000Z'
"""
import time
epoch = float(self.text)/1000
return time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(epoch))
def datetime(self):
"""(datetime.datetime) Return the timestamp as a datetime.datetime object
Requires python 2.3
"""
import datetime
epoch = float(self.text)/1000
return datetime.datetime.fromtimestamp(epoch)
def TimestampFromString(xml_string):
return atom.CreateClassFromXMLString(Timestamp, xml_string)
class Truncated(PhotosBaseElement):
"""The Google Photo `Truncated' element
You'll find this element in searches -- that is, feeds that combine the
`kind=photo' and `q=yoursearch' parameters in the request.
See also gphoto:snippet and gphoto:snippettype.
Possible values and their interpretation:
0 -- unknown
"""
_tag = 'Truncated'
def TruncatedFromString(xml_string):
return atom.CreateClassFromXMLString(Truncated, xml_string)
class User(PhotosBaseElement):
"The Google Photo `User' element"
_tag = 'user'
def UserFromString(xml_string):
return atom.CreateClassFromXMLString(User, xml_string)
class Version(PhotosBaseElement):
"The Google Photo `Version' element"
_tag = 'version'
def VersionFromString(xml_string):
return atom.CreateClassFromXMLString(Version, xml_string)
class Width(PhotosBaseElement):
"The Google Photo `Width' element"
_tag = 'width'
def WidthFromString(xml_string):
return atom.CreateClassFromXMLString(Width, xml_string)
class Weight(PhotosBaseElement):
"""The Google Photo `Weight' element.
The weight of the tag is the number of times the tag
appears in the collection of tags currently being viewed.
The default weight is 1, in which case this tags is omitted."""
_tag = 'weight'
def WeightFromString(xml_string):
return atom.CreateClassFromXMLString(Weight, xml_string)
class CommentAuthor(atom.Author):
"""The Atom `Author' element in CommentEntry entries is augmented to
contain elements from the PHOTOS_NAMESPACE
http://groups.google.com/group/Google-Picasa-Data-API/msg/819b0025b5ff5e38
"""
_children = atom.Author._children.copy()
_children['{%s}user' % PHOTOS_NAMESPACE] = ('user', User)
_children['{%s}nickname' % PHOTOS_NAMESPACE] = ('nickname', Nickname)
_children['{%s}thumbnail' % PHOTOS_NAMESPACE] = ('thumbnail', Thumbnail)
def CommentAuthorFromString(xml_string):
return atom.CreateClassFromXMLString(CommentAuthor, xml_string)
########################## ################################
class AlbumData(object):
_children = {}
_children['{%s}id' % PHOTOS_NAMESPACE] = ('gphoto_id', Id)
_children['{%s}name' % PHOTOS_NAMESPACE] = ('name', Name)
_children['{%s}location' % PHOTOS_NAMESPACE] = ('location', Location)
_children['{%s}access' % PHOTOS_NAMESPACE] = ('access', Access)
_children['{%s}bytesUsed' % PHOTOS_NAMESPACE] = ('bytesUsed', BytesUsed)
_children['{%s}timestamp' % PHOTOS_NAMESPACE] = ('timestamp', Timestamp)
_children['{%s}numphotos' % PHOTOS_NAMESPACE] = ('numphotos', Numphotos)
_children['{%s}numphotosremaining' % PHOTOS_NAMESPACE] = \
('numphotosremaining', Numphotosremaining)
_children['{%s}user' % PHOTOS_NAMESPACE] = ('user', User)
_children['{%s}nickname' % PHOTOS_NAMESPACE] = ('nickname', Nickname)
_children['{%s}commentingEnabled' % PHOTOS_NAMESPACE] = \
('commentingEnabled', CommentingEnabled)
_children['{%s}commentCount' % PHOTOS_NAMESPACE] = \
('commentCount', CommentCount)
## NOTE: storing media:group as self.media, to create a self-explaining api
gphoto_id = None
name = None
location = None
access = None
bytesUsed = None
timestamp = None
numphotos = None
numphotosremaining = None
user = None
nickname = None
commentingEnabled = None
commentCount = None
class AlbumEntry(GPhotosBaseEntry, AlbumData):
"""All metadata for a Google Photos Album
Take a look at AlbumData for metadata accessible as attributes to this object.
Notes:
To avoid name clashes, and to create a more sensible api, some
objects have names that differ from the original elements:
o media:group -> self.media,
o geo:where -> self.geo,
o photo:id -> self.gphoto_id
"""
_kind = 'album'
_children = GPhotosBaseEntry._children.copy()
_children.update(AlbumData._children.copy())
# child tags only for Album entries, not feeds
_children['{%s}where' % GEORSS_NAMESPACE] = ('geo', Geo.Where)
_children['{%s}group' % MEDIA_NAMESPACE] = ('media', Media.Group)
media = Media.Group()
geo = Geo.Where()
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
#GPHOTO NAMESPACE:
gphoto_id=None, name=None, location=None, access=None,
timestamp=None, numphotos=None, user=None, nickname=None,
commentingEnabled=None, commentCount=None, thumbnail=None,
# MEDIA NAMESPACE:
media=None,
# GEORSS NAMESPACE:
geo=None,
extended_property=None,
extension_elements=None, extension_attributes=None, text=None):
GPhotosBaseEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title,
updated=updated, text=text,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
## NOTE: storing photo:id as self.gphoto_id, to avoid name clash with atom:id
self.gphoto_id = gphoto_id
self.name = name
self.location = location
self.access = access
self.timestamp = timestamp
self.numphotos = numphotos
self.user = user
self.nickname = nickname
self.commentingEnabled = commentingEnabled
self.commentCount = commentCount
self.thumbnail = thumbnail
self.extended_property = extended_property or []
self.text = text
## NOTE: storing media:group as self.media, and geo:where as geo,
## to create a self-explaining api
self.media = media or Media.Group()
self.geo = geo or Geo.Where()
def GetAlbumId(self):
"Return the id of this album"
return self.GetFeedLink().href.split('/')[-1]
def GetPhotosUri(self):
"(string) Return the uri to this albums feed of the PhotoEntry kind"
return self._feedUri('photo')
def GetCommentsUri(self):
"(string) Return the uri to this albums feed of the CommentEntry kind"
return self._feedUri('comment')
def GetTagsUri(self):
"(string) Return the uri to this albums feed of the TagEntry kind"
return self._feedUri('tag')
def AlbumEntryFromString(xml_string):
return atom.CreateClassFromXMLString(AlbumEntry, xml_string)
class AlbumFeed(GPhotosBaseFeed, AlbumData):
"""All metadata for a Google Photos Album, including its sub-elements
This feed represents an album as the container for other objects.
A Album feed contains entries of
PhotoEntry, CommentEntry or TagEntry,
depending on the `kind' parameter in the original query.
Take a look at AlbumData for accessible attributes.
"""
_children = GPhotosBaseFeed._children.copy()
_children.update(AlbumData._children.copy())
def GetPhotosUri(self):
"(string) Return the uri to the same feed, but of the PhotoEntry kind"
return self._feedUri('photo')
def GetTagsUri(self):
"(string) Return the uri to the same feed, but of the TagEntry kind"
return self._feedUri('tag')
def GetCommentsUri(self):
"(string) Return the uri to the same feed, but of the CommentEntry kind"
return self._feedUri('comment')
def AlbumFeedFromString(xml_string):
return atom.CreateClassFromXMLString(AlbumFeed, xml_string)
class PhotoData(object):
_children = {}
## NOTE: storing photo:id as self.gphoto_id, to avoid name clash with atom:id
_children['{%s}id' % PHOTOS_NAMESPACE] = ('gphoto_id', Id)
_children['{%s}albumid' % PHOTOS_NAMESPACE] = ('albumid', Albumid)
_children['{%s}checksum' % PHOTOS_NAMESPACE] = ('checksum', Checksum)
_children['{%s}client' % PHOTOS_NAMESPACE] = ('client', Client)
_children['{%s}height' % PHOTOS_NAMESPACE] = ('height', Height)
_children['{%s}position' % PHOTOS_NAMESPACE] = ('position', Position)
_children['{%s}rotation' % PHOTOS_NAMESPACE] = ('rotation', Rotation)
_children['{%s}size' % PHOTOS_NAMESPACE] = ('size', Size)
_children['{%s}timestamp' % PHOTOS_NAMESPACE] = ('timestamp', Timestamp)
_children['{%s}version' % PHOTOS_NAMESPACE] = ('version', Version)
_children['{%s}width' % PHOTOS_NAMESPACE] = ('width', Width)
_children['{%s}commentingEnabled' % PHOTOS_NAMESPACE] = \
('commentingEnabled', CommentingEnabled)
_children['{%s}commentCount' % PHOTOS_NAMESPACE] = \
('commentCount', CommentCount)
## NOTE: storing media:group as self.media, exif:tags as self.exif, and
## geo:where as self.geo, to create a self-explaining api
_children['{%s}tags' % EXIF_NAMESPACE] = ('exif', Exif.Tags)
_children['{%s}where' % GEORSS_NAMESPACE] = ('geo', Geo.Where)
_children['{%s}group' % MEDIA_NAMESPACE] = ('media', Media.Group)
# These elements show up in search feeds
_children['{%s}snippet' % PHOTOS_NAMESPACE] = ('snippet', Snippet)
_children['{%s}snippettype' % PHOTOS_NAMESPACE] = ('snippettype', Snippettype)
_children['{%s}truncated' % PHOTOS_NAMESPACE] = ('truncated', Truncated)
gphoto_id = None
albumid = None
checksum = None
client = None
height = None
position = None
rotation = None
size = None
timestamp = None
version = None
width = None
commentingEnabled = None
commentCount = None
snippet=None
snippettype=None
truncated=None
media = Media.Group()
geo = Geo.Where()
tags = Exif.Tags()
class PhotoEntry(GPhotosBaseEntry, PhotoData):
"""All metadata for a Google Photos Photo
Take a look at PhotoData for metadata accessible as attributes to this object.
Notes:
To avoid name clashes, and to create a more sensible api, some
objects have names that differ from the original elements:
o media:group -> self.media,
o exif:tags -> self.exif,
o geo:where -> self.geo,
o photo:id -> self.gphoto_id
"""
_kind = 'photo'
_children = GPhotosBaseEntry._children.copy()
_children.update(PhotoData._children.copy())
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None, text=None,
# GPHOTO NAMESPACE:
gphoto_id=None, albumid=None, checksum=None, client=None, height=None,
position=None, rotation=None, size=None, timestamp=None, version=None,
width=None, commentCount=None, commentingEnabled=None,
# MEDIARSS NAMESPACE:
media=None,
# EXIF_NAMESPACE:
exif=None,
# GEORSS NAMESPACE:
geo=None,
extension_elements=None, extension_attributes=None):
GPhotosBaseEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
title=title, updated=updated, text=text,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
## NOTE: storing photo:id as self.gphoto_id, to avoid name clash with atom:id
self.gphoto_id = gphoto_id
self.albumid = albumid
self.checksum = checksum
self.client = client
self.height = height
self.position = position
self.rotation = rotation
self.size = size
self.timestamp = timestamp
self.version = version
self.width = width
self.commentingEnabled = commentingEnabled
self.commentCount = commentCount
## NOTE: storing media:group as self.media, to create a self-explaining api
self.media = media or Media.Group()
self.exif = exif or Exif.Tags()
self.geo = geo or Geo.Where()
def GetPostLink(self):
"Return the uri to this photo's `POST' link (use it for updates of the object)"
return self.GetFeedLink()
def GetCommentsUri(self):
"Return the uri to this photo's feed of CommentEntry comments"
return self._feedUri('comment')
def GetTagsUri(self):
"Return the uri to this photo's feed of TagEntry tags"
return self._feedUri('tag')
def GetAlbumUri(self):
"""Return the uri to the AlbumEntry containing this photo"""
href = self.GetSelfLink().href
return href[:href.find('/photoid')]
def PhotoEntryFromString(xml_string):
return atom.CreateClassFromXMLString(PhotoEntry, xml_string)
class PhotoFeed(GPhotosBaseFeed, PhotoData):
"""All metadata for a Google Photos Photo, including its sub-elements
This feed represents a photo as the container for other objects.
A Photo feed contains entries of
CommentEntry or TagEntry,
depending on the `kind' parameter in the original query.
Take a look at PhotoData for metadata accessible as attributes to this object.
"""
_children = GPhotosBaseFeed._children.copy()
_children.update(PhotoData._children.copy())
def GetTagsUri(self):
"(string) Return the uri to the same feed, but of the TagEntry kind"
return self._feedUri('tag')
def GetCommentsUri(self):
"(string) Return the uri to the same feed, but of the CommentEntry kind"
return self._feedUri('comment')
def PhotoFeedFromString(xml_string):
return atom.CreateClassFromXMLString(PhotoFeed, xml_string)
class TagData(GPhotosBaseData):
_children = {}
_children['{%s}weight' % PHOTOS_NAMESPACE] = ('weight', Weight)
weight=None
class TagEntry(GPhotosBaseEntry, TagData):
"""All metadata for a Google Photos Tag
The actual tag is stored in the .title.text attribute
"""
_kind = 'tag'
_children = GPhotosBaseEntry._children.copy()
_children.update(TagData._children.copy())
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
# GPHOTO NAMESPACE:
weight=None,
extended_property=None,
extension_elements=None, extension_attributes=None, text=None):
GPhotosBaseEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
title=title, updated=updated, text=text,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
self.weight = weight
def GetAlbumUri(self):
"""Return the uri to the AlbumEntry containing this tag"""
href = self.GetSelfLink().href
pos = href.find('/photoid')
if pos == -1:
return None
return href[:pos]
def GetPhotoUri(self):
"""Return the uri to the PhotoEntry containing this tag"""
href = self.GetSelfLink().href
pos = href.find('/tag')
if pos == -1:
return None
return href[:pos]
def TagEntryFromString(xml_string):
return atom.CreateClassFromXMLString(TagEntry, xml_string)
class TagFeed(GPhotosBaseFeed, TagData):
"""All metadata for a Google Photos Tag, including its sub-elements"""
_children = GPhotosBaseFeed._children.copy()
_children.update(TagData._children.copy())
def TagFeedFromString(xml_string):
return atom.CreateClassFromXMLString(TagFeed, xml_string)
class CommentData(GPhotosBaseData):
_children = {}
## NOTE: storing photo:id as self.gphoto_id, to avoid name clash with atom:id
_children['{%s}id' % PHOTOS_NAMESPACE] = ('gphoto_id', Id)
_children['{%s}albumid' % PHOTOS_NAMESPACE] = ('albumid', Albumid)
_children['{%s}photoid' % PHOTOS_NAMESPACE] = ('photoid', Photoid)
_children['{%s}author' % atom.ATOM_NAMESPACE] = ('author', [CommentAuthor,])
gphoto_id=None
albumid=None
photoid=None
author=None
class CommentEntry(GPhotosBaseEntry, CommentData):
"""All metadata for a Google Photos Comment
The comment is stored in the .content.text attribute,
with a content type in .content.type.
"""
_kind = 'comment'
_children = GPhotosBaseEntry._children.copy()
_children.update(CommentData._children.copy())
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
# GPHOTO NAMESPACE:
gphoto_id=None, albumid=None, photoid=None,
extended_property=None,
extension_elements=None, extension_attributes=None, text=None):
GPhotosBaseEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
title=title, updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.gphoto_id = gphoto_id
self.albumid = albumid
self.photoid = photoid
def GetCommentId(self):
"""Return the globally unique id of this comment"""
return self.GetSelfLink().href.split('/')[-1]
def GetAlbumUri(self):
"""Return the uri to the AlbumEntry containing this comment"""
href = self.GetSelfLink().href
return href[:href.find('/photoid')]
def GetPhotoUri(self):
"""Return the uri to the PhotoEntry containing this comment"""
href = self.GetSelfLink().href
return href[:href.find('/commentid')]
def CommentEntryFromString(xml_string):
return atom.CreateClassFromXMLString(CommentEntry, xml_string)
class CommentFeed(GPhotosBaseFeed, CommentData):
"""All metadata for a Google Photos Comment, including its sub-elements"""
_children = GPhotosBaseFeed._children.copy()
_children.update(CommentData._children.copy())
def CommentFeedFromString(xml_string):
return atom.CreateClassFromXMLString(CommentFeed, xml_string)
class UserData(GPhotosBaseData):
_children = {}
_children['{%s}maxPhotosPerAlbum' % PHOTOS_NAMESPACE] = ('maxPhotosPerAlbum', MaxPhotosPerAlbum)
_children['{%s}nickname' % PHOTOS_NAMESPACE] = ('nickname', Nickname)
_children['{%s}quotalimit' % PHOTOS_NAMESPACE] = ('quotalimit', Quotalimit)
_children['{%s}quotacurrent' % PHOTOS_NAMESPACE] = ('quotacurrent', Quotacurrent)
_children['{%s}thumbnail' % PHOTOS_NAMESPACE] = ('thumbnail', Thumbnail)
_children['{%s}user' % PHOTOS_NAMESPACE] = ('user', User)
_children['{%s}id' % PHOTOS_NAMESPACE] = ('gphoto_id', Id)
maxPhotosPerAlbum=None
nickname=None
quotalimit=None
quotacurrent=None
thumbnail=None
user=None
gphoto_id=None
class UserEntry(GPhotosBaseEntry, UserData):
"""All metadata for a Google Photos User
This entry represents an album owner and all appropriate metadata.
Take a look at at the attributes of the UserData for metadata available.
"""
_children = GPhotosBaseEntry._children.copy()
_children.update(UserData._children.copy())
_kind = 'user'
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
# GPHOTO NAMESPACE:
gphoto_id=None, maxPhotosPerAlbum=None, nickname=None, quotalimit=None,
quotacurrent=None, thumbnail=None, user=None,
extended_property=None,
extension_elements=None, extension_attributes=None, text=None):
GPhotosBaseEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
title=title, updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.gphoto_id=gphoto_id
self.maxPhotosPerAlbum=maxPhotosPerAlbum
self.nickname=nickname
self.quotalimit=quotalimit
self.quotacurrent=quotacurrent
self.thumbnail=thumbnail
self.user=user
def GetAlbumsUri(self):
"(string) Return the uri to this user's feed of the AlbumEntry kind"
return self._feedUri('album')
def GetPhotosUri(self):
"(string) Return the uri to this user's feed of the PhotoEntry kind"
return self._feedUri('photo')
def GetCommentsUri(self):
"(string) Return the uri to this user's feed of the CommentEntry kind"
return self._feedUri('comment')
def GetTagsUri(self):
"(string) Return the uri to this user's feed of the TagEntry kind"
return self._feedUri('tag')
def UserEntryFromString(xml_string):
return atom.CreateClassFromXMLString(UserEntry, xml_string)
class UserFeed(GPhotosBaseFeed, UserData):
"""Feed for a User in the google photos api.
This feed represents a user as the container for other objects.
A User feed contains entries of
AlbumEntry, PhotoEntry, CommentEntry, UserEntry or TagEntry,
depending on the `kind' parameter in the original query.
The user feed itself also contains all of the metadata available
as part of a UserData object."""
_children = GPhotosBaseFeed._children.copy()
_children.update(UserData._children.copy())
def GetAlbumsUri(self):
"""Get the uri to this feed, but with entries of the AlbumEntry kind."""
return self._feedUri('album')
def GetTagsUri(self):
"""Get the uri to this feed, but with entries of the TagEntry kind."""
return self._feedUri('tag')
def GetPhotosUri(self):
"""Get the uri to this feed, but with entries of the PhotosEntry kind."""
return self._feedUri('photo')
def GetCommentsUri(self):
"""Get the uri to this feed, but with entries of the CommentsEntry kind."""
return self._feedUri('comment')
def UserFeedFromString(xml_string):
return atom.CreateClassFromXMLString(UserFeed, xml_string)
def AnyFeedFromString(xml_string):
"""Creates an instance of the appropriate feed class from the
xml string contents.
Args:
xml_string: str A string which contains valid XML. The root element
of the XML string should match the tag and namespace of the desired
class.
Returns:
An instance of the target class with members assigned according to the
contents of the XML - or a basic gdata.GDataFeed instance if it is
impossible to determine the appropriate class (look for extra elements
in GDataFeed's .FindExtensions() and extension_elements[] ).
"""
tree = ElementTree.fromstring(xml_string)
category = tree.find('{%s}category' % atom.ATOM_NAMESPACE)
if category is None:
# TODO: is this the best way to handle this?
return atom._CreateClassFromElementTree(GPhotosBaseFeed, tree)
namespace, kind = category.get('term').split('#')
if namespace != PHOTOS_NAMESPACE:
# TODO: is this the best way to handle this?
return atom._CreateClassFromElementTree(GPhotosBaseFeed, tree)
## TODO: is getattr safe this way?
feed_class = getattr(gdata.photos, '%sFeed' % kind.title())
return atom._CreateClassFromElementTree(feed_class, tree)
def AnyEntryFromString(xml_string):
"""Creates an instance of the appropriate entry class from the
xml string contents.
Args:
xml_string: str A string which contains valid XML. The root element
of the XML string should match the tag and namespace of the desired
class.
Returns:
An instance of the target class with members assigned according to the
contents of the XML - or a basic gdata.GDataEndry instance if it is
impossible to determine the appropriate class (look for extra elements
in GDataEntry's .FindExtensions() and extension_elements[] ).
"""
tree = ElementTree.fromstring(xml_string)
category = tree.find('{%s}category' % atom.ATOM_NAMESPACE)
if category is None:
# TODO: is this the best way to handle this?
return atom._CreateClassFromElementTree(GPhotosBaseEntry, tree)
namespace, kind = category.get('term').split('#')
if namespace != PHOTOS_NAMESPACE:
# TODO: is this the best way to handle this?
return atom._CreateClassFromElementTree(GPhotosBaseEntry, tree)
## TODO: is getattr safe this way?
feed_class = getattr(gdata.photos, '%sEntry' % kind.title())
return atom._CreateClassFromElementTree(feed_class, tree)
| Python |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2007 Benoit Chesneau <benoitc@metavers.net>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""CodesearchService extends GDataService to streamline Google Codesearch
operations"""
__author__ = 'Benoit Chesneau'
import atom
import gdata.service
import gdata.codesearch
class CodesearchService(gdata.service.GDataService):
"""Client extension for Google codesearch service"""
def __init__(self, email=None, password=None, source=None,
server='www.google.com', additional_headers=None):
"""Constructor for the CodesearchService.
Args:
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.
Yields:
A CodesearchService object used to communicate with the Google Codesearch
service.
"""
gdata.service.GDataService.__init__(self,
email=email, password=password, service='codesearch',
source=source,server=server,
additional_headers=additional_headers)
def Query(self, uri, converter=gdata.codesearch.CodesearchFeedFromString):
"""Queries the Codesearch feed and returns the resulting feed of
entries.
Args:
uri: string The full URI to be queried. This can contain query
parameters, a hostname, or simply the relative path to a Document
List feed. The DocumentQuery object is useful when constructing
query parameters.
converter: func (optional) A function which will be executed on the
retrieved item, generally to render it into a Python object.
By default the CodesearchFeedFromString function is used to
return a CodesearchFeed object. This is because most feed
queries will result in a feed and not a single entry.
Returns :
A CodesearchFeed objects representing the feed returned by the server
"""
return self.Get(uri, converter=converter)
def GetSnippetsFeed(self, text_query=None):
"""Retrieve Codesearch feed for a keyword
Args:
text_query : string (optional) The contents of the q query parameter. This
string is URL escaped upon conversion to a URI.
Returns:
A CodesearchFeed objects representing the feed returned by the server
"""
query=gdata.codesearch.service.CodesearchQuery(text_query=text_query)
feed = self.Query(query.ToUri())
return feed
class CodesearchQuery(gdata.service.Query):
"""Object used to construct the query to the Google Codesearch feed. here only as a shorcut"""
def __init__(self, feed='/codesearch/feeds/search', text_query=None,
params=None, categories=None):
"""Constructor for Codesearch Query.
Args:
feed: string (optional) The path for the feed. (e.g. '/codesearch/feeds/search')
text_query: string (optional) The contents of the q query parameter. This
string is URL escaped upon conversion to a URI.
params: dict (optional) Parameter value string pairs which become URL
params when translated to a URI. These parameters are added to
the query's items.
categories: list (optional) List of category strings which should be
included as query categories. See gdata.service.Query for
additional documentation.
Yelds:
A CodesearchQuery object to construct a URI based on Codesearch feed
"""
gdata.service.Query.__init__(self, feed, text_query, params, categories)
| Python |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2007 Benoit Chesneau <benoitc@metavers.net>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""Contains extensions to Atom objects used by Google Codesearch"""
__author__ = 'Benoit Chesneau'
import atom
import gdata
CODESEARCH_NAMESPACE='http://schemas.google.com/codesearch/2006'
CODESEARCH_TEMPLATE='{http://shema.google.com/codesearch/2006}%s'
class Match(atom.AtomBase):
""" The Google Codesearch match element """
_tag = 'match'
_namespace = CODESEARCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['lineNumber'] = 'line_number'
_attributes['type'] = 'type'
def __init__(self, line_number=None, type=None, extension_elements=None,
extension_attributes=None, text=None):
self.text = text
self.type = type
self.line_number = line_number
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class File(atom.AtomBase):
""" The Google Codesearch file element"""
_tag = 'file'
_namespace = CODESEARCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['name'] = 'name'
def __init__(self, name=None, extension_elements=None,
extension_attributes=None, text=None):
self.text = text
self.name = name
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Package(atom.AtomBase):
""" The Google Codesearch package element"""
_tag = 'package'
_namespace = CODESEARCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['name'] = 'name'
_attributes['uri'] = 'uri'
def __init__(self, name=None, uri=None, extension_elements=None,
extension_attributes=None, text=None):
self.text = text
self.name = name
self.uri = uri
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class CodesearchEntry(gdata.GDataEntry):
""" Google codesearch atom entry"""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}file' % CODESEARCH_NAMESPACE] = ('file', File)
_children['{%s}package' % CODESEARCH_NAMESPACE] = ('package', Package)
_children['{%s}match' % CODESEARCH_NAMESPACE] = ('match', [Match])
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
match=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title,
updated=updated, text=None)
self.match = match or []
def CodesearchEntryFromString(xml_string):
"""Converts an XML string into a CodesearchEntry object.
Args:
xml_string: string The XML describing a Codesearch feed entry.
Returns:
A CodesearchEntry object corresponding to the given XML.
"""
return atom.CreateClassFromXMLString(CodesearchEntry, xml_string)
class CodesearchFeed(gdata.GDataFeed):
"""feed containing list of Google codesearch Items"""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CodesearchEntry])
def CodesearchFeedFromString(xml_string):
"""Converts an XML string into a CodesearchFeed object.
Args:
xml_string: string The XML describing a Codesearch feed.
Returns:
A CodeseartchFeed object corresponding to the given XML.
"""
return atom.CreateClassFromXMLString(CodesearchFeed, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to Atom objects used with Google Base."""
__author__ = 'api.jscudder (Jeffrey Scudder)'
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import atom
import gdata
# XML namespaces which are often used in Google Base entities.
GBASE_NAMESPACE = 'http://base.google.com/ns/1.0'
GBASE_TEMPLATE = '{http://base.google.com/ns/1.0}%s'
GMETA_NAMESPACE = 'http://base.google.com/ns-metadata/1.0'
GMETA_TEMPLATE = '{http://base.google.com/ns-metadata/1.0}%s'
class ItemAttributeContainer(object):
"""Provides methods for finding Google Base Item attributes.
Google Base item attributes are child nodes in the gbase namespace. Google
Base allows you to define your own item attributes and this class provides
methods to interact with the custom attributes.
"""
def GetItemAttributes(self, name):
"""Returns a list of all item attributes which have the desired name.
Args:
name: str The tag of the desired base attributes. For example, calling
this method with 'rating' would return a list of ItemAttributes
represented by a 'g:rating' tag.
Returns:
A list of matching ItemAttribute objects.
"""
result = []
for attrib in self.item_attributes:
if attrib.name == name:
result.append(attrib)
return result
def FindItemAttribute(self, name):
"""Get the contents of the first Base item attribute which matches name.
This method is deprecated, please use GetItemAttributes instead.
Args:
name: str The tag of the desired base attribute. For example, calling
this method with name = 'rating' would search for a tag rating
in the GBase namespace in the item attributes.
Returns:
The text contents of the item attribute, or none if the attribute was
not found.
"""
for attrib in self.item_attributes:
if attrib.name == name:
return attrib.text
return None
def AddItemAttribute(self, name, value, value_type=None, access=None):
"""Adds a new item attribute tag containing the value.
Creates a new extension element in the GBase namespace to represent a
Google Base item attribute.
Args:
name: str The tag name for the new attribute. This must be a valid xml
tag name. The tag will be placed in the GBase namespace.
value: str Contents for the item attribute
value_type: str (optional) The type of data in the vlaue, Examples: text
float
access: str (optional) Used to hide attributes. The attribute is not
exposed in the snippets feed if access is set to 'private'.
"""
new_attribute = ItemAttribute(name, text=value,
text_type=value_type, access=access)
self.item_attributes.append(new_attribute)
def SetItemAttribute(self, name, value):
"""Changes an existing item attribute's value."""
for attrib in self.item_attributes:
if attrib.name == name:
attrib.text = value
return
def RemoveItemAttribute(self, name):
"""Deletes the first extension element which matches name.
Deletes the first extension element which matches name.
"""
for i in xrange(len(self.item_attributes)):
if self.item_attributes[i].name == name:
del self.item_attributes[i]
return
# We need to overwrite _ConvertElementTreeToMember to add special logic to
# convert custom attributes to members
def _ConvertElementTreeToMember(self, child_tree):
# Find the element's tag in this class's list of child members
if self.__class__._children.has_key(child_tree.tag):
member_name = self.__class__._children[child_tree.tag][0]
member_class = self.__class__._children[child_tree.tag][1]
# If the class member is supposed to contain a list, make sure the
# matching member is set to a list, then append the new member
# instance to the list.
if isinstance(member_class, list):
if getattr(self, member_name) is None:
setattr(self, member_name, [])
getattr(self, member_name).append(atom._CreateClassFromElementTree(
member_class[0], child_tree))
else:
setattr(self, member_name,
atom._CreateClassFromElementTree(member_class, child_tree))
elif child_tree.tag.find('{%s}' % GBASE_NAMESPACE) == 0:
# If this is in the gbase namespace, make it into an extension element.
name = child_tree.tag[child_tree.tag.index('}')+1:]
value = child_tree.text
if child_tree.attrib.has_key('type'):
value_type = child_tree.attrib['type']
else:
value_type = None
self.AddItemAttribute(name, value, value_type)
else:
atom.ExtensionContainer._ConvertElementTreeToMember(self, child_tree)
# We need to overwtite _AddMembersToElementTree to add special logic to
# convert custom members to XML nodes.
def _AddMembersToElementTree(self, tree):
# Convert the members of this class which are XML child nodes.
# This uses the class's _children dictionary to find the members which
# should become XML child nodes.
member_node_names = [values[0] for tag, values in
self.__class__._children.iteritems()]
for member_name in member_node_names:
member = getattr(self, member_name)
if member is None:
pass
elif isinstance(member, list):
for instance in member:
instance._BecomeChildElement(tree)
else:
member._BecomeChildElement(tree)
# Convert the members of this class which are XML attributes.
for xml_attribute, member_name in self.__class__._attributes.iteritems():
member = getattr(self, member_name)
if member is not None:
tree.attrib[xml_attribute] = member
# Convert all special custom item attributes to nodes
for attribute in self.item_attributes:
attribute._BecomeChildElement(tree)
# Lastly, call the ExtensionContainers's _AddMembersToElementTree to
# convert any extension attributes.
atom.ExtensionContainer._AddMembersToElementTree(self, tree)
class ItemAttribute(atom.Text):
"""An optional or user defined attribute for a GBase item.
Google Base allows items to have custom attribute child nodes. These nodes
have contents and a type attribute which tells Google Base whether the
contents are text, a float value with units, etc. The Atom text class has
the same structure, so this class inherits from Text.
"""
_namespace = GBASE_NAMESPACE
_children = atom.Text._children.copy()
_attributes = atom.Text._attributes.copy()
_attributes['access'] = 'access'
def __init__(self, name, text_type=None, access=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for a GBase item attribute
Args:
name: str The name of the attribute. Examples include
price, color, make, model, pages, salary, etc.
text_type: str (optional) The type associated with the text contents
access: str (optional) If the access attribute is set to 'private', the
attribute will not be included in the item's description in the
snippets feed
text: str (optional) The text data in the this element
extension_elements: list (optional) A list of ExtensionElement
instances
extension_attributes: dict (optional) A dictionary of attribute
value string pairs
"""
self.name = name
self.type = text_type
self.access = access
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def _BecomeChildElement(self, tree):
new_child = ElementTree.Element('')
tree.append(new_child)
new_child.tag = '{%s}%s' % (self.__class__._namespace,
self.name)
self._AddMembersToElementTree(new_child)
def _ToElementTree(self):
new_tree = ElementTree.Element('{%s}%s' % (self.__class__._namespace,
self.name))
self._AddMembersToElementTree(new_tree)
return new_tree
def ItemAttributeFromString(xml_string):
element_tree = ElementTree.fromstring(xml_string)
return _ItemAttributeFromElementTree(element_tree)
def _ItemAttributeFromElementTree(element_tree):
if element_tree.tag.find(GBASE_TEMPLATE % '') == 0:
to_return = ItemAttribute('')
to_return._HarvestElementTree(element_tree)
to_return.name = element_tree.tag[element_tree.tag.index('}')+1:]
if to_return.name and to_return.name != '':
return to_return
return None
class Label(atom.AtomBase):
"""The Google Base label element"""
_tag = 'label'
_namespace = GBASE_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def LabelFromString(xml_string):
return atom.CreateClassFromXMLString(Label, xml_string)
class Thumbnail(atom.AtomBase):
"""The Google Base thumbnail element"""
_tag = 'thumbnail'
_namespace = GMETA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['width'] = 'width'
_attributes['height'] = 'height'
def __init__(self, width=None, height=None, text=None, extension_elements=None,
extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.width = width
self.height = height
def ThumbnailFromString(xml_string):
return atom.CreateClassFromXMLString(Thumbnail, xml_string)
class ImageLink(atom.Text):
"""The Google Base image_link element"""
_tag = 'image_link'
_namespace = GBASE_NAMESPACE
_children = atom.Text._children.copy()
_attributes = atom.Text._attributes.copy()
_children['{%s}thumbnail' % GMETA_NAMESPACE] = ('thumbnail', [Thumbnail])
def __init__(self, thumbnail=None, text=None, extension_elements=None,
text_type=None, extension_attributes=None):
self.thumbnail = thumbnail or []
self.text = text
self.type = text_type
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ImageLinkFromString(xml_string):
return atom.CreateClassFromXMLString(ImageLink, xml_string)
class ItemType(atom.Text):
"""The Google Base item_type element"""
_tag = 'item_type'
_namespace = GBASE_NAMESPACE
_children = atom.Text._children.copy()
_attributes = atom.Text._attributes.copy()
def __init__(self, text=None, extension_elements=None,
text_type=None, extension_attributes=None):
self.text = text
self.type = text_type
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ItemTypeFromString(xml_string):
return atom.CreateClassFromXMLString(ItemType, xml_string)
class MetaItemType(ItemType):
"""The Google Base item_type element"""
_tag = 'item_type'
_namespace = GMETA_NAMESPACE
_children = ItemType._children.copy()
_attributes = ItemType._attributes.copy()
def MetaItemTypeFromString(xml_string):
return atom.CreateClassFromXMLString(MetaItemType, xml_string)
class Value(atom.AtomBase):
"""Metadata about common values for a given attribute
A value is a child of an attribute which comes from the attributes feed.
The value's text is a commonly used value paired with an attribute name
and the value's count tells how often this value appears for the given
attribute in the search results.
"""
_tag = 'value'
_namespace = GMETA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['count'] = 'count'
def __init__(self, count=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Attribute metadata element
Args:
count: str (optional) The number of times the value in text is given
for the parent attribute.
text: str (optional) The value which appears in the search results.
extension_elements: list (optional) A list of ExtensionElement
instances
extension_attributes: dict (optional) A dictionary of attribute value
string pairs
"""
self.count = count
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ValueFromString(xml_string):
return atom.CreateClassFromXMLString(Value, xml_string)
class Attribute(atom.Text):
"""Metadata about an attribute from the attributes feed
An entry from the attributes feed contains a list of attributes. Each
attribute describes the attribute's type and count of the items which
use the attribute.
"""
_tag = 'attribute'
_namespace = GMETA_NAMESPACE
_children = atom.Text._children.copy()
_attributes = atom.Text._attributes.copy()
_children['{%s}value' % GMETA_NAMESPACE] = ('value', [Value])
_attributes['count'] = 'count'
_attributes['name'] = 'name'
def __init__(self, name=None, attribute_type=None, count=None, value=None,
text=None, extension_elements=None, extension_attributes=None):
"""Constructor for Attribute metadata element
Args:
name: str (optional) The name of the attribute
attribute_type: str (optional) The type for the attribute. Examples:
test, float, etc.
count: str (optional) The number of times this attribute appears in
the query results.
value: list (optional) The values which are often used for this
attirbute.
text: str (optional) The text contents of the XML for this attribute.
extension_elements: list (optional) A list of ExtensionElement
instances
extension_attributes: dict (optional) A dictionary of attribute value
string pairs
"""
self.name = name
self.type = attribute_type
self.count = count
self.value = value or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def AttributeFromString(xml_string):
return atom.CreateClassFromXMLString(Attribute, xml_string)
class Attributes(atom.AtomBase):
"""A collection of Google Base metadata attributes"""
_tag = 'attributes'
_namespace = GMETA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}attribute' % GMETA_NAMESPACE] = ('attribute', [Attribute])
def __init__(self, attribute=None, extension_elements=None,
extension_attributes=None, text=None):
self.attribute = attribute or []
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
class GBaseItem(ItemAttributeContainer, gdata.BatchEntry):
"""An Google Base flavor of an Atom Entry.
Google Base items have required attributes, recommended attributes, and user
defined attributes. The required attributes are stored in this class as
members, and other attributes are stored as extension elements. You can
access the recommended and user defined attributes by using
AddItemAttribute, SetItemAttribute, FindItemAttribute, and
RemoveItemAttribute.
The Base Item
"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.BatchEntry._children.copy()
_attributes = gdata.BatchEntry._attributes.copy()
_children['{%s}label' % GBASE_NAMESPACE] = ('label', [Label])
_children['{%s}item_type' % GBASE_NAMESPACE] = ('item_type', ItemType)
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, updated=None, control=None,
label=None, item_type=None, item_attributes=None,
batch_operation=None, batch_id=None, batch_status=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.title = title
self.updated = updated
self.control = control
self.label = label or []
self.item_type = item_type
self.item_attributes = item_attributes or []
self.batch_operation = batch_operation
self.batch_id = batch_id
self.batch_status = batch_status
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GBaseItemFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseItem, xml_string)
class GBaseSnippet(GBaseItem):
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = GBaseItem._children.copy()
_attributes = GBaseItem._attributes.copy()
def GBaseSnippetFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseSnippet, xml_string)
class GBaseAttributeEntry(gdata.GDataEntry):
"""An Atom Entry from the attributes feed"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}attribute' % GMETA_NAMESPACE] = ('attribute', [Attribute])
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, updated=None, label=None,
attribute=None, control=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.control = control
self.title = title
self.updated = updated
self.label = label or []
self.attribute = attribute or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GBaseAttributeEntryFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseAttributeEntry, xml_string)
class GBaseItemTypeEntry(gdata.GDataEntry):
"""An Atom entry from the item types feed
These entries contain a list of attributes which are stored in one
XML node called attributes. This class simplifies the data structure
by treating attributes as a list of attribute instances.
Note that the item_type for an item type entry is in the Google Base meta
namespace as opposed to item_types encountered in other feeds.
"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}attributes' % GMETA_NAMESPACE] = ('attributes', Attributes)
_children['{%s}attribute' % GMETA_NAMESPACE] = ('attribute', [Attribute])
_children['{%s}item_type' % GMETA_NAMESPACE] = ('item_type', MetaItemType)
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, updated=None, label=None,
item_type=None, control=None, attribute=None, attributes=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.title = title
self.updated = updated
self.control = control
self.label = label or []
self.item_type = item_type
self.attributes = attributes
self.attribute = attribute or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GBaseItemTypeEntryFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseItemTypeEntry, xml_string)
class GBaseItemFeed(gdata.BatchFeed):
"""A feed containing Google Base Items"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.BatchFeed._children.copy()
_attributes = gdata.BatchFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GBaseItem])
def GBaseItemFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseItemFeed, xml_string)
class GBaseSnippetFeed(gdata.GDataFeed):
"""A feed containing Google Base Snippets"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GBaseSnippet])
def GBaseSnippetFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseSnippetFeed, xml_string)
class GBaseAttributesFeed(gdata.GDataFeed):
"""A feed containing Google Base Attributes
A query sent to the attributes feed will return a feed of
attributes which are present in the items that match the
query.
"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[GBaseAttributeEntry])
def GBaseAttributesFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseAttributesFeed, xml_string)
class GBaseLocalesFeed(gdata.GDataFeed):
"""The locales feed from Google Base.
This read-only feed defines the permitted locales for Google Base. The
locale value identifies the language, currency, and date formats used in a
feed.
"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
def GBaseLocalesFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseLocalesFeed, xml_string)
class GBaseItemTypesFeed(gdata.GDataFeed):
"""A feed from the Google Base item types feed"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GBaseItemTypeEntry])
def GBaseItemTypesFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseItemTypesFeed, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""GBaseService extends the GDataService to streamline Google Base operations.
GBaseService: Provides methods to query feeds and manipulate items. Extends
GDataService.
DictionaryToParamList: Function which converts a dictionary into a list of
URL arguments (represented as strings). This is a
utility function used in CRUD operations.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
import urllib
import gdata
import atom.service
import gdata.service
import gdata.base
import atom
# URL to which all batch requests are sent.
BASE_BATCH_URL = 'http://www.google.com/base/feeds/items/batch'
class Error(Exception):
pass
class RequestError(Error):
pass
class GBaseService(gdata.service.GDataService):
"""Client for the Google Base service."""
def __init__(self, email=None, password=None, source=None,
server='base.google.com', api_key=None,
additional_headers=None, handler=None):
gdata.service.GDataService.__init__(self, email=email, password=password,
service='gbase', source=source,
server=server,
additional_headers=additional_headers,
handler=handler)
self.api_key = api_key
def _SetAPIKey(self, api_key):
if not isinstance(self.additional_headers, dict):
self.additional_headers = {}
self.additional_headers['X-Google-Key'] = api_key
def __SetAPIKey(self, api_key):
self._SetAPIKey(api_key)
def _GetAPIKey(self):
if 'X-Google-Key' not in self.additional_headers:
return None
else:
return self.additional_headers['X-Google-Key']
def __GetAPIKey(self):
return self._GetAPIKey()
api_key = property(__GetAPIKey, __SetAPIKey,
doc="""Get or set the API key to be included in all requests.""")
def Query(self, uri, converter=None):
"""Performs a style query and returns a resulting feed or entry.
Args:
uri: string The full URI which be queried. Examples include
'/base/feeds/snippets?bq=digital+camera',
'http://www.google.com/base/feeds/snippets?bq=digital+camera'
'/base/feeds/items'
I recommend creating a URI using a query class.
converter: func (optional) A function which will be executed on the
server's response. Examples include GBaseItemFromString, etc.
Returns:
If converter was specified, returns the results of calling converter on
the server's response. If converter was not specified, and the result
was an Atom Entry, returns a GBaseItem, by default, the method returns
the result of calling gdata.service's Get method.
"""
result = self.Get(uri, converter=converter)
if converter:
return result
elif isinstance(result, atom.Entry):
return gdata.base.GBaseItemFromString(result.ToString())
return result
def QuerySnippetsFeed(self, uri):
return self.Get(uri, converter=gdata.base.GBaseSnippetFeedFromString)
def QueryItemsFeed(self, uri):
return self.Get(uri, converter=gdata.base.GBaseItemFeedFromString)
def QueryAttributesFeed(self, uri):
return self.Get(uri, converter=gdata.base.GBaseAttributesFeedFromString)
def QueryItemTypesFeed(self, uri):
return self.Get(uri, converter=gdata.base.GBaseItemTypesFeedFromString)
def QueryLocalesFeed(self, uri):
return self.Get(uri, converter=gdata.base.GBaseLocalesFeedFromString)
def GetItem(self, uri):
return self.Get(uri, converter=gdata.base.GBaseItemFromString)
def GetSnippet(self, uri):
return self.Get(uri, converter=gdata.base.GBaseSnippetFromString)
def GetAttribute(self, uri):
return self.Get(uri, converter=gdata.base.GBaseAttributeEntryFromString)
def GetItemType(self, uri):
return self.Get(uri, converter=gdata.base.GBaseItemTypeEntryFromString)
def GetLocale(self, uri):
return self.Get(uri, converter=gdata.base.GDataEntryFromString)
def InsertItem(self, new_item, url_params=None, escape_params=True,
converter=None):
"""Adds an item to Google Base.
Args:
new_item: atom.Entry or subclass A new item which is to be added to
Google Base.
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
converter: func (optional) Function which is executed on the server's
response before it is returned. Usually this is a function like
GBaseItemFromString which will parse the response and turn it into
an object.
Returns:
If converter is defined, the results of running converter on the server's
response. Otherwise, it will be a GBaseItem.
"""
response = self.Post(new_item, '/base/feeds/items', url_params=url_params,
escape_params=escape_params, converter=converter)
if not converter and isinstance(response, atom.Entry):
return gdata.base.GBaseItemFromString(response.ToString())
return response
def DeleteItem(self, item_id, url_params=None, escape_params=True):
"""Removes an item with the specified ID from Google Base.
Args:
item_id: string The ID of the item to be deleted. Example:
'http://www.google.com/base/feeds/items/13185446517496042648'
url_params: dict (optional) Additional URL parameters to be included
in the deletion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
True if the delete succeeded.
"""
return self.Delete('/%s' % (item_id.lstrip('http://www.google.com/')),
url_params=url_params, escape_params=escape_params)
def UpdateItem(self, item_id, updated_item, url_params=None,
escape_params=True,
converter=gdata.base.GBaseItemFromString):
"""Updates an existing item.
Args:
item_id: string The ID of the item to be updated. Example:
'http://www.google.com/base/feeds/items/13185446517496042648'
updated_item: atom.Entry, subclass, or string, containing
the Atom Entry which will replace the base item which is
stored at the item_id.
url_params: dict (optional) Additional URL parameters to be included
in the update request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
converter: func (optional) Function which is executed on the server's
response before it is returned. Usually this is a function like
GBaseItemFromString which will parse the response and turn it into
an object.
Returns:
If converter is defined, the results of running converter on the server's
response. Otherwise, it will be a GBaseItem.
"""
response = self.Put(updated_item,
item_id, url_params=url_params, escape_params=escape_params,
converter=converter)
if not converter and isinstance(response, atom.Entry):
return gdata.base.GBaseItemFromString(response.ToString())
return response
def ExecuteBatch(self, batch_feed,
converter=gdata.base.GBaseItemFeedFromString):
"""Sends a batch request feed to the server.
Args:
batch_feed: gdata.BatchFeed A feed containing BatchEntry elements which
contain the desired CRUD operation and any necessary entry data.
converter: Function (optional) Function to be executed on the server's
response. This function should take one string as a parameter. The
default value is GBaseItemFeedFromString which will turn the result
into a gdata.base.GBaseItem object.
Returns:
A gdata.BatchFeed containing the results.
"""
return self.Post(batch_feed, BASE_BATCH_URL, converter=converter)
class BaseQuery(gdata.service.Query):
def _GetBaseQuery(self):
return self['bq']
def _SetBaseQuery(self, base_query):
self['bq'] = base_query
bq = property(_GetBaseQuery, _SetBaseQuery,
doc="""The bq query parameter""")
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""GBaseService extends the GDataService to streamline Google Base operations.
GBaseService: Provides methods to query feeds and manipulate items. Extends
GDataService.
DictionaryToParamList: Function which converts a dictionary into a list of
URL arguments (represented as strings). This is a
utility function used in CRUD operations.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
import urllib
import gdata
import atom.service
import gdata.service
import gdata.base
import atom
# URL to which all batch requests are sent.
BASE_BATCH_URL = 'http://www.google.com/base/feeds/items/batch'
class Error(Exception):
pass
class RequestError(Error):
pass
class GBaseService(gdata.service.GDataService):
"""Client for the Google Base service."""
def __init__(self, email=None, password=None, source=None,
server='base.google.com', api_key=None,
additional_headers=None, handler=None):
gdata.service.GDataService.__init__(self, email=email, password=password,
service='gbase', source=source,
server=server,
additional_headers=additional_headers,
handler=handler)
self.api_key = api_key
def _SetAPIKey(self, api_key):
if not isinstance(self.additional_headers, dict):
self.additional_headers = {}
self.additional_headers['X-Google-Key'] = api_key
def __SetAPIKey(self, api_key):
self._SetAPIKey(api_key)
def _GetAPIKey(self):
if 'X-Google-Key' not in self.additional_headers:
return None
else:
return self.additional_headers['X-Google-Key']
def __GetAPIKey(self):
return self._GetAPIKey()
api_key = property(__GetAPIKey, __SetAPIKey,
doc="""Get or set the API key to be included in all requests.""")
def Query(self, uri, converter=None):
"""Performs a style query and returns a resulting feed or entry.
Args:
uri: string The full URI which be queried. Examples include
'/base/feeds/snippets?bq=digital+camera',
'http://www.google.com/base/feeds/snippets?bq=digital+camera'
'/base/feeds/items'
I recommend creating a URI using a query class.
converter: func (optional) A function which will be executed on the
server's response. Examples include GBaseItemFromString, etc.
Returns:
If converter was specified, returns the results of calling converter on
the server's response. If converter was not specified, and the result
was an Atom Entry, returns a GBaseItem, by default, the method returns
the result of calling gdata.service's Get method.
"""
result = self.Get(uri, converter=converter)
if converter:
return result
elif isinstance(result, atom.Entry):
return gdata.base.GBaseItemFromString(result.ToString())
return result
def QuerySnippetsFeed(self, uri):
return self.Get(uri, converter=gdata.base.GBaseSnippetFeedFromString)
def QueryItemsFeed(self, uri):
return self.Get(uri, converter=gdata.base.GBaseItemFeedFromString)
def QueryAttributesFeed(self, uri):
return self.Get(uri, converter=gdata.base.GBaseAttributesFeedFromString)
def QueryItemTypesFeed(self, uri):
return self.Get(uri, converter=gdata.base.GBaseItemTypesFeedFromString)
def QueryLocalesFeed(self, uri):
return self.Get(uri, converter=gdata.base.GBaseLocalesFeedFromString)
def GetItem(self, uri):
return self.Get(uri, converter=gdata.base.GBaseItemFromString)
def GetSnippet(self, uri):
return self.Get(uri, converter=gdata.base.GBaseSnippetFromString)
def GetAttribute(self, uri):
return self.Get(uri, converter=gdata.base.GBaseAttributeEntryFromString)
def GetItemType(self, uri):
return self.Get(uri, converter=gdata.base.GBaseItemTypeEntryFromString)
def GetLocale(self, uri):
return self.Get(uri, converter=gdata.base.GDataEntryFromString)
def InsertItem(self, new_item, url_params=None, escape_params=True,
converter=None):
"""Adds an item to Google Base.
Args:
new_item: atom.Entry or subclass A new item which is to be added to
Google Base.
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
converter: func (optional) Function which is executed on the server's
response before it is returned. Usually this is a function like
GBaseItemFromString which will parse the response and turn it into
an object.
Returns:
If converter is defined, the results of running converter on the server's
response. Otherwise, it will be a GBaseItem.
"""
response = self.Post(new_item, '/base/feeds/items', url_params=url_params,
escape_params=escape_params, converter=converter)
if not converter and isinstance(response, atom.Entry):
return gdata.base.GBaseItemFromString(response.ToString())
return response
def DeleteItem(self, item_id, url_params=None, escape_params=True):
"""Removes an item with the specified ID from Google Base.
Args:
item_id: string The ID of the item to be deleted. Example:
'http://www.google.com/base/feeds/items/13185446517496042648'
url_params: dict (optional) Additional URL parameters to be included
in the deletion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
True if the delete succeeded.
"""
return self.Delete('/%s' % (item_id.lstrip('http://www.google.com/')),
url_params=url_params, escape_params=escape_params)
def UpdateItem(self, item_id, updated_item, url_params=None,
escape_params=True,
converter=gdata.base.GBaseItemFromString):
"""Updates an existing item.
Args:
item_id: string The ID of the item to be updated. Example:
'http://www.google.com/base/feeds/items/13185446517496042648'
updated_item: atom.Entry, subclass, or string, containing
the Atom Entry which will replace the base item which is
stored at the item_id.
url_params: dict (optional) Additional URL parameters to be included
in the update request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
converter: func (optional) Function which is executed on the server's
response before it is returned. Usually this is a function like
GBaseItemFromString which will parse the response and turn it into
an object.
Returns:
If converter is defined, the results of running converter on the server's
response. Otherwise, it will be a GBaseItem.
"""
response = self.Put(updated_item,
item_id, url_params=url_params, escape_params=escape_params,
converter=converter)
if not converter and isinstance(response, atom.Entry):
return gdata.base.GBaseItemFromString(response.ToString())
return response
def ExecuteBatch(self, batch_feed,
converter=gdata.base.GBaseItemFeedFromString):
"""Sends a batch request feed to the server.
Args:
batch_feed: gdata.BatchFeed A feed containing BatchEntry elements which
contain the desired CRUD operation and any necessary entry data.
converter: Function (optional) Function to be executed on the server's
response. This function should take one string as a parameter. The
default value is GBaseItemFeedFromString which will turn the result
into a gdata.base.GBaseItem object.
Returns:
A gdata.BatchFeed containing the results.
"""
return self.Post(batch_feed, BASE_BATCH_URL, converter=converter)
class BaseQuery(gdata.service.Query):
def _GetBaseQuery(self):
return self['bq']
def _SetBaseQuery(self, base_query):
self['bq'] = base_query
bq = property(_GetBaseQuery, _SetBaseQuery,
doc="""The bq query parameter""")
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to Atom objects used with Google Base."""
__author__ = 'api.jscudder (Jeffrey Scudder)'
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import atom
import gdata
# XML namespaces which are often used in Google Base entities.
GBASE_NAMESPACE = 'http://base.google.com/ns/1.0'
GBASE_TEMPLATE = '{http://base.google.com/ns/1.0}%s'
GMETA_NAMESPACE = 'http://base.google.com/ns-metadata/1.0'
GMETA_TEMPLATE = '{http://base.google.com/ns-metadata/1.0}%s'
class ItemAttributeContainer(object):
"""Provides methods for finding Google Base Item attributes.
Google Base item attributes are child nodes in the gbase namespace. Google
Base allows you to define your own item attributes and this class provides
methods to interact with the custom attributes.
"""
def GetItemAttributes(self, name):
"""Returns a list of all item attributes which have the desired name.
Args:
name: str The tag of the desired base attributes. For example, calling
this method with 'rating' would return a list of ItemAttributes
represented by a 'g:rating' tag.
Returns:
A list of matching ItemAttribute objects.
"""
result = []
for attrib in self.item_attributes:
if attrib.name == name:
result.append(attrib)
return result
def FindItemAttribute(self, name):
"""Get the contents of the first Base item attribute which matches name.
This method is deprecated, please use GetItemAttributes instead.
Args:
name: str The tag of the desired base attribute. For example, calling
this method with name = 'rating' would search for a tag rating
in the GBase namespace in the item attributes.
Returns:
The text contents of the item attribute, or none if the attribute was
not found.
"""
for attrib in self.item_attributes:
if attrib.name == name:
return attrib.text
return None
def AddItemAttribute(self, name, value, value_type=None, access=None):
"""Adds a new item attribute tag containing the value.
Creates a new extension element in the GBase namespace to represent a
Google Base item attribute.
Args:
name: str The tag name for the new attribute. This must be a valid xml
tag name. The tag will be placed in the GBase namespace.
value: str Contents for the item attribute
value_type: str (optional) The type of data in the vlaue, Examples: text
float
access: str (optional) Used to hide attributes. The attribute is not
exposed in the snippets feed if access is set to 'private'.
"""
new_attribute = ItemAttribute(name, text=value,
text_type=value_type, access=access)
self.item_attributes.append(new_attribute)
def SetItemAttribute(self, name, value):
"""Changes an existing item attribute's value."""
for attrib in self.item_attributes:
if attrib.name == name:
attrib.text = value
return
def RemoveItemAttribute(self, name):
"""Deletes the first extension element which matches name.
Deletes the first extension element which matches name.
"""
for i in xrange(len(self.item_attributes)):
if self.item_attributes[i].name == name:
del self.item_attributes[i]
return
# We need to overwrite _ConvertElementTreeToMember to add special logic to
# convert custom attributes to members
def _ConvertElementTreeToMember(self, child_tree):
# Find the element's tag in this class's list of child members
if self.__class__._children.has_key(child_tree.tag):
member_name = self.__class__._children[child_tree.tag][0]
member_class = self.__class__._children[child_tree.tag][1]
# If the class member is supposed to contain a list, make sure the
# matching member is set to a list, then append the new member
# instance to the list.
if isinstance(member_class, list):
if getattr(self, member_name) is None:
setattr(self, member_name, [])
getattr(self, member_name).append(atom._CreateClassFromElementTree(
member_class[0], child_tree))
else:
setattr(self, member_name,
atom._CreateClassFromElementTree(member_class, child_tree))
elif child_tree.tag.find('{%s}' % GBASE_NAMESPACE) == 0:
# If this is in the gbase namespace, make it into an extension element.
name = child_tree.tag[child_tree.tag.index('}')+1:]
value = child_tree.text
if child_tree.attrib.has_key('type'):
value_type = child_tree.attrib['type']
else:
value_type = None
self.AddItemAttribute(name, value, value_type)
else:
atom.ExtensionContainer._ConvertElementTreeToMember(self, child_tree)
# We need to overwtite _AddMembersToElementTree to add special logic to
# convert custom members to XML nodes.
def _AddMembersToElementTree(self, tree):
# Convert the members of this class which are XML child nodes.
# This uses the class's _children dictionary to find the members which
# should become XML child nodes.
member_node_names = [values[0] for tag, values in
self.__class__._children.iteritems()]
for member_name in member_node_names:
member = getattr(self, member_name)
if member is None:
pass
elif isinstance(member, list):
for instance in member:
instance._BecomeChildElement(tree)
else:
member._BecomeChildElement(tree)
# Convert the members of this class which are XML attributes.
for xml_attribute, member_name in self.__class__._attributes.iteritems():
member = getattr(self, member_name)
if member is not None:
tree.attrib[xml_attribute] = member
# Convert all special custom item attributes to nodes
for attribute in self.item_attributes:
attribute._BecomeChildElement(tree)
# Lastly, call the ExtensionContainers's _AddMembersToElementTree to
# convert any extension attributes.
atom.ExtensionContainer._AddMembersToElementTree(self, tree)
class ItemAttribute(atom.Text):
"""An optional or user defined attribute for a GBase item.
Google Base allows items to have custom attribute child nodes. These nodes
have contents and a type attribute which tells Google Base whether the
contents are text, a float value with units, etc. The Atom text class has
the same structure, so this class inherits from Text.
"""
_namespace = GBASE_NAMESPACE
_children = atom.Text._children.copy()
_attributes = atom.Text._attributes.copy()
_attributes['access'] = 'access'
def __init__(self, name, text_type=None, access=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for a GBase item attribute
Args:
name: str The name of the attribute. Examples include
price, color, make, model, pages, salary, etc.
text_type: str (optional) The type associated with the text contents
access: str (optional) If the access attribute is set to 'private', the
attribute will not be included in the item's description in the
snippets feed
text: str (optional) The text data in the this element
extension_elements: list (optional) A list of ExtensionElement
instances
extension_attributes: dict (optional) A dictionary of attribute
value string pairs
"""
self.name = name
self.type = text_type
self.access = access
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def _BecomeChildElement(self, tree):
new_child = ElementTree.Element('')
tree.append(new_child)
new_child.tag = '{%s}%s' % (self.__class__._namespace,
self.name)
self._AddMembersToElementTree(new_child)
def _ToElementTree(self):
new_tree = ElementTree.Element('{%s}%s' % (self.__class__._namespace,
self.name))
self._AddMembersToElementTree(new_tree)
return new_tree
def ItemAttributeFromString(xml_string):
element_tree = ElementTree.fromstring(xml_string)
return _ItemAttributeFromElementTree(element_tree)
def _ItemAttributeFromElementTree(element_tree):
if element_tree.tag.find(GBASE_TEMPLATE % '') == 0:
to_return = ItemAttribute('')
to_return._HarvestElementTree(element_tree)
to_return.name = element_tree.tag[element_tree.tag.index('}')+1:]
if to_return.name and to_return.name != '':
return to_return
return None
class Label(atom.AtomBase):
"""The Google Base label element"""
_tag = 'label'
_namespace = GBASE_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def LabelFromString(xml_string):
return atom.CreateClassFromXMLString(Label, xml_string)
class Thumbnail(atom.AtomBase):
"""The Google Base thumbnail element"""
_tag = 'thumbnail'
_namespace = GMETA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['width'] = 'width'
_attributes['height'] = 'height'
def __init__(self, width=None, height=None, text=None, extension_elements=None,
extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.width = width
self.height = height
def ThumbnailFromString(xml_string):
return atom.CreateClassFromXMLString(Thumbnail, xml_string)
class ImageLink(atom.Text):
"""The Google Base image_link element"""
_tag = 'image_link'
_namespace = GBASE_NAMESPACE
_children = atom.Text._children.copy()
_attributes = atom.Text._attributes.copy()
_children['{%s}thumbnail' % GMETA_NAMESPACE] = ('thumbnail', [Thumbnail])
def __init__(self, thumbnail=None, text=None, extension_elements=None,
text_type=None, extension_attributes=None):
self.thumbnail = thumbnail or []
self.text = text
self.type = text_type
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ImageLinkFromString(xml_string):
return atom.CreateClassFromXMLString(ImageLink, xml_string)
class ItemType(atom.Text):
"""The Google Base item_type element"""
_tag = 'item_type'
_namespace = GBASE_NAMESPACE
_children = atom.Text._children.copy()
_attributes = atom.Text._attributes.copy()
def __init__(self, text=None, extension_elements=None,
text_type=None, extension_attributes=None):
self.text = text
self.type = text_type
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ItemTypeFromString(xml_string):
return atom.CreateClassFromXMLString(ItemType, xml_string)
class MetaItemType(ItemType):
"""The Google Base item_type element"""
_tag = 'item_type'
_namespace = GMETA_NAMESPACE
_children = ItemType._children.copy()
_attributes = ItemType._attributes.copy()
def MetaItemTypeFromString(xml_string):
return atom.CreateClassFromXMLString(MetaItemType, xml_string)
class Value(atom.AtomBase):
"""Metadata about common values for a given attribute
A value is a child of an attribute which comes from the attributes feed.
The value's text is a commonly used value paired with an attribute name
and the value's count tells how often this value appears for the given
attribute in the search results.
"""
_tag = 'value'
_namespace = GMETA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['count'] = 'count'
def __init__(self, count=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Attribute metadata element
Args:
count: str (optional) The number of times the value in text is given
for the parent attribute.
text: str (optional) The value which appears in the search results.
extension_elements: list (optional) A list of ExtensionElement
instances
extension_attributes: dict (optional) A dictionary of attribute value
string pairs
"""
self.count = count
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ValueFromString(xml_string):
return atom.CreateClassFromXMLString(Value, xml_string)
class Attribute(atom.Text):
"""Metadata about an attribute from the attributes feed
An entry from the attributes feed contains a list of attributes. Each
attribute describes the attribute's type and count of the items which
use the attribute.
"""
_tag = 'attribute'
_namespace = GMETA_NAMESPACE
_children = atom.Text._children.copy()
_attributes = atom.Text._attributes.copy()
_children['{%s}value' % GMETA_NAMESPACE] = ('value', [Value])
_attributes['count'] = 'count'
_attributes['name'] = 'name'
def __init__(self, name=None, attribute_type=None, count=None, value=None,
text=None, extension_elements=None, extension_attributes=None):
"""Constructor for Attribute metadata element
Args:
name: str (optional) The name of the attribute
attribute_type: str (optional) The type for the attribute. Examples:
test, float, etc.
count: str (optional) The number of times this attribute appears in
the query results.
value: list (optional) The values which are often used for this
attirbute.
text: str (optional) The text contents of the XML for this attribute.
extension_elements: list (optional) A list of ExtensionElement
instances
extension_attributes: dict (optional) A dictionary of attribute value
string pairs
"""
self.name = name
self.type = attribute_type
self.count = count
self.value = value or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def AttributeFromString(xml_string):
return atom.CreateClassFromXMLString(Attribute, xml_string)
class Attributes(atom.AtomBase):
"""A collection of Google Base metadata attributes"""
_tag = 'attributes'
_namespace = GMETA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}attribute' % GMETA_NAMESPACE] = ('attribute', [Attribute])
def __init__(self, attribute=None, extension_elements=None,
extension_attributes=None, text=None):
self.attribute = attribute or []
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
class GBaseItem(ItemAttributeContainer, gdata.BatchEntry):
"""An Google Base flavor of an Atom Entry.
Google Base items have required attributes, recommended attributes, and user
defined attributes. The required attributes are stored in this class as
members, and other attributes are stored as extension elements. You can
access the recommended and user defined attributes by using
AddItemAttribute, SetItemAttribute, FindItemAttribute, and
RemoveItemAttribute.
The Base Item
"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.BatchEntry._children.copy()
_attributes = gdata.BatchEntry._attributes.copy()
_children['{%s}label' % GBASE_NAMESPACE] = ('label', [Label])
_children['{%s}item_type' % GBASE_NAMESPACE] = ('item_type', ItemType)
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, updated=None, control=None,
label=None, item_type=None, item_attributes=None,
batch_operation=None, batch_id=None, batch_status=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.title = title
self.updated = updated
self.control = control
self.label = label or []
self.item_type = item_type
self.item_attributes = item_attributes or []
self.batch_operation = batch_operation
self.batch_id = batch_id
self.batch_status = batch_status
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GBaseItemFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseItem, xml_string)
class GBaseSnippet(GBaseItem):
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = GBaseItem._children.copy()
_attributes = GBaseItem._attributes.copy()
def GBaseSnippetFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseSnippet, xml_string)
class GBaseAttributeEntry(gdata.GDataEntry):
"""An Atom Entry from the attributes feed"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}attribute' % GMETA_NAMESPACE] = ('attribute', [Attribute])
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, updated=None, label=None,
attribute=None, control=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.control = control
self.title = title
self.updated = updated
self.label = label or []
self.attribute = attribute or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GBaseAttributeEntryFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseAttributeEntry, xml_string)
class GBaseItemTypeEntry(gdata.GDataEntry):
"""An Atom entry from the item types feed
These entries contain a list of attributes which are stored in one
XML node called attributes. This class simplifies the data structure
by treating attributes as a list of attribute instances.
Note that the item_type for an item type entry is in the Google Base meta
namespace as opposed to item_types encountered in other feeds.
"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}attributes' % GMETA_NAMESPACE] = ('attributes', Attributes)
_children['{%s}attribute' % GMETA_NAMESPACE] = ('attribute', [Attribute])
_children['{%s}item_type' % GMETA_NAMESPACE] = ('item_type', MetaItemType)
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, updated=None, label=None,
item_type=None, control=None, attribute=None, attributes=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.title = title
self.updated = updated
self.control = control
self.label = label or []
self.item_type = item_type
self.attributes = attributes
self.attribute = attribute or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GBaseItemTypeEntryFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseItemTypeEntry, xml_string)
class GBaseItemFeed(gdata.BatchFeed):
"""A feed containing Google Base Items"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.BatchFeed._children.copy()
_attributes = gdata.BatchFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GBaseItem])
def GBaseItemFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseItemFeed, xml_string)
class GBaseSnippetFeed(gdata.GDataFeed):
"""A feed containing Google Base Snippets"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GBaseSnippet])
def GBaseSnippetFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseSnippetFeed, xml_string)
class GBaseAttributesFeed(gdata.GDataFeed):
"""A feed containing Google Base Attributes
A query sent to the attributes feed will return a feed of
attributes which are present in the items that match the
query.
"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[GBaseAttributeEntry])
def GBaseAttributesFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseAttributesFeed, xml_string)
class GBaseLocalesFeed(gdata.GDataFeed):
"""The locales feed from Google Base.
This read-only feed defines the permitted locales for Google Base. The
locale value identifies the language, currency, and date formats used in a
feed.
"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
def GBaseLocalesFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseLocalesFeed, xml_string)
class GBaseItemTypesFeed(gdata.GDataFeed):
"""A feed from the Google Base item types feed"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GBaseItemTypeEntry])
def GBaseItemTypesFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GBaseItemTypesFeed, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains classes representing Google Data elements.
Extends Atom classes to add Google Data specific elements.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
import os
import atom
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
# XML namespaces which are often used in GData entities.
GDATA_NAMESPACE = 'http://schemas.google.com/g/2005'
GDATA_TEMPLATE = '{http://schemas.google.com/g/2005}%s'
OPENSEARCH_NAMESPACE = 'http://a9.com/-/spec/opensearchrss/1.0/'
OPENSEARCH_TEMPLATE = '{http://a9.com/-/spec/opensearchrss/1.0/}%s'
BATCH_NAMESPACE = 'http://schemas.google.com/gdata/batch'
GACL_NAMESPACE = 'http://schemas.google.com/acl/2007'
GACL_TEMPLATE = '{http://schemas.google.com/acl/2007}%s'
# Labels used in batch request entries to specify the desired CRUD operation.
BATCH_INSERT = 'insert'
BATCH_UPDATE = 'update'
BATCH_DELETE = 'delete'
BATCH_QUERY = 'query'
class Error(Exception):
pass
class MissingRequiredParameters(Error):
pass
class MediaSource(object):
"""GData Entries can refer to media sources, so this class provides a
place to store references to these objects along with some metadata.
"""
def __init__(self, file_handle=None, content_type=None, content_length=None,
file_path=None, file_name=None):
"""Creates an object of type MediaSource.
Args:
file_handle: A file handle pointing to the file to be encapsulated in the
MediaSource
content_type: string The MIME type of the file. Required if a file_handle
is given.
content_length: int The size of the file. Required if a file_handle is
given.
file_path: string (optional) A full path name to the file. Used in
place of a file_handle.
file_name: string The name of the file without any path information.
Required if a file_handle is given.
"""
self.file_handle = file_handle
self.content_type = content_type
self.content_length = content_length
self.file_name = file_name
if (file_handle is None and content_type is not None and
file_path is not None):
self.setFile(file_path, content_type)
def setFile(self, file_name, content_type):
"""A helper function which can create a file handle from a given filename
and set the content type and length all at once.
Args:
file_name: string The path and file name to the file containing the media
content_type: string A MIME type representing the type of the media
"""
self.file_handle = open(file_name, 'rb')
self.content_type = content_type
self.content_length = os.path.getsize(file_name)
self.file_name = os.path.basename(file_name)
class LinkFinder(atom.LinkFinder):
"""An "interface" providing methods to find link elements
GData Entry elements often contain multiple links which differ in the rel
attribute or content type. Often, developers are interested in a specific
type of link so this class provides methods to find specific classes of
links.
This class is used as a mixin in GData entries.
"""
def GetSelfLink(self):
"""Find the first link with rel set to 'self'
Returns:
An atom.Link or none if none of the links had rel equal to 'self'
"""
for a_link in self.link:
if a_link.rel == 'self':
return a_link
return None
def GetEditLink(self):
for a_link in self.link:
if a_link.rel == 'edit':
return a_link
return None
def GetEditMediaLink(self):
"""The Picasa API mistakenly returns media-edit rather than edit-media, but
this may change soon.
"""
for a_link in self.link:
if a_link.rel == 'edit-media':
return a_link
if a_link.rel == 'media-edit':
return a_link
return None
def GetHtmlLink(self):
"""Find the first link with rel of alternate and type of text/html
Returns:
An atom.Link or None if no links matched
"""
for a_link in self.link:
if a_link.rel == 'alternate' and a_link.type == 'text/html':
return a_link
return None
def GetPostLink(self):
"""Get a link containing the POST target URL.
The POST target URL is used to insert new entries.
Returns:
A link object with a rel matching the POST type.
"""
for a_link in self.link:
if a_link.rel == 'http://schemas.google.com/g/2005#post':
return a_link
return None
def GetAclLink(self):
for a_link in self.link:
if a_link.rel == 'http://schemas.google.com/acl/2007#accessControlList':
return a_link
return None
def GetFeedLink(self):
for a_link in self.link:
if a_link.rel == 'http://schemas.google.com/g/2005#feed':
return a_link
return None
def GetNextLink(self):
for a_link in self.link:
if a_link.rel == 'next':
return a_link
return None
class TotalResults(atom.AtomBase):
"""opensearch:TotalResults for a GData feed"""
_tag = 'totalResults'
_namespace = OPENSEARCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def TotalResultsFromString(xml_string):
return atom.CreateClassFromXMLString(TotalResults, xml_string)
class StartIndex(atom.AtomBase):
"""The opensearch:startIndex element in GData feed"""
_tag = 'startIndex'
_namespace = OPENSEARCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def StartIndexFromString(xml_string):
return atom.CreateClassFromXMLString(StartIndex, xml_string)
class ItemsPerPage(atom.AtomBase):
"""The opensearch:itemsPerPage element in GData feed"""
_tag = 'itemsPerPage'
_namespace = OPENSEARCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ItemsPerPageFromString(xml_string):
return atom.CreateClassFromXMLString(ItemsPerPage, xml_string)
class ExtendedProperty(atom.AtomBase):
"""The Google Data extendedProperty element.
Used to store arbitrary key-value information specific to your
application. The value can either be a text string stored as an XML
attribute (.value), or an XML node (XmlBlob) as a child element.
This element is used in the Google Calendar data API and the Google
Contacts data API.
"""
_tag = 'extendedProperty'
_namespace = GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['name'] = 'name'
_attributes['value'] = 'value'
def __init__(self, name=None, value=None, extension_elements=None,
extension_attributes=None, text=None):
self.name = name
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GetXmlBlobExtensionElement(self):
"""Returns the XML blob as an atom.ExtensionElement.
Returns:
An atom.ExtensionElement representing the blob's XML, or None if no
blob was set.
"""
if len(self.extension_elements) < 1:
return None
else:
return self.extension_elements[0]
def GetXmlBlobString(self):
"""Returns the XML blob as a string.
Returns:
A string containing the blob's XML, or None if no blob was set.
"""
blob = self.GetXmlBlobExtensionElement()
if blob:
return blob.ToString()
return None
def SetXmlBlob(self, blob):
"""Sets the contents of the extendedProperty to XML as a child node.
Since the extendedProperty is only allowed one child element as an XML
blob, setting the XML blob will erase any preexisting extension elements
in this object.
Args:
blob: str, ElementTree Element or atom.ExtensionElement representing
the XML blob stored in the extendedProperty.
"""
# Erase any existing extension_elements, clears the child nodes from the
# extendedProperty.
self.extension_elements = []
if isinstance(blob, atom.ExtensionElement):
self.extension_elements.append(blob)
elif ElementTree.iselement(blob):
self.extension_elements.append(atom._ExtensionElementFromElementTree(
blob))
else:
self.extension_elements.append(atom.ExtensionElementFromString(blob))
def ExtendedPropertyFromString(xml_string):
return atom.CreateClassFromXMLString(ExtendedProperty, xml_string)
class GDataEntry(atom.Entry, LinkFinder):
"""Extends Atom Entry to provide data processing"""
_tag = atom.Entry._tag
_namespace = atom.Entry._namespace
_children = atom.Entry._children.copy()
_attributes = atom.Entry._attributes.copy()
def __GetId(self):
return self.__id
# This method was created to strip the unwanted whitespace from the id's
# text node.
def __SetId(self, id):
self.__id = id
if id is not None and id.text is not None:
self.__id.text = id.text.strip()
id = property(__GetId, __SetId)
def IsMedia(self):
"""Determines whether or not an entry is a GData Media entry.
"""
if (self.GetEditMediaLink()):
return True
else:
return False
def GetMediaURL(self):
"""Returns the URL to the media content, if the entry is a media entry.
Otherwise returns None.
"""
if not self.IsMedia():
return None
else:
return self.content.src
def GDataEntryFromString(xml_string):
"""Creates a new GDataEntry instance given a string of XML."""
return atom.CreateClassFromXMLString(GDataEntry, xml_string)
class GDataFeed(atom.Feed, LinkFinder):
"""A Feed from a GData service"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = atom.Feed._children.copy()
_attributes = atom.Feed._attributes.copy()
_children['{%s}totalResults' % OPENSEARCH_NAMESPACE] = ('total_results',
TotalResults)
_children['{%s}startIndex' % OPENSEARCH_NAMESPACE] = ('start_index',
StartIndex)
_children['{%s}itemsPerPage' % OPENSEARCH_NAMESPACE] = ('items_per_page',
ItemsPerPage)
# Add a conversion rule for atom:entry to make it into a GData
# Entry.
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GDataEntry])
def __GetId(self):
return self.__id
def __SetId(self, id):
self.__id = id
if id is not None and id.text is not None:
self.__id.text = id.text.strip()
id = property(__GetId, __SetId)
def __GetGenerator(self):
return self.__generator
def __SetGenerator(self, generator):
self.__generator = generator
if generator is not None:
self.__generator.text = generator.text.strip()
generator = property(__GetGenerator, __SetGenerator)
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None, entry=None,
total_results=None, start_index=None, items_per_page=None,
extension_elements=None, extension_attributes=None, text=None):
"""Constructor for Source
Args:
author: list (optional) A list of Author instances which belong to this
class.
category: list (optional) A list of Category instances
contributor: list (optional) A list on Contributor instances
generator: Generator (optional)
icon: Icon (optional)
id: Id (optional) The entry's Id element
link: list (optional) A list of Link instances
logo: Logo (optional)
rights: Rights (optional) The entry's Rights element
subtitle: Subtitle (optional) The entry's subtitle element
title: Title (optional) the entry's title element
updated: Updated (optional) the entry's updated element
entry: list (optional) A list of the Entry instances contained in the
feed.
text: String (optional) The text contents of the element. This is the
contents of the Entry's XML text node.
(Example: <foo>This is the text</foo>)
extension_elements: list (optional) A list of ExtensionElement instances
which are children of this element.
extension_attributes: dict (optional) A dictionary of strings which are
the values for additional XML attributes of this element.
"""
self.author = author or []
self.category = category or []
self.contributor = contributor or []
self.generator = generator
self.icon = icon
self.id = atom_id
self.link = link or []
self.logo = logo
self.rights = rights
self.subtitle = subtitle
self.title = title
self.updated = updated
self.entry = entry or []
self.total_results = total_results
self.start_index = start_index
self.items_per_page = items_per_page
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GDataFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GDataFeed, xml_string)
class BatchId(atom.AtomBase):
_tag = 'id'
_namespace = BATCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def BatchIdFromString(xml_string):
return atom.CreateClassFromXMLString(BatchId, xml_string)
class BatchOperation(atom.AtomBase):
_tag = 'operation'
_namespace = BATCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['type'] = 'type'
def __init__(self, op_type=None, extension_elements=None,
extension_attributes=None,
text=None):
self.type = op_type
atom.AtomBase.__init__(self,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def BatchOperationFromString(xml_string):
return atom.CreateClassFromXMLString(BatchOperation, xml_string)
class BatchStatus(atom.AtomBase):
"""The batch:status element present in a batch response entry.
A status element contains the code (HTTP response code) and
reason as elements. In a single request these fields would
be part of the HTTP response, but in a batch request each
Entry operation has a corresponding Entry in the response
feed which includes status information.
See http://code.google.com/apis/gdata/batch.html#Handling_Errors
"""
_tag = 'status'
_namespace = BATCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['code'] = 'code'
_attributes['reason'] = 'reason'
_attributes['content-type'] = 'content_type'
def __init__(self, code=None, reason=None, content_type=None,
extension_elements=None, extension_attributes=None, text=None):
self.code = code
self.reason = reason
self.content_type = content_type
atom.AtomBase.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def BatchStatusFromString(xml_string):
return atom.CreateClassFromXMLString(BatchStatus, xml_string)
class BatchEntry(GDataEntry):
"""An atom:entry for use in batch requests.
The BatchEntry contains additional members to specify the operation to be
performed on this entry and a batch ID so that the server can reference
individual operations in the response feed. For more information, see:
http://code.google.com/apis/gdata/batch.html
"""
_tag = GDataEntry._tag
_namespace = GDataEntry._namespace
_children = GDataEntry._children.copy()
_children['{%s}operation' % BATCH_NAMESPACE] = ('batch_operation', BatchOperation)
_children['{%s}id' % BATCH_NAMESPACE] = ('batch_id', BatchId)
_children['{%s}status' % BATCH_NAMESPACE] = ('batch_status', BatchStatus)
_attributes = GDataEntry._attributes.copy()
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, control=None, title=None, updated=None,
batch_operation=None, batch_id=None, batch_status=None,
extension_elements=None, extension_attributes=None, text=None):
self.batch_operation = batch_operation
self.batch_id = batch_id
self.batch_status = batch_status
GDataEntry.__init__(self, author=author, category=category,
content=content, contributor=contributor, atom_id=atom_id, link=link,
published=published, rights=rights, source=source, summary=summary,
control=control, title=title, updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes, text=text)
def BatchEntryFromString(xml_string):
return atom.CreateClassFromXMLString(BatchEntry, xml_string)
class BatchInterrupted(atom.AtomBase):
"""The batch:interrupted element sent if batch request was interrupted.
Only appears in a feed if some of the batch entries could not be processed.
See: http://code.google.com/apis/gdata/batch.html#Handling_Errors
"""
_tag = 'interrupted'
_namespace = BATCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['reason'] = 'reason'
_attributes['success'] = 'success'
_attributes['failures'] = 'failures'
_attributes['parsed'] = 'parsed'
def __init__(self, reason=None, success=None, failures=None, parsed=None,
extension_elements=None, extension_attributes=None, text=None):
self.reason = reason
self.success = success
self.failures = failures
self.parsed = parsed
atom.AtomBase.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def BatchInterruptedFromString(xml_string):
return atom.CreateClassFromXMLString(BatchInterrupted, xml_string)
class BatchFeed(GDataFeed):
"""A feed containing a list of batch request entries."""
_tag = GDataFeed._tag
_namespace = GDataFeed._namespace
_children = GDataFeed._children.copy()
_attributes = GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [BatchEntry])
_children['{%s}interrupted' % BATCH_NAMESPACE] = ('interrupted', BatchInterrupted)
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None, entry=None,
total_results=None, start_index=None, items_per_page=None,
interrupted=None,
extension_elements=None, extension_attributes=None, text=None):
self.interrupted = interrupted
GDataFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results, start_index=start_index,
items_per_page=items_per_page,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def AddBatchEntry(self, entry=None, id_url_string=None,
batch_id_string=None, operation_string=None):
"""Logic for populating members of a BatchEntry and adding to the feed.
If the entry is not a BatchEntry, it is converted to a BatchEntry so
that the batch specific members will be present.
The id_url_string can be used in place of an entry if the batch operation
applies to a URL. For example query and delete operations require just
the URL of an entry, no body is sent in the HTTP request. If an
id_url_string is sent instead of an entry, a BatchEntry is created and
added to the feed.
This method also assigns the desired batch id to the entry so that it
can be referenced in the server's response. If the batch_id_string is
None, this method will assign a batch_id to be the index at which this
entry will be in the feed's entry list.
Args:
entry: BatchEntry, atom.Entry, or another Entry flavor (optional) The
entry which will be sent to the server as part of the batch request.
The item must have a valid atom id so that the server knows which
entry this request references.
id_url_string: str (optional) The URL of the entry to be acted on. You
can find this URL in the text member of the atom id for an entry.
If an entry is not sent, this id will be used to construct a new
BatchEntry which will be added to the request feed.
batch_id_string: str (optional) The batch ID to be used to reference
this batch operation in the results feed. If this parameter is None,
the current length of the feed's entry array will be used as a
count. Note that batch_ids should either always be specified or
never, mixing could potentially result in duplicate batch ids.
operation_string: str (optional) The desired batch operation which will
set the batch_operation.type member of the entry. Options are
'insert', 'update', 'delete', and 'query'
Raises:
MissingRequiredParameters: Raised if neither an id_ url_string nor an
entry are provided in the request.
Returns:
The added entry.
"""
if entry is None and id_url_string is None:
raise MissingRequiredParameters('supply either an entry or URL string')
if entry is None and id_url_string is not None:
entry = BatchEntry(atom_id=atom.Id(text=id_url_string))
# TODO: handle cases in which the entry lacks batch_... members.
#if not isinstance(entry, BatchEntry):
# Convert the entry to a batch entry.
if batch_id_string is not None:
entry.batch_id = BatchId(text=batch_id_string)
elif entry.batch_id is None or entry.batch_id.text is None:
entry.batch_id = BatchId(text=str(len(self.entry)))
if operation_string is not None:
entry.batch_operation = BatchOperation(op_type=operation_string)
self.entry.append(entry)
return entry
def AddInsert(self, entry, batch_id_string=None):
"""Add an insert request to the operations in this batch request feed.
If the entry doesn't yet have an operation or a batch id, these will
be set to the insert operation and a batch_id specified as a parameter.
Args:
entry: BatchEntry The entry which will be sent in the batch feed as an
insert request.
batch_id_string: str (optional) The batch ID to be used to reference
this batch operation in the results feed. If this parameter is None,
the current length of the feed's entry array will be used as a
count. Note that batch_ids should either always be specified or
never, mixing could potentially result in duplicate batch ids.
"""
entry = self.AddBatchEntry(entry=entry, batch_id_string=batch_id_string,
operation_string=BATCH_INSERT)
def AddUpdate(self, entry, batch_id_string=None):
"""Add an update request to the list of batch operations in this feed.
Sets the operation type of the entry to insert if it is not already set
and assigns the desired batch id to the entry so that it can be
referenced in the server's response.
Args:
entry: BatchEntry The entry which will be sent to the server as an
update (HTTP PUT) request. The item must have a valid atom id
so that the server knows which entry to replace.
batch_id_string: str (optional) The batch ID to be used to reference
this batch operation in the results feed. If this parameter is None,
the current length of the feed's entry array will be used as a
count. See also comments for AddInsert.
"""
entry = self.AddBatchEntry(entry=entry, batch_id_string=batch_id_string,
operation_string=BATCH_UPDATE)
def AddDelete(self, url_string=None, entry=None, batch_id_string=None):
"""Adds a delete request to the batch request feed.
This method takes either the url_string which is the atom id of the item
to be deleted, or the entry itself. The atom id of the entry must be
present so that the server knows which entry should be deleted.
Args:
url_string: str (optional) The URL of the entry to be deleted. You can
find this URL in the text member of the atom id for an entry.
entry: BatchEntry (optional) The entry to be deleted.
batch_id_string: str (optional)
Raises:
MissingRequiredParameters: Raised if neither a url_string nor an entry
are provided in the request.
"""
entry = self.AddBatchEntry(entry=entry, id_url_string=url_string,
batch_id_string=batch_id_string,
operation_string=BATCH_DELETE)
def AddQuery(self, url_string=None, entry=None, batch_id_string=None):
"""Adds a query request to the batch request feed.
This method takes either the url_string which is the query URL
whose results will be added to the result feed. The query URL will
be encapsulated in a BatchEntry, and you may pass in the BatchEntry
with a query URL instead of sending a url_string.
Args:
url_string: str (optional)
entry: BatchEntry (optional)
batch_id_string: str (optional)
Raises:
MissingRequiredParameters
"""
entry = self.AddBatchEntry(entry=entry, id_url_string=url_string,
batch_id_string=batch_id_string,
operation_string=BATCH_QUERY)
def GetBatchLink(self):
for link in self.link:
if link.rel == 'http://schemas.google.com/g/2005#batch':
return link
return None
def BatchFeedFromString(xml_string):
return atom.CreateClassFromXMLString(BatchFeed, xml_string)
class EntryLink(atom.AtomBase):
"""The gd:entryLink element"""
_tag = 'entryLink'
_namespace = GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
# The entry used to be an atom.Entry, now it is a GDataEntry.
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', GDataEntry)
_attributes['rel'] = 'rel',
_attributes['readOnly'] = 'read_only'
_attributes['href'] = 'href'
def __init__(self, href=None, read_only=None, rel=None,
entry=None, extension_elements=None,
extension_attributes=None, text=None):
self.href = href
self.read_only = read_only
self.rel = rel
self.entry = entry
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def EntryLinkFromString(xml_string):
return atom.CreateClassFromXMLString(EntryLink, xml_string)
class FeedLink(atom.AtomBase):
"""The gd:feedLink element"""
_tag = 'feedLink'
_namespace = GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}feed' % atom.ATOM_NAMESPACE] = ('feed', GDataFeed)
_attributes['rel'] = 'rel'
_attributes['readOnly'] = 'read_only'
_attributes['countHint'] = 'count_hint'
_attributes['href'] = 'href'
def __init__(self, count_hint=None, href=None, read_only=None, rel=None,
feed=None, extension_elements=None, extension_attributes=None,
text=None):
self.count_hint = count_hint
self.href = href
self.read_only = read_only
self.rel = rel
self.feed = feed
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def FeedLinkFromString(xml_string):
return atom.CreateClassFromXMLString(EntryLink, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright Google 2007-2008, all rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import StringIO
import gdata
import gdata.service
import gdata.spreadsheet
import gdata.spreadsheet.service
import gdata.docs
import gdata.docs.service
"""Make the Google Documents API feel more like using a database.
This module contains a client and other classes which make working with the
Google Documents List Data API and the Google Spreadsheets Data API look a
bit more like working with a heirarchical database. Using the DatabaseClient,
you can create or find spreadsheets and use them like a database, with
worksheets representing tables and rows representing records.
Example Usage:
# Create a new database, a new table, and add records.
client = gdata.spreadsheet.text_db.DatabaseClient(username='jo@example.com',
password='12345')
database = client.CreateDatabase('My Text Database')
table = database.CreateTable('addresses', ['name','email',
'phonenumber', 'mailingaddress'])
record = table.AddRecord({'name':'Bob', 'email':'bob@example.com',
'phonenumber':'555-555-1234', 'mailingaddress':'900 Imaginary St.'})
# Edit a record
record.content['email'] = 'bob2@example.com'
record.Push()
# Delete a table
table.Delete
Warnings:
Care should be exercised when using this module on spreadsheets
which contain formulas. This module treats all rows as containing text and
updating a row will overwrite any formula with the output of the formula.
The intended use case is to allow easy storage of text data in a spreadsheet.
Error: Domain specific extension of Exception.
BadCredentials: Error raised is username or password was incorrect.
CaptchaRequired: Raised if a login attempt failed and a CAPTCHA challenge
was issued.
DatabaseClient: Communicates with Google Docs APIs servers.
Database: Represents a spreadsheet and interacts with tables.
Table: Represents a worksheet and interacts with records.
RecordResultSet: A list of records in a table.
Record: Represents a row in a worksheet allows manipulation of text data.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
class Error(Exception):
pass
class BadCredentials(Error):
pass
class CaptchaRequired(Error):
pass
class DatabaseClient(object):
"""Allows creation and finding of Google Spreadsheets databases.
The DatabaseClient simplifies the process of creating and finding Google
Spreadsheets and will talk to both the Google Spreadsheets API and the
Google Documents List API.
"""
def __init__(self, username=None, password=None):
"""Constructor for a Database Client.
If the username and password are present, the constructor will contact
the Google servers to authenticate.
Args:
username: str (optional) Example: jo@example.com
password: str (optional)
"""
self.__docs_client = gdata.docs.service.DocsService()
self.__spreadsheets_client = (
gdata.spreadsheet.service.SpreadsheetsService())
self.SetCredentials(username, password)
def SetCredentials(self, username, password):
"""Attempts to log in to Google APIs using the provided credentials.
If the username or password are None, the client will not request auth
tokens.
Args:
username: str (optional) Example: jo@example.com
password: str (optional)
"""
self.__docs_client.email = username
self.__docs_client.password = password
self.__spreadsheets_client.email = username
self.__spreadsheets_client.password = password
if username and password:
try:
self.__docs_client.ProgrammaticLogin()
self.__spreadsheets_client.ProgrammaticLogin()
except gdata.service.CaptchaRequired:
raise CaptchaRequired('Please visit https://www.google.com/accounts/'
'DisplayUnlockCaptcha to unlock your account.')
except gdata.service.BadAuthentication:
raise BadCredentials('Username or password incorrect.')
def CreateDatabase(self, name):
"""Creates a new Google Spreadsheet with the desired name.
Args:
name: str The title for the spreadsheet.
Returns:
A Database instance representing the new spreadsheet.
"""
# Create a Google Spreadsheet to form the foundation of this database.
# Spreadsheet is created by uploading a file to the Google Documents
# List API.
virtual_csv_file = StringIO.StringIO(',,,')
virtual_media_source = gdata.MediaSource(file_handle=virtual_csv_file, content_type='text/csv', content_length=3)
db_entry = self.__docs_client.UploadSpreadsheet(virtual_media_source, name)
return Database(spreadsheet_entry=db_entry, database_client=self)
def GetDatabases(self, spreadsheet_key=None, name=None):
"""Finds spreadsheets which have the unique key or title.
If querying on the spreadsheet_key there will be at most one result, but
searching by name could yield multiple results.
Args:
spreadsheet_key: str The unique key for the spreadsheet, this
usually in the the form 'pk23...We' or 'o23...423.12,,,3'.
name: str The title of the spreadsheets.
Returns:
A list of Database objects representing the desired spreadsheets.
"""
if spreadsheet_key:
db_entry = self.__docs_client.GetDocumentListEntry(
r'/feeds/documents/private/full/spreadsheet%3A' + spreadsheet_key)
return [Database(spreadsheet_entry=db_entry, database_client=self)]
else:
title_query = gdata.docs.service.DocumentQuery()
title_query['title'] = name
db_feed = self.__docs_client.QueryDocumentListFeed(title_query.ToUri())
matching_databases = []
for entry in db_feed.entry:
matching_databases.append(Database(spreadsheet_entry=entry,
database_client=self))
return matching_databases
def _GetDocsClient(self):
return self.__docs_client
def _GetSpreadsheetsClient(self):
return self.__spreadsheets_client
class Database(object):
"""Provides interface to find and create tables.
The database represents a Google Spreadsheet.
"""
def __init__(self, spreadsheet_entry=None, database_client=None):
"""Constructor for a database object.
Args:
spreadsheet_entry: gdata.docs.DocumentListEntry The
Atom entry which represents the Google Spreadsheet. The
spreadsheet's key is extracted from the entry and stored as a
member.
database_client: DatabaseClient A client which can talk to the
Google Spreadsheets servers to perform operations on worksheets
within this spreadsheet.
"""
self.entry = spreadsheet_entry
if self.entry:
id_parts = spreadsheet_entry.id.text.split('/')
self.spreadsheet_key = id_parts[-1].replace('spreadsheet%3A', '')
self.client = database_client
def CreateTable(self, name, fields=None):
"""Add a new worksheet to this spreadsheet and fill in column names.
Args:
name: str The title of the new worksheet.
fields: list of strings The column names which are placed in the
first row of this worksheet. These names are converted into XML
tags by the server. To avoid changes during the translation
process I recommend using all lowercase alphabetic names. For
example ['somelongname', 'theothername']
Returns:
Table representing the newly created worksheet.
"""
worksheet = self.client._GetSpreadsheetsClient().AddWorksheet(title=name,
row_count=1, col_count=len(fields), key=self.spreadsheet_key)
return Table(name=name, worksheet_entry=worksheet,
database_client=self.client,
spreadsheet_key=self.spreadsheet_key, fields=fields)
def GetTables(self, worksheet_id=None, name=None):
"""Searches for a worksheet with the specified ID or name.
The list of results should have one table at most, or no results
if the id or name were not found.
Args:
worksheet_id: str The ID of the worksheet, example: 'od6'
name: str The title of the worksheet.
Returns:
A list of length 0 or 1 containing the desired Table. A list is returned
to make this method feel like GetDatabases and GetRecords.
"""
if worksheet_id:
worksheet_entry = self.client._GetSpreadsheetsClient().GetWorksheetsFeed(
self.spreadsheet_key, wksht_id=worksheet_id)
return [Table(name=worksheet_entry.title.text,
worksheet_entry=worksheet_entry, database_client=self.client,
spreadsheet_key=self.spreadsheet_key)]
else:
matching_tables = []
title_query = gdata.spreadsheet.service.DocumentQuery()
title_query.title = name
worksheet_feed = self.client._GetSpreadsheetsClient().GetWorksheetsFeed(
self.spreadsheet_key, query=title_query)
for entry in worksheet_feed.entry:
matching_tables.append(Table(name=entry.title.text,
worksheet_entry=entry, database_client=self.client,
spreadsheet_key=self.spreadsheet_key))
return matching_tables
def Delete(self):
"""Deletes the entire database spreadsheet from Google Spreadsheets."""
entry = self.client._GetDocsClient().Get(
r'http://docs.google.com/feeds/documents/private/full/spreadsheet%3A' +
self.spreadsheet_key)
self.client._GetDocsClient().Delete(entry.GetEditLink().href)
class Table(object):
def __init__(self, name=None, worksheet_entry=None, database_client=None,
spreadsheet_key=None, fields=None):
self.name = name
self.entry = worksheet_entry
id_parts = worksheet_entry.id.text.split('/')
self.worksheet_id = id_parts[-1]
self.spreadsheet_key = spreadsheet_key
self.client = database_client
self.fields = fields or []
if fields:
self.SetFields(fields)
def LookupFields(self):
"""Queries to find the column names in the first row of the worksheet.
Useful when you have retrieved the table from the server and you don't
know the column names.
"""
if self.entry:
first_row_contents = []
query = gdata.spreadsheet.service.CellQuery()
query.max_row = '1'
query.min_row = '1'
feed = self.client._GetSpreadsheetsClient().GetCellsFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id, query=query)
for entry in feed.entry:
first_row_contents.append(entry.content.text)
# Get the next set of cells if needed.
next_link = feed.GetNextLink()
while next_link:
feed = self.client._GetSpreadsheetsClient().Get(next_link.href,
converter=gdata.spreadsheet.SpreadsheetsCellsFeedFromString)
for entry in feed.entry:
first_row_contents.append(entry.content.text)
next_link = feed.GetNextLink()
# Convert the contents of the cells to valid headers.
self.fields = ConvertStringsToColumnHeaders(first_row_contents)
def SetFields(self, fields):
"""Changes the contents of the cells in the first row of this worksheet.
Args:
fields: list of strings The names in the list comprise the
first row of the worksheet. These names are converted into XML
tags by the server. To avoid changes during the translation
process I recommend using all lowercase alphabetic names. For
example ['somelongname', 'theothername']
"""
# TODO: If the table already had fields, we might want to clear out the,
# current column headers.
self.fields = fields
i = 0
for column_name in fields:
i = i + 1
# TODO: speed this up by using a batch request to update cells.
self.client._GetSpreadsheetsClient().UpdateCell(1, i, column_name,
self.spreadsheet_key, self.worksheet_id)
def Delete(self):
"""Deletes this worksheet from the spreadsheet."""
worksheet = self.client._GetSpreadsheetsClient().GetWorksheetsFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id)
self.client._GetSpreadsheetsClient().DeleteWorksheet(
worksheet_entry=worksheet)
def AddRecord(self, data):
"""Adds a new row to this worksheet.
Args:
data: dict of strings Mapping of string values to column names.
Returns:
Record which represents this row of the spreadsheet.
"""
new_row = self.client._GetSpreadsheetsClient().InsertRow(data,
self.spreadsheet_key, wksht_id=self.worksheet_id)
return Record(content=data, row_entry=new_row,
spreadsheet_key=self.spreadsheet_key, worksheet_id=self.worksheet_id,
database_client=self.client)
def GetRecord(self, row_id=None, row_number=None):
"""Gets a single record from the worksheet based on row ID or number.
Args:
row_id: The ID for the individual row.
row_number: str or int The position of the desired row. Numbering
begins at 1, which refers to the second row in the worksheet since
the first row is used for column names.
Returns:
Record for the desired row.
"""
if row_id:
row_entry = self.client._GetSpreadsheetsClient().GetListFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id, row_id=row_id)
return Record(content=None, row_entry=row_entry,
spreadsheet_key=self.spreadsheet_key,
worksheet_id=self.worksheet_id, database_client=self.client)
else:
row_query = gdata.spreadsheet.service.ListQuery()
row_query.start_index = str(row_number)
row_query.max_results = '1'
row_feed = self.client._GetSpreadsheetsClient().GetListFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id, query=row_query)
if len(row_feed.entry) >= 1:
return Record(content=None, row_entry=row_feed.entry[0],
spreadsheet_key=self.spreadsheet_key,
worksheet_id=self.worksheet_id, database_client=self.client)
else:
return None
def GetRecords(self, start_row, end_row):
"""Gets all rows between the start and end row numbers inclusive.
Args:
start_row: str or int
end_row: str or int
Returns:
RecordResultSet for the desired rows.
"""
start_row = int(start_row)
end_row = int(end_row)
max_rows = end_row - start_row + 1
row_query = gdata.spreadsheet.service.ListQuery()
row_query.start_index = str(start_row)
row_query.max_results = str(max_rows)
rows_feed = self.client._GetSpreadsheetsClient().GetListFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id, query=row_query)
return RecordResultSet(rows_feed, self.client, self.spreadsheet_key,
self.worksheet_id)
def FindRecords(self, query_string):
"""Performs a query against the worksheet to find rows which match.
For details on query string syntax see the section on sq under
http://code.google.com/apis/spreadsheets/reference.html#list_Parameters
Args:
query_string: str Examples: 'name == john' to find all rows with john
in the name column, '(cost < 19.50 and name != toy) or cost > 500'
Returns:
RecordResultSet with the first group of matches.
"""
row_query = gdata.spreadsheet.service.ListQuery()
row_query.sq = query_string
matching_feed = self.client._GetSpreadsheetsClient().GetListFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id, query=row_query)
return RecordResultSet(matching_feed, self.client,
self.spreadsheet_key, self.worksheet_id)
class RecordResultSet(list):
"""A collection of rows which allows fetching of the next set of results.
The server may not send all rows in the requested range because there are
too many. Using this result set you can access the first set of results
as if it is a list, then get the next batch (if there are more results) by
calling GetNext().
"""
def __init__(self, feed, client, spreadsheet_key, worksheet_id):
self.client = client
self.spreadsheet_key = spreadsheet_key
self.worksheet_id = worksheet_id
self.feed = feed
list(self)
for entry in self.feed.entry:
self.append(Record(content=None, row_entry=entry,
spreadsheet_key=spreadsheet_key, worksheet_id=worksheet_id,
database_client=client))
def GetNext(self):
"""Fetches the next batch of rows in the result set.
Returns:
A new RecordResultSet.
"""
next_link = self.feed.GetNextLink()
if next_link and next_link.href:
new_feed = self.client._GetSpreadsheetsClient().Get(next_link.href,
converter=gdata.spreadsheet.SpreadsheetsListFeedFromString)
return RecordResultSet(new_feed, self.client, self.spreadsheet_key,
self.worksheet_id)
class Record(object):
"""Represents one row in a worksheet and provides a dictionary of values.
Attributes:
custom: dict Represents the contents of the row with cell values mapped
to column headers.
"""
def __init__(self, content=None, row_entry=None, spreadsheet_key=None,
worksheet_id=None, database_client=None):
"""Constructor for a record.
Args:
content: dict of strings Mapping of string values to column names.
row_entry: gdata.spreadsheet.SpreadsheetsList The Atom entry
representing this row in the worksheet.
spreadsheet_key: str The ID of the spreadsheet in which this row
belongs.
worksheet_id: str The ID of the worksheet in which this row belongs.
database_client: DatabaseClient The client which can be used to talk
the Google Spreadsheets server to edit this row.
"""
self.entry = row_entry
self.spreadsheet_key = spreadsheet_key
self.worksheet_id = worksheet_id
if row_entry:
self.row_id = row_entry.id.text.split('/')[-1]
else:
self.row_id = None
self.client = database_client
self.content = content or {}
if not content:
self.ExtractContentFromEntry(row_entry)
def ExtractContentFromEntry(self, entry):
"""Populates the content and row_id based on content of the entry.
This method is used in the Record's contructor.
Args:
entry: gdata.spreadsheet.SpreadsheetsList The Atom entry
representing this row in the worksheet.
"""
self.content = {}
if entry:
self.row_id = entry.id.text.split('/')[-1]
for label, custom in entry.custom.iteritems():
self.content[label] = custom.text
def Push(self):
"""Send the content of the record to spreadsheets to edit the row.
All items in the content dictionary will be sent. Items which have been
removed from the content may remain in the row. The content member
of the record will not be modified so additional fields in the row
might be absent from this local copy.
"""
self.entry = self.client._GetSpreadsheetsClient().UpdateRow(self.entry, self.content)
def Pull(self):
"""Query Google Spreadsheets to get the latest data from the server.
Fetches the entry for this row and repopulates the content dictionary
with the data found in the row.
"""
if self.row_id:
self.entry = self.client._GetSpreadsheetsClient().GetListFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id, row_id=self.row_id)
self.ExtractContentFromEntry(self.entry)
def Delete(self):
self.client._GetSpreadsheetsClient().DeleteRow(self.entry)
def ConvertStringsToColumnHeaders(proposed_headers):
"""Converts a list of strings to column names which spreadsheets accepts.
When setting values in a record, the keys which represent column names must
fit certain rules. They are all lower case, contain no spaces or special
characters. If two columns have the same name after being sanitized, the
columns further to the right have _2, _3 _4, etc. appended to them.
If there are column names which consist of all special characters, or if
the column header is blank, an obfuscated value will be used for a column
name. This method does not handle blank column names or column names with
only special characters.
"""
headers = []
for input_string in proposed_headers:
# TODO: probably a more efficient way to do this. Perhaps regex.
sanitized = input_string.lower().replace('_', '').replace(
':', '').replace(' ', '')
# When the same sanitized header appears multiple times in the first row
# of a spreadsheet, _n is appended to the name to make it unique.
header_count = headers.count(sanitized)
if header_count > 0:
headers.append('%s_%i' % (sanitized, header_count+1))
else:
headers.append(sanitized)
return headers
| Python |
#!/usr/bin/python
#
# Copyright (C) 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to Atom objects used with Google Spreadsheets.
"""
__author__ = 'api.laurabeth@gmail.com (Laura Beth Lincoln)'
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import atom
import gdata
import re
import string
# XML namespaces which are often used in Google Spreadsheets entities.
GSPREADSHEETS_NAMESPACE = 'http://schemas.google.com/spreadsheets/2006'
GSPREADSHEETS_TEMPLATE = '{http://schemas.google.com/spreadsheets/2006}%s'
GSPREADSHEETS_EXTENDED_NAMESPACE = ('http://schemas.google.com/spreadsheets'
'/2006/extended')
GSPREADSHEETS_EXTENDED_TEMPLATE = ('{http://schemas.google.com/spreadsheets'
'/2006/extended}%s')
class ColCount(atom.AtomBase):
"""The Google Spreadsheets colCount element """
_tag = 'colCount'
_namespace = GSPREADSHEETS_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ColCountFromString(xml_string):
return atom.CreateClassFromXMLString(ColCount, xml_string)
class RowCount(atom.AtomBase):
"""The Google Spreadsheets rowCount element """
_tag = 'rowCount'
_namespace = GSPREADSHEETS_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def RowCountFromString(xml_string):
return atom.CreateClassFromXMLString(RowCount, xml_string)
class Cell(atom.AtomBase):
"""The Google Spreadsheets cell element """
_tag = 'cell'
_namespace = GSPREADSHEETS_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['row'] = 'row'
_attributes['col'] = 'col'
_attributes['inputValue'] = 'inputValue'
_attributes['numericValue'] = 'numericValue'
def __init__(self, text=None, row=None, col=None, inputValue=None,
numericValue=None, extension_elements=None, extension_attributes=None):
self.text = text
self.row = row
self.col = col
self.inputValue = inputValue
self.numericValue = numericValue
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def CellFromString(xml_string):
return atom.CreateClassFromXMLString(Cell, xml_string)
class Custom(atom.AtomBase):
"""The Google Spreadsheets custom element"""
_namespace = GSPREADSHEETS_EXTENDED_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, column=None, text=None, extension_elements=None,
extension_attributes=None):
self.column = column # The name of the column
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def _BecomeChildElement(self, tree):
new_child = ElementTree.Element('')
tree.append(new_child)
new_child.tag = '{%s}%s' % (self.__class__._namespace,
self.column)
self._AddMembersToElementTree(new_child)
def _ToElementTree(self):
new_tree = ElementTree.Element('{%s}%s' % (self.__class__._namespace,
self.column))
self._AddMembersToElementTree(new_tree)
return new_tree
def _HarvestElementTree(self, tree):
namespace_uri, local_tag = string.split(tree.tag[1:], "}", 1)
self.column = local_tag
# Fill in the instance members from the contents of the XML tree.
for child in tree:
self._ConvertElementTreeToMember(child)
for attribute, value in tree.attrib.iteritems():
self._ConvertElementAttributeToMember(attribute, value)
self.text = tree.text
def CustomFromString(xml_string):
element_tree = ElementTree.fromstring(xml_string)
return _CustomFromElementTree(element_tree)
def _CustomFromElementTree(element_tree):
namespace_uri, local_tag = string.split(element_tree.tag[1:], "}", 1)
if namespace_uri == GSPREADSHEETS_EXTENDED_NAMESPACE:
new_custom = Custom()
new_custom._HarvestElementTree(element_tree)
new_custom.column = local_tag
return new_custom
return None
class SpreadsheetsSpreadsheet(gdata.GDataEntry):
"""A Google Spreadsheets flavor of a Spreadsheet Atom Entry """
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, control=None, updated=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.control = control
self.title = title
self.updated = updated
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SpreadsheetsSpreadsheetFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsSpreadsheet,
xml_string)
class SpreadsheetsWorksheet(gdata.GDataEntry):
"""A Google Spreadsheets flavor of a Worksheet Atom Entry """
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}rowCount' % GSPREADSHEETS_NAMESPACE] = ('row_count',
RowCount)
_children['{%s}colCount' % GSPREADSHEETS_NAMESPACE] = ('col_count',
ColCount)
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, control=None, updated=None,
row_count=None, col_count=None, text=None, extension_elements=None,
extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.control = control
self.title = title
self.updated = updated
self.row_count = row_count
self.col_count = col_count
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SpreadsheetsWorksheetFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsWorksheet,
xml_string)
class SpreadsheetsCell(gdata.BatchEntry):
"""A Google Spreadsheets flavor of a Cell Atom Entry """
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.BatchEntry._children.copy()
_attributes = gdata.BatchEntry._attributes.copy()
_children['{%s}cell' % GSPREADSHEETS_NAMESPACE] = ('cell', Cell)
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, control=None, updated=None,
cell=None, batch_operation=None, batch_id=None, batch_status=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.control = control
self.title = title
self.batch_operation = batch_operation
self.batch_id = batch_id
self.batch_status = batch_status
self.updated = updated
self.cell = cell
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SpreadsheetsCellFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsCell,
xml_string)
class SpreadsheetsList(gdata.GDataEntry):
"""A Google Spreadsheets flavor of a List Atom Entry """
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, control=None, updated=None,
custom=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.control = control
self.title = title
self.updated = updated
self.custom = custom or {}
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
# We need to overwrite _ConvertElementTreeToMember to add special logic to
# convert custom attributes to members
def _ConvertElementTreeToMember(self, child_tree):
# Find the element's tag in this class's list of child members
if self.__class__._children.has_key(child_tree.tag):
member_name = self.__class__._children[child_tree.tag][0]
member_class = self.__class__._children[child_tree.tag][1]
# If the class member is supposed to contain a list, make sure the
# matching member is set to a list, then append the new member
# instance to the list.
if isinstance(member_class, list):
if getattr(self, member_name) is None:
setattr(self, member_name, [])
getattr(self, member_name).append(atom._CreateClassFromElementTree(
member_class[0], child_tree))
else:
setattr(self, member_name,
atom._CreateClassFromElementTree(member_class, child_tree))
elif child_tree.tag.find('{%s}' % GSPREADSHEETS_EXTENDED_NAMESPACE) == 0:
# If this is in the custom namespace, make add it to the custom dict.
name = child_tree.tag[child_tree.tag.index('}')+1:]
custom = _CustomFromElementTree(child_tree)
if custom:
self.custom[name] = custom
else:
ExtensionContainer._ConvertElementTreeToMember(self, child_tree)
# We need to overwtite _AddMembersToElementTree to add special logic to
# convert custom members to XML nodes.
def _AddMembersToElementTree(self, tree):
# Convert the members of this class which are XML child nodes.
# This uses the class's _children dictionary to find the members which
# should become XML child nodes.
member_node_names = [values[0] for tag, values in
self.__class__._children.iteritems()]
for member_name in member_node_names:
member = getattr(self, member_name)
if member is None:
pass
elif isinstance(member, list):
for instance in member:
instance._BecomeChildElement(tree)
else:
member._BecomeChildElement(tree)
# Convert the members of this class which are XML attributes.
for xml_attribute, member_name in self.__class__._attributes.iteritems():
member = getattr(self, member_name)
if member is not None:
tree.attrib[xml_attribute] = member
# Convert all special custom item attributes to nodes
for name, custom in self.custom.iteritems():
custom._BecomeChildElement(tree)
# Lastly, call the ExtensionContainers's _AddMembersToElementTree to
# convert any extension attributes.
atom.ExtensionContainer._AddMembersToElementTree(self, tree)
def SpreadsheetsListFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsList,
xml_string)
element_tree = ElementTree.fromstring(xml_string)
return _SpreadsheetsListFromElementTree(element_tree)
class SpreadsheetsSpreadsheetsFeed(gdata.GDataFeed):
"""A feed containing Google Spreadsheets Spreadsheets"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[SpreadsheetsSpreadsheet])
def SpreadsheetsSpreadsheetsFeedFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsSpreadsheetsFeed,
xml_string)
class SpreadsheetsWorksheetsFeed(gdata.GDataFeed):
"""A feed containing Google Spreadsheets Spreadsheets"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[SpreadsheetsWorksheet])
def SpreadsheetsWorksheetsFeedFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsWorksheetsFeed,
xml_string)
class SpreadsheetsCellsFeed(gdata.BatchFeed):
"""A feed containing Google Spreadsheets Cells"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.BatchFeed._children.copy()
_attributes = gdata.BatchFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[SpreadsheetsCell])
_children['{%s}rowCount' % GSPREADSHEETS_NAMESPACE] = ('row_count',
RowCount)
_children['{%s}colCount' % GSPREADSHEETS_NAMESPACE] = ('col_count',
ColCount)
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None,
entry=None, total_results=None, start_index=None,
items_per_page=None, extension_elements=None,
extension_attributes=None, text=None, row_count=None,
col_count=None, interrupted=None):
gdata.BatchFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text, interrupted=interrupted)
self.row_count = row_count
self.col_count = col_count
def GetBatchLink(self):
for link in self.link:
if link.rel == 'http://schemas.google.com/g/2005#batch':
return link
return None
def SpreadsheetsCellsFeedFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsCellsFeed,
xml_string)
class SpreadsheetsListFeed(gdata.GDataFeed):
"""A feed containing Google Spreadsheets Spreadsheets"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[SpreadsheetsList])
def SpreadsheetsListFeedFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsListFeed,
xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""SpreadsheetsService extends the GDataService to streamline Google
Spreadsheets operations.
GBaseService: Provides methods to query feeds and manipulate items. Extends
GDataService.
DictionaryToParamList: Function which converts a dictionary into a list of
URL arguments (represented as strings). This is a
utility function used in CRUD operations.
"""
__author__ = 'api.laurabeth@gmail.com (Laura Beth Lincoln)'
import gdata
import atom.service
import gdata.service
import gdata.spreadsheet
import atom
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class RequestError(Error):
pass
class SpreadsheetsService(gdata.service.GDataService):
"""Client for the Google Spreadsheets service."""
def __init__(self, email=None, password=None, source=None,
server='spreadsheets.google.com',
additional_headers=None):
gdata.service.GDataService.__init__(self, email=email, password=password,
service='wise', source=source,
server=server,
additional_headers=additional_headers)
def GetSpreadsheetsFeed(self, key=None, query=None, visibility='private',
projection='full'):
"""Gets a spreadsheets feed or a specific entry if a key is defined
Args:
key: string (optional) The spreadsheet key defined in /ccc?key=
query: DocumentQuery (optional) Query parameters
Returns:
If there is no key, then a SpreadsheetsSpreadsheetsFeed.
If there is a key, then a SpreadsheetsSpreadsheet.
"""
uri = ('http://%s/feeds/spreadsheets/%s/%s'
% (self.server, visibility, projection))
if key is not None:
uri = '%s/%s' % (uri, key)
if query != None:
query.feed = uri
uri = query.ToUri()
if key:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsSpreadsheetFromString)
else:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsSpreadsheetsFeedFromString)
def GetWorksheetsFeed(self, key, wksht_id=None, query=None,
visibility='private', projection='full'):
"""Gets a worksheets feed or a specific entry if a wksht is defined
Args:
key: string The spreadsheet key defined in /ccc?key=
wksht_id: string (optional) The id for a specific worksheet entry
query: DocumentQuery (optional) Query parameters
Returns:
If there is no wksht_id, then a SpreadsheetsWorksheetsFeed.
If there is a wksht_id, then a SpreadsheetsWorksheet.
"""
uri = ('http://%s/feeds/worksheets/%s/%s/%s'
% (self.server, key, visibility, projection))
if wksht_id != None:
uri = '%s/%s' % (uri, wksht_id)
if query != None:
query.feed = uri
uri = query.ToUri()
if wksht_id:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsWorksheetFromString)
else:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsWorksheetsFeedFromString)
def AddWorksheet(self, title, row_count, col_count, key):
"""Creates a new worksheet in the desired spreadsheet.
The new worksheet is appended to the end of the list of worksheets. The
new worksheet will only have the available number of columns and cells
specified.
Args:
title: str The title which will be displayed in the list of worksheets.
row_count: int or str The number of rows in the new worksheet.
col_count: int or str The number of columns in the new worksheet.
key: str The spreadsheet key to the spreadsheet to which the new
worksheet should be added.
Returns:
A SpreadsheetsWorksheet if the new worksheet was created succesfully.
"""
new_worksheet = gdata.spreadsheet.SpreadsheetsWorksheet(
title=atom.Title(text=title),
row_count=gdata.spreadsheet.RowCount(text=str(row_count)),
col_count=gdata.spreadsheet.ColCount(text=str(col_count)))
return self.Post(new_worksheet,
'http://%s/feeds/worksheets/%s/private/full' % (self.server, key),
converter=gdata.spreadsheet.SpreadsheetsWorksheetFromString)
def UpdateWorksheet(self, worksheet_entry, url=None):
"""Changes the size and/or title of the desired worksheet.
Args:
worksheet_entry: SpreadsheetWorksheet The new contents of the
worksheet.
url: str (optional) The URL to which the edited worksheet entry should
be sent. If the url is None, the edit URL from the worksheet will
be used.
Returns:
A SpreadsheetsWorksheet with the new information about the worksheet.
"""
target_url = url or worksheet_entry.GetEditLink().href
return self.Put(worksheet_entry, target_url,
converter=gdata.spreadsheet.SpreadsheetsWorksheetFromString)
def DeleteWorksheet(self, worksheet_entry=None, url=None):
"""Removes the desired worksheet from the spreadsheet
Args:
worksheet_entry: SpreadsheetWorksheet (optional) The worksheet to
be deleted. If this is none, then the DELETE reqest is sent to
the url specified in the url parameter.
url: str (optaional) The URL to which the DELETE request should be
sent. If left as None, the worksheet's edit URL is used.
Returns:
True if the worksheet was deleted successfully.
"""
if url:
target_url = url
else:
target_url = worksheet_entry.GetEditLink().href
return self.Delete(target_url)
def GetCellsFeed(self, key, wksht_id='default', cell=None, query=None,
visibility='private', projection='full'):
"""Gets a cells feed or a specific entry if a cell is defined
Args:
key: string The spreadsheet key defined in /ccc?key=
wksht_id: string The id for a specific worksheet entry
cell: string (optional) The R1C1 address of the cell
query: DocumentQuery (optional) Query parameters
Returns:
If there is no cell, then a SpreadsheetsCellsFeed.
If there is a cell, then a SpreadsheetsCell.
"""
uri = ('http://%s/feeds/cells/%s/%s/%s/%s'
% (self.server, key, wksht_id, visibility, projection))
if cell != None:
uri = '%s/%s' % (uri, cell)
if query != None:
query.feed = uri
uri = query.ToUri()
if cell:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsCellFromString)
else:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsCellsFeedFromString)
def GetListFeed(self, key, wksht_id='default', row_id=None, query=None,
visibility='private', projection='full'):
"""Gets a list feed or a specific entry if a row_id is defined
Args:
key: string The spreadsheet key defined in /ccc?key=
wksht_id: string The id for a specific worksheet entry
row_id: string (optional) The row_id of a row in the list
query: DocumentQuery (optional) Query parameters
Returns:
If there is no row_id, then a SpreadsheetsListFeed.
If there is a row_id, then a SpreadsheetsList.
"""
uri = ('http://%s/feeds/list/%s/%s/%s/%s'
% (self.server, key, wksht_id, visibility, projection))
if row_id is not None:
uri = '%s/%s' % (uri, row_id)
if query is not None:
query.feed = uri
uri = query.ToUri()
if row_id:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsListFromString)
else:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsListFeedFromString)
def UpdateCell(self, row, col, inputValue, key, wksht_id='default'):
"""Updates an existing cell.
Args:
row: int The row the cell to be editted is in
col: int The column the cell to be editted is in
inputValue: str the new value of the cell
key: str The key of the spreadsheet in which this cell resides.
wksht_id: str The ID of the worksheet which holds this cell.
Returns:
The updated cell entry
"""
row = str(row)
col = str(col)
# make the new cell
new_cell = gdata.spreadsheet.Cell(row=row, col=col, inputValue=inputValue)
# get the edit uri and PUT
cell = 'R%sC%s' % (row, col)
entry = self.GetCellsFeed(key, wksht_id, cell)
for a_link in entry.link:
if a_link.rel == 'edit':
entry.cell = new_cell
return self.Put(entry, a_link.href,
converter=gdata.spreadsheet.SpreadsheetsCellFromString)
def _GenerateCellsBatchUrl(self, spreadsheet_key, worksheet_id):
return ('http://spreadsheets.google.com/feeds/cells/%s/%s/'
'private/full/batch' % (spreadsheet_key, worksheet_id))
def ExecuteBatch(self, batch_feed, url=None, spreadsheet_key=None,
worksheet_id=None,
converter=gdata.spreadsheet.SpreadsheetsCellsFeedFromString):
"""Sends a batch request feed to the server.
The batch request needs to be sent to the batch URL for a particular
worksheet. You can specify the worksheet by providing the spreadsheet_key
and worksheet_id, or by sending the URL from the cells feed's batch link.
Args:
batch_feed: gdata.spreadsheet.SpreadsheetsCellFeed A feed containing
BatchEntry elements which contain the desired CRUD operation and
any necessary data to modify a cell.
url: str (optional) The batch URL for the cells feed to which these
changes should be applied. This can be found by calling
cells_feed.GetBatchLink().href.
spreadsheet_key: str (optional) Used to generate the batch request URL
if the url argument is None. If using the spreadsheet key to
generate the URL, the worksheet id is also required.
worksheet_id: str (optional) Used if the url is not provided, it is
oart of the batch feed target URL. This is used with the spreadsheet
key.
converter: Function (optional) Function to be executed on the server's
response. This function should take one string as a parameter. The
default value is SpreadsheetsCellsFeedFromString which will turn the result
into a gdata.base.GBaseItem object.
Returns:
A gdata.BatchFeed containing the results.
"""
if url is None:
url = self._GenerateCellsBatchUrl(spreadsheet_key, worksheet_id)
return self.Post(batch_feed, url, converter=converter)
def InsertRow(self, row_data, key, wksht_id='default'):
"""Inserts a new row with the provided data
Args:
uri: string The post uri of the list feed
row_data: dict A dictionary of column header to row data
Returns:
The inserted row
"""
new_entry = gdata.spreadsheet.SpreadsheetsList()
for k, v in row_data.iteritems():
new_custom = gdata.spreadsheet.Custom()
new_custom.column = k
new_custom.text = v
new_entry.custom[new_custom.column] = new_custom
# Generate the post URL for the worksheet which will receive the new entry.
post_url = 'http://spreadsheets.google.com/feeds/list/%s/%s/private/full'%(
key, wksht_id)
return self.Post(new_entry, post_url,
converter=gdata.spreadsheet.SpreadsheetsListFromString)
def UpdateRow(self, entry, new_row_data):
"""Updates a row with the provided data
Args:
entry: gdata.spreadsheet.SpreadsheetsList The entry to be updated
new_row_data: dict A dictionary of column header to row data
Returns:
The updated row
"""
entry.custom = {}
for k, v in new_row_data.iteritems():
new_custom = gdata.spreadsheet.Custom()
new_custom.column = k
new_custom.text = v
entry.custom[k] = new_custom
for a_link in entry.link:
if a_link.rel == 'edit':
return self.Put(entry, a_link.href,
converter=gdata.spreadsheet.SpreadsheetsListFromString)
def DeleteRow(self, entry):
"""Deletes a row, the provided entry
Args:
entry: gdata.spreadsheet.SpreadsheetsList The row to be deleted
Returns:
The delete response
"""
for a_link in entry.link:
if a_link.rel == 'edit':
return self.Delete(a_link.href)
class DocumentQuery(gdata.service.Query):
def _GetTitleQuery(self):
return self['title']
def _SetTitleQuery(self, document_query):
self['title'] = document_query
title = property(_GetTitleQuery, _SetTitleQuery,
doc="""The title query parameter""")
def _GetTitleExactQuery(self):
return self['title-exact']
def _SetTitleExactQuery(self, document_query):
self['title-exact'] = document_query
title_exact = property(_GetTitleExactQuery, _SetTitleExactQuery,
doc="""The title-exact query parameter""")
class CellQuery(gdata.service.Query):
def _GetMinRowQuery(self):
return self['min-row']
def _SetMinRowQuery(self, cell_query):
self['min-row'] = cell_query
min_row = property(_GetMinRowQuery, _SetMinRowQuery,
doc="""The min-row query parameter""")
def _GetMaxRowQuery(self):
return self['max-row']
def _SetMaxRowQuery(self, cell_query):
self['max-row'] = cell_query
max_row = property(_GetMaxRowQuery, _SetMaxRowQuery,
doc="""The max-row query parameter""")
def _GetMinColQuery(self):
return self['min-col']
def _SetMinColQuery(self, cell_query):
self['min-col'] = cell_query
min_col = property(_GetMinColQuery, _SetMinColQuery,
doc="""The min-col query parameter""")
def _GetMaxColQuery(self):
return self['max-col']
def _SetMaxColQuery(self, cell_query):
self['max-col'] = cell_query
max_col = property(_GetMaxColQuery, _SetMaxColQuery,
doc="""The max-col query parameter""")
def _GetRangeQuery(self):
return self['range']
def _SetRangeQuery(self, cell_query):
self['range'] = cell_query
range = property(_GetRangeQuery, _SetRangeQuery,
doc="""The range query parameter""")
def _GetReturnEmptyQuery(self):
return self['return-empty']
def _SetReturnEmptyQuery(self, cell_query):
self['return-empty'] = cell_query
return_empty = property(_GetReturnEmptyQuery, _SetReturnEmptyQuery,
doc="""The return-empty query parameter""")
class ListQuery(gdata.service.Query):
def _GetSpreadsheetQuery(self):
return self['sq']
def _SetSpreadsheetQuery(self, list_query):
self['sq'] = list_query
sq = property(_GetSpreadsheetQuery, _SetSpreadsheetQuery,
doc="""The sq query parameter""")
def _GetOrderByQuery(self):
return self['orderby']
def _SetOrderByQuery(self, list_query):
self['orderby'] = list_query
orderby = property(_GetOrderByQuery, _SetOrderByQuery,
doc="""The orderby query parameter""")
def _GetReverseQuery(self):
return self['reverse']
def _SetReverseQuery(self, list_query):
self['reverse'] = list_query
reverse = property(_GetReverseQuery, _SetReverseQuery,
doc="""The reverse query parameter""")
| Python |
#!/usr/bin/python
#
# Copyright (C) 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""SpreadsheetsService extends the GDataService to streamline Google
Spreadsheets operations.
GBaseService: Provides methods to query feeds and manipulate items. Extends
GDataService.
DictionaryToParamList: Function which converts a dictionary into a list of
URL arguments (represented as strings). This is a
utility function used in CRUD operations.
"""
__author__ = 'api.laurabeth@gmail.com (Laura Beth Lincoln)'
import gdata
import atom.service
import gdata.service
import gdata.spreadsheet
import atom
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class RequestError(Error):
pass
class SpreadsheetsService(gdata.service.GDataService):
"""Client for the Google Spreadsheets service."""
def __init__(self, email=None, password=None, source=None,
server='spreadsheets.google.com',
additional_headers=None):
gdata.service.GDataService.__init__(self, email=email, password=password,
service='wise', source=source,
server=server,
additional_headers=additional_headers)
def GetSpreadsheetsFeed(self, key=None, query=None, visibility='private',
projection='full'):
"""Gets a spreadsheets feed or a specific entry if a key is defined
Args:
key: string (optional) The spreadsheet key defined in /ccc?key=
query: DocumentQuery (optional) Query parameters
Returns:
If there is no key, then a SpreadsheetsSpreadsheetsFeed.
If there is a key, then a SpreadsheetsSpreadsheet.
"""
uri = ('http://%s/feeds/spreadsheets/%s/%s'
% (self.server, visibility, projection))
if key is not None:
uri = '%s/%s' % (uri, key)
if query != None:
query.feed = uri
uri = query.ToUri()
if key:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsSpreadsheetFromString)
else:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsSpreadsheetsFeedFromString)
def GetWorksheetsFeed(self, key, wksht_id=None, query=None,
visibility='private', projection='full'):
"""Gets a worksheets feed or a specific entry if a wksht is defined
Args:
key: string The spreadsheet key defined in /ccc?key=
wksht_id: string (optional) The id for a specific worksheet entry
query: DocumentQuery (optional) Query parameters
Returns:
If there is no wksht_id, then a SpreadsheetsWorksheetsFeed.
If there is a wksht_id, then a SpreadsheetsWorksheet.
"""
uri = ('http://%s/feeds/worksheets/%s/%s/%s'
% (self.server, key, visibility, projection))
if wksht_id != None:
uri = '%s/%s' % (uri, wksht_id)
if query != None:
query.feed = uri
uri = query.ToUri()
if wksht_id:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsWorksheetFromString)
else:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsWorksheetsFeedFromString)
def AddWorksheet(self, title, row_count, col_count, key):
"""Creates a new worksheet in the desired spreadsheet.
The new worksheet is appended to the end of the list of worksheets. The
new worksheet will only have the available number of columns and cells
specified.
Args:
title: str The title which will be displayed in the list of worksheets.
row_count: int or str The number of rows in the new worksheet.
col_count: int or str The number of columns in the new worksheet.
key: str The spreadsheet key to the spreadsheet to which the new
worksheet should be added.
Returns:
A SpreadsheetsWorksheet if the new worksheet was created succesfully.
"""
new_worksheet = gdata.spreadsheet.SpreadsheetsWorksheet(
title=atom.Title(text=title),
row_count=gdata.spreadsheet.RowCount(text=str(row_count)),
col_count=gdata.spreadsheet.ColCount(text=str(col_count)))
return self.Post(new_worksheet,
'http://%s/feeds/worksheets/%s/private/full' % (self.server, key),
converter=gdata.spreadsheet.SpreadsheetsWorksheetFromString)
def UpdateWorksheet(self, worksheet_entry, url=None):
"""Changes the size and/or title of the desired worksheet.
Args:
worksheet_entry: SpreadsheetWorksheet The new contents of the
worksheet.
url: str (optional) The URL to which the edited worksheet entry should
be sent. If the url is None, the edit URL from the worksheet will
be used.
Returns:
A SpreadsheetsWorksheet with the new information about the worksheet.
"""
target_url = url or worksheet_entry.GetEditLink().href
return self.Put(worksheet_entry, target_url,
converter=gdata.spreadsheet.SpreadsheetsWorksheetFromString)
def DeleteWorksheet(self, worksheet_entry=None, url=None):
"""Removes the desired worksheet from the spreadsheet
Args:
worksheet_entry: SpreadsheetWorksheet (optional) The worksheet to
be deleted. If this is none, then the DELETE reqest is sent to
the url specified in the url parameter.
url: str (optaional) The URL to which the DELETE request should be
sent. If left as None, the worksheet's edit URL is used.
Returns:
True if the worksheet was deleted successfully.
"""
if url:
target_url = url
else:
target_url = worksheet_entry.GetEditLink().href
return self.Delete(target_url)
def GetCellsFeed(self, key, wksht_id='default', cell=None, query=None,
visibility='private', projection='full'):
"""Gets a cells feed or a specific entry if a cell is defined
Args:
key: string The spreadsheet key defined in /ccc?key=
wksht_id: string The id for a specific worksheet entry
cell: string (optional) The R1C1 address of the cell
query: DocumentQuery (optional) Query parameters
Returns:
If there is no cell, then a SpreadsheetsCellsFeed.
If there is a cell, then a SpreadsheetsCell.
"""
uri = ('http://%s/feeds/cells/%s/%s/%s/%s'
% (self.server, key, wksht_id, visibility, projection))
if cell != None:
uri = '%s/%s' % (uri, cell)
if query != None:
query.feed = uri
uri = query.ToUri()
if cell:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsCellFromString)
else:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsCellsFeedFromString)
def GetListFeed(self, key, wksht_id='default', row_id=None, query=None,
visibility='private', projection='full'):
"""Gets a list feed or a specific entry if a row_id is defined
Args:
key: string The spreadsheet key defined in /ccc?key=
wksht_id: string The id for a specific worksheet entry
row_id: string (optional) The row_id of a row in the list
query: DocumentQuery (optional) Query parameters
Returns:
If there is no row_id, then a SpreadsheetsListFeed.
If there is a row_id, then a SpreadsheetsList.
"""
uri = ('http://%s/feeds/list/%s/%s/%s/%s'
% (self.server, key, wksht_id, visibility, projection))
if row_id is not None:
uri = '%s/%s' % (uri, row_id)
if query is not None:
query.feed = uri
uri = query.ToUri()
if row_id:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsListFromString)
else:
return self.Get(uri,
converter=gdata.spreadsheet.SpreadsheetsListFeedFromString)
def UpdateCell(self, row, col, inputValue, key, wksht_id='default'):
"""Updates an existing cell.
Args:
row: int The row the cell to be editted is in
col: int The column the cell to be editted is in
inputValue: str the new value of the cell
key: str The key of the spreadsheet in which this cell resides.
wksht_id: str The ID of the worksheet which holds this cell.
Returns:
The updated cell entry
"""
row = str(row)
col = str(col)
# make the new cell
new_cell = gdata.spreadsheet.Cell(row=row, col=col, inputValue=inputValue)
# get the edit uri and PUT
cell = 'R%sC%s' % (row, col)
entry = self.GetCellsFeed(key, wksht_id, cell)
for a_link in entry.link:
if a_link.rel == 'edit':
entry.cell = new_cell
return self.Put(entry, a_link.href,
converter=gdata.spreadsheet.SpreadsheetsCellFromString)
def _GenerateCellsBatchUrl(self, spreadsheet_key, worksheet_id):
return ('http://spreadsheets.google.com/feeds/cells/%s/%s/'
'private/full/batch' % (spreadsheet_key, worksheet_id))
def ExecuteBatch(self, batch_feed, url=None, spreadsheet_key=None,
worksheet_id=None,
converter=gdata.spreadsheet.SpreadsheetsCellsFeedFromString):
"""Sends a batch request feed to the server.
The batch request needs to be sent to the batch URL for a particular
worksheet. You can specify the worksheet by providing the spreadsheet_key
and worksheet_id, or by sending the URL from the cells feed's batch link.
Args:
batch_feed: gdata.spreadsheet.SpreadsheetsCellFeed A feed containing
BatchEntry elements which contain the desired CRUD operation and
any necessary data to modify a cell.
url: str (optional) The batch URL for the cells feed to which these
changes should be applied. This can be found by calling
cells_feed.GetBatchLink().href.
spreadsheet_key: str (optional) Used to generate the batch request URL
if the url argument is None. If using the spreadsheet key to
generate the URL, the worksheet id is also required.
worksheet_id: str (optional) Used if the url is not provided, it is
oart of the batch feed target URL. This is used with the spreadsheet
key.
converter: Function (optional) Function to be executed on the server's
response. This function should take one string as a parameter. The
default value is SpreadsheetsCellsFeedFromString which will turn the result
into a gdata.base.GBaseItem object.
Returns:
A gdata.BatchFeed containing the results.
"""
if url is None:
url = self._GenerateCellsBatchUrl(spreadsheet_key, worksheet_id)
return self.Post(batch_feed, url, converter=converter)
def InsertRow(self, row_data, key, wksht_id='default'):
"""Inserts a new row with the provided data
Args:
uri: string The post uri of the list feed
row_data: dict A dictionary of column header to row data
Returns:
The inserted row
"""
new_entry = gdata.spreadsheet.SpreadsheetsList()
for k, v in row_data.iteritems():
new_custom = gdata.spreadsheet.Custom()
new_custom.column = k
new_custom.text = v
new_entry.custom[new_custom.column] = new_custom
# Generate the post URL for the worksheet which will receive the new entry.
post_url = 'http://spreadsheets.google.com/feeds/list/%s/%s/private/full'%(
key, wksht_id)
return self.Post(new_entry, post_url,
converter=gdata.spreadsheet.SpreadsheetsListFromString)
def UpdateRow(self, entry, new_row_data):
"""Updates a row with the provided data
Args:
entry: gdata.spreadsheet.SpreadsheetsList The entry to be updated
new_row_data: dict A dictionary of column header to row data
Returns:
The updated row
"""
entry.custom = {}
for k, v in new_row_data.iteritems():
new_custom = gdata.spreadsheet.Custom()
new_custom.column = k
new_custom.text = v
entry.custom[k] = new_custom
for a_link in entry.link:
if a_link.rel == 'edit':
return self.Put(entry, a_link.href,
converter=gdata.spreadsheet.SpreadsheetsListFromString)
def DeleteRow(self, entry):
"""Deletes a row, the provided entry
Args:
entry: gdata.spreadsheet.SpreadsheetsList The row to be deleted
Returns:
The delete response
"""
for a_link in entry.link:
if a_link.rel == 'edit':
return self.Delete(a_link.href)
class DocumentQuery(gdata.service.Query):
def _GetTitleQuery(self):
return self['title']
def _SetTitleQuery(self, document_query):
self['title'] = document_query
title = property(_GetTitleQuery, _SetTitleQuery,
doc="""The title query parameter""")
def _GetTitleExactQuery(self):
return self['title-exact']
def _SetTitleExactQuery(self, document_query):
self['title-exact'] = document_query
title_exact = property(_GetTitleExactQuery, _SetTitleExactQuery,
doc="""The title-exact query parameter""")
class CellQuery(gdata.service.Query):
def _GetMinRowQuery(self):
return self['min-row']
def _SetMinRowQuery(self, cell_query):
self['min-row'] = cell_query
min_row = property(_GetMinRowQuery, _SetMinRowQuery,
doc="""The min-row query parameter""")
def _GetMaxRowQuery(self):
return self['max-row']
def _SetMaxRowQuery(self, cell_query):
self['max-row'] = cell_query
max_row = property(_GetMaxRowQuery, _SetMaxRowQuery,
doc="""The max-row query parameter""")
def _GetMinColQuery(self):
return self['min-col']
def _SetMinColQuery(self, cell_query):
self['min-col'] = cell_query
min_col = property(_GetMinColQuery, _SetMinColQuery,
doc="""The min-col query parameter""")
def _GetMaxColQuery(self):
return self['max-col']
def _SetMaxColQuery(self, cell_query):
self['max-col'] = cell_query
max_col = property(_GetMaxColQuery, _SetMaxColQuery,
doc="""The max-col query parameter""")
def _GetRangeQuery(self):
return self['range']
def _SetRangeQuery(self, cell_query):
self['range'] = cell_query
range = property(_GetRangeQuery, _SetRangeQuery,
doc="""The range query parameter""")
def _GetReturnEmptyQuery(self):
return self['return-empty']
def _SetReturnEmptyQuery(self, cell_query):
self['return-empty'] = cell_query
return_empty = property(_GetReturnEmptyQuery, _SetReturnEmptyQuery,
doc="""The return-empty query parameter""")
class ListQuery(gdata.service.Query):
def _GetSpreadsheetQuery(self):
return self['sq']
def _SetSpreadsheetQuery(self, list_query):
self['sq'] = list_query
sq = property(_GetSpreadsheetQuery, _SetSpreadsheetQuery,
doc="""The sq query parameter""")
def _GetOrderByQuery(self):
return self['orderby']
def _SetOrderByQuery(self, list_query):
self['orderby'] = list_query
orderby = property(_GetOrderByQuery, _SetOrderByQuery,
doc="""The orderby query parameter""")
def _GetReverseQuery(self):
return self['reverse']
def _SetReverseQuery(self, list_query):
self['reverse'] = list_query
reverse = property(_GetReverseQuery, _SetReverseQuery,
doc="""The reverse query parameter""")
| Python |
#!/usr/bin/python
#
# Copyright Google 2007-2008, all rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import StringIO
import gdata
import gdata.service
import gdata.spreadsheet
import gdata.spreadsheet.service
import gdata.docs
import gdata.docs.service
"""Make the Google Documents API feel more like using a database.
This module contains a client and other classes which make working with the
Google Documents List Data API and the Google Spreadsheets Data API look a
bit more like working with a heirarchical database. Using the DatabaseClient,
you can create or find spreadsheets and use them like a database, with
worksheets representing tables and rows representing records.
Example Usage:
# Create a new database, a new table, and add records.
client = gdata.spreadsheet.text_db.DatabaseClient(username='jo@example.com',
password='12345')
database = client.CreateDatabase('My Text Database')
table = database.CreateTable('addresses', ['name','email',
'phonenumber', 'mailingaddress'])
record = table.AddRecord({'name':'Bob', 'email':'bob@example.com',
'phonenumber':'555-555-1234', 'mailingaddress':'900 Imaginary St.'})
# Edit a record
record.content['email'] = 'bob2@example.com'
record.Push()
# Delete a table
table.Delete
Warnings:
Care should be exercised when using this module on spreadsheets
which contain formulas. This module treats all rows as containing text and
updating a row will overwrite any formula with the output of the formula.
The intended use case is to allow easy storage of text data in a spreadsheet.
Error: Domain specific extension of Exception.
BadCredentials: Error raised is username or password was incorrect.
CaptchaRequired: Raised if a login attempt failed and a CAPTCHA challenge
was issued.
DatabaseClient: Communicates with Google Docs APIs servers.
Database: Represents a spreadsheet and interacts with tables.
Table: Represents a worksheet and interacts with records.
RecordResultSet: A list of records in a table.
Record: Represents a row in a worksheet allows manipulation of text data.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
class Error(Exception):
pass
class BadCredentials(Error):
pass
class CaptchaRequired(Error):
pass
class DatabaseClient(object):
"""Allows creation and finding of Google Spreadsheets databases.
The DatabaseClient simplifies the process of creating and finding Google
Spreadsheets and will talk to both the Google Spreadsheets API and the
Google Documents List API.
"""
def __init__(self, username=None, password=None):
"""Constructor for a Database Client.
If the username and password are present, the constructor will contact
the Google servers to authenticate.
Args:
username: str (optional) Example: jo@example.com
password: str (optional)
"""
self.__docs_client = gdata.docs.service.DocsService()
self.__spreadsheets_client = (
gdata.spreadsheet.service.SpreadsheetsService())
self.SetCredentials(username, password)
def SetCredentials(self, username, password):
"""Attempts to log in to Google APIs using the provided credentials.
If the username or password are None, the client will not request auth
tokens.
Args:
username: str (optional) Example: jo@example.com
password: str (optional)
"""
self.__docs_client.email = username
self.__docs_client.password = password
self.__spreadsheets_client.email = username
self.__spreadsheets_client.password = password
if username and password:
try:
self.__docs_client.ProgrammaticLogin()
self.__spreadsheets_client.ProgrammaticLogin()
except gdata.service.CaptchaRequired:
raise CaptchaRequired('Please visit https://www.google.com/accounts/'
'DisplayUnlockCaptcha to unlock your account.')
except gdata.service.BadAuthentication:
raise BadCredentials('Username or password incorrect.')
def CreateDatabase(self, name):
"""Creates a new Google Spreadsheet with the desired name.
Args:
name: str The title for the spreadsheet.
Returns:
A Database instance representing the new spreadsheet.
"""
# Create a Google Spreadsheet to form the foundation of this database.
# Spreadsheet is created by uploading a file to the Google Documents
# List API.
virtual_csv_file = StringIO.StringIO(',,,')
virtual_media_source = gdata.MediaSource(file_handle=virtual_csv_file, content_type='text/csv', content_length=3)
db_entry = self.__docs_client.UploadSpreadsheet(virtual_media_source, name)
return Database(spreadsheet_entry=db_entry, database_client=self)
def GetDatabases(self, spreadsheet_key=None, name=None):
"""Finds spreadsheets which have the unique key or title.
If querying on the spreadsheet_key there will be at most one result, but
searching by name could yield multiple results.
Args:
spreadsheet_key: str The unique key for the spreadsheet, this
usually in the the form 'pk23...We' or 'o23...423.12,,,3'.
name: str The title of the spreadsheets.
Returns:
A list of Database objects representing the desired spreadsheets.
"""
if spreadsheet_key:
db_entry = self.__docs_client.GetDocumentListEntry(
r'/feeds/documents/private/full/spreadsheet%3A' + spreadsheet_key)
return [Database(spreadsheet_entry=db_entry, database_client=self)]
else:
title_query = gdata.docs.service.DocumentQuery()
title_query['title'] = name
db_feed = self.__docs_client.QueryDocumentListFeed(title_query.ToUri())
matching_databases = []
for entry in db_feed.entry:
matching_databases.append(Database(spreadsheet_entry=entry,
database_client=self))
return matching_databases
def _GetDocsClient(self):
return self.__docs_client
def _GetSpreadsheetsClient(self):
return self.__spreadsheets_client
class Database(object):
"""Provides interface to find and create tables.
The database represents a Google Spreadsheet.
"""
def __init__(self, spreadsheet_entry=None, database_client=None):
"""Constructor for a database object.
Args:
spreadsheet_entry: gdata.docs.DocumentListEntry The
Atom entry which represents the Google Spreadsheet. The
spreadsheet's key is extracted from the entry and stored as a
member.
database_client: DatabaseClient A client which can talk to the
Google Spreadsheets servers to perform operations on worksheets
within this spreadsheet.
"""
self.entry = spreadsheet_entry
if self.entry:
id_parts = spreadsheet_entry.id.text.split('/')
self.spreadsheet_key = id_parts[-1].replace('spreadsheet%3A', '')
self.client = database_client
def CreateTable(self, name, fields=None):
"""Add a new worksheet to this spreadsheet and fill in column names.
Args:
name: str The title of the new worksheet.
fields: list of strings The column names which are placed in the
first row of this worksheet. These names are converted into XML
tags by the server. To avoid changes during the translation
process I recommend using all lowercase alphabetic names. For
example ['somelongname', 'theothername']
Returns:
Table representing the newly created worksheet.
"""
worksheet = self.client._GetSpreadsheetsClient().AddWorksheet(title=name,
row_count=1, col_count=len(fields), key=self.spreadsheet_key)
return Table(name=name, worksheet_entry=worksheet,
database_client=self.client,
spreadsheet_key=self.spreadsheet_key, fields=fields)
def GetTables(self, worksheet_id=None, name=None):
"""Searches for a worksheet with the specified ID or name.
The list of results should have one table at most, or no results
if the id or name were not found.
Args:
worksheet_id: str The ID of the worksheet, example: 'od6'
name: str The title of the worksheet.
Returns:
A list of length 0 or 1 containing the desired Table. A list is returned
to make this method feel like GetDatabases and GetRecords.
"""
if worksheet_id:
worksheet_entry = self.client._GetSpreadsheetsClient().GetWorksheetsFeed(
self.spreadsheet_key, wksht_id=worksheet_id)
return [Table(name=worksheet_entry.title.text,
worksheet_entry=worksheet_entry, database_client=self.client,
spreadsheet_key=self.spreadsheet_key)]
else:
matching_tables = []
title_query = gdata.spreadsheet.service.DocumentQuery()
title_query.title = name
worksheet_feed = self.client._GetSpreadsheetsClient().GetWorksheetsFeed(
self.spreadsheet_key, query=title_query)
for entry in worksheet_feed.entry:
matching_tables.append(Table(name=entry.title.text,
worksheet_entry=entry, database_client=self.client,
spreadsheet_key=self.spreadsheet_key))
return matching_tables
def Delete(self):
"""Deletes the entire database spreadsheet from Google Spreadsheets."""
entry = self.client._GetDocsClient().Get(
r'http://docs.google.com/feeds/documents/private/full/spreadsheet%3A' +
self.spreadsheet_key)
self.client._GetDocsClient().Delete(entry.GetEditLink().href)
class Table(object):
def __init__(self, name=None, worksheet_entry=None, database_client=None,
spreadsheet_key=None, fields=None):
self.name = name
self.entry = worksheet_entry
id_parts = worksheet_entry.id.text.split('/')
self.worksheet_id = id_parts[-1]
self.spreadsheet_key = spreadsheet_key
self.client = database_client
self.fields = fields or []
if fields:
self.SetFields(fields)
def LookupFields(self):
"""Queries to find the column names in the first row of the worksheet.
Useful when you have retrieved the table from the server and you don't
know the column names.
"""
if self.entry:
first_row_contents = []
query = gdata.spreadsheet.service.CellQuery()
query.max_row = '1'
query.min_row = '1'
feed = self.client._GetSpreadsheetsClient().GetCellsFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id, query=query)
for entry in feed.entry:
first_row_contents.append(entry.content.text)
# Get the next set of cells if needed.
next_link = feed.GetNextLink()
while next_link:
feed = self.client._GetSpreadsheetsClient().Get(next_link.href,
converter=gdata.spreadsheet.SpreadsheetsCellsFeedFromString)
for entry in feed.entry:
first_row_contents.append(entry.content.text)
next_link = feed.GetNextLink()
# Convert the contents of the cells to valid headers.
self.fields = ConvertStringsToColumnHeaders(first_row_contents)
def SetFields(self, fields):
"""Changes the contents of the cells in the first row of this worksheet.
Args:
fields: list of strings The names in the list comprise the
first row of the worksheet. These names are converted into XML
tags by the server. To avoid changes during the translation
process I recommend using all lowercase alphabetic names. For
example ['somelongname', 'theothername']
"""
# TODO: If the table already had fields, we might want to clear out the,
# current column headers.
self.fields = fields
i = 0
for column_name in fields:
i = i + 1
# TODO: speed this up by using a batch request to update cells.
self.client._GetSpreadsheetsClient().UpdateCell(1, i, column_name,
self.spreadsheet_key, self.worksheet_id)
def Delete(self):
"""Deletes this worksheet from the spreadsheet."""
worksheet = self.client._GetSpreadsheetsClient().GetWorksheetsFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id)
self.client._GetSpreadsheetsClient().DeleteWorksheet(
worksheet_entry=worksheet)
def AddRecord(self, data):
"""Adds a new row to this worksheet.
Args:
data: dict of strings Mapping of string values to column names.
Returns:
Record which represents this row of the spreadsheet.
"""
new_row = self.client._GetSpreadsheetsClient().InsertRow(data,
self.spreadsheet_key, wksht_id=self.worksheet_id)
return Record(content=data, row_entry=new_row,
spreadsheet_key=self.spreadsheet_key, worksheet_id=self.worksheet_id,
database_client=self.client)
def GetRecord(self, row_id=None, row_number=None):
"""Gets a single record from the worksheet based on row ID or number.
Args:
row_id: The ID for the individual row.
row_number: str or int The position of the desired row. Numbering
begins at 1, which refers to the second row in the worksheet since
the first row is used for column names.
Returns:
Record for the desired row.
"""
if row_id:
row_entry = self.client._GetSpreadsheetsClient().GetListFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id, row_id=row_id)
return Record(content=None, row_entry=row_entry,
spreadsheet_key=self.spreadsheet_key,
worksheet_id=self.worksheet_id, database_client=self.client)
else:
row_query = gdata.spreadsheet.service.ListQuery()
row_query.start_index = str(row_number)
row_query.max_results = '1'
row_feed = self.client._GetSpreadsheetsClient().GetListFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id, query=row_query)
if len(row_feed.entry) >= 1:
return Record(content=None, row_entry=row_feed.entry[0],
spreadsheet_key=self.spreadsheet_key,
worksheet_id=self.worksheet_id, database_client=self.client)
else:
return None
def GetRecords(self, start_row, end_row):
"""Gets all rows between the start and end row numbers inclusive.
Args:
start_row: str or int
end_row: str or int
Returns:
RecordResultSet for the desired rows.
"""
start_row = int(start_row)
end_row = int(end_row)
max_rows = end_row - start_row + 1
row_query = gdata.spreadsheet.service.ListQuery()
row_query.start_index = str(start_row)
row_query.max_results = str(max_rows)
rows_feed = self.client._GetSpreadsheetsClient().GetListFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id, query=row_query)
return RecordResultSet(rows_feed, self.client, self.spreadsheet_key,
self.worksheet_id)
def FindRecords(self, query_string):
"""Performs a query against the worksheet to find rows which match.
For details on query string syntax see the section on sq under
http://code.google.com/apis/spreadsheets/reference.html#list_Parameters
Args:
query_string: str Examples: 'name == john' to find all rows with john
in the name column, '(cost < 19.50 and name != toy) or cost > 500'
Returns:
RecordResultSet with the first group of matches.
"""
row_query = gdata.spreadsheet.service.ListQuery()
row_query.sq = query_string
matching_feed = self.client._GetSpreadsheetsClient().GetListFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id, query=row_query)
return RecordResultSet(matching_feed, self.client,
self.spreadsheet_key, self.worksheet_id)
class RecordResultSet(list):
"""A collection of rows which allows fetching of the next set of results.
The server may not send all rows in the requested range because there are
too many. Using this result set you can access the first set of results
as if it is a list, then get the next batch (if there are more results) by
calling GetNext().
"""
def __init__(self, feed, client, spreadsheet_key, worksheet_id):
self.client = client
self.spreadsheet_key = spreadsheet_key
self.worksheet_id = worksheet_id
self.feed = feed
list(self)
for entry in self.feed.entry:
self.append(Record(content=None, row_entry=entry,
spreadsheet_key=spreadsheet_key, worksheet_id=worksheet_id,
database_client=client))
def GetNext(self):
"""Fetches the next batch of rows in the result set.
Returns:
A new RecordResultSet.
"""
next_link = self.feed.GetNextLink()
if next_link and next_link.href:
new_feed = self.client._GetSpreadsheetsClient().Get(next_link.href,
converter=gdata.spreadsheet.SpreadsheetsListFeedFromString)
return RecordResultSet(new_feed, self.client, self.spreadsheet_key,
self.worksheet_id)
class Record(object):
"""Represents one row in a worksheet and provides a dictionary of values.
Attributes:
custom: dict Represents the contents of the row with cell values mapped
to column headers.
"""
def __init__(self, content=None, row_entry=None, spreadsheet_key=None,
worksheet_id=None, database_client=None):
"""Constructor for a record.
Args:
content: dict of strings Mapping of string values to column names.
row_entry: gdata.spreadsheet.SpreadsheetsList The Atom entry
representing this row in the worksheet.
spreadsheet_key: str The ID of the spreadsheet in which this row
belongs.
worksheet_id: str The ID of the worksheet in which this row belongs.
database_client: DatabaseClient The client which can be used to talk
the Google Spreadsheets server to edit this row.
"""
self.entry = row_entry
self.spreadsheet_key = spreadsheet_key
self.worksheet_id = worksheet_id
if row_entry:
self.row_id = row_entry.id.text.split('/')[-1]
else:
self.row_id = None
self.client = database_client
self.content = content or {}
if not content:
self.ExtractContentFromEntry(row_entry)
def ExtractContentFromEntry(self, entry):
"""Populates the content and row_id based on content of the entry.
This method is used in the Record's contructor.
Args:
entry: gdata.spreadsheet.SpreadsheetsList The Atom entry
representing this row in the worksheet.
"""
self.content = {}
if entry:
self.row_id = entry.id.text.split('/')[-1]
for label, custom in entry.custom.iteritems():
self.content[label] = custom.text
def Push(self):
"""Send the content of the record to spreadsheets to edit the row.
All items in the content dictionary will be sent. Items which have been
removed from the content may remain in the row. The content member
of the record will not be modified so additional fields in the row
might be absent from this local copy.
"""
self.entry = self.client._GetSpreadsheetsClient().UpdateRow(self.entry, self.content)
def Pull(self):
"""Query Google Spreadsheets to get the latest data from the server.
Fetches the entry for this row and repopulates the content dictionary
with the data found in the row.
"""
if self.row_id:
self.entry = self.client._GetSpreadsheetsClient().GetListFeed(
self.spreadsheet_key, wksht_id=self.worksheet_id, row_id=self.row_id)
self.ExtractContentFromEntry(self.entry)
def Delete(self):
self.client._GetSpreadsheetsClient().DeleteRow(self.entry)
def ConvertStringsToColumnHeaders(proposed_headers):
"""Converts a list of strings to column names which spreadsheets accepts.
When setting values in a record, the keys which represent column names must
fit certain rules. They are all lower case, contain no spaces or special
characters. If two columns have the same name after being sanitized, the
columns further to the right have _2, _3 _4, etc. appended to them.
If there are column names which consist of all special characters, or if
the column header is blank, an obfuscated value will be used for a column
name. This method does not handle blank column names or column names with
only special characters.
"""
headers = []
for input_string in proposed_headers:
# TODO: probably a more efficient way to do this. Perhaps regex.
sanitized = input_string.lower().replace('_', '').replace(
':', '').replace(' ', '')
# When the same sanitized header appears multiple times in the first row
# of a spreadsheet, _n is appended to the name to make it unique.
header_count = headers.count(sanitized)
if header_count > 0:
headers.append('%s_%i' % (sanitized, header_count+1))
else:
headers.append(sanitized)
return headers
| Python |
#!/usr/bin/python
#
# Copyright (C) 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to Atom objects used with Google Spreadsheets.
"""
__author__ = 'api.laurabeth@gmail.com (Laura Beth Lincoln)'
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import atom
import gdata
import re
import string
# XML namespaces which are often used in Google Spreadsheets entities.
GSPREADSHEETS_NAMESPACE = 'http://schemas.google.com/spreadsheets/2006'
GSPREADSHEETS_TEMPLATE = '{http://schemas.google.com/spreadsheets/2006}%s'
GSPREADSHEETS_EXTENDED_NAMESPACE = ('http://schemas.google.com/spreadsheets'
'/2006/extended')
GSPREADSHEETS_EXTENDED_TEMPLATE = ('{http://schemas.google.com/spreadsheets'
'/2006/extended}%s')
class ColCount(atom.AtomBase):
"""The Google Spreadsheets colCount element """
_tag = 'colCount'
_namespace = GSPREADSHEETS_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ColCountFromString(xml_string):
return atom.CreateClassFromXMLString(ColCount, xml_string)
class RowCount(atom.AtomBase):
"""The Google Spreadsheets rowCount element """
_tag = 'rowCount'
_namespace = GSPREADSHEETS_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def RowCountFromString(xml_string):
return atom.CreateClassFromXMLString(RowCount, xml_string)
class Cell(atom.AtomBase):
"""The Google Spreadsheets cell element """
_tag = 'cell'
_namespace = GSPREADSHEETS_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['row'] = 'row'
_attributes['col'] = 'col'
_attributes['inputValue'] = 'inputValue'
_attributes['numericValue'] = 'numericValue'
def __init__(self, text=None, row=None, col=None, inputValue=None,
numericValue=None, extension_elements=None, extension_attributes=None):
self.text = text
self.row = row
self.col = col
self.inputValue = inputValue
self.numericValue = numericValue
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def CellFromString(xml_string):
return atom.CreateClassFromXMLString(Cell, xml_string)
class Custom(atom.AtomBase):
"""The Google Spreadsheets custom element"""
_namespace = GSPREADSHEETS_EXTENDED_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, column=None, text=None, extension_elements=None,
extension_attributes=None):
self.column = column # The name of the column
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def _BecomeChildElement(self, tree):
new_child = ElementTree.Element('')
tree.append(new_child)
new_child.tag = '{%s}%s' % (self.__class__._namespace,
self.column)
self._AddMembersToElementTree(new_child)
def _ToElementTree(self):
new_tree = ElementTree.Element('{%s}%s' % (self.__class__._namespace,
self.column))
self._AddMembersToElementTree(new_tree)
return new_tree
def _HarvestElementTree(self, tree):
namespace_uri, local_tag = string.split(tree.tag[1:], "}", 1)
self.column = local_tag
# Fill in the instance members from the contents of the XML tree.
for child in tree:
self._ConvertElementTreeToMember(child)
for attribute, value in tree.attrib.iteritems():
self._ConvertElementAttributeToMember(attribute, value)
self.text = tree.text
def CustomFromString(xml_string):
element_tree = ElementTree.fromstring(xml_string)
return _CustomFromElementTree(element_tree)
def _CustomFromElementTree(element_tree):
namespace_uri, local_tag = string.split(element_tree.tag[1:], "}", 1)
if namespace_uri == GSPREADSHEETS_EXTENDED_NAMESPACE:
new_custom = Custom()
new_custom._HarvestElementTree(element_tree)
new_custom.column = local_tag
return new_custom
return None
class SpreadsheetsSpreadsheet(gdata.GDataEntry):
"""A Google Spreadsheets flavor of a Spreadsheet Atom Entry """
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, control=None, updated=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.control = control
self.title = title
self.updated = updated
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SpreadsheetsSpreadsheetFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsSpreadsheet,
xml_string)
class SpreadsheetsWorksheet(gdata.GDataEntry):
"""A Google Spreadsheets flavor of a Worksheet Atom Entry """
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}rowCount' % GSPREADSHEETS_NAMESPACE] = ('row_count',
RowCount)
_children['{%s}colCount' % GSPREADSHEETS_NAMESPACE] = ('col_count',
ColCount)
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, control=None, updated=None,
row_count=None, col_count=None, text=None, extension_elements=None,
extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.control = control
self.title = title
self.updated = updated
self.row_count = row_count
self.col_count = col_count
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SpreadsheetsWorksheetFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsWorksheet,
xml_string)
class SpreadsheetsCell(gdata.BatchEntry):
"""A Google Spreadsheets flavor of a Cell Atom Entry """
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.BatchEntry._children.copy()
_attributes = gdata.BatchEntry._attributes.copy()
_children['{%s}cell' % GSPREADSHEETS_NAMESPACE] = ('cell', Cell)
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, control=None, updated=None,
cell=None, batch_operation=None, batch_id=None, batch_status=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.control = control
self.title = title
self.batch_operation = batch_operation
self.batch_id = batch_id
self.batch_status = batch_status
self.updated = updated
self.cell = cell
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SpreadsheetsCellFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsCell,
xml_string)
class SpreadsheetsList(gdata.GDataEntry):
"""A Google Spreadsheets flavor of a List Atom Entry """
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, title=None, control=None, updated=None,
custom=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.control = control
self.title = title
self.updated = updated
self.custom = custom or {}
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
# We need to overwrite _ConvertElementTreeToMember to add special logic to
# convert custom attributes to members
def _ConvertElementTreeToMember(self, child_tree):
# Find the element's tag in this class's list of child members
if self.__class__._children.has_key(child_tree.tag):
member_name = self.__class__._children[child_tree.tag][0]
member_class = self.__class__._children[child_tree.tag][1]
# If the class member is supposed to contain a list, make sure the
# matching member is set to a list, then append the new member
# instance to the list.
if isinstance(member_class, list):
if getattr(self, member_name) is None:
setattr(self, member_name, [])
getattr(self, member_name).append(atom._CreateClassFromElementTree(
member_class[0], child_tree))
else:
setattr(self, member_name,
atom._CreateClassFromElementTree(member_class, child_tree))
elif child_tree.tag.find('{%s}' % GSPREADSHEETS_EXTENDED_NAMESPACE) == 0:
# If this is in the custom namespace, make add it to the custom dict.
name = child_tree.tag[child_tree.tag.index('}')+1:]
custom = _CustomFromElementTree(child_tree)
if custom:
self.custom[name] = custom
else:
ExtensionContainer._ConvertElementTreeToMember(self, child_tree)
# We need to overwtite _AddMembersToElementTree to add special logic to
# convert custom members to XML nodes.
def _AddMembersToElementTree(self, tree):
# Convert the members of this class which are XML child nodes.
# This uses the class's _children dictionary to find the members which
# should become XML child nodes.
member_node_names = [values[0] for tag, values in
self.__class__._children.iteritems()]
for member_name in member_node_names:
member = getattr(self, member_name)
if member is None:
pass
elif isinstance(member, list):
for instance in member:
instance._BecomeChildElement(tree)
else:
member._BecomeChildElement(tree)
# Convert the members of this class which are XML attributes.
for xml_attribute, member_name in self.__class__._attributes.iteritems():
member = getattr(self, member_name)
if member is not None:
tree.attrib[xml_attribute] = member
# Convert all special custom item attributes to nodes
for name, custom in self.custom.iteritems():
custom._BecomeChildElement(tree)
# Lastly, call the ExtensionContainers's _AddMembersToElementTree to
# convert any extension attributes.
atom.ExtensionContainer._AddMembersToElementTree(self, tree)
def SpreadsheetsListFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsList,
xml_string)
element_tree = ElementTree.fromstring(xml_string)
return _SpreadsheetsListFromElementTree(element_tree)
class SpreadsheetsSpreadsheetsFeed(gdata.GDataFeed):
"""A feed containing Google Spreadsheets Spreadsheets"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[SpreadsheetsSpreadsheet])
def SpreadsheetsSpreadsheetsFeedFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsSpreadsheetsFeed,
xml_string)
class SpreadsheetsWorksheetsFeed(gdata.GDataFeed):
"""A feed containing Google Spreadsheets Spreadsheets"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[SpreadsheetsWorksheet])
def SpreadsheetsWorksheetsFeedFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsWorksheetsFeed,
xml_string)
class SpreadsheetsCellsFeed(gdata.BatchFeed):
"""A feed containing Google Spreadsheets Cells"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.BatchFeed._children.copy()
_attributes = gdata.BatchFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[SpreadsheetsCell])
_children['{%s}rowCount' % GSPREADSHEETS_NAMESPACE] = ('row_count',
RowCount)
_children['{%s}colCount' % GSPREADSHEETS_NAMESPACE] = ('col_count',
ColCount)
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None,
entry=None, total_results=None, start_index=None,
items_per_page=None, extension_elements=None,
extension_attributes=None, text=None, row_count=None,
col_count=None, interrupted=None):
gdata.BatchFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text, interrupted=interrupted)
self.row_count = row_count
self.col_count = col_count
def GetBatchLink(self):
for link in self.link:
if link.rel == 'http://schemas.google.com/g/2005#batch':
return link
return None
def SpreadsheetsCellsFeedFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsCellsFeed,
xml_string)
class SpreadsheetsListFeed(gdata.GDataFeed):
"""A feed containing Google Spreadsheets Spreadsheets"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[SpreadsheetsList])
def SpreadsheetsListFeedFromString(xml_string):
return atom.CreateClassFromXMLString(SpreadsheetsListFeed,
xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains classes representing Atom elements.
Module objective: provide data classes for Atom constructs. These classes hide
the XML-ness of Atom and provide a set of native Python classes to interact
with.
Conversions to and from XML should only be necessary when the Atom classes
"touch the wire" and are sent over HTTP. For this reason this module
provides methods and functions to convert Atom classes to and from strings.
For more information on the Atom data model, see RFC 4287
(http://www.ietf.org/rfc/rfc4287.txt)
AtomBase: A foundation class on which Atom classes are built. It
handles the parsing of attributes and children which are common to all
Atom classes. By default, the AtomBase class translates all XML child
nodes into ExtensionElements.
ExtensionElement: Atom allows Atom objects to contain XML which is not part
of the Atom specification, these are called extension elements. If a
classes parser encounters an unexpected XML construct, it is translated
into an ExtensionElement instance. ExtensionElement is designed to fully
capture the information in the XML. Child nodes in an XML extension are
turned into ExtensionElements as well.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
# XML namespaces which are often used in Atom entities.
ATOM_NAMESPACE = 'http://www.w3.org/2005/Atom'
ELEMENT_TEMPLATE = '{http://www.w3.org/2005/Atom}%s'
APP_NAMESPACE = 'http://purl.org/atom/app#'
APP_TEMPLATE = '{http://purl.org/atom/app#}%s'
# This encoding is used for converting strings before translating the XML
# into an object.
XML_STRING_ENCODING = 'utf-8'
# The desired string encoding for object members.
MEMBER_STRING_ENCODING = 'utf-8'
def CreateClassFromXMLString(target_class, xml_string, string_encoding=None):
"""Creates an instance of the target class from the string contents.
Args:
target_class: class The class which will be instantiated and populated
with the contents of the XML. This class must have a _tag and a
_namespace class variable.
xml_string: str A string which contains valid XML. The root element
of the XML string should match the tag and namespace of the desired
class.
string_encoding: str The character encoding which the xml_string should
be converted to before it is interpreted and translated into
objects. The default is None in which case the string encoding
is not changed.
Returns:
An instance of the target class with members assigned according to the
contents of the XML - or None if the root XML tag and namespace did not
match those of the target class.
"""
encoding = string_encoding or XML_STRING_ENCODING
if encoding and isinstance(xml_string, unicode):
xml_string = xml_string.encode(encoding)
tree = ElementTree.fromstring(xml_string)
return _CreateClassFromElementTree(target_class, tree)
def _CreateClassFromElementTree(target_class, tree, namespace=None, tag=None):
"""Instantiates the class and populates members according to the tree.
Note: Only use this function with classes that have _namespace and _tag
class members.
Args:
target_class: class The class which will be instantiated and populated
with the contents of the XML.
tree: ElementTree An element tree whose contents will be converted into
members of the new target_class instance.
namespace: str (optional) The namespace which the XML tree's root node must
match. If omitted, the namespace defaults to the _namespace of the
target class.
tag: str (optional) The tag which the XML tree's root node must match. If
omitted, the tag defaults to the _tag class member of the target
class.
Returns:
An instance of the target class - or None if the tag and namespace of
the XML tree's root node did not match the desired namespace and tag.
"""
if namespace is None:
namespace = target_class._namespace
if tag is None:
tag = target_class._tag
if tree.tag == '{%s}%s' % (namespace, tag):
target = target_class()
target._HarvestElementTree(tree)
return target
else:
return None
class ExtensionContainer(object):
def __init__(self, extension_elements=None, extension_attributes=None,
text=None):
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
# Three methods to create an object from an ElementTree
def _HarvestElementTree(self, tree):
# Fill in the instance members from the contents of the XML tree.
for child in tree:
self._ConvertElementTreeToMember(child)
for attribute, value in tree.attrib.iteritems():
self._ConvertElementAttributeToMember(attribute, value)
# Encode the text string according to the desired encoding type. (UTF-8)
if tree.text:
self.text = tree.text.encode(MEMBER_STRING_ENCODING)
def _ConvertElementTreeToMember(self, child_tree, current_class=None):
self.extension_elements.append(_ExtensionElementFromElementTree(
child_tree))
def _ConvertElementAttributeToMember(self, attribute, value):
# Encode the attribute value's string with the desired type Default UTF-8
if value:
self.extension_attributes[attribute] = value.encode(
MEMBER_STRING_ENCODING)
# One method to create an ElementTree from an object
def _AddMembersToElementTree(self, tree):
for child in self.extension_elements:
child._BecomeChildElement(tree)
for attribute, value in self.extension_attributes.iteritems():
if value:
# Decode the value from the desired encoding (default UTF-8).
tree.attrib[attribute] = value.decode(MEMBER_STRING_ENCODING)
if self.text and not isinstance(self.text, unicode):
tree.text = self.text.decode(MEMBER_STRING_ENCODING)
else:
tree.text = self.text
def FindExtensions(self, tag=None, namespace=None):
"""Searches extension elements for child nodes with the desired name.
Returns a list of extension elements within this object whose tag
and/or namespace match those passed in. To find all extensions in
a particular namespace, specify the namespace but not the tag name.
If you specify only the tag, the result list may contain extension
elements in multiple namespaces.
Args:
tag: str (optional) The desired tag
namespace: str (optional) The desired namespace
Returns:
A list of elements whose tag and/or namespace match the parameters
values
"""
results = []
if tag and namespace:
for element in self.extension_elements:
if element.tag == tag and element.namespace == namespace:
results.append(element)
elif tag and not namespace:
for element in self.extension_elements:
if element.tag == tag:
results.append(element)
elif namespace and not tag:
for element in self.extension_elements:
if element.namespace == namespace:
results.append(element)
else:
for element in self.extension_elements:
results.append(element)
return results
class AtomBase(ExtensionContainer):
_children = {}
_attributes = {}
def __init__(self, extension_elements=None, extension_attributes=None,
text=None):
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
def _ConvertElementTreeToMember(self, child_tree):
# Find the element's tag in this class's list of child members
if self.__class__._children.has_key(child_tree.tag):
member_name = self.__class__._children[child_tree.tag][0]
member_class = self.__class__._children[child_tree.tag][1]
# If the class member is supposed to contain a list, make sure the
# matching member is set to a list, then append the new member
# instance to the list.
if isinstance(member_class, list):
if getattr(self, member_name) is None:
setattr(self, member_name, [])
getattr(self, member_name).append(_CreateClassFromElementTree(
member_class[0], child_tree))
else:
setattr(self, member_name,
_CreateClassFromElementTree(member_class, child_tree))
else:
ExtensionContainer._ConvertElementTreeToMember(self, child_tree)
def _ConvertElementAttributeToMember(self, attribute, value):
# Find the attribute in this class's list of attributes.
if self.__class__._attributes.has_key(attribute):
# Find the member of this class which corresponds to the XML attribute
# (lookup in current_class._attributes) and set this member to the
# desired value (using self.__dict__).
if value:
# Encode the string to capture non-ascii characters (default UTF-8)
setattr(self, self.__class__._attributes[attribute],
value.encode(MEMBER_STRING_ENCODING))
else:
ExtensionContainer._ConvertElementAttributeToMember(self, attribute,
value)
# Three methods to create an ElementTree from an object
def _AddMembersToElementTree(self, tree):
# Convert the members of this class which are XML child nodes.
# This uses the class's _children dictionary to find the members which
# should become XML child nodes.
member_node_names = [values[0] for tag, values in
self.__class__._children.iteritems()]
for member_name in member_node_names:
member = getattr(self, member_name)
if member is None:
pass
elif isinstance(member, list):
for instance in member:
instance._BecomeChildElement(tree)
else:
member._BecomeChildElement(tree)
# Convert the members of this class which are XML attributes.
for xml_attribute, member_name in self.__class__._attributes.iteritems():
member = getattr(self, member_name)
if member is not None:
tree.attrib[xml_attribute] = member.decode(MEMBER_STRING_ENCODING)
# Lastly, call the ExtensionContainers's _AddMembersToElementTree to
# convert any extension attributes.
ExtensionContainer._AddMembersToElementTree(self, tree)
def _BecomeChildElement(self, tree):
"""
Note: Only for use with classes that have a _tag and _namespace class
member. It is in AtomBase so that it can be inherited but it should
not be called on instances of AtomBase.
"""
new_child = ElementTree.Element('')
tree.append(new_child)
new_child.tag = '{%s}%s' % (self.__class__._namespace,
self.__class__._tag)
self._AddMembersToElementTree(new_child)
def _ToElementTree(self):
"""
Note, this method is designed to be used only with classes that have a
_tag and _namespace. It is placed in AtomBase for inheritance but should
not be called on this class.
"""
new_tree = ElementTree.Element('{%s}%s' % (self.__class__._namespace,
self.__class__._tag))
self._AddMembersToElementTree(new_tree)
return new_tree
def ToString(self, string_encoding='UTF-8'):
"""Converts the Atom object to a string containing XML."""
return ElementTree.tostring(self._ToElementTree(), encoding=string_encoding)
def __str__(self):
return self.ToString()
class Name(AtomBase):
"""The atom:name element"""
_tag = 'name'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Name
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def NameFromString(xml_string):
return CreateClassFromXMLString(Name, xml_string)
class Email(AtomBase):
"""The atom:email element"""
_tag = 'email'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Email
Args:
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def EmailFromString(xml_string):
return CreateClassFromXMLString(Email, xml_string)
class Uri(AtomBase):
"""The atom:uri element"""
_tag = 'uri'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Uri
Args:
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def UriFromString(xml_string):
return CreateClassFromXMLString(Uri, xml_string)
class Person(AtomBase):
"""A foundation class from which atom:author and atom:contributor extend.
A person contains information like name, email address, and web page URI for
an author or contributor to an Atom feed.
"""
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_children['{%s}name' % (ATOM_NAMESPACE)] = ('name', Name)
_children['{%s}email' % (ATOM_NAMESPACE)] = ('email', Email)
_children['{%s}uri' % (ATOM_NAMESPACE)] = ('uri', Uri)
def __init__(self, name=None, email=None, uri=None,
extension_elements=None, extension_attributes=None, text=None):
"""Foundation from which author and contributor are derived.
The constructor is provided for illustrative purposes, you should not
need to instantiate a Person.
Args:
name: Name The person's name
email: Email The person's email address
uri: Uri The URI of the person's webpage
extension_elements: list A list of ExtensionElement instances which are
children of this element.
extension_attributes: dict A dictionary of strings which are the values
for additional XML attributes of this element.
text: String The text contents of the element. This is the contents
of the Entry's XML text node. (Example: <foo>This is the text</foo>)
"""
self.name = name
self.email = email
self.uri = uri
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
class Author(Person):
"""The atom:author element
An author is a required element in Feed.
"""
_tag = 'author'
_namespace = ATOM_NAMESPACE
_children = Person._children.copy()
_attributes = Person._attributes.copy()
#_children = {}
#_attributes = {}
def __init__(self, name=None, email=None, uri=None,
extension_elements=None, extension_attributes=None, text=None):
"""Constructor for Author
Args:
name: Name
email: Email
uri: Uri
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.name = name
self.email = email
self.uri = uri
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
def AuthorFromString(xml_string):
return CreateClassFromXMLString(Author, xml_string)
class Contributor(Person):
"""The atom:contributor element"""
_tag = 'contributor'
_namespace = ATOM_NAMESPACE
_children = Person._children.copy()
_attributes = Person._attributes.copy()
def __init__(self, name=None, email=None, uri=None,
extension_elements=None, extension_attributes=None, text=None):
"""Constructor for Contributor
Args:
name: Name
email: Email
uri: Uri
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.name = name
self.email = email
self.uri = uri
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
def ContributorFromString(xml_string):
return CreateClassFromXMLString(Contributor, xml_string)
class Link(AtomBase):
"""The atom:link element"""
_tag = 'link'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_attributes['rel'] = 'rel'
_attributes['href'] = 'href'
_attributes['type'] = 'type'
_attributes['title'] = 'title'
_attributes['length'] = 'length'
_attributes['hreflang'] = 'hreflang'
def __init__(self, href=None, rel=None, link_type=None, hreflang=None,
title=None, length=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Link
Args:
href: string The href attribute of the link
rel: string
type: string
hreflang: string The language for the href
title: string
length: string The length of the href's destination
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.href = href
self.rel = rel
self.type = link_type
self.hreflang = hreflang
self.title = title
self.length = length
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def LinkFromString(xml_string):
return CreateClassFromXMLString(Link, xml_string)
class Generator(AtomBase):
"""The atom:generator element"""
_tag = 'generator'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_attributes['uri'] = 'uri'
_attributes['version'] = 'version'
def __init__(self, uri=None, version=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for Generator
Args:
uri: string
version: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.uri = uri
self.version = version
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GeneratorFromString(xml_string):
return CreateClassFromXMLString(Generator, xml_string)
class Text(AtomBase):
"""A foundation class from which atom:title, summary, etc. extend.
This class should never be instantiated.
"""
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_attributes['type'] = 'type'
def __init__(self, text_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Text
Args:
text_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = text_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Title(Text):
"""The atom:title element"""
_tag = 'title'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
def __init__(self, title_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Title
Args:
title_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = title_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def TitleFromString(xml_string):
return CreateClassFromXMLString(Title, xml_string)
class Subtitle(Text):
"""The atom:subtitle element"""
_tag = 'subtitle'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
def __init__(self, subtitle_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Subtitle
Args:
subtitle_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = subtitle_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SubtitleFromString(xml_string):
return CreateClassFromXMLString(Subtitle, xml_string)
class Rights(Text):
"""The atom:rights element"""
_tag = 'rights'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
def __init__(self, rights_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Rights
Args:
rights_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = rights_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def RightsFromString(xml_string):
return CreateClassFromXMLString(Rights, xml_string)
class Summary(Text):
"""The atom:summary element"""
_tag = 'summary'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
def __init__(self, summary_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Summary
Args:
summary_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = summary_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SummaryFromString(xml_string):
return CreateClassFromXMLString(Summary, xml_string)
class Content(Text):
"""The atom:content element"""
_tag = 'content'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
_attributes['src'] = 'src'
def __init__(self, content_type=None, src=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for Content
Args:
content_type: string
src: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = content_type
self.src = src
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ContentFromString(xml_string):
return CreateClassFromXMLString(Content, xml_string)
class Category(AtomBase):
"""The atom:category element"""
_tag = 'category'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_attributes['term'] = 'term'
_attributes['scheme'] = 'scheme'
_attributes['label'] = 'label'
def __init__(self, term=None, scheme=None, label=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for Category
Args:
term: str
scheme: str
label: str
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.term = term
self.scheme = scheme
self.label = label
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def CategoryFromString(xml_string):
return CreateClassFromXMLString(Category, xml_string)
class Id(AtomBase):
"""The atom:id element."""
_tag = 'id'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Id
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def IdFromString(xml_string):
return CreateClassFromXMLString(Id, xml_string)
class Icon(AtomBase):
"""The atom:icon element."""
_tag = 'icon'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Icon
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def IconFromString(xml_string):
return CreateClassFromXMLString(Icon, xml_string)
class Logo(AtomBase):
"""The atom:logo element."""
_tag = 'logo'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Logo
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def LogoFromString(xml_string):
return CreateClassFromXMLString(Logo, xml_string)
class Draft(AtomBase):
"""The app:draft element which indicates if this entry should be public."""
_tag = 'draft'
_namespace = APP_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for app:draft
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def DraftFromString(xml_string):
return CreateClassFromXMLString(Draft, xml_string)
class Control(AtomBase):
"""The app:control element indicating restrictions on publication.
The APP control element may contain a draft element indicating whether or
not this entry should be publicly available.
"""
_tag = 'control'
_namespace = APP_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_children['{%s}draft' % APP_NAMESPACE] = ('draft', Draft)
def __init__(self, draft=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for app:control"""
self.draft = draft
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ControlFromString(xml_string):
return CreateClassFromXMLString(Control, xml_string)
class Date(AtomBase):
"""A parent class for atom:updated, published, etc."""
#TODO Add text to and from time conversion methods to allow users to set
# the contents of a Date to a python DateTime object.
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Updated(Date):
"""The atom:updated element."""
_tag = 'updated'
_namespace = ATOM_NAMESPACE
_children = Date._children.copy()
_attributes = Date._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Updated
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def UpdatedFromString(xml_string):
return CreateClassFromXMLString(Updated, xml_string)
class Published(Date):
"""The atom:published element."""
_tag = 'published'
_namespace = ATOM_NAMESPACE
_children = Date._children.copy()
_attributes = Date._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Published
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def PublishedFromString(xml_string):
return CreateClassFromXMLString(Published, xml_string)
class LinkFinder(object):
"""An "interface" providing methods to find link elements
Entry elements often contain multiple links which differ in the rel
attribute or content type. Often, developers are interested in a specific
type of link so this class provides methods to find specific classes of
links.
This class is used as a mixin in Atom entries and feeds.
"""
def GetSelfLink(self):
"""Find the first link with rel set to 'self'
Returns:
An atom.Link or none if none of the links had rel equal to 'self'
"""
for a_link in self.link:
if a_link.rel == 'self':
return a_link
return None
def GetEditLink(self):
for a_link in self.link:
if a_link.rel == 'edit':
return a_link
return None
def GetNextLink(self):
for a_link in self.link:
if a_link.rel == 'next':
return a_link
return None
def GetLicenseLink(self):
for a_link in self.link:
if a_link.rel == 'license':
return a_link
return None
def GetAlternateLink(self):
for a_link in self.link:
if a_link.rel == 'alternate':
return a_link
return None
class FeedEntryParent(AtomBase, LinkFinder):
"""A super class for atom:feed and entry, contains shared attributes"""
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_children['{%s}author' % ATOM_NAMESPACE] = ('author', [Author])
_children['{%s}category' % ATOM_NAMESPACE] = ('category', [Category])
_children['{%s}contributor' % ATOM_NAMESPACE] = ('contributor', [Contributor])
_children['{%s}id' % ATOM_NAMESPACE] = ('id', Id)
_children['{%s}link' % ATOM_NAMESPACE] = ('link', [Link])
_children['{%s}rights' % ATOM_NAMESPACE] = ('rights', Rights)
_children['{%s}title' % ATOM_NAMESPACE] = ('title', Title)
_children['{%s}updated' % ATOM_NAMESPACE] = ('updated', Updated)
def __init__(self, author=None, category=None, contributor=None,
atom_id=None, link=None, rights=None, title=None, updated=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.rights = rights
self.title = title
self.updated = updated
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Source(FeedEntryParent):
"""The atom:source element"""
_tag = 'source'
_namespace = ATOM_NAMESPACE
_children = FeedEntryParent._children.copy()
_attributes = FeedEntryParent._attributes.copy()
_children['{%s}generator' % ATOM_NAMESPACE] = ('generator', Generator)
_children['{%s}icon' % ATOM_NAMESPACE] = ('icon', Icon)
_children['{%s}logo' % ATOM_NAMESPACE] = ('logo', Logo)
_children['{%s}subtitle' % ATOM_NAMESPACE] = ('subtitle', Subtitle)
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for Source
Args:
author: list (optional) A list of Author instances which belong to this
class.
category: list (optional) A list of Category instances
contributor: list (optional) A list on Contributor instances
generator: Generator (optional)
icon: Icon (optional)
id: Id (optional) The entry's Id element
link: list (optional) A list of Link instances
logo: Logo (optional)
rights: Rights (optional) The entry's Rights element
subtitle: Subtitle (optional) The entry's subtitle element
title: Title (optional) the entry's title element
updated: Updated (optional) the entry's updated element
text: String (optional) The text contents of the element. This is the
contents of the Entry's XML text node.
(Example: <foo>This is the text</foo>)
extension_elements: list (optional) A list of ExtensionElement instances
which are children of this element.
extension_attributes: dict (optional) A dictionary of strings which are
the values for additional XML attributes of this element.
"""
self.author = author or []
self.category = category or []
self.contributor = contributor or []
self.generator = generator
self.icon = icon
self.id = atom_id
self.link = link or []
self.logo = logo
self.rights = rights
self.subtitle = subtitle
self.title = title
self.updated = updated
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SourceFromString(xml_string):
return CreateClassFromXMLString(Source, xml_string)
class Entry(FeedEntryParent):
"""The atom:entry element"""
_tag = 'entry'
_namespace = ATOM_NAMESPACE
_children = FeedEntryParent._children.copy()
_attributes = FeedEntryParent._attributes.copy()
_children['{%s}content' % ATOM_NAMESPACE] = ('content', Content)
_children['{%s}published' % ATOM_NAMESPACE] = ('published', Published)
_children['{%s}source' % ATOM_NAMESPACE] = ('source', Source)
_children['{%s}summary' % ATOM_NAMESPACE] = ('summary', Summary)
_children['{%s}control' % APP_NAMESPACE] = ('control', Control)
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, control=None, title=None, updated=None,
extension_elements=None, extension_attributes=None, text=None):
"""Constructor for atom:entry
Args:
author: list A list of Author instances which belong to this class.
category: list A list of Category instances
content: Content The entry's Content
contributor: list A list on Contributor instances
id: Id The entry's Id element
link: list A list of Link instances
published: Published The entry's Published element
rights: Rights The entry's Rights element
source: Source the entry's source element
summary: Summary the entry's summary element
title: Title the entry's title element
updated: Updated the entry's updated element
control: The entry's app:control element which can be used to mark an
entry as a draft which should not be publicly viewable.
text: String The text contents of the element. This is the contents
of the Entry's XML text node. (Example: <foo>This is the text</foo>)
extension_elements: list A list of ExtensionElement instances which are
children of this element.
extension_attributes: dict A dictionary of strings which are the values
for additional XML attributes of this element.
"""
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.title = title
self.updated = updated
self.control = control
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def EntryFromString(xml_string):
return CreateClassFromXMLString(Entry, xml_string)
class Feed(Source):
"""The atom:feed element"""
_tag = 'feed'
_namespace = ATOM_NAMESPACE
_children = Source._children.copy()
_attributes = Source._attributes.copy()
_children['{%s}entry' % ATOM_NAMESPACE] = ('entry', [Entry])
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None, entry=None,
text=None, extension_elements=None, extension_attributes=None):
"""Constructor for Source
Args:
author: list (optional) A list of Author instances which belong to this
class.
category: list (optional) A list of Category instances
contributor: list (optional) A list on Contributor instances
generator: Generator (optional)
icon: Icon (optional)
id: Id (optional) The entry's Id element
link: list (optional) A list of Link instances
logo: Logo (optional)
rights: Rights (optional) The entry's Rights element
subtitle: Subtitle (optional) The entry's subtitle element
title: Title (optional) the entry's title element
updated: Updated (optional) the entry's updated element
entry: list (optional) A list of the Entry instances contained in the
feed.
text: String (optional) The text contents of the element. This is the
contents of the Entry's XML text node.
(Example: <foo>This is the text</foo>)
extension_elements: list (optional) A list of ExtensionElement instances
which are children of this element.
extension_attributes: dict (optional) A dictionary of strings which are
the values for additional XML attributes of this element.
"""
self.author = author or []
self.category = category or []
self.contributor = contributor or []
self.generator = generator
self.icon = icon
self.id = atom_id
self.link = link or []
self.logo = logo
self.rights = rights
self.subtitle = subtitle
self.title = title
self.updated = updated
self.entry = entry or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def FeedFromString(xml_string):
return CreateClassFromXMLString(Feed, xml_string)
class ExtensionElement(object):
"""Represents extra XML elements contained in Atom classes."""
def __init__(self, tag, namespace=None, attributes=None,
children=None, text=None):
"""Constructor for EtensionElement
Args:
namespace: string (optional) The XML namespace for this element.
tag: string (optional) The tag (without the namespace qualifier) for
this element. To reconstruct the full qualified name of the element,
combine this tag with the namespace.
attributes: dict (optinal) The attribute value string pairs for the XML
attributes of this element.
children: list (optional) A list of ExtensionElements which represent
the XML child nodes of this element.
"""
self.namespace = namespace
self.tag = tag
self.attributes = attributes or {}
self.children = children or []
self.text = text
def ToString(self):
element_tree = self._TransferToElementTree(ElementTree.Element(''))
return ElementTree.tostring(element_tree, encoding="UTF-8")
def _TransferToElementTree(self, element_tree):
if self.tag is None:
return None
if self.namespace is not None:
element_tree.tag = '{%s}%s' % (self.namespace, self.tag)
else:
element_tree.tag = self.tag
for key, value in self.attributes.iteritems():
element_tree.attrib[key] = value
for child in self.children:
child._BecomeChildElement(element_tree)
element_tree.text = self.text
return element_tree
def _BecomeChildElement(self, element_tree):
"""Converts this object into an etree element and adds it as a child node.
Adds self to the ElementTree. This method is required to avoid verbose XML
which constantly redefines the namespace.
Args:
element_tree: ElementTree._Element The element to which this object's XML
will be added.
"""
new_element = ElementTree.Element('')
element_tree.append(new_element)
self._TransferToElementTree(new_element)
def FindChildren(self, tag=None, namespace=None):
"""Searches child nodes for objects with the desired tag/namespace.
Returns a list of extension elements within this object whose tag
and/or namespace match those passed in. To find all children in
a particular namespace, specify the namespace but not the tag name.
If you specify only the tag, the result list may contain extension
elements in multiple namespaces.
Args:
tag: str (optional) The desired tag
namespace: str (optional) The desired namespace
Returns:
A list of elements whose tag and/or namespace match the parameters
values
"""
results = []
if tag and namespace:
for element in self.children:
if element.tag == tag and element.namespace == namespace:
results.append(element)
elif tag and not namespace:
for element in self.children:
if element.tag == tag:
results.append(element)
elif namespace and not tag:
for element in self.children:
if element.namespace == namespace:
results.append(element)
else:
for element in self.children:
results.append(element)
return results
def ExtensionElementFromString(xml_string):
element_tree = ElementTree.fromstring(xml_string)
return _ExtensionElementFromElementTree(element_tree)
def _ExtensionElementFromElementTree(element_tree):
element_tag = element_tree.tag
if '}' in element_tag:
namespace = element_tag[1:element_tag.index('}')]
tag = element_tag[element_tag.index('}')+1:]
else:
namespace = None
tag = element_tag
extension = ExtensionElement(namespace=namespace, tag=tag)
for key, value in element_tree.attrib.iteritems():
extension.attributes[key] = value
for child in element_tree:
extension.children.append(_ExtensionElementFromElementTree(child))
extension.text = element_tree.text
return extension
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006, 2007, 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""AtomService provides CRUD ops. in line with the Atom Publishing Protocol.
AtomService: Encapsulates the ability to perform insert, update and delete
operations with the Atom Publishing Protocol on which GData is
based. An instance can perform query, insertion, deletion, and
update.
HttpRequest: Function that performs a GET, POST, PUT, or DELETE HTTP request
to the specified end point. An AtomService object or a subclass can be
used to specify information about the request.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
import os
import httplib
import urllib
import re
import base64
import socket
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
URL_REGEX = re.compile('http(s)?\://([\w\.-]*)(\:(\d+))?(/.*)?')
class AtomService(object):
"""Performs Atom Publishing Protocol CRUD operations.
The AtomService contains methods to perform HTTP CRUD operations.
"""
# Default values for members
port = 80
ssl = False
# If debug is True, the HTTPConnection will display debug information
debug = False
def __init__(self, server=None, additional_headers=None):
"""Creates a new AtomService client.
Args:
server: string (optional) The start of a URL for the server
to which all operations should be directed. Example:
'www.google.com'
additional_headers: dict (optional) Any additional HTTP headers which
should be included with CRUD operations.
"""
self.server = server
self.additional_headers = additional_headers or {}
self.additional_headers['User-Agent'] = 'Python Google Data Client Lib'
def _ProcessUrl(self, url, for_proxy=False):
"""Processes a passed URL. If the URL does not begin with https?, then
the default value for self.server is used"""
return ProcessUrl(self, url, for_proxy=for_proxy)
def 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
"""
UseBasicAuth(self, username, password, for_proxy=for_proxy)
def PrepareConnection(self, full_uri):
"""Opens a connection to the server based on the full URI.
Examines the target URI and the proxy settings, which are set as
environment variables, to open a connection with the server. This
connection is used to make an HTTP request.
Args:
full_uri: str Which is the target relative (lacks protocol and host) or
absolute URL to be opened. Example:
'https://www.google.com/accounts/ClientLogin' or
'base/feeds/snippets' where the server is set to www.google.com.
Returns:
A tuple containing the httplib.HTTPConnection and the full_uri for the
request.
"""
return PrepareConnection(self, full_uri)
# Alias the old name for the above method to preserve backwards
# compatibility.
_PrepareConnection = PrepareConnection
# CRUD operations
def Get(self, uri, extra_headers=None, url_params=None, escape_params=True):
"""Query the APP server with the given URI
The uri is the portion of the URI after the server value
(server example: 'www.google.com').
Example use:
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: dicty (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.
url_params: dict (optional) Additional URL parameters to be included
in the query. 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.
Returns:
httplib.HTTPResponse The server's response to the GET request.
"""
return HttpRequest(self, 'GET', None, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params)
def Post(self, data, uri, extra_headers=None, url_params=None,
escape_params=True, content_type='application/atom+xml'):
"""Insert data into an APP server at the given URI.
Args:
data: string, ElementTree._Element, or something with a __str__ method
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.
Returns:
httplib.HTTPResponse Server's response to the POST request.
"""
return HttpRequest(self, 'POST', data, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params,
content_type=content_type)
def Put(self, data, uri, extra_headers=None, url_params=None,
escape_params=True, content_type='application/atom+xml'):
"""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.
Returns:
httplib.HTTPResponse Server's response to the PUT request.
"""
return HttpRequest(self, 'PUT', data, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params,
content_type=content_type)
def Delete(self, uri, extra_headers=None, url_params=None,
escape_params=True):
"""Deletes the entry at the given URI.
Args:
uri: string The URI of the entry to be deleted. Example:
'/base/feeds/items/ITEM-ID'
extra_headers: dict (optional) HTTP headers which are to be included.
The client automatically sets the Content-Type and
Authorization 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.
Returns:
httplib.HTTPResponse Server's response to the DELETE request.
"""
return HttpRequest(self, 'DELETE', None, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params)
def HttpRequest(service, operation, data, uri, extra_headers=None,
url_params=None, escape_params=True, content_type='application/atom+xml'):
"""Performs an HTTP call to the server, supports GET, POST, PUT, and DELETE.
Usage example, perform and HTTP GET on http://www.google.com/:
import atom.service
client = atom.service.AtomService()
http_response = client.Get('http://www.google.com/')
or you could set the client.server to 'www.google.com' and use the
following:
client.server = 'www.google.com'
http_response = client.Get('/')
Args:
service: atom.AtomService object which contains some of the parameters
needed to make the request. The following members are used to
construct the HTTP call: server (str), additional_headers (dict),
port (int), and ssl (bool).
operation: str The HTTP operation to be performed. This is usually one of
'GET', 'POST', 'PUT', or 'DELETE'
data: ElementTree, filestream, list of parts, or other object which can be
converted to a string.
Should be set to None when performing a GET or PUT.
If data is a file-like object which can be read, this method will read
a chunk of 100K bytes at a time and send them.
If the data is a list of parts to be sent, each part will be evaluated
and sent.
uri: The beginning of the URL to which the request should be sent.
Examples: '/', '/base/feeds/snippets',
'/m8/feeds/contacts/default/base'
extra_headers: dict of strings. HTTP headers which should be sent
in the request. These headers are in addition to those stored in
service.additional_headers.
url_params: dict of strings. Key value pairs to be added to the URL as
URL parameters. For example {'foo':'bar', 'test':'param'} will
become ?foo=bar&test=param.
escape_params: bool default True. If true, the keys and values in
url_params will be URL escaped when the form is constructed
(Special characters converted to %XX form.)
content_type: str The MIME type for the data being sent. Defaults to
'application/atom+xml', this is only used if data is set.
"""
full_uri = BuildUri(uri, url_params, escape_params)
(connection, full_uri) = PrepareConnection(service, full_uri)
if extra_headers is None:
extra_headers = {}
# Turn on debug mode if the debug member is set.
if service.debug:
connection.debuglevel = 1
connection.putrequest(operation, full_uri)
# If the list of headers does not include a Content-Length, attempt to
# calculate it based on the data object.
if (data and not service.additional_headers.has_key('Content-Length') and
not extra_headers.has_key('Content-Length')):
content_length = __CalculateDataLength(data)
if content_length:
extra_headers['Content-Length'] = str(content_length)
if content_type:
extra_headers['Content-Type'] = content_type
# Send the HTTP headers.
if isinstance(service.additional_headers, dict):
for header in service.additional_headers:
connection.putheader(header, service.additional_headers[header])
if isinstance(extra_headers, dict):
for header in extra_headers:
connection.putheader(header, extra_headers[header])
connection.endheaders()
# If there is data, send it in the request.
if data:
if isinstance(data, list):
for data_part in data:
__SendDataPart(data_part, connection)
else:
__SendDataPart(data, connection)
# Return the HTTP Response from the server.
return connection.getresponse()
def __SendDataPart(data, connection):
if isinstance(data, str):
#TODO add handling for unicode.
connection.send(data)
return
elif ElementTree.iselement(data):
connection.send(ElementTree.tostring(data))
return
# Check to see if data is a file-like object that has a read method.
elif hasattr(data, 'read'):
# Read the file and send it a chunk at a time.
while 1:
binarydata = data.read(100000)
if binarydata == '': break
connection.send(binarydata)
return
else:
# The data object was not a file.
# Try to convert to a string and send the data.
connection.send(str(data))
return
def __CalculateDataLength(data):
"""Attempts to determine the length of the data to send.
This method will respond with a length only if the data is a string or
and ElementTree element.
Args:
data: object If this is not a string or ElementTree element this funtion
will return None.
"""
if isinstance(data, str):
return len(data)
elif isinstance(data, list):
return None
elif ElementTree.iselement(data):
return len(ElementTree.tostring(data))
elif hasattr(data, 'read'):
# If this is a file-like object, don't try to guess the length.
return None
else:
return len(str(data))
def PrepareConnection(service, full_uri):
"""Opens a connection to the server based on the full URI.
Examines the target URI and the proxy settings, which are set as
environment variables, to open a connection with the server. This
connection is used to make an HTTP request.
Args:
service: atom.AtomService or a subclass. It must have a server string which
represents the server host to which the request should be made. It may also
have a dictionary of additional_headers to send in the HTTP request.
full_uri: str Which is the target relative (lacks protocol and host) or
absolute URL to be opened. Example:
'https://www.google.com/accounts/ClientLogin' or
'base/feeds/snippets' where the server is set to www.google.com.
Returns:
A tuple containing the httplib.HTTPConnection and the full_uri for the
request.
"""
(server, port, ssl, partial_uri) = ProcessUrl(service, full_uri)
if ssl:
# destination is https
proxy = os.environ.get('https_proxy')
if proxy:
(p_server, p_port, p_ssl, p_uri) = ProcessUrl(service, proxy, True)
proxy_username = os.environ.get('proxy-username')
if not proxy_username:
proxy_username = os.environ.get('proxy_username')
proxy_password = os.environ.get('proxy-password')
if not proxy_password:
proxy_password = os.environ.get('proxy_password')
if proxy_username:
user_auth = base64.encodestring('%s:%s' % (proxy_username,
proxy_password))
proxy_authorization = ('Proxy-authorization: Basic %s\r\n' % (
user_auth.strip()))
else:
proxy_authorization = ''
proxy_connect = 'CONNECT %s:%s HTTP/1.0\r\n' % (server, port)
user_agent = 'User-Agent: %s\r\n' % (
service.additional_headers['User-Agent'])
proxy_pieces = (proxy_connect + proxy_authorization + user_agent
+ '\r\n')
#now connect, very simple recv and error checking
p_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
p_sock.connect((p_server,p_port))
p_sock.sendall(proxy_pieces)
response = ''
# Wait for the full response.
while response.find("\r\n\r\n") == -1:
response += p_sock.recv(8192)
p_status=response.split()[1]
if p_status!=str(200):
raise 'Error status=',str(p_status)
# Trivial setup for ssl socket.
ssl = socket.ssl(p_sock, None, None)
fake_sock = httplib.FakeSocket(p_sock, ssl)
# Initalize httplib and replace with the proxy socket.
connection = httplib.HTTPConnection(server)
connection.sock=fake_sock
full_uri = partial_uri
else:
connection = httplib.HTTPSConnection(server, port)
full_uri = partial_uri
else:
# destination is http
proxy = os.environ.get('http_proxy')
if proxy:
(p_server, p_port, p_ssl, p_uri) = ProcessUrl(service.server, proxy, True)
proxy_username = os.environ.get('proxy-username')
if not proxy_username:
proxy_username = os.environ.get('proxy_username')
proxy_password = os.environ.get('proxy-password')
if not proxy_password:
proxy_password = os.environ.get('proxy_password')
if proxy_username:
UseBasicAuth(service, proxy_username, proxy_password, True)
connection = httplib.HTTPConnection(p_server, p_port)
if not full_uri.startswith("http://"):
if full_uri.startswith("/"):
full_uri = "http://%s%s" % (service.server, full_uri)
else:
full_uri = "http://%s/%s" % (service.server, full_uri)
else:
connection = httplib.HTTPConnection(server, port)
full_uri = partial_uri
return (connection, full_uri)
def UseBasicAuth(service, 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. The auth header is added to the
additional_headers dictionary in the service object.
Args:
service: atom.AtomService or a subclass which has an
additional_headers dict as a member.
username: str
password: str
"""
base_64_string = base64.encodestring('%s:%s' % (username, password))
base_64_string = base_64_string.strip()
if for_proxy:
header_name = 'Proxy-Authorization'
else:
header_name = 'Authorization'
service.additional_headers[header_name] = 'Basic %s' % (base_64_string,)
def ProcessUrl(service, url, for_proxy=False):
"""Processes a passed URL. If the URL does not begin with https?, then
the default value for server is used"""
server = None
port = 80
ssl = False
if hasattr(service, 'server'):
server = service.server
else:
server = service
if not for_proxy:
if hasattr(service, 'port'):
port = service.port
if hasattr(service, 'ssl'):
ssl = service.ssl
uri = url
m = URL_REGEX.match(url)
if m is None:
return (server, port, ssl, uri)
else:
if m.group(1) is not None:
port = 443
ssl = True
if m.group(3) is None:
server = m.group(2)
else:
server = m.group(2)
port = int(m.group(4))
if m.group(5) is not None:
uri = m.group(5)
else:
uri = '/'
return (server, port, ssl, uri)
def DictionaryToParamList(url_parameters, escape_params=True):
"""Convert a dictionary of URL arguments into a URL parameter string.
Args:
url_parameters: The dictionaty of key-value pairs which will be converted
into URL parameters. For example,
{'dry-run': 'true', 'foo': 'bar'}
will become ['dry-run=true', 'foo=bar'].
Returns:
A list which contains a string for each key-value pair. The strings are
ready to be incorporated into a URL by using '&'.join([] + parameter_list)
"""
# Choose which function to use when modifying the query and parameters.
# Use quote_plus when escape_params is true.
transform_op = [str, urllib.quote_plus][bool(escape_params)]
# Create a list of tuples containing the escaped version of the
# parameter-value pairs.
parameter_tuples = [(transform_op(param), transform_op(value))
for param, value in (url_parameters or {}).items()]
# Turn parameter-value tuples into a list of strings in the form
# 'PARAMETER=VALUE'.
return ['='.join(x) for x in parameter_tuples]
def BuildUri(uri, url_params=None, escape_params=True):
"""Converts a uri string and a collection of parameters into a URI.
Args:
uri: string
url_params: dict (optional)
escape_params: boolean (optional)
uri: string The start of the desired URI. This string can alrady contain
URL parameters. Examples: '/base/feeds/snippets',
'/base/feeds/snippets?bq=digital+camera'
url_parameters: dict (optional) Additional URL parameters to be included
in the query. 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.
Returns:
string The URI consisting of the escaped URL parameters appended to the
initial uri string.
"""
# Prepare URL parameters for inclusion into the GET request.
parameter_list = DictionaryToParamList(url_params, escape_params)
# Append the URL parameters to the URL.
if parameter_list:
if uri.find('?') != -1:
# If there are already URL parameters in the uri string, add the
# parameters after a new & character.
full_uri = '&'.join([uri] + parameter_list)
else:
# The uri string did not have any URL parameters (no ? character)
# so put a ? between the uri and URL parameters.
full_uri = '%s%s' % (uri, '?%s' % ('&'.join([] + parameter_list)))
else:
full_uri = uri
return full_uri
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006, 2007, 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""AtomService provides CRUD ops. in line with the Atom Publishing Protocol.
AtomService: Encapsulates the ability to perform insert, update and delete
operations with the Atom Publishing Protocol on which GData is
based. An instance can perform query, insertion, deletion, and
update.
HttpRequest: Function that performs a GET, POST, PUT, or DELETE HTTP request
to the specified end point. An AtomService object or a subclass can be
used to specify information about the request.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
import os
import httplib
import urllib
import re
import base64
import socket
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
URL_REGEX = re.compile('http(s)?\://([\w\.-]*)(\:(\d+))?(/.*)?')
class AtomService(object):
"""Performs Atom Publishing Protocol CRUD operations.
The AtomService contains methods to perform HTTP CRUD operations.
"""
# Default values for members
port = 80
ssl = False
# If debug is True, the HTTPConnection will display debug information
debug = False
def __init__(self, server=None, additional_headers=None):
"""Creates a new AtomService client.
Args:
server: string (optional) The start of a URL for the server
to which all operations should be directed. Example:
'www.google.com'
additional_headers: dict (optional) Any additional HTTP headers which
should be included with CRUD operations.
"""
self.server = server
self.additional_headers = additional_headers or {}
self.additional_headers['User-Agent'] = 'Python Google Data Client Lib'
def _ProcessUrl(self, url, for_proxy=False):
"""Processes a passed URL. If the URL does not begin with https?, then
the default value for self.server is used"""
return ProcessUrl(self, url, for_proxy=for_proxy)
def 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
"""
UseBasicAuth(self, username, password, for_proxy=for_proxy)
def PrepareConnection(self, full_uri):
"""Opens a connection to the server based on the full URI.
Examines the target URI and the proxy settings, which are set as
environment variables, to open a connection with the server. This
connection is used to make an HTTP request.
Args:
full_uri: str Which is the target relative (lacks protocol and host) or
absolute URL to be opened. Example:
'https://www.google.com/accounts/ClientLogin' or
'base/feeds/snippets' where the server is set to www.google.com.
Returns:
A tuple containing the httplib.HTTPConnection and the full_uri for the
request.
"""
return PrepareConnection(self, full_uri)
# Alias the old name for the above method to preserve backwards
# compatibility.
_PrepareConnection = PrepareConnection
# CRUD operations
def Get(self, uri, extra_headers=None, url_params=None, escape_params=True):
"""Query the APP server with the given URI
The uri is the portion of the URI after the server value
(server example: 'www.google.com').
Example use:
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: dicty (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.
url_params: dict (optional) Additional URL parameters to be included
in the query. 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.
Returns:
httplib.HTTPResponse The server's response to the GET request.
"""
return HttpRequest(self, 'GET', None, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params)
def Post(self, data, uri, extra_headers=None, url_params=None,
escape_params=True, content_type='application/atom+xml'):
"""Insert data into an APP server at the given URI.
Args:
data: string, ElementTree._Element, or something with a __str__ method
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.
Returns:
httplib.HTTPResponse Server's response to the POST request.
"""
return HttpRequest(self, 'POST', data, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params,
content_type=content_type)
def Put(self, data, uri, extra_headers=None, url_params=None,
escape_params=True, content_type='application/atom+xml'):
"""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.
Returns:
httplib.HTTPResponse Server's response to the PUT request.
"""
return HttpRequest(self, 'PUT', data, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params,
content_type=content_type)
def Delete(self, uri, extra_headers=None, url_params=None,
escape_params=True):
"""Deletes the entry at the given URI.
Args:
uri: string The URI of the entry to be deleted. Example:
'/base/feeds/items/ITEM-ID'
extra_headers: dict (optional) HTTP headers which are to be included.
The client automatically sets the Content-Type and
Authorization 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.
Returns:
httplib.HTTPResponse Server's response to the DELETE request.
"""
return HttpRequest(self, 'DELETE', None, uri, extra_headers=extra_headers,
url_params=url_params, escape_params=escape_params)
def HttpRequest(service, operation, data, uri, extra_headers=None,
url_params=None, escape_params=True, content_type='application/atom+xml'):
"""Performs an HTTP call to the server, supports GET, POST, PUT, and DELETE.
Usage example, perform and HTTP GET on http://www.google.com/:
import atom.service
client = atom.service.AtomService()
http_response = client.Get('http://www.google.com/')
or you could set the client.server to 'www.google.com' and use the
following:
client.server = 'www.google.com'
http_response = client.Get('/')
Args:
service: atom.AtomService object which contains some of the parameters
needed to make the request. The following members are used to
construct the HTTP call: server (str), additional_headers (dict),
port (int), and ssl (bool).
operation: str The HTTP operation to be performed. This is usually one of
'GET', 'POST', 'PUT', or 'DELETE'
data: ElementTree, filestream, list of parts, or other object which can be
converted to a string.
Should be set to None when performing a GET or PUT.
If data is a file-like object which can be read, this method will read
a chunk of 100K bytes at a time and send them.
If the data is a list of parts to be sent, each part will be evaluated
and sent.
uri: The beginning of the URL to which the request should be sent.
Examples: '/', '/base/feeds/snippets',
'/m8/feeds/contacts/default/base'
extra_headers: dict of strings. HTTP headers which should be sent
in the request. These headers are in addition to those stored in
service.additional_headers.
url_params: dict of strings. Key value pairs to be added to the URL as
URL parameters. For example {'foo':'bar', 'test':'param'} will
become ?foo=bar&test=param.
escape_params: bool default True. If true, the keys and values in
url_params will be URL escaped when the form is constructed
(Special characters converted to %XX form.)
content_type: str The MIME type for the data being sent. Defaults to
'application/atom+xml', this is only used if data is set.
"""
full_uri = BuildUri(uri, url_params, escape_params)
(connection, full_uri) = PrepareConnection(service, full_uri)
if extra_headers is None:
extra_headers = {}
# Turn on debug mode if the debug member is set.
if service.debug:
connection.debuglevel = 1
connection.putrequest(operation, full_uri)
# If the list of headers does not include a Content-Length, attempt to
# calculate it based on the data object.
if (data and not service.additional_headers.has_key('Content-Length') and
not extra_headers.has_key('Content-Length')):
content_length = __CalculateDataLength(data)
if content_length:
extra_headers['Content-Length'] = str(content_length)
if content_type:
extra_headers['Content-Type'] = content_type
# Send the HTTP headers.
if isinstance(service.additional_headers, dict):
for header in service.additional_headers:
connection.putheader(header, service.additional_headers[header])
if isinstance(extra_headers, dict):
for header in extra_headers:
connection.putheader(header, extra_headers[header])
connection.endheaders()
# If there is data, send it in the request.
if data:
if isinstance(data, list):
for data_part in data:
__SendDataPart(data_part, connection)
else:
__SendDataPart(data, connection)
# Return the HTTP Response from the server.
return connection.getresponse()
def __SendDataPart(data, connection):
if isinstance(data, str):
#TODO add handling for unicode.
connection.send(data)
return
elif ElementTree.iselement(data):
connection.send(ElementTree.tostring(data))
return
# Check to see if data is a file-like object that has a read method.
elif hasattr(data, 'read'):
# Read the file and send it a chunk at a time.
while 1:
binarydata = data.read(100000)
if binarydata == '': break
connection.send(binarydata)
return
else:
# The data object was not a file.
# Try to convert to a string and send the data.
connection.send(str(data))
return
def __CalculateDataLength(data):
"""Attempts to determine the length of the data to send.
This method will respond with a length only if the data is a string or
and ElementTree element.
Args:
data: object If this is not a string or ElementTree element this funtion
will return None.
"""
if isinstance(data, str):
return len(data)
elif isinstance(data, list):
return None
elif ElementTree.iselement(data):
return len(ElementTree.tostring(data))
elif hasattr(data, 'read'):
# If this is a file-like object, don't try to guess the length.
return None
else:
return len(str(data))
def PrepareConnection(service, full_uri):
"""Opens a connection to the server based on the full URI.
Examines the target URI and the proxy settings, which are set as
environment variables, to open a connection with the server. This
connection is used to make an HTTP request.
Args:
service: atom.AtomService or a subclass. It must have a server string which
represents the server host to which the request should be made. It may also
have a dictionary of additional_headers to send in the HTTP request.
full_uri: str Which is the target relative (lacks protocol and host) or
absolute URL to be opened. Example:
'https://www.google.com/accounts/ClientLogin' or
'base/feeds/snippets' where the server is set to www.google.com.
Returns:
A tuple containing the httplib.HTTPConnection and the full_uri for the
request.
"""
(server, port, ssl, partial_uri) = ProcessUrl(service, full_uri)
if ssl:
# destination is https
proxy = os.environ.get('https_proxy')
if proxy:
(p_server, p_port, p_ssl, p_uri) = ProcessUrl(service, proxy, True)
proxy_username = os.environ.get('proxy-username')
if not proxy_username:
proxy_username = os.environ.get('proxy_username')
proxy_password = os.environ.get('proxy-password')
if not proxy_password:
proxy_password = os.environ.get('proxy_password')
if proxy_username:
user_auth = base64.encodestring('%s:%s' % (proxy_username,
proxy_password))
proxy_authorization = ('Proxy-authorization: Basic %s\r\n' % (
user_auth.strip()))
else:
proxy_authorization = ''
proxy_connect = 'CONNECT %s:%s HTTP/1.0\r\n' % (server, port)
user_agent = 'User-Agent: %s\r\n' % (
service.additional_headers['User-Agent'])
proxy_pieces = (proxy_connect + proxy_authorization + user_agent
+ '\r\n')
#now connect, very simple recv and error checking
p_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
p_sock.connect((p_server,p_port))
p_sock.sendall(proxy_pieces)
response = ''
# Wait for the full response.
while response.find("\r\n\r\n") == -1:
response += p_sock.recv(8192)
p_status=response.split()[1]
if p_status!=str(200):
raise 'Error status=',str(p_status)
# Trivial setup for ssl socket.
ssl = socket.ssl(p_sock, None, None)
fake_sock = httplib.FakeSocket(p_sock, ssl)
# Initalize httplib and replace with the proxy socket.
connection = httplib.HTTPConnection(server)
connection.sock=fake_sock
full_uri = partial_uri
else:
connection = httplib.HTTPSConnection(server, port)
full_uri = partial_uri
else:
# destination is http
proxy = os.environ.get('http_proxy')
if proxy:
(p_server, p_port, p_ssl, p_uri) = ProcessUrl(service.server, proxy, True)
proxy_username = os.environ.get('proxy-username')
if not proxy_username:
proxy_username = os.environ.get('proxy_username')
proxy_password = os.environ.get('proxy-password')
if not proxy_password:
proxy_password = os.environ.get('proxy_password')
if proxy_username:
UseBasicAuth(service, proxy_username, proxy_password, True)
connection = httplib.HTTPConnection(p_server, p_port)
if not full_uri.startswith("http://"):
if full_uri.startswith("/"):
full_uri = "http://%s%s" % (service.server, full_uri)
else:
full_uri = "http://%s/%s" % (service.server, full_uri)
else:
connection = httplib.HTTPConnection(server, port)
full_uri = partial_uri
return (connection, full_uri)
def UseBasicAuth(service, 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. The auth header is added to the
additional_headers dictionary in the service object.
Args:
service: atom.AtomService or a subclass which has an
additional_headers dict as a member.
username: str
password: str
"""
base_64_string = base64.encodestring('%s:%s' % (username, password))
base_64_string = base_64_string.strip()
if for_proxy:
header_name = 'Proxy-Authorization'
else:
header_name = 'Authorization'
service.additional_headers[header_name] = 'Basic %s' % (base_64_string,)
def ProcessUrl(service, url, for_proxy=False):
"""Processes a passed URL. If the URL does not begin with https?, then
the default value for server is used"""
server = None
port = 80
ssl = False
if hasattr(service, 'server'):
server = service.server
else:
server = service
if not for_proxy:
if hasattr(service, 'port'):
port = service.port
if hasattr(service, 'ssl'):
ssl = service.ssl
uri = url
m = URL_REGEX.match(url)
if m is None:
return (server, port, ssl, uri)
else:
if m.group(1) is not None:
port = 443
ssl = True
if m.group(3) is None:
server = m.group(2)
else:
server = m.group(2)
port = int(m.group(4))
if m.group(5) is not None:
uri = m.group(5)
else:
uri = '/'
return (server, port, ssl, uri)
def DictionaryToParamList(url_parameters, escape_params=True):
"""Convert a dictionary of URL arguments into a URL parameter string.
Args:
url_parameters: The dictionaty of key-value pairs which will be converted
into URL parameters. For example,
{'dry-run': 'true', 'foo': 'bar'}
will become ['dry-run=true', 'foo=bar'].
Returns:
A list which contains a string for each key-value pair. The strings are
ready to be incorporated into a URL by using '&'.join([] + parameter_list)
"""
# Choose which function to use when modifying the query and parameters.
# Use quote_plus when escape_params is true.
transform_op = [str, urllib.quote_plus][bool(escape_params)]
# Create a list of tuples containing the escaped version of the
# parameter-value pairs.
parameter_tuples = [(transform_op(param), transform_op(value))
for param, value in (url_parameters or {}).items()]
# Turn parameter-value tuples into a list of strings in the form
# 'PARAMETER=VALUE'.
return ['='.join(x) for x in parameter_tuples]
def BuildUri(uri, url_params=None, escape_params=True):
"""Converts a uri string and a collection of parameters into a URI.
Args:
uri: string
url_params: dict (optional)
escape_params: boolean (optional)
uri: string The start of the desired URI. This string can alrady contain
URL parameters. Examples: '/base/feeds/snippets',
'/base/feeds/snippets?bq=digital+camera'
url_parameters: dict (optional) Additional URL parameters to be included
in the query. 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.
Returns:
string The URI consisting of the escaped URL parameters appended to the
initial uri string.
"""
# Prepare URL parameters for inclusion into the GET request.
parameter_list = DictionaryToParamList(url_params, escape_params)
# Append the URL parameters to the URL.
if parameter_list:
if uri.find('?') != -1:
# If there are already URL parameters in the uri string, add the
# parameters after a new & character.
full_uri = '&'.join([uri] + parameter_list)
else:
# The uri string did not have any URL parameters (no ? character)
# so put a ? between the uri and URL parameters.
full_uri = '%s%s' % (uri, '?%s' % ('&'.join([] + parameter_list)))
else:
full_uri = uri
return full_uri
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains classes representing Atom elements.
Module objective: provide data classes for Atom constructs. These classes hide
the XML-ness of Atom and provide a set of native Python classes to interact
with.
Conversions to and from XML should only be necessary when the Atom classes
"touch the wire" and are sent over HTTP. For this reason this module
provides methods and functions to convert Atom classes to and from strings.
For more information on the Atom data model, see RFC 4287
(http://www.ietf.org/rfc/rfc4287.txt)
AtomBase: A foundation class on which Atom classes are built. It
handles the parsing of attributes and children which are common to all
Atom classes. By default, the AtomBase class translates all XML child
nodes into ExtensionElements.
ExtensionElement: Atom allows Atom objects to contain XML which is not part
of the Atom specification, these are called extension elements. If a
classes parser encounters an unexpected XML construct, it is translated
into an ExtensionElement instance. ExtensionElement is designed to fully
capture the information in the XML. Child nodes in an XML extension are
turned into ExtensionElements as well.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
# XML namespaces which are often used in Atom entities.
ATOM_NAMESPACE = 'http://www.w3.org/2005/Atom'
ELEMENT_TEMPLATE = '{http://www.w3.org/2005/Atom}%s'
APP_NAMESPACE = 'http://purl.org/atom/app#'
APP_TEMPLATE = '{http://purl.org/atom/app#}%s'
# This encoding is used for converting strings before translating the XML
# into an object.
XML_STRING_ENCODING = 'utf-8'
# The desired string encoding for object members.
MEMBER_STRING_ENCODING = 'utf-8'
def CreateClassFromXMLString(target_class, xml_string, string_encoding=None):
"""Creates an instance of the target class from the string contents.
Args:
target_class: class The class which will be instantiated and populated
with the contents of the XML. This class must have a _tag and a
_namespace class variable.
xml_string: str A string which contains valid XML. The root element
of the XML string should match the tag and namespace of the desired
class.
string_encoding: str The character encoding which the xml_string should
be converted to before it is interpreted and translated into
objects. The default is None in which case the string encoding
is not changed.
Returns:
An instance of the target class with members assigned according to the
contents of the XML - or None if the root XML tag and namespace did not
match those of the target class.
"""
encoding = string_encoding or XML_STRING_ENCODING
if encoding and isinstance(xml_string, unicode):
xml_string = xml_string.encode(encoding)
tree = ElementTree.fromstring(xml_string)
return _CreateClassFromElementTree(target_class, tree)
def _CreateClassFromElementTree(target_class, tree, namespace=None, tag=None):
"""Instantiates the class and populates members according to the tree.
Note: Only use this function with classes that have _namespace and _tag
class members.
Args:
target_class: class The class which will be instantiated and populated
with the contents of the XML.
tree: ElementTree An element tree whose contents will be converted into
members of the new target_class instance.
namespace: str (optional) The namespace which the XML tree's root node must
match. If omitted, the namespace defaults to the _namespace of the
target class.
tag: str (optional) The tag which the XML tree's root node must match. If
omitted, the tag defaults to the _tag class member of the target
class.
Returns:
An instance of the target class - or None if the tag and namespace of
the XML tree's root node did not match the desired namespace and tag.
"""
if namespace is None:
namespace = target_class._namespace
if tag is None:
tag = target_class._tag
if tree.tag == '{%s}%s' % (namespace, tag):
target = target_class()
target._HarvestElementTree(tree)
return target
else:
return None
class ExtensionContainer(object):
def __init__(self, extension_elements=None, extension_attributes=None,
text=None):
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
# Three methods to create an object from an ElementTree
def _HarvestElementTree(self, tree):
# Fill in the instance members from the contents of the XML tree.
for child in tree:
self._ConvertElementTreeToMember(child)
for attribute, value in tree.attrib.iteritems():
self._ConvertElementAttributeToMember(attribute, value)
# Encode the text string according to the desired encoding type. (UTF-8)
if tree.text:
self.text = tree.text.encode(MEMBER_STRING_ENCODING)
def _ConvertElementTreeToMember(self, child_tree, current_class=None):
self.extension_elements.append(_ExtensionElementFromElementTree(
child_tree))
def _ConvertElementAttributeToMember(self, attribute, value):
# Encode the attribute value's string with the desired type Default UTF-8
if value:
self.extension_attributes[attribute] = value.encode(
MEMBER_STRING_ENCODING)
# One method to create an ElementTree from an object
def _AddMembersToElementTree(self, tree):
for child in self.extension_elements:
child._BecomeChildElement(tree)
for attribute, value in self.extension_attributes.iteritems():
if value:
# Decode the value from the desired encoding (default UTF-8).
tree.attrib[attribute] = value.decode(MEMBER_STRING_ENCODING)
if self.text and not isinstance(self.text, unicode):
tree.text = self.text.decode(MEMBER_STRING_ENCODING)
else:
tree.text = self.text
def FindExtensions(self, tag=None, namespace=None):
"""Searches extension elements for child nodes with the desired name.
Returns a list of extension elements within this object whose tag
and/or namespace match those passed in. To find all extensions in
a particular namespace, specify the namespace but not the tag name.
If you specify only the tag, the result list may contain extension
elements in multiple namespaces.
Args:
tag: str (optional) The desired tag
namespace: str (optional) The desired namespace
Returns:
A list of elements whose tag and/or namespace match the parameters
values
"""
results = []
if tag and namespace:
for element in self.extension_elements:
if element.tag == tag and element.namespace == namespace:
results.append(element)
elif tag and not namespace:
for element in self.extension_elements:
if element.tag == tag:
results.append(element)
elif namespace and not tag:
for element in self.extension_elements:
if element.namespace == namespace:
results.append(element)
else:
for element in self.extension_elements:
results.append(element)
return results
class AtomBase(ExtensionContainer):
_children = {}
_attributes = {}
def __init__(self, extension_elements=None, extension_attributes=None,
text=None):
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
def _ConvertElementTreeToMember(self, child_tree):
# Find the element's tag in this class's list of child members
if self.__class__._children.has_key(child_tree.tag):
member_name = self.__class__._children[child_tree.tag][0]
member_class = self.__class__._children[child_tree.tag][1]
# If the class member is supposed to contain a list, make sure the
# matching member is set to a list, then append the new member
# instance to the list.
if isinstance(member_class, list):
if getattr(self, member_name) is None:
setattr(self, member_name, [])
getattr(self, member_name).append(_CreateClassFromElementTree(
member_class[0], child_tree))
else:
setattr(self, member_name,
_CreateClassFromElementTree(member_class, child_tree))
else:
ExtensionContainer._ConvertElementTreeToMember(self, child_tree)
def _ConvertElementAttributeToMember(self, attribute, value):
# Find the attribute in this class's list of attributes.
if self.__class__._attributes.has_key(attribute):
# Find the member of this class which corresponds to the XML attribute
# (lookup in current_class._attributes) and set this member to the
# desired value (using self.__dict__).
if value:
# Encode the string to capture non-ascii characters (default UTF-8)
setattr(self, self.__class__._attributes[attribute],
value.encode(MEMBER_STRING_ENCODING))
else:
ExtensionContainer._ConvertElementAttributeToMember(self, attribute,
value)
# Three methods to create an ElementTree from an object
def _AddMembersToElementTree(self, tree):
# Convert the members of this class which are XML child nodes.
# This uses the class's _children dictionary to find the members which
# should become XML child nodes.
member_node_names = [values[0] for tag, values in
self.__class__._children.iteritems()]
for member_name in member_node_names:
member = getattr(self, member_name)
if member is None:
pass
elif isinstance(member, list):
for instance in member:
instance._BecomeChildElement(tree)
else:
member._BecomeChildElement(tree)
# Convert the members of this class which are XML attributes.
for xml_attribute, member_name in self.__class__._attributes.iteritems():
member = getattr(self, member_name)
if member is not None:
tree.attrib[xml_attribute] = member.decode(MEMBER_STRING_ENCODING)
# Lastly, call the ExtensionContainers's _AddMembersToElementTree to
# convert any extension attributes.
ExtensionContainer._AddMembersToElementTree(self, tree)
def _BecomeChildElement(self, tree):
"""
Note: Only for use with classes that have a _tag and _namespace class
member. It is in AtomBase so that it can be inherited but it should
not be called on instances of AtomBase.
"""
new_child = ElementTree.Element('')
tree.append(new_child)
new_child.tag = '{%s}%s' % (self.__class__._namespace,
self.__class__._tag)
self._AddMembersToElementTree(new_child)
def _ToElementTree(self):
"""
Note, this method is designed to be used only with classes that have a
_tag and _namespace. It is placed in AtomBase for inheritance but should
not be called on this class.
"""
new_tree = ElementTree.Element('{%s}%s' % (self.__class__._namespace,
self.__class__._tag))
self._AddMembersToElementTree(new_tree)
return new_tree
def ToString(self, string_encoding='UTF-8'):
"""Converts the Atom object to a string containing XML."""
return ElementTree.tostring(self._ToElementTree(), encoding=string_encoding)
def __str__(self):
return self.ToString()
class Name(AtomBase):
"""The atom:name element"""
_tag = 'name'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Name
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def NameFromString(xml_string):
return CreateClassFromXMLString(Name, xml_string)
class Email(AtomBase):
"""The atom:email element"""
_tag = 'email'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Email
Args:
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def EmailFromString(xml_string):
return CreateClassFromXMLString(Email, xml_string)
class Uri(AtomBase):
"""The atom:uri element"""
_tag = 'uri'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Uri
Args:
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def UriFromString(xml_string):
return CreateClassFromXMLString(Uri, xml_string)
class Person(AtomBase):
"""A foundation class from which atom:author and atom:contributor extend.
A person contains information like name, email address, and web page URI for
an author or contributor to an Atom feed.
"""
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_children['{%s}name' % (ATOM_NAMESPACE)] = ('name', Name)
_children['{%s}email' % (ATOM_NAMESPACE)] = ('email', Email)
_children['{%s}uri' % (ATOM_NAMESPACE)] = ('uri', Uri)
def __init__(self, name=None, email=None, uri=None,
extension_elements=None, extension_attributes=None, text=None):
"""Foundation from which author and contributor are derived.
The constructor is provided for illustrative purposes, you should not
need to instantiate a Person.
Args:
name: Name The person's name
email: Email The person's email address
uri: Uri The URI of the person's webpage
extension_elements: list A list of ExtensionElement instances which are
children of this element.
extension_attributes: dict A dictionary of strings which are the values
for additional XML attributes of this element.
text: String The text contents of the element. This is the contents
of the Entry's XML text node. (Example: <foo>This is the text</foo>)
"""
self.name = name
self.email = email
self.uri = uri
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
class Author(Person):
"""The atom:author element
An author is a required element in Feed.
"""
_tag = 'author'
_namespace = ATOM_NAMESPACE
_children = Person._children.copy()
_attributes = Person._attributes.copy()
#_children = {}
#_attributes = {}
def __init__(self, name=None, email=None, uri=None,
extension_elements=None, extension_attributes=None, text=None):
"""Constructor for Author
Args:
name: Name
email: Email
uri: Uri
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.name = name
self.email = email
self.uri = uri
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
def AuthorFromString(xml_string):
return CreateClassFromXMLString(Author, xml_string)
class Contributor(Person):
"""The atom:contributor element"""
_tag = 'contributor'
_namespace = ATOM_NAMESPACE
_children = Person._children.copy()
_attributes = Person._attributes.copy()
def __init__(self, name=None, email=None, uri=None,
extension_elements=None, extension_attributes=None, text=None):
"""Constructor for Contributor
Args:
name: Name
email: Email
uri: Uri
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.name = name
self.email = email
self.uri = uri
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
def ContributorFromString(xml_string):
return CreateClassFromXMLString(Contributor, xml_string)
class Link(AtomBase):
"""The atom:link element"""
_tag = 'link'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_attributes['rel'] = 'rel'
_attributes['href'] = 'href'
_attributes['type'] = 'type'
_attributes['title'] = 'title'
_attributes['length'] = 'length'
_attributes['hreflang'] = 'hreflang'
def __init__(self, href=None, rel=None, link_type=None, hreflang=None,
title=None, length=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Link
Args:
href: string The href attribute of the link
rel: string
type: string
hreflang: string The language for the href
title: string
length: string The length of the href's destination
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.href = href
self.rel = rel
self.type = link_type
self.hreflang = hreflang
self.title = title
self.length = length
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def LinkFromString(xml_string):
return CreateClassFromXMLString(Link, xml_string)
class Generator(AtomBase):
"""The atom:generator element"""
_tag = 'generator'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_attributes['uri'] = 'uri'
_attributes['version'] = 'version'
def __init__(self, uri=None, version=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for Generator
Args:
uri: string
version: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.uri = uri
self.version = version
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GeneratorFromString(xml_string):
return CreateClassFromXMLString(Generator, xml_string)
class Text(AtomBase):
"""A foundation class from which atom:title, summary, etc. extend.
This class should never be instantiated.
"""
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_attributes['type'] = 'type'
def __init__(self, text_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Text
Args:
text_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = text_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Title(Text):
"""The atom:title element"""
_tag = 'title'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
def __init__(self, title_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Title
Args:
title_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = title_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def TitleFromString(xml_string):
return CreateClassFromXMLString(Title, xml_string)
class Subtitle(Text):
"""The atom:subtitle element"""
_tag = 'subtitle'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
def __init__(self, subtitle_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Subtitle
Args:
subtitle_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = subtitle_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SubtitleFromString(xml_string):
return CreateClassFromXMLString(Subtitle, xml_string)
class Rights(Text):
"""The atom:rights element"""
_tag = 'rights'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
def __init__(self, rights_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Rights
Args:
rights_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = rights_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def RightsFromString(xml_string):
return CreateClassFromXMLString(Rights, xml_string)
class Summary(Text):
"""The atom:summary element"""
_tag = 'summary'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
def __init__(self, summary_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Summary
Args:
summary_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = summary_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SummaryFromString(xml_string):
return CreateClassFromXMLString(Summary, xml_string)
class Content(Text):
"""The atom:content element"""
_tag = 'content'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
_attributes['src'] = 'src'
def __init__(self, content_type=None, src=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for Content
Args:
content_type: string
src: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = content_type
self.src = src
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ContentFromString(xml_string):
return CreateClassFromXMLString(Content, xml_string)
class Category(AtomBase):
"""The atom:category element"""
_tag = 'category'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_attributes['term'] = 'term'
_attributes['scheme'] = 'scheme'
_attributes['label'] = 'label'
def __init__(self, term=None, scheme=None, label=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for Category
Args:
term: str
scheme: str
label: str
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.term = term
self.scheme = scheme
self.label = label
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def CategoryFromString(xml_string):
return CreateClassFromXMLString(Category, xml_string)
class Id(AtomBase):
"""The atom:id element."""
_tag = 'id'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Id
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def IdFromString(xml_string):
return CreateClassFromXMLString(Id, xml_string)
class Icon(AtomBase):
"""The atom:icon element."""
_tag = 'icon'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Icon
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def IconFromString(xml_string):
return CreateClassFromXMLString(Icon, xml_string)
class Logo(AtomBase):
"""The atom:logo element."""
_tag = 'logo'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Logo
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def LogoFromString(xml_string):
return CreateClassFromXMLString(Logo, xml_string)
class Draft(AtomBase):
"""The app:draft element which indicates if this entry should be public."""
_tag = 'draft'
_namespace = APP_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for app:draft
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def DraftFromString(xml_string):
return CreateClassFromXMLString(Draft, xml_string)
class Control(AtomBase):
"""The app:control element indicating restrictions on publication.
The APP control element may contain a draft element indicating whether or
not this entry should be publicly available.
"""
_tag = 'control'
_namespace = APP_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_children['{%s}draft' % APP_NAMESPACE] = ('draft', Draft)
def __init__(self, draft=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for app:control"""
self.draft = draft
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ControlFromString(xml_string):
return CreateClassFromXMLString(Control, xml_string)
class Date(AtomBase):
"""A parent class for atom:updated, published, etc."""
#TODO Add text to and from time conversion methods to allow users to set
# the contents of a Date to a python DateTime object.
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Updated(Date):
"""The atom:updated element."""
_tag = 'updated'
_namespace = ATOM_NAMESPACE
_children = Date._children.copy()
_attributes = Date._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Updated
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def UpdatedFromString(xml_string):
return CreateClassFromXMLString(Updated, xml_string)
class Published(Date):
"""The atom:published element."""
_tag = 'published'
_namespace = ATOM_NAMESPACE
_children = Date._children.copy()
_attributes = Date._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Published
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def PublishedFromString(xml_string):
return CreateClassFromXMLString(Published, xml_string)
class LinkFinder(object):
"""An "interface" providing methods to find link elements
Entry elements often contain multiple links which differ in the rel
attribute or content type. Often, developers are interested in a specific
type of link so this class provides methods to find specific classes of
links.
This class is used as a mixin in Atom entries and feeds.
"""
def GetSelfLink(self):
"""Find the first link with rel set to 'self'
Returns:
An atom.Link or none if none of the links had rel equal to 'self'
"""
for a_link in self.link:
if a_link.rel == 'self':
return a_link
return None
def GetEditLink(self):
for a_link in self.link:
if a_link.rel == 'edit':
return a_link
return None
def GetNextLink(self):
for a_link in self.link:
if a_link.rel == 'next':
return a_link
return None
def GetLicenseLink(self):
for a_link in self.link:
if a_link.rel == 'license':
return a_link
return None
def GetAlternateLink(self):
for a_link in self.link:
if a_link.rel == 'alternate':
return a_link
return None
class FeedEntryParent(AtomBase, LinkFinder):
"""A super class for atom:feed and entry, contains shared attributes"""
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_children['{%s}author' % ATOM_NAMESPACE] = ('author', [Author])
_children['{%s}category' % ATOM_NAMESPACE] = ('category', [Category])
_children['{%s}contributor' % ATOM_NAMESPACE] = ('contributor', [Contributor])
_children['{%s}id' % ATOM_NAMESPACE] = ('id', Id)
_children['{%s}link' % ATOM_NAMESPACE] = ('link', [Link])
_children['{%s}rights' % ATOM_NAMESPACE] = ('rights', Rights)
_children['{%s}title' % ATOM_NAMESPACE] = ('title', Title)
_children['{%s}updated' % ATOM_NAMESPACE] = ('updated', Updated)
def __init__(self, author=None, category=None, contributor=None,
atom_id=None, link=None, rights=None, title=None, updated=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.rights = rights
self.title = title
self.updated = updated
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Source(FeedEntryParent):
"""The atom:source element"""
_tag = 'source'
_namespace = ATOM_NAMESPACE
_children = FeedEntryParent._children.copy()
_attributes = FeedEntryParent._attributes.copy()
_children['{%s}generator' % ATOM_NAMESPACE] = ('generator', Generator)
_children['{%s}icon' % ATOM_NAMESPACE] = ('icon', Icon)
_children['{%s}logo' % ATOM_NAMESPACE] = ('logo', Logo)
_children['{%s}subtitle' % ATOM_NAMESPACE] = ('subtitle', Subtitle)
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for Source
Args:
author: list (optional) A list of Author instances which belong to this
class.
category: list (optional) A list of Category instances
contributor: list (optional) A list on Contributor instances
generator: Generator (optional)
icon: Icon (optional)
id: Id (optional) The entry's Id element
link: list (optional) A list of Link instances
logo: Logo (optional)
rights: Rights (optional) The entry's Rights element
subtitle: Subtitle (optional) The entry's subtitle element
title: Title (optional) the entry's title element
updated: Updated (optional) the entry's updated element
text: String (optional) The text contents of the element. This is the
contents of the Entry's XML text node.
(Example: <foo>This is the text</foo>)
extension_elements: list (optional) A list of ExtensionElement instances
which are children of this element.
extension_attributes: dict (optional) A dictionary of strings which are
the values for additional XML attributes of this element.
"""
self.author = author or []
self.category = category or []
self.contributor = contributor or []
self.generator = generator
self.icon = icon
self.id = atom_id
self.link = link or []
self.logo = logo
self.rights = rights
self.subtitle = subtitle
self.title = title
self.updated = updated
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SourceFromString(xml_string):
return CreateClassFromXMLString(Source, xml_string)
class Entry(FeedEntryParent):
"""The atom:entry element"""
_tag = 'entry'
_namespace = ATOM_NAMESPACE
_children = FeedEntryParent._children.copy()
_attributes = FeedEntryParent._attributes.copy()
_children['{%s}content' % ATOM_NAMESPACE] = ('content', Content)
_children['{%s}published' % ATOM_NAMESPACE] = ('published', Published)
_children['{%s}source' % ATOM_NAMESPACE] = ('source', Source)
_children['{%s}summary' % ATOM_NAMESPACE] = ('summary', Summary)
_children['{%s}control' % APP_NAMESPACE] = ('control', Control)
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None, rights=None,
source=None, summary=None, control=None, title=None, updated=None,
extension_elements=None, extension_attributes=None, text=None):
"""Constructor for atom:entry
Args:
author: list A list of Author instances which belong to this class.
category: list A list of Category instances
content: Content The entry's Content
contributor: list A list on Contributor instances
id: Id The entry's Id element
link: list A list of Link instances
published: Published The entry's Published element
rights: Rights The entry's Rights element
source: Source the entry's source element
summary: Summary the entry's summary element
title: Title the entry's title element
updated: Updated the entry's updated element
control: The entry's app:control element which can be used to mark an
entry as a draft which should not be publicly viewable.
text: String The text contents of the element. This is the contents
of the Entry's XML text node. (Example: <foo>This is the text</foo>)
extension_elements: list A list of ExtensionElement instances which are
children of this element.
extension_attributes: dict A dictionary of strings which are the values
for additional XML attributes of this element.
"""
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.title = title
self.updated = updated
self.control = control
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def EntryFromString(xml_string):
return CreateClassFromXMLString(Entry, xml_string)
class Feed(Source):
"""The atom:feed element"""
_tag = 'feed'
_namespace = ATOM_NAMESPACE
_children = Source._children.copy()
_attributes = Source._attributes.copy()
_children['{%s}entry' % ATOM_NAMESPACE] = ('entry', [Entry])
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None, entry=None,
text=None, extension_elements=None, extension_attributes=None):
"""Constructor for Source
Args:
author: list (optional) A list of Author instances which belong to this
class.
category: list (optional) A list of Category instances
contributor: list (optional) A list on Contributor instances
generator: Generator (optional)
icon: Icon (optional)
id: Id (optional) The entry's Id element
link: list (optional) A list of Link instances
logo: Logo (optional)
rights: Rights (optional) The entry's Rights element
subtitle: Subtitle (optional) The entry's subtitle element
title: Title (optional) the entry's title element
updated: Updated (optional) the entry's updated element
entry: list (optional) A list of the Entry instances contained in the
feed.
text: String (optional) The text contents of the element. This is the
contents of the Entry's XML text node.
(Example: <foo>This is the text</foo>)
extension_elements: list (optional) A list of ExtensionElement instances
which are children of this element.
extension_attributes: dict (optional) A dictionary of strings which are
the values for additional XML attributes of this element.
"""
self.author = author or []
self.category = category or []
self.contributor = contributor or []
self.generator = generator
self.icon = icon
self.id = atom_id
self.link = link or []
self.logo = logo
self.rights = rights
self.subtitle = subtitle
self.title = title
self.updated = updated
self.entry = entry or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def FeedFromString(xml_string):
return CreateClassFromXMLString(Feed, xml_string)
class ExtensionElement(object):
"""Represents extra XML elements contained in Atom classes."""
def __init__(self, tag, namespace=None, attributes=None,
children=None, text=None):
"""Constructor for EtensionElement
Args:
namespace: string (optional) The XML namespace for this element.
tag: string (optional) The tag (without the namespace qualifier) for
this element. To reconstruct the full qualified name of the element,
combine this tag with the namespace.
attributes: dict (optinal) The attribute value string pairs for the XML
attributes of this element.
children: list (optional) A list of ExtensionElements which represent
the XML child nodes of this element.
"""
self.namespace = namespace
self.tag = tag
self.attributes = attributes or {}
self.children = children or []
self.text = text
def ToString(self):
element_tree = self._TransferToElementTree(ElementTree.Element(''))
return ElementTree.tostring(element_tree, encoding="UTF-8")
def _TransferToElementTree(self, element_tree):
if self.tag is None:
return None
if self.namespace is not None:
element_tree.tag = '{%s}%s' % (self.namespace, self.tag)
else:
element_tree.tag = self.tag
for key, value in self.attributes.iteritems():
element_tree.attrib[key] = value
for child in self.children:
child._BecomeChildElement(element_tree)
element_tree.text = self.text
return element_tree
def _BecomeChildElement(self, element_tree):
"""Converts this object into an etree element and adds it as a child node.
Adds self to the ElementTree. This method is required to avoid verbose XML
which constantly redefines the namespace.
Args:
element_tree: ElementTree._Element The element to which this object's XML
will be added.
"""
new_element = ElementTree.Element('')
element_tree.append(new_element)
self._TransferToElementTree(new_element)
def FindChildren(self, tag=None, namespace=None):
"""Searches child nodes for objects with the desired tag/namespace.
Returns a list of extension elements within this object whose tag
and/or namespace match those passed in. To find all children in
a particular namespace, specify the namespace but not the tag name.
If you specify only the tag, the result list may contain extension
elements in multiple namespaces.
Args:
tag: str (optional) The desired tag
namespace: str (optional) The desired namespace
Returns:
A list of elements whose tag and/or namespace match the parameters
values
"""
results = []
if tag and namespace:
for element in self.children:
if element.tag == tag and element.namespace == namespace:
results.append(element)
elif tag and not namespace:
for element in self.children:
if element.tag == tag:
results.append(element)
elif namespace and not tag:
for element in self.children:
if element.namespace == namespace:
results.append(element)
else:
for element in self.children:
results.append(element)
return results
def ExtensionElementFromString(xml_string):
element_tree = ElementTree.fromstring(xml_string)
return _ExtensionElementFromElementTree(element_tree)
def _ExtensionElementFromElementTree(element_tree):
element_tag = element_tree.tag
if '}' in element_tag:
namespace = element_tag[1:element_tag.index('}')]
tag = element_tag[element_tag.index('}')+1:]
else:
namespace = None
tag = element_tag
extension = ExtensionElement(namespace=namespace, tag=tag)
for key, value in element_tree.attrib.iteritems():
extension.attributes[key] = value
for child in element_tree:
extension.children.append(_ExtensionElementFromElementTree(child))
extension.text = element_tree.text
return extension
| Python |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class MainHandler(webapp.RequestHandler):
def get(self):
self.response.out.write("""
<html>
<body>
<center>
<h1>Hello world!</h1>
</center>
</body>
</html> """)
def main():
application = webapp.WSGIApplication(
[
('/', MainHandler)
],
debug=True)
run_wsgi_app(application)
if __name__ == '__main__':
main()
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.