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 addRecommendation(self, title, url, comment=""): entry = douban.RecommendationEntry() entry.title = atom.Title(text=title) entry.link = atom.Link(href=url, rel="related") attribute = douban.Attribute('comment', comment) entry.attribute.append(attribute) return self.__parsed(self.__post("/recommendations", entry.ToString()), douban.RecommendationEntryFromString)
def AddRecommendation(self, title, url, comment=""): entry = douban.RecommendationEntry() entry.title = atom.Title(text=title) entry.link = atom.Link(href=url, rel="related") attribute = douban.Attribute('comment', comment) entry.attribute.append(attribute) return self.Post(entry, '/recommendations', converter=douban.RecommendationEntryFromString)
def __getEntryForDocument(self, queryPath, id): """ @param queryPath: Query to search for the entry @type queryPath: String @param id: Id to be applied to atom feed @type id: String @rtype: ElementTree._Element, or xml_wrapper.ElementWrapper @return entry """ docPath = self.rep.getPathForId(id) # check docPath if docPath.startswith(queryPath): item = self.rep.getItem(docPath) if item.hasHtml: docPath = self.iceContext.fs.splitExt(docPath)[0] + ".htm" title = item.getMeta("title") try: title = title.decode("utf-8") except: msg = "[Can not display title because of an encoding error!]" print "%s\n title='%s' path='%s'\n" % (msg, title, docPath) title = msg content = item.getRendition(".xhtml.body") if content is None: content = "<p>[Not rendered!]</p>" contentElem = ElementTree.XML(content) firstPara = contentElem.find("p") summary = "No summary" if firstPara != None: summary = ElementTree.tostring(firstPara) name = item.name lastModifiedTime = self.iceContext.fs.getModifiedTime( self.rep.getAbsPath(name)) entryDate = datetime.fromtimestamp( lastModifiedTime).isoformat() + 'Z' srcUrl = "http://%s:%s%s" % (self.hostname, self.iceWebPort, docPath) entry = atom.Entry(title=atom.Title(text=title)) entry.id = atom.Id(text="urn:uid:%s" % id) entry.link = [atom.Link(href=srcUrl, rel="alternate")] entry.updated = atom.Updated(text=entryDate) entry.published = atom.Published(text=entryDate) entry.summary = atom.Summary(summary_type="html", text=unicode(summary, "utf-8")) entry.content = atom.Content(content_type="html", text=unicode(content, "utf-8")) return entry else: return None
def __init__(self, siteName=None, title=None, summary=None, theme=None, sourceSite=None, category=None, etag=None): gdata.BatchEntry.__init__(self, category=category) self.siteName = siteName self.title = title self.summary = summary self.theme = theme if sourceSite is not None: sourceLink = atom.Link(href=sourceSite, rel=SITES_SOURCE_LINK_REL, link_type='application/atom+xml') self.link.append(sourceLink) self.etag = etag
def testConstruct(self): thumb_url = 'http://base.googlehosted.com/base_media?q=http%3A%2F%2Fexample.com%2FEOS%2F1AEOS01008.jpg' item = gdata.base.GBaseItem() item.title = atom.Title(text='Olds Cutlass Supreme Oxygen O2 Sensor') item.link.append( atom.Link(rel='alternate', link_type='text/html', href='http://www.example.com/123456jsh9')) item.item_type = gdata.base.ItemType(text='Products') item.AddItemAttribute(name='price', value_type='floatUnit', value='41.94 usd') item.AddItemAttribute(name='id', value_type='text', value='1AEOS01008-415676-XXX') item.AddItemAttribute(name='quantity', value_type='int', value='5') attr = item.AddItemAttribute(name='image_link', value_type='url', value=None) attr.AddItemAttribute(name='thumb', value=thumb_url, value_type='url') image_attr = item.GetItemAttributes("image_link")[0] self.assert_(isinstance(image_attr, gdata.base.ItemAttributeContainer)) self.assert_( isinstance(image_attr.item_attributes[0], gdata.base.ItemAttributeContainer)) self.assert_( isinstance(image_attr.item_attributes[0], gdata.base.ItemAttribute)) self.assert_(image_attr.item_attributes[0].type == 'url') self.assert_(image_attr.item_attributes[0].text == thumb_url) self.assert_(len(image_attr.item_attributes) == 1) new_item = gdata.base.GBaseItemFromString(item.ToString()) image_attr = item.GetItemAttributes("image_link")[0] self.assert_( isinstance(image_attr.item_attributes[0], gdata.base.ItemAttributeContainer)) self.assert_(image_attr.item_attributes[0].type == 'url') self.assert_(image_attr.item_attributes[0].text == thumb_url) self.assert_(len(image_attr.item_attributes) == 1)
def testLinkType(self): test_link = atom.Link(link_type='text/html') self.assert_(test_link.type == 'text/html')
def setUp(self): self.link = atom.Link()
def _CreateBirthdayWebContentEvent(self, name, birthday, photo_url): """ Create the birthday web content event. This function creates and populates a CalendarEventEntry. webContent specific attributes are set. To learn more about the webContent format: http://www.google.com/support/calendar/bin/answer.py?answer=48528 Args: name: string birthday: string - expected format (MM/DD) photo_url: string Returns: the webContent CalendarEventEntry """ title = "%s's Birthday!" % name content = "It's %s's Birthday!" % name month = string.atoi(birthday.split("/")[0]) day = string.atoi(birthday.split("/")[1]) # Get current year year = time.ctime()[-4:] year = string.atoi(year) # Calculate the "end date" for the all day event start_time = datetime.date(year, month, day) one_day = datetime.timedelta(days=1) end_time = start_time + one_day start_time_str = start_time.strftime("%Y-%m-%d") end_time_str = end_time.strftime("%Y-%m-%d") # Create yearly recurrence rule recurrence_data = ( "DTSTART;VALUE=DATE:%s\r\n" "DTEND;VALUE=DATE:%s\r\n" "RRULE:FREQ=YEARLY;WKST=SU\r\n" % (start_time.strftime("%Y%m%d"), end_time.strftime("%Y%m%d"))) web_rel = "http://schemas.google.com/gCal/2005/webContent" icon_href = "http://www.perstephanie.com/images/birthdayicon.gif" icon_type = "image/gif" extension_text = ( 'gCal:webContent xmlns:gCal="http://schemas.google.com/gCal/2005"' ' url="%s" width="300" height="225"' % (photo_url)) event = gdata.calendar.CalendarEventEntry() event.title = atom.Title(text=title) event.content = atom.Content(text=content) event.recurrence = gdata.calendar.Recurrence(text=recurrence_data) event.when.append( gdata.calendar.When(start_time=start_time_str, end_time=end_time_str)) # Adding the webContent specific XML event.link.append( atom.Link(rel=web_rel, title=title, href=icon_href, link_type=icon_type)) event.link[0].extension_elements.append( atom.ExtensionElement(extension_text)) return event
# 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'}) # Send the XML from the server to standard out. print 'Here\'s the XML from the server\'s simulated insert' print str(result)