예제 #1
0
 def testIdParsing(self):
     entry = gdata.blogger.BlogEntry()
     entry.id = atom.Id(
         text='tag:blogger.com,1999:user-146606542.blog-4023408167658848')
     self.assertEquals(entry.GetBlogId(), '4023408167658848')
     entry.id = atom.Id(text='tag:blogger.com,1999:blog-4023408167658848')
     self.assertEquals(entry.GetBlogId(), '4023408167658848')
예제 #2
0
  def testAddInsert(self):
    
    first_entry = gdata.BatchEntry(
        atom_id=atom.Id(text='http://example.com/1'), text='This is a test1')
    self.batch_feed.AddInsert(first_entry)
    self.assertEquals(self.batch_feed.entry[0].batch_operation.type, 
                      gdata.BATCH_INSERT)
    self.assertEquals(self.batch_feed.entry[0].batch_id.text, '0')

    second_entry = gdata.BatchEntry(
        atom_id=atom.Id(text='http://example.com/2'), text='This is a test2')
    self.batch_feed.AddInsert(second_entry, batch_id_string='foo')
    self.assertEquals(self.batch_feed.entry[1].batch_operation.type, 
                      gdata.BATCH_INSERT)
    self.assertEquals(self.batch_feed.entry[1].batch_id.text, 'foo')

    
    third_entry = gdata.BatchEntry(
        atom_id=atom.Id(text='http://example.com/3'), text='This is a test3')
    third_entry.batch_operation = gdata.BatchOperation(
        op_type=gdata.BATCH_DELETE)
    # Add an entry with a delete operation already assigned.
    self.batch_feed.AddInsert(third_entry)
    # The batch entry should not have the original operation, it should 
    # have been changed to an insert.
    self.assertEquals(self.batch_feed.entry[2].batch_operation.type, 
                      gdata.BATCH_INSERT)
    self.assertEquals(self.batch_feed.entry[2].batch_id.text, '2')
예제 #3
0
    def testAddBatchEntry(self):
        try:
            self.batch_feed.AddBatchEntry(batch_id_string='a')
            self.fail(
                'AddBatchEntry with neither entry or URL should raise Error')
        except gdata.MissingRequiredParameters:
            pass

        new_entry = self.batch_feed.AddBatchEntry(
            id_url_string='http://example.com/1')
        self.assertEquals(len(self.batch_feed.entry), 1)
        self.assertEquals(self.batch_feed.entry[0].id.text,
                          'http://example.com/1')
        self.assertEquals(self.batch_feed.entry[0].batch_id.text, '0')
        self.assertEquals(new_entry.id.text, 'http://example.com/1')
        self.assertEquals(new_entry.batch_id.text, '0')

        to_add = gdata.BatchEntry(atom_id=atom.Id(text='originalId'))
        new_entry = self.batch_feed.AddBatchEntry(entry=to_add,
                                                  batch_id_string='foo')
        self.assertEquals(new_entry.batch_id.text, 'foo')
        self.assertEquals(new_entry.id.text, 'originalId')

        to_add = gdata.BatchEntry(atom_id=atom.Id(text='originalId'),
                                  batch_id=gdata.BatchId(text='bar'))
        new_entry = self.batch_feed.AddBatchEntry(entry=to_add,
                                                  id_url_string='newId',
                                                  batch_id_string='foo')
        self.assertEquals(new_entry.batch_id.text, 'foo')
        self.assertEquals(new_entry.id.text, 'originalId')

        to_add = gdata.BatchEntry(atom_id=atom.Id(text='originalId'),
                                  batch_id=gdata.BatchId(text='bar'))
        new_entry = self.batch_feed.AddBatchEntry(entry=to_add,
                                                  id_url_string='newId')
        self.assertEquals(new_entry.batch_id.text, 'bar')
        self.assertEquals(new_entry.id.text, 'originalId')

        to_add = gdata.BatchEntry(
            atom_id=atom.Id(text='originalId'),
            batch_id=gdata.BatchId(text='bar'),
            batch_operation=gdata.BatchOperation(op_type=gdata.BATCH_INSERT))
        self.assertEquals(to_add.batch_operation.type, gdata.BATCH_INSERT)
        new_entry = self.batch_feed.AddBatchEntry(
            entry=to_add,
            id_url_string='newId',
            batch_id_string='foo',
            operation_string=gdata.BATCH_UPDATE)
        self.assertEquals(new_entry.batch_operation.type, gdata.BATCH_UPDATE)
    def testMakeBatchRequests(self):
        try:
            self.gd_client.ProgrammaticLogin()
            self.assert_(self.gd_client.GetClientLoginToken() is not None)
            self.assert_(self.gd_client.captcha_token is None)
            self.assert_(self.gd_client.captcha_url is None)
        except gdata.service.CaptchaRequired:
            self.fail('Required Captcha')

        request_feed = gdata.base.GBaseItemFeed(atom_id=atom.Id(
            text='test batch'))
        entry1 = gdata.base.GBaseItemFromString(test_data.TEST_BASE_ENTRY)
        entry1.title.text = 'first batch request item'
        entry2 = gdata.base.GBaseItemFromString(test_data.TEST_BASE_ENTRY)
        entry2.title.text = 'second batch request item'
        request_feed.AddInsert(entry1)
        request_feed.AddInsert(entry2)

        result_feed = self.gd_client.ExecuteBatch(request_feed)
        self.assertEquals(result_feed.entry[0].batch_status.code, '201')
        self.assertEquals(result_feed.entry[0].batch_status.reason, 'Created')
        self.assertEquals(result_feed.entry[0].title.text,
                          'first batch request item')
        self.assertEquals(result_feed.entry[0].item_type.text, 'products')
        self.assertEquals(result_feed.entry[1].batch_status.code, '201')
        self.assertEquals(result_feed.entry[1].batch_status.reason, 'Created')
        self.assertEquals(result_feed.entry[1].title.text,
                          'second batch request item')

        # Now delete the newly created items.
        request_feed = gdata.base.GBaseItemFeed(atom_id=atom.Id(
            text='test deletions'))
        request_feed.AddDelete(entry=result_feed.entry[0])
        request_feed.AddDelete(entry=result_feed.entry[1])
        self.assertEquals(request_feed.entry[0].batch_operation.type,
                          gdata.BATCH_DELETE)
        self.assertEquals(request_feed.entry[1].batch_operation.type,
                          gdata.BATCH_DELETE)

        result_feed = self.gd_client.ExecuteBatch(request_feed)
        self.assertEquals(result_feed.entry[0].batch_status.code, '200')
        self.assertEquals(result_feed.entry[0].batch_status.reason, 'Success')
        self.assertEquals(result_feed.entry[0].title.text,
                          'first batch request item')
        self.assertEquals(result_feed.entry[1].batch_status.code, '200')
        self.assertEquals(result_feed.entry[1].batch_status.reason, 'Success')
        self.assertEquals(result_feed.entry[1].title.text,
                          'second batch request item')
예제 #5
0
 def DeleteDoumails(self, uris):
     feed = gdata.GDataFeed()
     for uri in uris:
         entry = gdata.GDataEntry()
         entry.id = atom.Id(text=uri)
         feed.entry.append(entry)
     return self.Post(feed, '/doumail/delete')
예제 #6
0
    def testPostUpdateAndDeleteSubscription(self):
        """Test posting a new subscription, updating it, deleting it"""
        self.cal_client.ProgrammaticLogin()

        subscription_id = 'c4o4i7m2lbamc4k26sc2vokh5g%40group.calendar.google.com'
        subscription_url = '%s%s' % (
            'http://www.google.com/calendar/feeds/default/allcalendars/full/',
            subscription_id)

        # Subscribe to Google Doodles calendar
        calendar = gdata.calendar.CalendarListEntry()
        calendar.id = atom.Id(text=subscription_id)
        returned_calendar = self.cal_client.InsertCalendarSubscription(
            calendar)
        self.assertEquals(subscription_url, returned_calendar.id.text)
        self.assertEquals('Google Doodles', returned_calendar.title.text)

        # Update subscription
        calendar_to_update = self.cal_client.GetCalendarListEntry(
            subscription_url)
        self.assertEquals('Google Doodles', calendar_to_update.title.text)
        self.assertEquals('true', calendar_to_update.selected.value)
        calendar_to_update.selected.value = 'false'
        self.assertEquals('false', calendar_to_update.selected.value)
        updated_calendar = self.cal_client.UpdateCalendar(calendar_to_update)
        self.assertEquals('false', updated_calendar.selected.value)

        # Delete subscription
        response = self.cal_client.DeleteCalendarEntry(
            returned_calendar.GetEditLink().href)
        self.assertEquals(True, response)
