Monday, January 31, 2011

JSON decorator for CherryPy

#!/usr/bin/env python

from functools import wraps
import json
from cherrypy import response, expose

def jsonify(func):
    '''JSON decorator for CherryPy'''
    @wraps(func)
    def wrapper(*args, **kw):
        value = func(*args, **kw)
        response.headers["Content-Type"] = "application/json"
        return json.dumps(value)

    return wrapper

def example():
    from cherrypy import quickstart
    from datetime import datetime
    class Time:
        @expose
        @jsonify
        def index(self):
            now = datetime.now()
            return {
                "date" : now.strftime("%Y-%m-%d"),
                "time" : now.strftime("%H:%M"),
                "day" : now.strftime("%A"),
            }

    quickstart(Time())

if __name__ == "__main__":
    example()

$curl -i localhost:8080
HTTP/1.1 200 OK
Date: Mon, 31 Jan 2011 03:18:34 GMT
Content-Length: 56
Content-Type: application/json
Server: CherryPy/3.1.2

{"date": "2011-01-30", "day": "Sunday", "time": "19:18"}

4 comments:

  1. perfect, but how to do without expose?? I'm guessing you have to parse args, kwargs on your own...

    ReplyDelete
  2. What do you mean "without expose"?

    If you mean the @expose decorator, it's just a way to tell CherryPy that this method should be exposed as an HTTP endpoint. It does not alter the method, it does "index.exposed = True" and that it.

    ReplyDelete
  3. Hi admin
    this is really nice to read..informative post is very good to read..thanks a lot!
    دمج pdf

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete