Package rats :: Module serialize
[hide private]
[frames] | no frames]

Source Code for Module rats.serialize

 1  #!/usr/bin/env python 
 2  # -*- coding: utf-8 -*- 
 3  # 
 4  # Toonloop for Python 
 5  # 
 6  # Copyright 2008 Alexandre Quessy & Tristan Matthews 
 7  # http://toonloop.com 
 8  #  
 9  # Original idea by Alexandre Quessy 
10  # http://alexandre.quessy.net 
11  # 
12  # Toonloop is free software: you can redistribute it and/or modify 
13  # it under the terms of the GNU General Public License as published by 
14  # the Free Software Foundation, either version 3 of the License, or 
15  # (at your option) any later version. 
16  # 
17  # Toonloop is distributed in the hope that it will be useful, 
18  # but WITHOUT ANY WARRANTY; without even the implied warranty of 
19  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
20  # GNU General Public License for more details. 
21  # 
22  # You should have received a copy of the gnu general public license 
23  # along with Toonloop.  If not, see <http://www.gnu.org/licenses/>. 
24  # 
25  """ 
26  State saving utilies. 
27   
28  Easily readable and editable. 
29  Support objects as well as simpler data types. 
30   
31  The original file is : toonloop/trunk/py/rats/serialize.py 
32  """ 
33  from twisted.spread import jelly 
34  import pprint 
35   
36 -class SerializeError(Exception):
37 """ 38 Error occuring while trying to save serialized data. 39 """ 40 pass
41
42 -class UnserializeError(Exception):
43 """ 44 Error occuring while trying to load serialized data. 45 """ 46 pass
47
48 -class Serializable(jelly.Jellyable):
49 """ 50 Any class that is serializable using these tools 51 should extend this one. 52 """ 53 pass
54
55 -def save(filename, obj):
56 """ 57 Saves any python data type to a file. 58 59 Might throw an SerializeError 60 """ 61 global _verbose 62 li = jelly.jelly(obj) 63 try: 64 f = open(filename, 'w') 65 f.write(pprint.pformat(li)) 66 f.close() 67 except IOError, e: 68 raise SerializeError(e.message) 69 except OSError, e: 70 raise SerializeError(e.message)
71
72 -def load(filename):
73 """ 74 Loads any python data type from a file. 75 76 Might throw an UnserializeError 77 """ 78 try: 79 f = open(filename, 'r') 80 li = eval(f.read()) # do this only on trusted data ! 81 f.close() 82 except IOError, e: 83 raise UnserializeError(e.message) 84 except OSError, e: 85 raise UnserializeError(e.message) 86 try: 87 obj = jelly.unjelly(li) 88 except jelly.InsecureJelly, e: 89 raise UnserializeError(e.message) 90 except AttributeError, e: 91 raise UnserializeError(e.message) 92 else: 93 return obj
94