Thursday, December 2, 2010

Curl web content on a CherryPy web server

Here are two snippets from a Python CherryPy web server test run:

    def index(self):
        cherrypy.response.headers['Content-Type'] = 'text/vnd.curl'
        return """{curl 7.0 applet}{br}{paragraph Test CherryPy}{br}"""
                   
    index.exposed = True
  
    def home(self):
        cherrypy.response.headers['Content-Type'] = 'text/vnd.curl'
        return """{curl 7.0 applet}{br}{paragraph Curl Test for CherryPy}{br}"""
  
    home.exposed = True

 It is also possible to specify a path to static Curl files and an index to that directory - in which cases files could appear with .CURL extensions.

In the two cases above, the working URL's are
http://localhost:18787/
http://localhost:18787/index
http://localhost:18787/home
and the Curl content displays as intended in linux (Ubuntu maverick) FireFox.

This test run was done using CherryPy 3.1.2 but it would only run on Python 2.6.6 as of today

The test daemon was launched from a local code folder using
sudo python /usr/local/lib/python2.6/dist-packages/cherrypy/cherryd -c ./curl/site.conf
That ./curl web app folder was modelled on the CherryPy3 scaffold folder in their python module distribution (which also includes a working ./tutorial for HTML content.)

Although I was setting a content-type globally for cherrypy.server I found that I still had to flip the MIME type in the individual 'page' methods as you see above in order to send a response with "text/vnd.curl".
Solution: tool decorator

@cherrypy.tools.response_headers([('Content-Type', 'text/vnd.curl')])
def curlHome(self): { // etcetc
//or
class Root:
  @mimetype("text/vnd.curl")
  def someView(self):
// using
def mimetype(type):
    def decorate(func):
        def wrapper(*args, **kwargs):
            cherrypy.response.headers['Content-Type'] = type
            return func(*args, **kwargs)
        return wrapper
    return decorate
// thanks to 
http://stackoverflow.com/users/11549/ddaa

 

No comments: