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.rss2 as rss2 
12   
13  try: 
14      import json as json_parser                      # try stdlib (Python 2.6) 
15  except ImportError: 
16      try: 
17          import simplejson as json_parser            # try external module 
18      except: 
19          import contrib.simplejson as json_parser    # fallback to pure-Python module 
20   
21 -def custom_json(o):
22 if hasattr(o,'custom_json') and callable(o.custom_json): 23 return o.custom_json() 24 if isinstance(o, (datetime.date, 25 datetime.datetime, 26 datetime.time)): 27 return o.isoformat()[:19].replace('T',' ') 28 elif isinstance(o, (int, long)): 29 return int(o) 30 elif isinstance(o, lazyT): 31 return str(o) 32 elif hasattr(o,'as_list') and callable(o.as_list): 33 return o.as_list() 34 elif hasattr(o,'as_dict') and callable(o.as_dict): 35 return o.as_dict() 36 else: 37 raise TypeError(repr(o) + " is not JSON serializable")
38 39
40 -def xml_rec(value, key):
41 if hasattr(value,'custom_xml') and callable(value.custom_xml): 42 return value.custom_xml() 43 elif isinstance(value, (dict, Storage)): 44 return TAG[key](*[TAG[k](xml_rec(v, '')) for k, v in value.items()]) 45 elif isinstance(value, list): 46 return TAG[key](*[TAG.item(xml_rec(item, '')) for item in value]) 47 elif hasattr(value,'as_list') and callable(value.as_list): 48 return str(xml_rec(value.as_list(),'')) 49 elif hasattr(value,'as_dict') and callable(value.as_dict): 50 return str(xml_rec(value.as_dict(),'')) 51 else: 52 return xmlescape(value)
53 54
55 -def xml(value, encoding='UTF-8', key='document'):
56 return ('<?xml version="1.0" encoding="%s"?>' % encoding) + str(xml_rec(value,key))
57 58
59 -def json(value,default=custom_json):
60 return json_parser.dumps(value,default=default)
61 62
63 -def csv(value):
64 return ''
65 66
67 -def rss(feed):
68 if not 'entries' in feed and 'items' in feed: 69 feed['entries'] = feed['items'] 70 now=datetime.datetime.now() 71 rss = rss2.RSS2(title = feed['title'], 72 link = str(feed['link']), 73 description = feed['description'], 74 lastBuildDate = feed.get('created_on', now), 75 items = [rss2.RSSItem(\ 76 title=entry['title'], 77 link=str(entry['link']), 78 description=entry['description'], 79 pubDate=entry.get('created_on', now) 80 )\ 81 for entry in feed['entries'] 82 ] 83 ) 84 return rss2.dumps(rss)
85