예제 #7
0
  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
예제 #8
0
 def _InsertSubscription(self, 
     id='c4o4i7m2lbamc4k26sc2vokh5g%40group.calendar.google.com'):
   """Subscribes to the calendar with the specified ID."""
   print 'Subscribing to the calendar with ID: %s' % id
   calendar = gdata.calendar.CalendarListEntry()
   calendar.id = atom.Id(text=id)
   returned_calendar = self.cal_client.InsertCalendarSubscription(calendar)
   return returned_calendar
예제 #9
0
 def _InsertSubscription(self, 
     id='python.gcal.test%40gmail.com'):
   """Subscribes to the calendar with the specified ID."""
   print 'Subscribing to the calendar with ID: %s' % id
   calendar = gdata.calendar.CalendarListEntry()
   calendar.id = atom.Id(text=id)
   returned_calendar = self.cal_client.InsertCalendarSubscription(calendar)
   return returned_calendar
예제 #10
0
 def MarkDoumailRead(self, uris):
     feed = gdata.GDataFeed()
     for uri in uris:
         entry = gdata.GDataEntry()
         entry.id = atom.Id(text=uri)
         entry.attribute = []
         entry.attribute.append(douban.Attribute('unread', 'false'))
         feed.entry.append(entry)
     return self.Put(feed, '/doumail/')
예제 #11
0
 def testAddUpdate(self):
   # Try updating an entry
   delete_entry = gdata.BatchEntry(
       atom_id=atom.Id(text='http://example.com/1'), text='This is a test')
   self.batch_feed.AddUpdate(entry=delete_entry)
   self.assertEquals(self.batch_feed.entry[0].batch_operation.type,
                     gdata.BATCH_UPDATE)
   self.assertEquals(self.batch_feed.entry[0].id.text,
                     'http://example.com/1')
   self.assertEquals(self.batch_feed.entry[0].text, 'This is a test')
예제 #12
0
    def AddNewsSitemap(self,
                       site_uri,
                       sitemap_uri,
                       sitemap_news_publication_label,
                       uri=SITEMAPS_FEED_TEMPLATE,
                       url_params=None,
                       escape_params=True,
                       converter=None):
        """Adds a news sitemap to a site.

        Args:
          site_uri: str URI of which site to add sitemap for.
          sitemap_uri: str URI of sitemap to add to a site.
          sitemap_news_publication_label: str, list of str Publication Labels for
                                          sitemap.
          uri: str (optional) URI template to add a sitemap.
               Default SITEMAP_FEED_TEMPLATE.
          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
              SitemapsEntryFromString 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 SitemapsEntry object.
        """

        sitemap_entry = webmastertools.SitemapsEntry(
            atom_id=atom.Id(text=sitemap_uri),
            category=atom.Category(
                scheme='http://schemas.google.com/g/2005#kind',
                term=
                'http://schemas.google.com/webmasters/tools/2007#sitemap-news'
            ),
            sitemap_news_publication_label=[],
        )
        if isinstance(sitemap_news_publication_label, str):
            sitemap_news_publication_label = [sitemap_news_publication_label]
        for label in sitemap_news_publication_label:
            sitemap_entry.sitemap_news_publication_label.append(
                webmastertools.SitemapNewsPublicationLabel(text=label))
        print(sitemap_entry)
        response = self.Post(sitemap_entry,
                             uri %
                             {'site_id': urllib.parse.quote_plus(site_uri)},
                             url_params=url_params,
                             escape_params=escape_params,
                             converter=converter)
        if not converter and isinstance(response, atom.Entry):
            return webmastertools.SitemapsEntryFromString(response.ToString())
        return response
    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
예제 #14
0
    def AddMobileSitemap(self,
                         site_uri,
                         sitemap_uri,
                         sitemap_mobile_markup_language='XHTML',
                         uri=SITEMAPS_FEED_TEMPLATE,
                         url_params=None,
                         escape_params=True,
                         converter=None):
        """Adds a mobile sitemap to a site.

        Args:
          site_uri: str URI of which site to add sitemap for.
          sitemap_uri: str URI of sitemap to add to a site.
          sitemap_mobile_markup_language: str Format of added sitemap. Valid types:
                                          XHTML, WML, or cHTML.
          uri: str (optional) URI template to add a sitemap.
               Default SITEMAP_FEED_TEMPLATE.
          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
              SitemapsEntryFromString 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 SitemapsEntry object.
        """
        # FIXME
        sitemap_entry = webmastertools.SitemapsEntry(
            atom_id=atom.Id(text=sitemap_uri),
            category=atom.Category(
                scheme='http://schemas.google.com/g/2005#kind',
                term='http://schemas.google.com/webmasters/tools/2007#sitemap-mobile'),
            sitemap_mobile_markup_language= \
                webmastertools.SitemapMobileMarkupLanguage(
                    text=sitemap_mobile_markup_language))
        print(sitemap_entry)
        response = self.Post(sitemap_entry,
                             uri %
                             {'site_id': urllib.parse.quote_plus(site_uri)},
                             url_params=url_params,
                             escape_params=escape_params,
                             converter=converter)
        if not converter and isinstance(response, atom.Entry):
            return webmastertools.SitemapsEntryFromString(response.ToString())
        return response
예제 #15
0
def modifyBlogRedirectUrl(blog_id, proxy_url, client):
    """ Modifies the given blog settings to make the feed redirect to the given proxy. """

    # The basic idea here is to PUT a new value to the Atom entry defined at
    # /feeds/blogid/settings/BLOG_FEED_REDIRECT_URL, which updates it.  I'm not sure
    # why the code also needs to see the BLOG_FEED_REDIRECT_URL name in the id as well
    # as the POSTed URL...  anyway, this works and it's just for demo purposes:
    data = atom.Entry(
        atom_id=atom.Id(text='tag:blogger.com,1999:blog-' + blog_id +
                        '.settings.BLOG_FEED_REDIRECT_URL'),
        content=atom.Content(text=proxy_url)
    )  # The content of the setting is just the proxy URL
    logging.info("Data is: %s", data)
    uri = 'http://www.blogger.com/feeds/' + blog_id + '/settings/BLOG_FEED_REDIRECT_URL'
    client.blogger.Put(data, uri, extra_headers=None, url_params=None)
예제 #16
0
    def UpdatePreferredDomain(self,
                              site_uri,
                              preferred_domain,
                              uri=SITE_TEMPLATE,
                              url_params=None,
                              escape_params=True,
                              converter=None):
        """Updates preferred domain setting of a site.

        Note that if using 'preferwww', will also need www.example.com in account to
        take effect.

        Args:
          site_uri: str URI of which site to add sitemap for.
          preferred_domain: str The preferred domain for a site. Valid values are 'none',
                            'preferwww', and 'prefernowww'.
          uri: str (optional) URI template to update a site.
               Default SITE_TEMPLATE.
          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
              SitemapsEntryFromString 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 SitesEntry object.
        """

        site_entry = webmastertools.SitesEntry(
            atom_id=atom.Id(text=site_uri),
            category=atom.Category(
                scheme='http://schemas.google.com/g/2005#kind',
                term=
                'http://schemas.google.com/webmasters/tools/2007#sites-info'),
            preferred_domain=webmastertools.PreferredDomain(
                text=preferred_domain))
        response = self.Put(site_entry,
                            uri % urllib.quote_plus(site_uri),
                            url_params=url_params,
                            escape_params=escape_params,
                            converter=converter)
        if not converter and isinstance(response, atom.Entry):
            return webmastertools.SitesEntryFromString(response.ToString())
        return response
예제 #17
0
  def testAddQuery(self):
    # Try querying with an existing batch entry
    delete_entry = gdata.BatchEntry(
        atom_id=atom.Id(text='http://example.com/1'))
    self.batch_feed.AddQuery(entry=delete_entry)
    self.assertEquals(self.batch_feed.entry[0].batch_operation.type,
                      gdata.BATCH_QUERY)
    self.assertEquals(self.batch_feed.entry[0].id.text,
                      'http://example.com/1')

    # Try querying a URL
    self.batch_feed.AddQuery(url_string='http://example.com/2')
    self.assertEquals(self.batch_feed.entry[0].batch_operation.type,
                      gdata.BATCH_QUERY)
    self.assertEquals(self.batch_feed.entry[1].id.text,
                      'http://example.com/2')
예제 #18
0
    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
예제 #20
0
    def VerifySite(self,
                   site_uri,
                   verification_method,
                   uri=SITE_TEMPLATE,
                   url_params=None,
                   escape_params=True,
                   converter=None):
        """Requests a verification of a site.

    Args: 
      site_uri: str URI of which site to add sitemap for.
      verification_method: str The method to verify a site. Valid values are
                           'htmlpage', and 'metatag'.
      uri: str (optional) URI template to update a site.
           Default SITE_TEMPLATE.
      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
          SitemapsEntryFromString 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 SitesEntry object.
    """

        site_entry = webmastertools.SitesEntry(
            atom_id=atom.Id(text=site_uri),
            category=atom.Category(
                scheme='http://schemas.google.com/g/2005#kind',
                term=
                'http://schemas.google.com/webmasters/tools/2007#sites-info'),
            verification_method=webmastertools.VerificationMethod(
                type=verification_method, in_use='true'))
        response = self.Put(site_entry,
                            uri % six.moves.urllib.parse.quote_plus(site_uri),
                            url_params=url_params,
                            escape_params=escape_params,
                            converter=converter)
        if not converter and isinstance(response, atom.Entry):
            return webmastertools.SitesEntryFromString(response.ToString())
        return response
예제 #21
0
    def UpdateEnhancedImageSearch(self,
                                  site_uri,
                                  enhanced_image_search,
                                  uri=SITE_TEMPLATE,
                                  url_params=None,
                                  escape_params=True,
                                  converter=None):
        """Updates enhanced image search setting of a site.

        Args:
          site_uri: str URI of which site to add sitemap for.
          enhanced_image_search: str The enhanced image search setting for a site.
                                 Valid values are 'true', and 'false'.
          uri: str (optional) URI template to update a site.
               Default SITE_TEMPLATE.
          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
              SitemapsEntryFromString 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 SitesEntry object.
        """

        site_entry = webmastertools.SitesEntry(
            atom_id=atom.Id(text=site_uri),
            category=atom.Category(
                scheme='http://schemas.google.com/g/2005#kind',
                term=
                'http://schemas.google.com/webmasters/tools/2007#sites-info'),
            enhanced_image_search=webmastertools.EnhancedImageSearch(
                text=enhanced_image_search))
        response = self.Put(site_entry,
                            uri % urllib.quote_plus(site_uri),
                            url_params=url_params,
                            escape_params=escape_params,
                            converter=converter)
        if not converter and isinstance(response, atom.Entry):
            return webmastertools.SitesEntryFromString(response.ToString())
        return response
예제 #22
0
def add_video_to_playlist(yt_service, playlist_url, video_id, position):
  """Adds a video to a playlist, optionally setting the position.

  If position is None, we use the native client library call.
  Otherwise, we construct our own PlaylistVideoEntry and set the position
  attribute, then manually insert it.

  Returns the new gdata.youtube.PlaylistVideoEntry.
  
  """
  if position is None:
    return yt_service.AddPlaylistVideoEntryToPlaylist(playlist_url, video_id)

  playlist_video_entry = gdata.youtube.YouTubePlaylistVideoEntry(
    atom_id=atom.Id(text=video_id),
    position=gdata.youtube.Position(text=position))
  return yt_service.Post(playlist_video_entry, playlist_url,
    converter=gdata.youtube.YouTubePlaylistVideoEntryFromString)
예제 #23
0
  def testAddDelete(self):
    # Try deleting an entry
    delete_entry = gdata.BatchEntry(
        atom_id=atom.Id(text='http://example.com/1'), text='This is a test')
    self.batch_feed.AddDelete(entry=delete_entry)
    self.assertEquals(self.batch_feed.entry[0].batch_operation.type, 
                      gdata.BATCH_DELETE)
    self.assertEquals(self.batch_feed.entry[0].id.text, 
                      'http://example.com/1')
    self.assertEquals(self.batch_feed.entry[0].text, 'This is a test') 

    # Try deleting a URL
    self.batch_feed.AddDelete(url_string='http://example.com/2')
    self.assertEquals(self.batch_feed.entry[0].batch_operation.type, 
                      gdata.BATCH_DELETE)
    self.assertEquals(self.batch_feed.entry[1].id.text, 
                      'http://example.com/2')
    self.assert_(self.batch_feed.entry[1].text is None) 
예제 #24
0
    def UpdateGeoLocation(self,
                          site_uri,
                          geolocation,
                          uri=SITE_TEMPLATE,
                          url_params=None,
                          escape_params=True,
                          converter=None):
        """Updates geolocation setting of a site.

        Args:
          site_uri: str URI of which site to add sitemap for.
          geolocation: str The geographic location. Valid values are listed in
                       http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
          uri: str (optional) URI template to update a site.
               Default SITE_TEMPLATE.
          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
              SitemapsEntryFromString 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 SitesEntry object.
        """

        site_entry = webmastertools.SitesEntry(
            atom_id=atom.Id(text=site_uri),
            category=atom.Category(
                scheme='http://schemas.google.com/g/2005#kind',
                term=
                'http://schemas.google.com/webmasters/tools/2007#sites-info'),
            geolocation=webmastertools.GeoLocation(text=geolocation))
        response = self.Put(site_entry,
                            uri % urllib.parse.quote_plus(site_uri),
                            url_params=url_params,
                            escape_params=escape_params,
                            converter=converter)
        if not converter and isinstance(response, atom.Entry):
            return webmastertools.SitesEntryFromString(response.ToString())
        return response
예제 #25
0
    def testAtomBaseConvertsExtensions(self):
        # Using Id because it adds no additional members.
        atom_base = atom.Id()
        extension_child = atom.ExtensionElement('foo',
                                                namespace='http://ns0.com')
        extension_grandchild = atom.ExtensionElement(
            'bar', namespace='http://ns0.com')
        extension_child.children.append(extension_grandchild)
        atom_base.extension_elements.append(extension_child)
        self.assertEquals(len(atom_base.extension_elements), 1)
        self.assertEquals(len(atom_base.extension_elements[0].children), 1)
        self.assertEquals(atom_base.extension_elements[0].tag, 'foo')
        self.assertEquals(atom_base.extension_elements[0].children[0].tag,
                          'bar')

        element_tree = atom_base._ToElementTree()
        self.assert_(element_tree.find('{http://ns0.com}foo') is not None)
        self.assert_(
            element_tree.find('{http://ns0.com}foo').find(
                '{http://ns0.com}bar') is not None)
예제 #26
0
 def setUp(self):
     self.my_id = atom.Id()
예제 #27
0
 def setUp(self):
   self.batch_feed = gdata.BatchFeed()
   self.example_entry = gdata.BatchEntry(
       atom_id=atom.Id(text='http://example.com/1'), text='This is a test')
예제 #28
0
 def testAllowsEmptyId(self):
     feed = gdata.GDataFeed()
     try:
         feed.id = atom.Id()
     except AttributeError:
         self.fail('Empty id should not raise an attribute error.')
예제 #29
0
 def subsribe(self, id):
     calendar = gdata.calendar.CalendarListEntry()
     calendar.id = atom.Id(text=id)
     returned_calendar = calendar_service.InsertCalendarSubscription(calendar)
예제 #30
0
 def testAllowsEmptyId(self):
     entry = gdata.GDataEntry()
     try:
         entry.id = atom.Id()
     except AttributeError:
         self.fail('Empty id should not raise an attribute error.')