Re: returning postID

Kimbro Staken <[email protected]> Thu, 30 Oct 2003 16:03:49 -0700
Newsgroups gmane.comp.web.syncato.general
Message-ID <[email protected]>
Shoot, that's old code, I just committed the version I had on disk. It 
might take a day or two to make it to the anonymous servers so I'll 
also attach it here. Sorry about that, I meant to check it in before.

Here's that method as it stands now.

     def getRecentPosts(self, blogId, username, password, numberOfPosts):
         posts = []
         client = WeblogClient.WeblogClient(self.host, self.baseURL, 
username, password)

         itemRoot = 
self.config.xpathEval("/blog/post-root-element")[0].content
         query = "/" + itemRoot + "[pubDate/@seconds > " + 
str(time.time() - ONE_WEEK) + "]"

         result = client.runRequest("GET", self.baseURL + query)

         recentRSS = libxml2.parseDoc(result.read())

         results = recentRSS.xpathEval('/results/item')
         for item in results:
             entry = {}

             entry['title'] = item.xpathEval('title')[0].content
             entry['postid'] = self.baseURL + "/" + 
item.xpathEval('@id')[0].content

             body = item.xpathEval('description')[0].serialize(format = 
1)
             body = re.sub("^<description>", "", body)
             body = re.sub("</description>$", "", body)

             entry['description'] = body
             posts.append(entry)

         return posts


On Oct 30, 2003, at 3:38 PM, darryl wrote:

> hey,
>
> Poking around the metaweblog API (what a mess :) )
>
> I need to return a struct which includes the postID from 
> getRecentPosts()
>
> I'm not sure how to do this,
> --------------------------------
> we iterate over the posts here:
>
>  results = recentRSS.xpathEval('/results/item')
>         for item in results:
>             entry = {}
>
>             entry['title'] = item.xpathEval('title')[0].content
>             body = item.xpathEval('description')[0].serialize(format = 
> 1)
> 	    print body
>             body = re.sub("^<description>", "", body)
>             body = re.sub("</description>$", "", body)
>
>             entry['description'] = body
>             posts.append(entry)
>   return posts
> ---------------------------------
>
> how can i get the post ID ?
>
> cheers,
> darryl
>
>
>
>
> -------------------------------------------------------
> This SF.net email is sponsored by: SF.net Giveback Program.
> Does SourceForge.net help you be more productive?  Does it
> help you create better code?   SHARE THE LOVE, and help us help
> YOU!  Click Here: http://sourceforge.net/donate/
> _______________________________________________
> Syncato-general mailing list
> Syncato-general-5NWGOfrQmneRv+LV9MX5uipxlwaOVQ5f@public.gmane.org
> https://lists.sourceforge.net/lists/listinfo/syncato-general
>
>
Kimbro Staken
Software, Consulting and Writing http://www.xmldatabases.org/
Apache Xindice native XML database http://xml.apache.org/xindice
XML:DB Initiative http://www.xmldb.org
MetaWeblog.py (application/octet-stream, 9.9 KB)
#
# xmldatabases.org License, Version 1.0
# 
# Copyright (c) 2003 Kimbro Staken
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
# 
# 3. The end-user documentation included with the redistribution,
#    if any, must include the following acknowledgment:
#       "This product includes software developed by
#        Kimbro Staken (http://www.xmldatabases.org/)."
#    Alternately, this acknowledgment may appear in the software
#    itself, if and wherever such third-party acknowledgments normally
#    appear.
# 
# 4. The names "xmldatabases.org" or "Syncato" must not be used to
#    endorse or promote products derived from this software without
#    prior written permission. For written permission, please contact
#    kstaken-9QPlwUgsgvSWZzwIpzCHH+G/[email protected]
# 
# THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED.  IN NO EVENT SHALL KIMBRO STAKEN OR CONTRIBUTORS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
# OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#  
# $Id: MetaWeblog.py,v 1.3 2003/10/30 22:57:56 kstaken Exp $
import sys, string, traceback, os, httplib, time, re

try:
	from xmlrpclib import xmlrpclib
except ImportError:
	import xmlrpclib

from xmlrpclib import Boolean

import libxml2
    
from WebKit.XMLRPCServlet import XMLRPCServlet
from WebKit.XMLRPCServlet import _getXmlDeclAttr

import WeblogClient

ONE_WEEK = 60 * 60 *  24 * 7;

