| OLD | NEW |
| (Empty) | |
| 1 #!/usr/bin/env python |
| 2 # Copyright 2010 Google Inc. All Rights Reserved. |
| 3 # |
| 4 # Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 # you may not use this file except in compliance with the License. |
| 6 # You may obtain a copy of the License at |
| 7 # |
| 8 # http://www.apache.org/licenses/LICENSE-2.0 |
| 9 # |
| 10 # Unless required by applicable law or agreed to in writing, software |
| 11 # distributed under the License is distributed on an "AS IS" BASIS, |
| 12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 # See the License for the specific language governing permissions and |
| 14 # limitations under the License. |
| 15 |
| 16 |
| 17 import cPickle |
| 18 import os |
| 19 |
| 20 class PersistentMixin: |
| 21 """Mixin class which provides facilities for persisting and restoring.""" |
| 22 |
| 23 @classmethod |
| 24 def AssertWritable(cls, filename): |
| 25 """Raises an IOError if filename is not writable.""" |
| 26 persist_dir = os.path.dirname(os.path.abspath(filename)) |
| 27 if not os.path.exists(persist_dir): |
| 28 raise IOError('Directory does not exist: %s' % persist_dir) |
| 29 if os.path.exists(filename): |
| 30 if not os.access(filename, os.W_OK): |
| 31 raise IOError('Need write permission on file: %s' % filename) |
| 32 elif not os.access(persist_dir, os.W_OK): |
| 33 raise IOError('Need write permission on directory: %s' % persist_dir) |
| 34 |
| 35 @classmethod |
| 36 def Load(cls, filename): |
| 37 """Load an instance from filename.""" |
| 38 return cPickle.load(open(filename, 'rb')) |
| 39 |
| 40 def Persist(self, filename): |
| 41 """Persist all state to filename.""" |
| 42 cPickle.dump(self, open(filename, 'wb'), cPickle.HIGHEST_PROTOCOL) |
| OLD | NEW |