简体   繁体   English

Python中的自定义词典和JSON模块

[英]Custom Dictionary and JSON Module in Python

I have a custom Python class that extends the 'dict' built-in type. 我有一个自定义Python类,用于扩展“ dict”内置类型。

########################################################################
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. 自从dict继承以来,我就可以使用json.dumps(<object>)将类转储为字符串值。

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. 您误解了__dict__它不是存放dict数据的地方,而是存放大多数类的属性的地方。 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 . 因此, a.__dict__['x']通常(但不总是)与ax相同。

As a general rule: do not use __dict__ unless you really love dark forbidden magicks . 作为一般规则: 除非您确实喜欢深色的禁忌魔法师,否则请勿使用__dict__

To make your class work and happily serialize into json, just use dict.__getitem__ as with any ordinary superclass method call. 为了使您的类正常工作并愉快地序列化为json,只需将dict.__getitem__用作任何普通的超类方法调用即可。

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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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