Feed2json: Difference between revisions

From XPUB & Lens-Based wiki
No edit summary
No edit summary
Line 35: Line 35:
</source>
</source>


[[Category: Cookbook]] [[Category: RSS]] [[Category: JSON]]
[[Category: Cookbook]] [[Category: Python]] [[Category: RSS]] [[Category: JSON]]

Revision as of 20:44, 7 October 2012

Useful proxy CGI to read an RSS feed from Javascript

#!/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)