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, quote=True):
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, '',quote)) \ 45 for k, v in value.items()]) 46 elif isinstance(value, list): 47 return TAG[key](*[TAG.item(xml_rec(item, '',quote)) for item in value]) 48 elif hasattr(value,'as_list') and callable(value.as_list): 49 return str(xml_rec(value.as_list(),'',quote)) 50 elif hasattr(value,'as_dict') and callable(value.as_dict): 51 return str(xml_rec(value.as_dict(),'',quote)) 52 else: 53 return xmlescape(value,quote)
54 55
56 -def xml(value, encoding='UTF-8', key='document', quote=True):
57 return ('<?xml version="1.0" encoding="%s"?>' % encoding) + str(xml_rec(value,key,quote))
58 59
60 -def json(value,default=custom_json):
61 return json_parser.dumps(value,default=default)
62 63
64 -def csv(value):
65 return ''
66 67
68 -def rss(feed):
69 if not 'entries' in feed and 'items' in feed: 70 feed['entries'] = feed['items'] 71 now=datetime.datetime.now() 72 rss = rss2.RSS2(title = feed['title'], 73 link = str(feed['link']), 74 description = feed['description'], 75 lastBuildDate = feed.get('created_on', now), 76 items = [rss2.RSSItem(\ 77 title=entry['title'], 78 link=str(entry['link']), 79 description=entry['description'], 80 pubDate=entry.get('created_on', now) 81 )\ 82 for entry in feed['entries'] 83 ] 84 ) 85 return rss2.dumps(rss)
86