class MetaWeblog(XMLRPCServlet):
    """
    Implementation of the MetaWeblog and Blogger APIs.
    """
    
    def __init__(self):
        XMLRPCServlet.__init__(self)
        self.config = libxml2.parseFile("../config/config.xml")
        baseURL = self.config.xpathEval("/blog/base-url")[0].content
        baseURL = string.replace(baseURL, "http://", "")
        slash = baseURL.find('/')
        self.host = baseURL[0:slash]
        self.baseURL = baseURL[slash:]     
        
    def exposedMethods(self):
        return ['newPost', 'editPost', 'getPost', 'getRecentPosts', 'deletePost', 'getCategoryList', 'getPostCategories', 'setPostCategories', 'publishPost']
    
    def runRequest(self, method, url, body = None):
        conn = httplib.HTTPConnection(self.host)
        headers = {"Content-type": "text/xml" }
        
        conn.request(method, url, body, headers)
            
        result = conn.getresponse()
        
        return result
        
    def newPost(self, blogId, username, password, content, publish):
        client = WeblogClient.WeblogClient(self.host, self.baseURL, username, password)

        categories = []
        if (content.has_key("categories")):
           categories = content['categories']
            
        postID = client.addPost(content['title'], content['description'], categories)
       
        if (postID == ""):
            raise "Unable to post new entry"
        
        return postID
        
    def editPost(self, postID, username, password, content, publish):
        client = WeblogClient.WeblogClient(self.host, self.baseURL, username, password)
        
        categories = []
        if (content.has_key("categories")):
           categories = content['categories']
       
        client.editPost(postID, content['title'], content['description'], categories)
 
        return Boolean(1)
        
    def getPost(self, postID, username, password):
        client = WeblogClient.WeblogClient(self.host, self.baseURL, username, password)

        result = client.getPost(postID)
        
        finalResult = {}
        finalResult['title'] = result['title']
        finalResult['description'] = result['body']
        
        return finalResult        
        
    def getRecentPosts(self, blogId, username, password, numberOfPosts):
        posts = []
        client = WeblogClient.WeblogClient(self.host, self.baseURL, username, password)
        
        itemRoot = self.config.xpathEval("/blog/post-root-element")[0].content 
        query = "/" + itemRoot + "[pubDate/@seconds > " + str(time.time() - ONE_WEEK) + "]"
        
        result = client.runRequest("GET", self.baseURL + query)
        
        recentRSS = libxml2.parseDoc(result.read())
        
        results = recentRSS.xpathEval('/results/item')
        for item in results:
            entry = {} 
            
            entry['title'] = item.xpathEval('title')[0].content
            entry['postid'] = self.baseURL + "/" + item.xpathEval('@id')[0].content
            
            body = item.xpathEval('description')[0].serialize(format = 1)             
            body = re.sub("^<description>", "", body)
            body = re.sub("</description>$", "", body)
            
            entry['description'] = body
            posts.append(entry)
        
        return posts
        
    def deletePost(self, appkey, postID, username, password, publish):
        client = WeblogClient.WeblogClient(self.host, self.baseURL, username, password)
        
        client.deletePost(postID)
        return Boolean(1)
        
    def getCategoryList(self, blogid, username, password):
        return { 'XML' : {'description' : 'blah', 'htmlUrl': 'http://blah', 'rssUrl': 'http://blah'} }
    
    def getPostCategories(self, postID, username, password):
        client = WeblogClient.WeblogClient(self.host, self.baseURL, username, password)
        print postID
        result = client.getPost(postID)
        
        categories = result['categories']
        finalResult = []
        print categories
        for category in categories:
            print category
            rec = {}
            rec['categoryId'] = category
            rec['categoryName'] = category
            rec['isPrimary']= Boolean(0)
            finalResult.append(rec)
             
        return finalResult 
        
    def setPostCategories(self, postID, username, password, categories=[]):
        return Boolean(1)
        
    def publishPost(self, postID, username, password):
        # We don't support this concept so we just return true.
        return Boolean(1)
        
    # We don't actually care about these methods.    
    def getTemplate(self, appkey, blogid, username, password, templateType):
        return ""

    def setTemplate(self, appkey, blogid, username, password, template, templateType):
        return Boolean(1)

    def getUsersBlogs(self, appkey, username, password):
        return ()
        
    def newMediaObject(self, blogid, username, password, struct):
        return {}
        
    # Reimplementation from XMLRPCServlet to enable the metaweblog.name convention
    def respondToPost(self, transaction):
        """
        This is similar to the xmlrpcserver.py example from the xmlrpc
        library distribution, only it's been adapted to work within a
        WebKit servlet.
        """
        try:
            # get arguments
            data = transaction.request().rawInput(rewind=1).read()
            encoding = _getXmlDeclAttr(data, "encoding")
            params, method = xmlrpclib.loads(data)

            # Strip the prefix of the method name.
            method = method.split(".")[1]
            # generate response
            try:
                # This first test helps us to support PythonWin, which uses
                # repeated calls to __methods__.__getitem__ to determine the
                # allowed methods of an object.
                if method == '__methods__.__getitem__':
                    response = self.exposedMethods()[params[0]]
                else:
                    response = self.call(method, *params)
                if type(response) != type(()):
                    response = (response,)
            except Exception, e:
                fault = self.resultForException(e, transaction)
                response = xmlrpclib.dumps(xmlrpclib.Fault(1, fault), encoding=encoding)
                self.sendOK('text/xml', response, transaction)
                self.handleException(transaction)
            except:  # if it's a string exception, this gets triggered
                fault = self.resultForException(sys.exc_info()[0], transaction)
                response = xmlrpclib.dumps(xmlrpclib.Fault(1, fault), encoding=encoding)
                self.sendOK('text/xml', response, transaction)
                self.handleException(transaction)
            else:                
                response = xmlrpclib.dumps(response, methodresponse=1, encoding=encoding)
                self.sendOK('text/xml', response, transaction)
        except:
            # internal error, report as HTTP server error
            print 'XMLRPCServlet internal error'
            print string.join(traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]))
            transaction.response().setStatus(500, 'Server Error')
            self.handleException(transaction)

def encode(data):
    data = string.replace(data, '&', '&amp;')
    data = string.replace(data, '<', '&lt;')
    data = string.replace(data, '>', '&gt;')
    data = string.replace(data, '"', '&quot;')
    data = string.replace(data, "'", '&apos;')
    return data