def editPost(self, blogID, postID, title, content, author_name, is_draft, timestamp=None): # Create the entry to insert. entry = gdata.GDataEntry() entry.author.append(atom.Author(atom.Name(text='Post author'))) entry.title = atom.Title('xhtml', text=title) entry.content = atom.Content('html', text=content) if is_draft: control = atom.Control() control.draft = atom.Draft(text='yes') entry.control = control # If a timestamp is specified, use that timestamp if timestamp: entry.published = atom.Published(timestamp) # Ask the service to insert the new entry. return self.service.Put( entry, '/feeds/' + blogID + '/posts/default/' + postID)
def _export_task(self, cr, uid, data, context): obj_user = pooler.get_pool(cr.dbname).get('res.users') blog_auth_details = obj_user.read(cr, uid, uid, []) if not blog_auth_details['blogger_email'] or not blog_auth_details[ 'blogger_password']: raise osv.except_osv( 'Warning !', 'Please blogger Enter email id and password in users') try: self.blog_service = service.GDataService( blog_auth_details['blogger_email'], blog_auth_details['blogger_password']) self.blog_service.source = 'Tiny' self.blog_service.service = 'blogger' self.blog_service.server = 'www.blogger.com' self.blog_service.ProgrammaticLogin() feed = self.blog_service.Get('/feeds/default/blogs') self_link = feed.entry[0].GetSelfLink() if self_link: self.blog_id = self_link.href.split('/')[-1] obj_task = pooler.get_pool(cr.dbname).get('project.task') data_task = obj_task.read(cr, uid, data['form']['blog_id'][0][2], []) for task in data_task: entry = gdata.GDataEntry() entry.author.append(atom.Author(atom.Name(text='uid'))) entry.title = atom.Title(title_type='xhtml', text=task['name']) entry.content = atom.Content(content_type='html', text=task['description']) self.blog_service.Post( entry, '/feeds/' + self.blog_id + '/posts/default') return {'summary': 'Succefully sent tasks to blogger'} except Exception, e: raise osv.except_osv('Error !', e)
def createPost(self, title, content, authorName, labels=None, isDraft=False): # Create a gdata entry. entry = gdata.GDataEntry() # append author. entry.author.append(atom.Author(atom.Name(text=authorName))) entry.title = atom.Title(title_type='xhtml', text=title) # handle labels by using atom.Category. if labels: for label in labels: category = atom.Category(scheme=blogger.LABEL_SCHEME, term=label) entry.category.append(category) # handle draft, if isDraft: control = atom.Control() control.draft = atom.Draft(text='yes') entry.control = control # add content. entry.content = atom.Content(content_type='html', text=content) return self.gdService.Post(entry, self.postsUri)
def createPost(self, blogID, title, content, author_name, is_draft, timestamp=None): """This method creates a new post on a blog. The new post can be stored as a draft or published based on the value of the is_draft parameter. The method creates an GDataEntry for the new post using the title, content, author_name and is_draft parameters. With is_draft, True saves the post as a draft, while False publishes the post. Then it uses the given GDataService to insert the new post. If the insertion is successful, the added post (GDataEntry) will be returned. """ # Create the entry to insert. entry = gdata.GDataEntry() entry.author.append(atom.Author(atom.Name(text='Post author'))) entry.title = atom.Title('xhtml', text=title) entry.content = atom.Content('html', text=content) if is_draft: control = atom.Control() control.draft = atom.Draft(text='yes') entry.control = control # If a timestamp is specified, use that timestamp if timestamp: entry.published = atom.Published(timestamp) # Ask the service to insert the new entry. return self.service.Post(entry, '/feeds/' + blogID + '/posts/default')
def CreatePost(self, title, content, author_name, tags, is_draft): """This method creates a new post on a blog. The new post can be stored as a draft or published based on the value of the is_draft parameter. The method creates an GDataEntry for the new post using the title, content, author_name and is_draft parameters. With is_draft, True saves the post as a draft, while False publishes the post. Then it uses the given GDataService to insert the new post. If the insertion is successful, the added post (GDataEntry) will be returned. """ # Create the entry to insert. entry = gdata.GDataEntry() entry.author.append(atom.Author(atom.Name(text=author_name))) entry.title = atom.Title(title_type='xhtml', text=title) entry.content = atom.Content(content_type='html', text=content) for tag in tags: category = atom.Category(term=tag, scheme="http://www.blogger.com/atom/ns#") entry.category.append(category) if is_draft: control = atom.Control() control.draft = atom.Draft(text='yes') entry.control = control # Ask the service to insert the new entry. return self.service.Post(entry, '/feeds/' + self.blog_id + '/posts/default')
def testPostAndDeleteExtendedPropertyEvent(self): """Test posting a new entry with an extended property, deleting it""" # Get random data for creating event r = random.Random() r.seed() random_event_number = str(r.randint(100000, 1000000)) random_event_title = 'My Random Extended Property Test Event %s' % ( random_event_number) # Set event data event = gdata.calendar.CalendarEventEntry() event.author.append( atom.Author(name=atom.Name(text='GData Test user'))) event.title = atom.Title(text=random_event_title) event.content = atom.Content(text='Picnic with some lunch') event.extended_property.append( gdata.calendar.ExtendedProperty(name='prop test name', value='prop test value')) # Insert event self.cal_client.ProgrammaticLogin() new_event = self.cal_client.InsertEvent( event, '/calendar/feeds/default/private/full') self.assertEquals(event.extended_property[0].value, new_event.extended_property[0].value) # Delete the event self.cal_client.DeleteEvent(new_event.GetEditLink().href)
def testConvertToAndFromString(self): feed = atom.Feed() feed.author.append(atom.Author(name=atom.Name(text='js'))) feed.title = atom.Title(text='my test source') feed.generator = atom.Generator(text='gen') feed.entry.append( atom.Entry( author=[atom.Author(name=atom.Name(text='entry author'))])) self.assert_(feed.author[0].name.text == 'js') self.assert_(feed.title.text == 'my test source') self.assert_(feed.generator.text == 'gen') self.assert_(feed.entry[0].author[0].name.text == 'entry author') new_feed = atom.FeedFromString(feed.ToString()) self.assert_(new_feed.author[0].name.text == 'js') self.assert_(new_feed.title.text == 'my test source') self.assert_(new_feed.generator.text == 'gen') self.assert_(new_feed.entry[0].author[0].name.text == 'entry author')
def testConvertToAndFromString(self): entry = atom.Entry() entry.author.append(atom.Author(name=atom.Name(text='js'))) entry.title = atom.Title(text='my test entry') self.assert_(entry.author[0].name.text == 'js') self.assert_(entry.title.text == 'my test entry') new_entry = atom.EntryFromString(entry.ToString()) self.assert_(new_entry.author[0].name.text == 'js') self.assert_(new_entry.title.text == 'my test entry')
def testPostEntryWithCommentAndDelete(self): """Test posting a new entry with an extended property, deleting it""" # Get random data for creating event r = random.Random() r.seed() random_event_number = str(r.randint(100000, 1000000)) random_event_title = 'My Random Comments Test Event %s' % ( random_event_number) # Set event data event = gdata.calendar.CalendarEventEntry() event.author.append( atom.Author(name=atom.Name(text='GData Test user'))) event.title = atom.Title(text=random_event_title) event.content = atom.Content(text='Picnic with some lunch') # Insert event self.cal_client.ProgrammaticLogin() new_event = self.cal_client.InsertEvent( event, '/calendar/feeds/default/private/full') # Get comments feed comments_url = new_event.comments.feed_link.href comments_query = gdata.calendar.service.CalendarEventCommentQuery( comments_url) comments_feed = self.cal_client.CalendarQuery(comments_query) # Add comment comments_entry = gdata.calendar.CalendarEventCommentEntry() comments_entry.content = atom.Content(text='Comments content') comments_entry.author.append( atom.Author(name=atom.Name(text='GData Test user'), email=atom.Email(text=username))) new_comments_entry = self.cal_client.InsertEventComment( comments_entry, comments_feed.GetPostLink().href) # Delete the event event_to_delete = self.cal_client.GetCalendarEventEntry( new_event.id.text) self.cal_client.DeleteEvent(event_to_delete.GetEditLink().href)
def testConvertToAndFromString(self): source = atom.Source() source.author.append(atom.Author(name=atom.Name(text='js'))) source.title = atom.Title(text='my test source') source.generator = atom.Generator(text='gen') self.assert_(source.author[0].name.text == 'js') self.assert_(source.title.text == 'my test source') self.assert_(source.generator.text == 'gen') new_source = atom.SourceFromString(source.ToString()) self.assert_(new_source.author[0].name.text == 'js') self.assert_(new_source.title.text == 'my test source') self.assert_(new_source.generator.text == 'gen')
def __post(self, author, title, summary, content, category, draft, entryXml): """ to post the content to the server @param author: Author name @type author: String @param title: Title of the content @type title: String @param summary: Summary of the content @type summary: String @param content: Content @type content: String @param draft: Type of the document: @type draft: boolean @param entryXml: extra entry @type entryXml: String @rtype: (Atom Entry, String) @return: entry, httpResponse """ # create/update the atom entry if entryXml == None: entry = atom.Entry() entryUri = self.entryUri else: entry = atom.EntryFromString(entryXml) entryUri = entry.GetEditLink().href entry.author = [atom.Author(text=author)] entry.title = atom.Title(text=title) entry.summary = atom.Summary(text=summary) entry.content = atom.Content(content_type="html", text=unicode(content, "utf-8")) if category != "": entry.category = atom.Category(term=category) if draft: entry.control = atom.Control(draft=atom.Draft(text="yes")) else: entry.control = atom.Control(draft=atom.Draft(text="no")) # setup the http headers for authorisation extraHeaders = {"Slug": title} extraHeaders.update(self.authHeaders) # use POST or PUT depending on whether it is a new entry or an update if entryXml != None: publishFunc = self.atomService.Put else: publishFunc = self.atomService.Post self.__checkNoProxy(entryUri) httpResponse = publishFunc(data=entry, uri=entryUri, extra_headers=extraHeaders) self.__resetProxy() return entry, httpResponse
def post_job(self, title, content): """ Post a job with given title and content """ # Create the entry to insert. entry = gdata.GDataEntry() entry.author.append(atom.Author(atom.Name(text="Post Author"))) entry.title = atom.Title(title_type='xhtml', text=title) entry.content = atom.Content(content_type='html', text=content) # Ask the service to insert the new entry. job_post = self.service.Post( entry, '/feeds/' + str(self.blog_id) + '/posts/default') print "Successfully created post: \"" + job_post.title.text + "\".\n"
def testConvertToAndFromElementTree(self): # Use entry because FeedEntryParent doesn't have a tag or namespace. original = atom.Entry() copy = atom.FeedEntryParent() original.author.append(atom.Author(name=atom.Name(text='J Scud'))) self.assert_(original.author[0].name.text == 'J Scud') self.assert_(copy.author == []) original.id = atom.Id(text='test id') self.assert_(original.id.text == 'test id') self.assert_(copy.id is None) copy._HarvestElementTree(original._ToElementTree()) self.assert_(original.author[0].name.text == copy.author[0].name.text) self.assert_(original.id.text == copy.id.text)
def getSearchFeed(self, requestData): """ get the feed @param requestData: list of requestData @type requestData: RequestData @rtype: String @return feed as xml """ path = requestData.unquotedPath[9:] query = requestData.value("query") entries = [] if query != None: results = self.rep.search(query) if len(results) > 0: for id in results: entry = self.__getEntryForDocument(path, id) if entry != None: entries.append(entry) queryStr = "/?" for key in requestData.keys(): val = requestData.value(key) if not key in ["func", "format"]: queryStr += "%s=%s&" % (key, val) altUrl = "http://%s:%s%s" % (self.hostname, self.iceWebPort, queryStr[:-1]) self.feed.id = atom.Id(text=self.__getAtomTagId(query)) self.feed.updated = atom.Updated(text=datetime.now().isoformat() + 'Z') self.feed.link = [ atom.Link(href="%s&format=atom" % altUrl, rel="self"), atom.Link(href=altUrl, rel="alternate") ] self.feed.author = [atom.Author(name=atom.Name(text="ICE"))] self.feed.entry = entries feedXml = self.feed.ToString() #remove the namespace generated by elementtree/gdata as it causes #problems with some readers feedXml = feedXml.replace(":ns0", "") feedXml = feedXml.replace("ns0:", "") #insert the title manually as elementtree/gdata places the title in the #wrong position insertPos = feedXml.find("<entry>") feedXml = "%s<title>%s - %s</title>%s" % ( feedXml[0:insertPos], self.title, query, feedXml[insertPos:]) return feedXml
def testCreateAndDeleteEventUsingBatch(self): # Get random data for creating event r = random.Random() r.seed() random_event_number = str(r.randint(100000, 1000000)) random_event_title = 'My Random Comments Test Event %s' % ( random_event_number) # Set event data event = gdata.calendar.CalendarEventEntry() event.author.append( atom.Author(name=atom.Name(text='GData Test user'))) event.title = atom.Title(text=random_event_title) event.content = atom.Content(text='Picnic with some lunch') # Form a batch request batch_request = gdata.calendar.CalendarEventFeed() batch_request.AddInsert(entry=event) # Execute the batch request to insert the event. self.cal_client.ProgrammaticLogin() batch_result = self.cal_client.ExecuteBatch( batch_request, gdata.calendar.service.DEFAULT_BATCH_URL) self.assertEquals(len(batch_result.entry), 1) self.assertEquals(batch_result.entry[0].title.text, random_event_title) self.assertEquals(batch_result.entry[0].batch_operation.type, gdata.BATCH_INSERT) self.assertEquals(batch_result.GetBatchLink().href, gdata.calendar.service.DEFAULT_BATCH_URL) # Create a batch request to delete the newly created entry. batch_delete_request = gdata.calendar.CalendarEventFeed() batch_delete_request.AddDelete(entry=batch_result.entry[0]) batch_delete_result = self.cal_client.ExecuteBatch( batch_delete_request, batch_result.GetBatchLink().href) self.assertEquals(len(batch_delete_result.entry), 1) self.assertEquals(batch_delete_result.entry[0].batch_operation.type, gdata.BATCH_DELETE)
def generate_feed(posts): author = atom.Author(name=settings['author'], email=settings['email']) entries = [] for post in posts[:5]: # Rewrite post path into the weird id form I used to use. id = settings['id_base'] + '/' + ( post.timestamp.strftime('%Y-%m-%d') + '/' + os.path.splitext(os.path.basename(post.path))[0]) timestamp = post.timestamp + datetime.timedelta(seconds=time.timezone) entries.append(atom.Entry(timestamp=timestamp, id=id, title=post.title, link=settings['link'] + post.path, content=post.content)) feed = atom.Feed(title=settings['title'], id=settings['id_base'], link=settings['link'], selflink=settings['link'] + 'atom.xml', author=author, entries=entries) return feed.to_xml()
def process(self): from gdata import service import gdata import atom gblog_service = self.connector.open() feed = gblog_service.Get('/feeds/default/blogs') self_link = feed.entry[0].GetSelfLink() if self_link: blog_id = self_link.href.split('/')[-1] for channel, trans in self.input_get().items(): for iterator in trans: for d in iterator: entry = gdata.GDataEntry() entry.author.append(atom.Author(atom.Name(text='uid'))) entry.title = atom.Title(title_type='xhtml', text=d['name']) entry.content = atom.Content(content_type='html', text=d['description']) gblog_service.Post(entry, '/feeds/' + blog_id + '/posts/default') yield d, 'main'
def createPost(self, title, content, author_name, is_draft): """This method creates a new post on a blog. The new post can be stored as a draft or published based on the value of the is_draft parameter. The method creates an GDataEntry for the new post using the title, content, author_name and is_draft parameters. With is_draft, True saves the post as a draft, while False publishes the post. Then it uses the given GDataService to insert the new post. If the insertion is successful, the added post (GDataEntry) will be returned. """ # Authenticate using ClientLogin. self.service = service.GDataService('user', 'password') self.service.source = 'Blogger_Python_Sample-1.0' self.service.service = 'blogger' self.service.server = 'www.blogger.com' self.service.ProgrammaticLogin() # Get the blog ID for the first blog. feed = self.service.Get('/feeds/default/blogs') self_link = feed.entry[0].GetSelfLink() if self_link: self.blog_id = self_link.href.split('/')[-1] # Create the entry to insert. entry = gdata.GDataEntry() entry.author.append(atom.Author(atom.Name(text=author_name))) entry.title = atom.Title(title_type='xhtml', text=title) entry.content = atom.Content(content_type='html', text=content) if is_draft: control = atom.Control() control.draft = atom.Draft(text='yes') entry.control = control # Ask the service to insert the new entry. return self.service.Post(entry, '/feeds/' + self.blog_id + '/posts/default')
servic = service.GDataService(user, password) servic.source = 'Blogger_Python_Sample-1.0' servic.service = 'blogger' servic.server = 'www.blogger.com' servic.ProgrammaticLogin() feed = servic.Get('/feeds/default/blogs') self_link = feed.entry[0].GetSelfLink() if self_link: blog_id = self_link.href.split('/')[-1] entry = gdata.GDataEntry() entry.author.append(atom.Author(atom.Name(text='author'))) entry.title = atom.Title(title_type='xhtml', text=fileHandle.readline() ) entry.content = atom.Content(content_type='html', text=fileHandle.read()) AtomCategory category = new AtomCategory(); category.Term = "labelToDisplay"; category.Scheme = "http://www.blogger.com/atom/ns#"; entry.Categories.Add(category); #if is_draft: # control = atom.Control() # control.draft = atom.Draft(text='yes') # entry.control = control # Ask the service to insert the new entry.
import gdata.base import getpass # Demonstrates item insertion with a dry run insert operation. The item will # NOT be added to Google Base. gb_client = gdata.base.service.GBaseService() gb_client.email = raw_input('Please enter your username: '******'Logging in' gb_client.ProgrammaticLogin() # Create a test item which will be used in a dry run insert item = gdata.base.GBaseItem() item.author.append(atom.Author(name=atom.Name(text='Mr. Smith'))) item.title = atom.Title(text='He Jingxian\'s chicken') item.link.append(atom.Link(rel='alternate', link_type='text/html', href='http://www.host.com/123456jsh9')) item.label.append(gdata.base.Label(text='kung pao chicken')) item.label.append(gdata.base.Label(text='chinese cuisine')) item.label.append(gdata.base.Label(text='testrecipes')) item.item_type = gdata.base.ItemType(text='recipes') item.AddItemAttribute(name='cooking_time', value_type='intUnit', value='30 minutes') item.AddItemAttribute(name='main_ingredient', value='chicken') item.AddItemAttribute(name='main_ingredient', value='chili') # Make an insert request with the dry run flag set so that the item will not # actually be created. result = gb_client.InsertItem(item, url_params={'dry-run': 'true'})
def setUp(self): self.author = atom.Author()
def testPostQueryUpdateAndDeleteEvents(self): """Test posting a new entry, updating it, deleting it, querying for it""" # Get random data for creating event r = random.Random() r.seed() random_event_number = str(r.randint(100000, 1000000)) random_event_title = 'My Random Test Event %s' % random_event_number random_start_hour = (r.randint(1, 1000000) % 23) random_end_hour = random_start_hour + 1 non_random_start_minute = 0 non_random_end_minute = 0 random_month = (r.randint(1, 1000000) % 12 + 1) random_day_of_month = (r.randint(1, 1000000) % 28 + 1) non_random_year = 2008 start_time = '%04d-%02d-%02dT%02d:%02d:00.000-05:00' % ( non_random_year, random_month, random_day_of_month, random_start_hour, non_random_start_minute, ) end_time = '%04d-%02d-%02dT%02d:%02d:00.000-05:00' % ( non_random_year, random_month, random_day_of_month, random_end_hour, non_random_end_minute, ) # Set event data event = gdata.calendar.CalendarEventEntry() event.author.append( atom.Author(name=atom.Name(text='GData Test user'))) event.title = atom.Title(text=random_event_title) event.content = atom.Content(text='Picnic with some lunch') event.where.append( gdata.calendar.Where(value_string='Down by the river')) event.when.append( gdata.calendar.When(start_time=start_time, end_time=end_time)) # Insert event self.cal_client.ProgrammaticLogin() new_event = self.cal_client.InsertEvent( event, '/calendar/feeds/default/private/full') # Ensure that atom data returned from calendar server equals atom data sent self.assertEquals(event.title.text, new_event.title.text) self.assertEquals(event.content.text, new_event.content.text) # Ensure that gd:where data returned from calendar equals value sent self.assertEquals(event.where[0].value_string, new_event.where[0].value_string) # Commented out as dateutil is not in this repository # Ensure that dates returned from calendar server equals dates sent #start_time_py = parse(event.when[0].start_time) #start_time_py_new = parse(new_event.when[0].start_time) #self.assertEquals(start_time_py, start_time_py_new) #end_time_py = parse(event.when[0].end_time) #end_time_py_new = parse(new_event.when[0].end_time) #self.assertEquals(end_time_py, end_time_py_new) # Update event event_to_update = new_event updated_title_text = event_to_update.title.text + ' - UPDATED' event_to_update.title = atom.Title(text=updated_title_text) updated_event = self.cal_client.UpdateEvent( event_to_update.GetEditLink().href, event_to_update) # Ensure that updated title was set in the updated event self.assertEquals(event_to_update.title.text, updated_event.title.text) # Delete the event self.cal_client.DeleteEvent(updated_event.GetEditLink().href) # Ensure deleted event is marked as canceled in the feed after_delete_query = gdata.calendar.service.CalendarEventQuery() after_delete_query.updated_min = '2007-01-01' after_delete_query.text_query = str(random_event_number) after_delete_query.max_results = '1' after_delete_query_result = self.cal_client.CalendarQuery( after_delete_query) # Ensure feed returned at max after_delete_query.max_results events self.assert_( len(after_delete_query_result.entry) <= after_delete_query.max_results) # Ensure status of returned event is canceled self.assertEquals( after_delete_query_result.entry[0].event_status.value, 'CANCELED')
def testEventWithSyncEventAndUID(self): """Test posting a new entry (with syncEvent and a UID) and deleting it.""" # Get random data for creating event r = random.Random() r.seed() random_event_number = str(r.randint(100000, 1000000)) random_event_title = 'My Random Test Event %s' % random_event_number random_start_hour = (r.randint(1, 1000000) % 23) random_end_hour = random_start_hour + 1 non_random_start_minute = 0 non_random_end_minute = 0 random_month = (r.randint(1, 1000000) % 12 + 1) random_day_of_month = (r.randint(1, 1000000) % 28 + 1) non_random_year = 2008 start_time = '%04d-%02d-%02dT%02d:%02d:00.000-05:00' % ( non_random_year, random_month, random_day_of_month, random_start_hour, non_random_start_minute, ) end_time = '%04d-%02d-%02dT%02d:%02d:00.000-05:00' % ( non_random_year, random_month, random_day_of_month, random_end_hour, non_random_end_minute, ) # create a random event ID. I'm mimicing an example from outlook here, # the format doesn't seem to be important per the RFC except for being # globally unique. uid_string = '' for i in xrange(121): uid_string += "%X" % r.randint(0, 0xf) # Set event data event = gdata.calendar.CalendarEventEntry() event.author.append( atom.Author(name=atom.Name(text='GData Test user'))) event.title = atom.Title(text=random_event_title) event.content = atom.Content(text='Picnic with some lunch') event.where.append( gdata.calendar.Where(value_string='Down by the river')) event.when.append( gdata.calendar.When(start_time=start_time, end_time=end_time)) event.sync_event = gdata.calendar.SyncEvent('true') event.uid = gdata.calendar.UID(value=uid_string) # Insert event self.cal_client.ProgrammaticLogin() new_event = self.cal_client.InsertEvent( event, '/calendar/feeds/default/private/full') # Inserting it a second time should fail, as it'll have the same UID try: bad_event = self.cal_client.InsertEvent( event, '/calendar/feeds/default/private/full') self.fail('Was able to insert an event with a duplicate UID') except gdata.service.RequestError, error: # for the current problem with redirects, just re-raise so the # failure doesn't seem to be because of the duplicate UIDs. status = error[0]['status'] if status == 302: raise # otherwise, make sure it was the right error self.assertEquals(error[0]['status'], 409) self.assertEquals(error[0]['reason'], 'Conflict')