2006/06/30

I was recently hunting for some docs on how to handle POST requests in Cherrypy 2.2 yourself, in stead of having the CP machinery decoding the variables for you.

“Why do you want to do this?” you may ask.

Well, in my case, I wanted to do some simple RPC calls to my server, but I wanted to do something even simpler than XMLRPC or JSONRPC. Specifically I didn’t want all my calls to be routed through a single URL, and have the methodnames be dispatched based on some paramter in the message payload. Rather I want to be able to do a POST on a URL where the body of my request contains a JSON serialized data packet, which is the paramters of my call. This is in spirit similar to those other RPC-over-HTTP schemes, but simpler and more in the HTTP spirit IMNHO.

Calling it, you want to do something like:

import httplib, simplejson
h = httplib.HTTPConnection('localhost:8080')
z = {'a':123, 'b':456}
h.request('POST', '/rpc', simplejson.dumps(z))
r = h.getresponse()
r.read()
# But I have wrapped it up in a utility class, so you can also do:
p = ssrpc.Proxy('localhost:8080')
p.rpc(a=123, b=456)

I found some examples on the CherryPy Wiki at http://www.cherrypy.org/wiki/FileUpload which started me on the way, and looking at tutorial_09 in the CherryPy distribution also helped. Some light reading of the source, and I came up with the following code for doing the server-side in CherryPy 2.2:

import cherrypy
import simplejson

class StreamFilter(cherrypy.filters.basefilter.BaseFilter):
    def before_request_body(self):
        if cherrypy.request.path == '/rpc':
            # if you don't check that it is a post method the server might lock up
            # we also check to make sure something was submitted
            if not 'Content-Length' in cherrypy.request.headerMap or \
               (cherrypy.request.method != 'POST'):
                raise cherrypy.HTTPRedirect('/')
            else:
                # Tell CherryPy not to parse the POST data itself for this URL
                cherrypy.request.processRequestBody = False

#
class Root:
    _cpFilterList = [StreamFilter()]
    def index(self):
        return """
            
            

Testing POST handling in body.

""" index.exposed = True def rpc(self): dataLength = int(cherrypy.request.headers.get('Content-Length') or 0) data = cherrypy.request.rfile.read(dataLength) o = simplejson.loads(data) return "You asked: %s" % o rpc.exposed = True cherrypy.root = Root() cherrypy.server.start()

Hope these snippets help someone else looking to do the same thing.

Last modified: 2006/06/30 10:12:13.648 GMT+2

RSS feed Blog Home
Weblog entries:
A belly-laugh can SO brighten a gloomy day My Amazon Wish-List Do you have my dongle? (dingle-dangle) flickrapi.py using JSON Presentation Stress London Hackday - Folksonomies Reloaded My eerste Potgooi Many dead fishes Amazon Elastic Compute Cloud Die kraaie gaap Super-simple RPC in CherryPy with JSON Recursive tree walk A picnic in the park Indisch Lexicon Flat tyre at speed on the bike Fun to watch the search terms roll by PUN Meeting 5 Great Illustrator Delicacies from Belgium Afrikaans op Nederlandse TV advertensies Tsotsitaal London Blasts Roald Theunis Posthumus SA Blogs Starting UML Web-content stored in SQL databases considered bullshit PUN Meeting 4 Hinke Screuders' Notes On Art 'n Pierneef vernietig Why I love reading Tim Bray Back from Scotland Google as web-hosting company Yet another cold-call on my mobile Die lewe word ge-outsource The Power of Two Parent Teacher Conference PUN Meeting 3 and Pornography Stef Bos in Kleine Komedie What The Hack Sometimes spam is useful Giving back to Zope/Python So what have you produced today? Iconclass Pi Day 2005 I don't like killing things Geslaagd! Polisiekoffie Heavy Snowfall Mixing Danish and Swedish Gates in Central park I love Python Python .setdefault on dict Sommer Blog Comments So how is Python on Solaris? Blogging in your sleep ADSL at work More IND mega-bucks paid: EUR 430 XML-bickering in Python land The impossible necessity of running elections Self-pity Vanwaar Gehasi? 2005 hier kom ons amsterdam.nl webmasters meta shower 2nd PUN meeting Office space It is 12 weeks now Losing the Past She is such a big girl suddenly Fluids ZA in Ukraine iBook therefore iAm Update on Van Gogh Murder PUN - Python Users Nederland Laibach Concert in Amsterdam Meta Bitten Google cheque ADSL at Kaya Anton got married Charmaine died Murder The Gross Test Image Index Prototype ILL WILL PRESS Sinusitis DNA as RFID alternative Sub-contracting note-to-self Flickr phot service On Spending Money Listening to Mauritz Lotz Home-brew time-slice Windows Puter We need more challenges in computing First Party at Kaya RSI Excessive MSN bot vists Magic Music Games I own All cut up Python on Series 60 - my quest for a phone Plone Rocks! African Dope Back Home Again John Died June has gone - too Beer Tasting note from Elise Edinburgh and Blisters Shave and a Haircut Emblembooks Prune Classics Zope Tips Creating SSL certs Red Hot Chili Peppers In search of an IMAP server Vusi Mahlasela and Johnny Clegg Interactive Interpreter Rules Meta Dolly Moment Fluidiom at V2 Back from EuroPython 2004 May has gone- again Thunderstruck! Planted a chestnut tree Don't tell me URLs aren't important Server being sucked dry Semi-Live Google search term display Een wijze les in woord en beeld Logfile analysis Neck Stress Illness in the House Museum Vrolik Quixote Webmail Open Galerie in Lisse, and Poly dinner Another weekend has zoomed by Nederlander Worden Tips for the day elise's first appearance Apache & Zope Config updated Allergic to vitamins Lust from The Economist Birfday 2004 RSS Auto-Discovery Swept Away - thrown away OS X Battery Status from Command Line No worries? Not. Getting Sidetracked in the midnight hours Blog To-Do List First Post!

The following search terms were used in Google to find pages on this site recently:

post json python· indexing with iconclass· cherrypy handle xml post body· time slice picture at home· recursively walk a tree· json interpreter cherrypy· +kraaie gaap· "sore eyeballs" after sinusitis· cherrypy post JSON data· iconclass xml· cherrypy + json· cherrypy json examples· "what have you produced"· json rpc python cherrypy· example using simplejson and urllib and cherrypy in a python program· cherrypy httplib.HTTPConnection GET· focus software dongle· httplib POST request json example· dojo cherrypy json· api fluidiom·
Get Firefox!