Feed2json: Difference between revisions

From XPUB & Lens-Based wiki
No edit summary
No edit summary
Line 1: Line 1:
Useful proxy CGI to read an RSS feed from Javascript
Useful proxy CGI to read an RSS feed from Javascript
Python's JSON module will take of many things, by datetime and time objects mess it up. A custom "jsonify" function takes care of the translation in these cases.


<source lang="python">
<source lang="python">

Revision as of 20:45, 7 October 2012

Useful proxy CGI to read an RSS feed from Javascript

Python's JSON module will take of many things, by datetime and time objects mess it up. A custom "jsonify" function takes care of the translation in these cases.

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import cgitb; cgitb.enable()
import cgi, urllib
import feedparser, json, time, datetime


request = cgi.FieldStorage()
feedurl = request.getvalue("f", "http://api.flickr.com/services/feeds/photos_public.gne")

q = {}
for key in request:
    if key != "f":
        q[key] = request.getvalue(key)
if q:
    feedurl += "?"+urllib.urlencode(q)

def jsonify(obj):
    """ http://stackoverflow.com/questions/455580/json-datetime-between-python-and-javascript"""
    if (type(obj) == time.struct_time):
        obj = datetime.datetime.fromtimestamp(time.mktime(obj))
    if hasattr(obj, 'isoformat'):
        return obj.isoformat()
    else:
        raise TypeError, 'Object of type %s with value of %s is not JSON serializable' % (type(obj), repr(obj))

print "Content-type: application/json"
print
feed = feedparser.parse(feedurl)
print json.dumps(feed, default=jsonify)