Package web2py :: Package gluon :: Module serializers
[hide private]
[frames] | no frames]

Source Code for Module web2py.gluon.serializers

 1  """ 
 2  This file is part of the web2py Web Framework 
 3  Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> 
 4  License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) 
 5  """ 
 6  import datetime 
 7  from storage import Storage 
 8  from html import TAG 
 9  from html import xmlescape 
10  from languages import lazyT 
11  import contrib.simplejson as simplejson 
12  import contrib.rss2 as rss2 
13   
14 -def custom_json(o):
15 if hasattr(o,'custom_json') and callable(o.custom_json): 16 return o.custom_json() 17 if isinstance(o, (datetime.date, 18 datetime.datetime, 19 datetime.time)): 20 return o.isoformat()[:19].replace('T',' ') 21 elif isinstance(o, (int, long)): 22 return int(o) 23 elif isinstance(o, lazyT): 24 return str(o) 25 elif hasattr(o,'as_list') and callable(o.as_list): 26 return o.as_list() 27 elif hasattr(o,'as_dict') and callable(o.as_dict): 28 return o.as_dict() 29 else: 30 raise TypeError(repr(o) + " is not JSON serializable")
31 32
33 -def xml_rec(value, key):
34 if hasattr(value,'custom_xml') and callable(value.custom_xml): 35 return value.custom_xml() 36 elif isinstance(value, (dict, Storage)): 37 return TAG[key](*[TAG[k](xml_rec(v, '')) for k, v in value.items()]) 38 elif isinstance(value, list): 39 return TAG[key](*[TAG.item(xml_rec(item, '')) for item in value]) 40 elif hasattr(value,'as_list') and callable(value.as_list): 41 return str(xml_rec(value.as_list(),'')) 42 elif hasattr(value,'as_dict') and callable(value.as_dict): 43 return str(xml_rec(value.as_dict(),'')) 44 else: 45 return xmlescape(value)
46 47
48 -def xml(value, encoding='UTF-8', key='document'):
49 return ('<?xml version="1.0" encoding="%s"?>' % encoding) + str(xml_rec(value,key))
50 51
52 -def json(value,default=custom_json):
53 return simplejson.dumps(value,default=default)
54 55
56 -def csv(value):
57 return ''
58 59
60 -def rss(feed):
61 if not 'entries' in feed and 'items' in feed: 62 feed['entries'] = feed['items'] 63 now=datetime.datetime.now() 64 rss = rss2.RSS2(title = feed['title'], 65 link = str(feed['link']), 66 description = feed['description'], 67 lastBuildDate = feed.get('created_on', now), 68 items = [rss2.RSSItem(\ 69 title=entry['title'], 70 link=str(entry['link']), 71 description=entry['description'], 72 pubDate=entry.get('created_on', now) 73 )\ 74 for entry in feed['entries'] 75 ] 76 ) 77 return rss2.dumps(rss)
78