Feed2json: Difference between revisions

From XPUB & Lens-Based wiki
(Created page with "<source lang="python"> #!/usr/bin/env python #-*- coding:utf-8 -*- import cgitb; cgitb.enable() import cgi, urllib import feedparser, json, time, datetime request = cgi.FieldS...")
 
No edit summary
 
(3 intermediate revisions by the same user not shown)
Line 1: Line 1:
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 (following [http://stackoverflow.com/questions/455580/json-datetime-between-python-and-javascript this example])
<source lang="python">
<source lang="python">
#!/usr/bin/env python
#!/usr/bin/env python
Line 19: Line 23:


def jsonify(obj):
def jsonify(obj):
    """ http://stackoverflow.com/questions/455580/json-datetime-between-python-and-javascript"""
     if (type(obj) == time.struct_time):
     if (type(obj) == time.struct_time):
         obj = datetime.datetime.fromtimestamp(time.mktime(obj))
         obj = datetime.datetime.fromtimestamp(time.mktime(obj))
Line 33: Line 36:
</source>
</source>


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

Latest revision as of 20:46, 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 (following this example)

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