简体   繁体   中英

Custom Dictionary and JSON Module in Python

I have a custom Python class that extends the 'dict' built-in type.

########################################################################
class ServiceParametersNew(dict):
    """"""
    _allowed = ['maxRecordCount', 'tables',
                'allowGeometryUpdates', 'supportsDisconnectedEditing',
                'description', 'name', 'xssPreventionInfo',
                'hasStaticData', 'capabilities', 'copyrightText',
                'currentVersion', 'size', 'hasVersionedData',
                'units', 'syncEnabled', 'supportedQueryFormats',
                'editorTrackingInfo', 'serviceDescription']
    _editorTrackingInfo = {
        "enableEditorTracking": True,
        "enableOwnershipAccessControl": False,
        "allowOthersToUpdate": True,
        "allowOthersToDelete": True}
    _xssPreventionInfo = {
        "xssPreventionEnabled": True,
        "xssPreventionRule": "InputOnly",
        "xssInputRule": "rejectInvalid"}
    _tables =  []
    #----------------------------------------------------------------------
    def __str__(self):
        """returns object as string"""
        val = {}
        for a in self._allowed:
            if a in self.__dict__:
                val[a] = self.__getitem__(a)
        val['table'] = self._tables
        val['xssPreventionInfo'] = self._xssPreventionInfo
        val['editorTrackingInfo'] = self._editorTrackingInfo
        return json.dumps(val)
    #----------------------------------------------------------------------
    def __getitem__(self, key):
        if key.lower() in [a.lower() for a in self._allowed]:
            return self.__dict__[key]
        raise Exception("Invalid parameter requested")
    #----------------------------------------------------------------------
    def __setitem__(self, index, value):
        self.__dict__[index] = value
    #----------------------------------------------------------------------
    @property
    def xssPreventionInfo(self):
        """gets the xssPreventionInfo"""
        return self._xssPreventionInfo
    #----------------------------------------------------------------------
    @property
    def editorTrackingInfo(self):
        """gets the editorTrackingInfo settings"""
        return self._editorTrackingInfo
    #----------------------------------------------------------------------
    def updateXssPreventionInfo(self, xssPreventionEnabled=True,
                                xssPreventionRule="InputOnly",
                                xssInputRule="rejectInvalid"):
        """updates the xss prevention information"""
        self._xssPreventionInfo = {
            "xssPreventionEnabled": True,
            "xssPreventionRule": "InputOnly",
            "xssInputRule": "rejectInvalid"
        }
    #----------------------------------------------------------------------
    def updateEditorTrackingInfo(self,
                                 enableEditorTracking=True,
                                 enableOwnershipAccessControl=False,
                                 allowOthersToUpdate=True,
                                 allowOthersToDelete=True
                                 ):
        """updates the editor tracking information"""
        self._editorTrackingInfo = {
            "enableEditorTracking": enableEditorTracking,
            "enableOwnershipAccessControl": enableOwnershipAccessControl,
            "allowOthersToUpdate": allowOthersToUpdate,
            "allowOthersToDelete": allowOthersToDelete
        }

The class basically is going to check if a value is in the allowed dictionary if it is, it is entered into the value.

I figured since I inherited from dict, I could use json.dumps(<object>) to dump the class to a string value.

Do I have to override another function to get this working?

You misunderstand __dict__ - it's not a place for data of dict , it's a place where attributes are stored for most classes. For example:

>>> class A(dict):
...   def __init__(self):
...     dict.__init__(self)
...     self.x = 123
... 
>>> a=A()
>>> a.__dict__
{'x': 123}

So, a.__dict__['x'] is often (but not always) the same as ax .

As a general rule: do not use __dict__ unless you really love dark forbidden magicks .

To make your class work and happily serialize into json, just use dict.__getitem__ as with any ordinary superclass method call.

class ExtendedDict(dict):
    _allowed = ['a', 'b']
    def __getitem__(self, key):
        if key.lower() in [a.lower() for a in self._allowed]:
            # Just call superclass method
            return dict.__getitem__(self, key)
        raise Exception("Invalid parameter requested")

d = ExtendedDict()
d['a'] = 1
d['b'] = 2
import json, sys
sys.stdout.write(json.dumps(d))

This will print:

{"a": 1, "b": 2}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM