mitmproxy/libmproxy/stateobject.py

52 lines
1.7 KiB
Python
Raw Normal View History

from __future__ import absolute_import
2016-02-08 03:19:25 +00:00
from netlib.utils import Serializable
2014-09-16 21:54:17 +00:00
2016-02-08 03:19:25 +00:00
class StateObject(Serializable):
2014-01-31 00:06:35 +00:00
"""
2016-02-08 03:19:25 +00:00
An object with serializable state.
2014-01-31 00:06:35 +00:00
2016-02-08 03:19:25 +00:00
State attributes can either be serializable types(str, tuple, bool, ...)
or StateObject instances themselves.
2014-01-31 00:06:35 +00:00
"""
2016-02-08 03:19:25 +00:00
_stateobject_attributes = None
"""
An attribute-name -> class-or-type dict containing all attributes that
should be serialized. If the attribute is a class, it must implement the
Serializable protocol.
"""
2014-01-31 00:06:35 +00:00
2016-02-08 01:10:10 +00:00
def get_state(self):
"""
2016-02-08 03:19:25 +00:00
Retrieve object state.
"""
state = {}
for attr, cls in self._stateobject_attributes.iteritems():
val = getattr(self, attr)
if hasattr(val, "get_state"):
2016-02-08 01:10:10 +00:00
state[attr] = val.get_state()
else:
state[attr] = val
return state
2014-09-16 21:54:17 +00:00
2016-02-08 03:19:25 +00:00
def set_state(self, state):
"""
2016-02-08 03:19:25 +00:00
Load object state from data returned by a get_state call.
"""
2016-02-08 03:19:25 +00:00
state = state.copy()
for attr, cls in self._stateobject_attributes.iteritems():
2016-02-08 03:19:25 +00:00
if state.get(attr) is None:
setattr(self, attr, state.pop(attr))
else:
curr = getattr(self, attr)
2016-02-08 03:19:25 +00:00
if hasattr(curr, "set_state"):
curr.set_state(state.pop(attr))
elif hasattr(cls, "from_state"):
2016-02-08 03:19:25 +00:00
obj = cls.from_state(state.pop(attr))
setattr(self, attr, obj)
else: # primitive types such as int, str, ...
setattr(self, attr, cls(state.pop(attr)))
if state:
raise RuntimeWarning("Unexpected State in __setstate__: {}".format(state))