Python json.JSONEncoder.default() Examples

The following are code examples for showing how to use json.JSONEncoder.default(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: Parallel.GAMIT   Author: demiangomez   File: pyDate.py    GNU General Public License v3.0 6 votes vote down vote up
def yeardoy2fyear(year,doy,hour=12,minute=0,second=0):

    # parse to integers (defensive)
    year = int(year)
    doy  = int(doy)
    hour = int(hour)

    # default number of days in a year
    diy = 365

    # check for leap years
    if year % 4 == 0:
        diy += 1.

    # make sure day of year is valid
    if doy < 1 or doy > diy:
        raise pyDateException('invalid day of year')

    # compute the fractional year
    fractionalYear = year + ((doy-1) + hour/24. + minute/1440. + second/86400.)/diy

    # that's all ...
    return fractionalYear 
Example 2
Project: eventsourcing   Author: johnbywater   File: transcoding.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def encoderpolicy(arg=None):
    """
    Decorator for encoder policy.

    Allows default behaviour to be built up from methods
    registered for different types of things, rather than
    chain of isinstance() calls in a long if-else block.
    """

    def _mutator(func):
        wrapped = singledispatch(func)

        @wraps(wrapped)
        def wrapper(*args, **kwargs):
            obj = kwargs.get("obj") or args[-1]
            return wrapped.dispatch(type(obj))(*args, **kwargs)

        wrapper.register = wrapped.register

        return wrapper

    assert isfunction(arg), arg
    return _mutator(arg) 
Example 3
Project: pyramid-zappa-api-boilerplate   Author: web-masons   File: default.py    MIT License 6 votes vote down vote up
def default(self, obj):
        if isinstance(obj, datetime):
            return {
                '__type__': 'datetime',
                'year': obj.year,
                'month': obj.month,
                'day': obj.day,
                'hour': obj.hour,
                'minute': obj.minute,
                'second': obj.second,
                'microsecond': obj.microsecond,
            }
        else:
            return JSONEncoder.default(self, obj)


# Get a list of all Users in Database 
Example 4
Project: cqrs-eventsource   Author: laskoviymishka   File: transcoding.py    GNU General Public License v2.0 6 votes vote down vote up
def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return {'ISO8601_datetime': obj.strftime('%Y-%m-%dT%H:%M:%S.%f%z')}
        elif isinstance(obj, datetime.date):
            return {'ISO8601_date': obj.isoformat()}
        elif isinstance(obj, UUID):
            return {'UUID': obj.hex}
        elif hasattr(obj, '__class__') and hasattr(obj, '__dict__'):
            topic = topic_from_domain_class(obj.__class__)
            state = obj.__dict__.copy()
            return {
                '__class__': {
                    'topic': topic,
                    'state': state,
                }
            }
        # Let the base class default method raise the TypeError.
        return JSONEncoder.default(self, obj) 
Example 5
Project: stone   Author: neuralsandwich   File: site.py    MIT License 6 votes vote down vote up
def default(self, o):
        if isinstance(o, Site):
            items = ['site', 'type', 'source', 'target', 'templates']
            result = {}
            for item in items:
                try:
                    result[item] = o[item]
                except KeyError:
                    pass
            result['pages'] = o.pages
            return result
        if isinstance(o, Page):
            return PageEncoder().default(o)

        # When not a page, call the JSONEncoder. It will call the correct fail.
        return JSONEncoder.default(self, o) 
Example 6
Project: BossAlienMediaPlayer   Author: zynga   File: dtos.py    MIT License 6 votes vote down vote up
def default(self, z):
        if isinstance(z, TrackDTO):
            return z.__dict__
        if isinstance(z, AlbumDTO):
            return z.__dict__
        if isinstance(z, ArtistDTO):
            return z.__dict__
        if isinstance(z, UserDTO):
            return z.__dict__
        if isinstance(z, QueueItemDTO):
            return z.__dict__
        if isinstance(z, PlaybackStateDTO):
            return z.__dict__
        if isinstance(z, HistoryItemDTO):
            return z.__dict__
        if isinstance(z, AvailableTrackActionsDTO):
            return z.__dict__
        else:
            return JSONEncoder.default(self, z) 
Example 7
Project: PyMISPWarningLists   Author: MISP   File: api.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, warninglist, slow_search=False):
        self.warninglist = warninglist
        self.list = self.warninglist['list']
        self.description = self.warninglist['description']
        self.version = int(self.warninglist['version'])
        self.name = self.warninglist['name']
        if self.warninglist['type'] not in self.expected_types:
            raise PyMISPWarningListsError('Unexpected type, please update the expected_type list')
        self.type = self.warninglist['type']
        if self.warninglist.get('matching_attributes'):
            self.matching_attributes = self.warninglist['matching_attributes']

        self.slow_search = slow_search
        self._network_objects = []

        if self.slow_search and self.type == 'cidr':
            self._network_objects = self._network_index()
            # If network objects is empty, reverting to default anyway
            if not self._network_objects:
                self.slow_search = False 
Example 8
Project: PyMISPWarningLists   Author: MISP   File: api.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _slow_search(self, value):
        if self.type == 'string':
            # Exact match only, using fast search
            return self._fast_search(value)
        elif self.type == 'substring':
            # Expected to match on a part of the value
            # i.e.: value = 'blah.de' self.list == ['.fr', '.de']
            return any(v in value for v in self.list)
        elif self.type == 'hostname':
            # Expected to match on hostnames in URLs (i.e. the search query is a URL)
            # So we do a reverse search if any of the entries in the list are present in the URL
            # i.e.: value = 'http://foo.blah.de/meh' self.list == ['blah.de', 'blah.fr']
            return any(v in value for v in self.list)
        elif self.type == 'cidr':
            try:
                value = ip_address(value)
            except ValueError:
                # The value to search isn't an IP address, falling back to default
                return self._fast_search(value)
            return any((value == obj or value in obj) for obj in self._network_objects) 
Example 9
Project: lacquer   Author: slaclab   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def default(self, obj):
        if isinstance(obj, QuerySpecification):
            keys = ("select", "from_", "where", "group_by", "having", "order_by", "limit")
            ret = OrderedDict([(key, getattr(obj, key)) for key in keys if getattr(obj, key)])
            return ret

        if isinstance(obj, (Node, JoinCriteria)):
            keys = [key for key in obj.__dict__.keys() if
                    key[0] != '_' and key not in ('line', 'pos')]
            ret = {key: getattr(obj, key) for key in keys if getattr(obj, key)}
            return ret

        if isinstance(obj, QualifiedName):
            return obj.parts

        return JSONEncoder.default(self, obj) 
Example 10
Project: tornado-alchemy-rest   Author: EzyInsights   File: encoders.py    Apache License 2.0 6 votes vote down vote up
def default(self, obj):
        if isinstance(obj, enum.IntEnum) or isinstance(obj, enum.Enum):
            return obj.value
        if isinstance(obj, RowProxy):
            return {
                k: obj[k] for k in obj.keys()
            }
        if isinstance(obj, datetime):
            return obj.timestamp()

        elif isinstance(obj, timedelta):
            return {
                '__type__' : 'timedelta',
                'days': obj.days,
                'hours': obj.seconds // 3600,
                'minutes': (obj.seconds // 60) % 60,
                'seconds': obj.seconds,
                'microseconds': obj.microseconds,
                }

        else:
            return JSONEncoder.default(self, obj) 
Example 11
Project: Splunk_CBER_App   Author: MHaggis   File: internals.py    MIT License 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example 12
Project: Parallel.GAMIT   Author: demiangomez   File: pyStationInfo.py    GNU General Public License v3.0 5 votes vote down vote up
def _default(self, obj):
    return getattr(obj.__class__, "to_json", _default.default)(obj) 
Example 13
Project: Parallel.GAMIT   Author: demiangomez   File: pyDate.py    GNU General Public License v3.0 5 votes vote down vote up
def _default(self, obj):
    return getattr(obj.__class__, "to_json", _default.default)(obj) 
Example 14
Project: misp42splunk   Author: remg427   File: internals.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example 15
Project: misp42splunk   Author: remg427   File: internals.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example 16
Project: misp42splunk   Author: remg427   File: internals.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example 17
Project: SplunkVersionControl   Author: gjanders   File: internals.py    Apache License 2.0 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example 18
Project: eventsourcing   Author: johnbywater   File: transcoding.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default(self, obj):
        try:
            return encoder(obj)
        except EncoderTypeError:
            return JSONEncoder.default(self, obj) 
Example 19
Project: grand_central   Author: amiracle   File: internals.py    MIT License 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example 20
Project: SplunkForPCAP   Author: DanielSchwartz1   File: internals.py    MIT License 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example 21
Project: dopplerr   Author: gsemet   File: json.py    MIT License 5 votes vote down vote up
def default(self, obj):  # pylint: disable=arguments-differ,method-hidden
        if isinstance(obj, Enum):
            return obj.name
        return JSONEncoder.default(self, obj) 
Example 22
Project: TA-Send_to_HEC   Author: georgestarcher   File: internals.py    MIT License 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example 23
Project: SA-dmarc   Author: aholzel   File: internals.py    GNU General Public License v3.0 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example 24
Project: git_for_splunk   Author: ChrisYounger   File: internals.py    Apache License 2.0 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example 25
Project: git_for_splunk   Author: ChrisYounger   File: internals.py    Apache License 2.0 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example 26
Project: TA-esreplacefields   Author: georgestarcher   File: internals.py    MIT License 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example 27
Project: pybel   Author: pybel   File: make_json_serializable.py    MIT License 5 votes vote down vote up
def _default(self, obj):
    return getattr(obj.__class__, "to_json", _default.default)(obj) 
Example 28
Project: stone   Author: neuralsandwich   File: page.py    MIT License 5 votes vote down vote up
def default(self, o):
        if isinstance(o, Page):
            return o.to_entry()

        # When not a page, call the JSONEncoder. It will call the correct fail.
        return JSONEncoder.default(self, o) 
Example 29
Project: stone   Author: neuralsandwich   File: page.py    MIT License 5 votes vote down vote up
def get(self, key, default=None):
        try:
            return self.data[key]
        except KeyError:
            return default 
Example 30
Project: shadowsocksr   Author: quniu   File: json_util.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, (list, dict, str, int, float, bool, type(None))):
            return JSONEncoder.default(self, obj)
        if isinstance(obj, set):
            return list(obj) 
Example 31
Project: linkit   Author: dreipol   File: manager.py    MIT License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, models.Model):
            return obj.pk
        return JSONEncoder.default(self, obj) 
Example 32
Project: pyods   Author: klattimer   File: __init__.py    MIT License 5 votes vote down vote up
def _default(self, obj):
    if type(obj) == datetime.datetime:
        return obj.isoformat()
    try:
        out = getattr(obj.__class__, "serialise", _default.default)(obj)
    except:
        raise Exception("Cannot JSON Serialise object: " + obj.__class__.__name__)
    return out 
Example 33
Project: SA-ctf_scoreboard_admin   Author: splunk   File: internals.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example 34
Project: SplunkAdmins   Author: gjanders   File: internals.py    Apache License 2.0 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example 35
Project: flare   Author: mir-group   File: util.py    MIT License 5 votes vote down vote up
def default(self, obj):
        """
        """
        if isinstance(obj, (np.int_, np.intc, np.intp, np.int8,
                            np.int16, np.int32, np.int64, np.uint8,
                            np.uint16, np.uint32, np.uint64)):
            return int(obj)
        elif isinstance(obj, (np.float_, np.float16, np.float32,
                              np.float64)):
            return float(obj)
        elif isinstance(obj, (np.ndarray,)):
            return obj.tolist()
        return JSONEncoder.default(self, obj) 
Example 36
Project: TA-statemachine   Author: doksu   File: internals.py    Apache License 2.0 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example 37
Project: flowbber   Author: kuralabs   File: iso8601.py    Apache License 2.0 5 votes vote down vote up
def default(self, o):
        if isinstance(o, datetime):
            return datetime_to_iso8601(o)
        return JSONEncoder.default(self, o) 
Example 38
Project: TA-asngen   Author: doksu   File: internals.py    MIT License 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example 39
Project: aliyun-log-cli   Author: aliyun   File: cli_core.py    MIT License 5 votes vote down vote up
def configure_confidential(secure_id, secure_key, endpoint, client_name=LOG_CONFIG_SECTION, sts_token=None):
    """ configure confidential
    :type secure_id: string
    :param secure_id: secure id

    :type secure_key: string
    :param secure_key: secure key

    :type endpoint: string
    :param endpoint: endpoint

    :type client_name: string
    :param client_name: section name, default is "main"

    :type sts_token: string
    :param sts_token: sts token name, default is None

    :return:
    """

    config = configparser.ConfigParser()

    config.read(LOG_CREDS_FILENAME)

    if not config.has_section(client_name):
        config.add_section(client_name)

    config.set(client_name, 'access-id', secure_id)
    config.set(client_name, 'access-key', secure_key)
    config.set(client_name, 'region-endpoint', endpoint)
    config.set(client_name, 'sts-token', verify_sts_token(secure_id, sts_token))

    with open(LOG_CREDS_FILENAME, 'w') as configfile:
        config.write(configfile) 
Example 40
Project: aliyun-log-cli   Author: aliyun   File: cli_core.py    MIT License 5 votes vote down vote up
def get_encoder_cls(encodings):
    class NonUtf8Encoder(JSONEncoder):
        def default(self, obj):
            if isinstance(obj, six.binary_type):
                for encoding in encodings:
                    try:
                        return obj.decode(encoding)
                    except UnicodeDecodeError as ex:
                        pass
                return obj.decode('utf8', "ignore")

            return JSONEncoder.default(self, obj)

    return NonUtf8Encoder 
Example 41
Project: PyMISPWarningLists   Author: MISP   File: api.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, WarningList):
            return obj.to_dict()
        return JSONEncoder.default(self, obj) 
Example 42
Project: argos   Author: titusjan   File: abstractcti.py    GNU General Public License v3.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, AbstractCti):
            return obj.asJsonDict()
        else:
            return JSONEncoder.default(self, obj) 
Example 43
Project: argos   Author: titusjan   File: abstractcti.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, nodeName, defaultData, enabled=True, expanded=True):
        """ Constructor
            :param nodeName: name of this node (used to construct the node path).
            :param data: the configuration data. If omitted the defaultData will be used.
            :param defaultData: default data to which the data can be reset by the reset button.
            :param enabled: True if the item is enabled
            :param expanded: True if the item is expanded
        """
        super(AbstractCti, self).__init__(nodeName=nodeName)

        self._defaultData = self._enforceDataType(defaultData)
        self._data = self.defaultData
        self._enabled = enabled
        self._expanded = expanded
        self._blockRefresh = False 
Example 44
Project: argos   Author: titusjan   File: abstractcti.py    GNU General Public License v3.0 5 votes vote down vote up
def _closeResources(self):
        """ Can be overridden to close the underlying resources or disconnect signals.
            The default implementation does nothing.
            Is called by self.finalize when the cti is deleted. There is no corresponding
            _openResources; all resources are claimed in the constructor.
        """
        pass 
Example 45
Project: argos   Author: titusjan   File: abstractcti.py    GNU General Public License v3.0 5 votes vote down vote up
def _dataToString(self, data):
        """ Conversion function used to convert the (default)data to the display value.
        """
        return str(data) 
Example 46
Project: argos   Author: titusjan   File: abstractcti.py    GNU General Public License v3.0 5 votes vote down vote up
def displayDefaultValue(self):
        """ Returns the string representation of default data for use in the tree view.
        """
        return self._dataToString(self.defaultData) 
Example 47
Project: argos   Author: titusjan   File: abstractcti.py    GNU General Public License v3.0 5 votes vote down vote up
def defaultData(self):
        """ Returns the default data of this item.
        """
        return self._defaultData 
Example 48
Project: argos   Author: titusjan   File: abstractcti.py    GNU General Public License v3.0 5 votes vote down vote up
def defaultData(self, defaultData):
        """ Sets the data of this item.
            Does type conversion to ensure default data is always of the correct type.
        """
        # Descendants should convert the data to the desired type here
        self._defaultData = self._enforceDataType(defaultData) 
Example 49
Project: argos   Author: titusjan   File: abstractcti.py    GNU General Public License v3.0 5 votes vote down vote up
def resetToDefault(self, resetChildren=True):
        """ Resets the data to the default data. By default the children will be reset as well
        """
        self.data = self.defaultData
        if resetChildren:
            for child in self.childItems:
                child.resetToDefault(resetChildren=True) 
Example 50
Project: argos   Author: titusjan   File: abstractcti.py    GNU General Public License v3.0 5 votes vote down vote up
def _refreshNodeFromTarget(self):
        """ Refreshes the configuration from the target it monitors (if present).
            The default implementation does nothing; subclasses can override it.
            During updateTarget's execution refreshFromTarget is blocked to avoid loops.
            Typically called from inspector.drawTarget
        """
        pass 
Example 51
Project: argos   Author: titusjan   File: abstractcti.py    GNU General Public License v3.0 5 votes vote down vote up
def _updateTargetFromNode(self):
        """ Applies the configuration to the target it monitors (if present).
            The default implementation does nothing; subclasses can override it.
            During updateTarget's execution refreshFromTarget is blocked to avoid loops.
        """
        pass



    #################
    # serialization #
    ################# 
Example 52
Project: argos   Author: titusjan   File: abstractcti.py    GNU General Public License v3.0 5 votes vote down vote up
def resetEditorValue(self, checked=False):
        """ Resets the editor to the default value. Also resets the children.
        """
        # Block all signals to prevent duplicate inspector updates.
        # No need to restore, the editors will be deleted after the reset.
        for subEditor in self._subEditors:
            subEditor.blockSignals(True)

        self.cti.resetToDefault(resetChildren=True)
        # This will commit the children as well.
        self.setData(self.cti.defaultData)
        self.commitAndClose() 
Example 53
Project: EncryptedSession   Author: SaintFlipper   File: encrypted_session.py    GNU General Public License v3.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, bytes):
            return {
                '__type__' : 'bytes',
                'b' : base64.b64encode (obj).decode ()
            }   

        else:
            return JSONEncoder.default(self, obj) 
Example 54
Project: pastebin2misp   Author: renzejongman   File: abstract.py    MIT License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, AbstractMISP):
            return obj.jsonable()
        elif isinstance(obj, datetime.datetime):
            return obj.isoformat()
        return JSONEncoder.default(self, obj) 
Example 55
Project: pastebin2misp   Author: renzejongman   File: abstract.py    MIT License 5 votes vote down vote up
def from_dict(self, **kwargs):
        """Loading all the parameters as class properties, if they aren't `None`.
        This method aims to be called when all the properties requiring a special
        treatment are processed.
        Note: This method is used when you initialize an object with existing data so by default,
        the class is flaged as not edited."""
        for prop, value in kwargs.items():
            if value is None:
                continue
            setattr(self, prop, value)
        # We load an existing dictionary, marking it an not-edited
        self.__edited = False 
Example 56
Project: nmeta2   Author: mattjhayes   File: api.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, req, link, data, **config):
        super(RESTAPIController, self).__init__(req, link, data, **config)
        self.nmeta_parent_self = data[NMETA_INSTANCE]
        #*** Get the parent logger and log against that:
        self.logger = data[LOGGER]
        #*** Performance Note: this init gets run for every API call...
        #*** Update JSON to support UUID encoding:
        JSONEncoder_olddefault = JSONEncoder.default
        def JSONEncoder_newdefault(self, o):
            if isinstance(o, UUID):
                return str(o)
            return JSONEncoder_olddefault(self, o)
        JSONEncoder.default = JSONEncoder_newdefault 
Example 57
Project: PyMISPGalaxies   Author: MISP   File: api.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, Galaxy):
            return obj.to_dict()
        return JSONEncoder.default(self, obj) 
Example 58
Project: PyMISPGalaxies   Author: MISP   File: api.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, (Cluster, ClusterValue, ClusterValueMeta)):
            return obj.to_dict()
        return JSONEncoder.default(self, obj) 
Example 59
Project: aliyun-log-python-sdk   Author: aliyun   File: logclient_operator.py    MIT License 5 votes vote down vote up
def get_encoder_cls(encodings):
    class NonUtf8Encoder(JSONEncoder):
        def default(self, obj):
            if isinstance(obj, six.binary_type):
                for encoding in encodings:
                    try:
                        return obj.decode(encoding)
                    except UnicodeDecodeError as ex:
                        pass
                return obj.decode('utf8', "ignore")

            return JSONEncoder.default(self, obj)

    return NonUtf8Encoder 
Example 60
Project: TA-thehive   Author: remg427   File: internals.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example 61
Project: TA-thehive   Author: remg427   File: internals.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example 62
Project: tri.table   Author: TriOptima   File: doc_output.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, set):
            return list(obj)
        if obj is q_MISSING:
            return '<MISSING>'

        return JSONEncoder.default(self, obj) 
Example 63
Project: Coursera-Calendar   Author: abhishekgahlot   File: main.py    MIT License 5 votes vote down vote up
def default(self, obj, markers=None):

        try:
            if obj.__module__.startswith("icalendar.prop"):
                return (obj.to_ical())
        except AttributeError:
            pass

        if isinstance(obj, datetime):
            return (obj.now().strftime('%d-%m-%YT%H:%M:%S'))

        return JSONEncoder.default(self,obj) 
Example 64
Project: mysplunk_csc   Author: patel-bhavin   File: internals.py    Apache License 2.0 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example 65
Project: alexafsm   Author: allenai   File: make_json_serializable.py    Apache License 2.0 5 votes vote down vote up
def _default(self, obj):
    return getattr(obj.__class__, "to_json", _default.default)(obj) 
Example 66
Project: TA-intezer   Author: secops4thewin   File: internals.py    MIT License 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example 67
Project: TA-intezer   Author: secops4thewin   File: internals.py    MIT License 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example 68
Project: jsonplustypes   Author: sloev   File: __init__.py    MIT License 5 votes vote down vote up
def default(self, obj):
        try:
            key = str(type(obj).__name__)
            return _TYPE_FUNCS[ key ](obj)
        except KeyError, e:
            print "JSONPLUSTYPES:'key':{0} not found".format(key)
            return JSONEncoder.default(self, obj) 
Example 69
Project: tornado-alchemy-rest   Author: EzyInsights   File: encoders.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, timedelta):
            return {
                'seconds': obj.total_seconds(),
                }

        else:
            return JSONEncoder.default(self, obj) 
Example 70
Project: frankly-python   Author: franklyinc-public   File: util.py    MIT License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, datetime):
            return format_date(obj)

        if isinstance(obj, set):
            return list(obj)

        return BaseJsonEncoder.default(self, obj) 
Example 71
Project: catalyst   Author: enigmampc   File: serialization_utils.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, pd.Timestamp):
            return obj.strftime(DATE_TIME_FORMAT)

        # Let the base class default method raise the TypeError
        return JSONEncoder.default(self, obj) 
Example 72
Project: mozilla-schema-generator   Author: mozilla   File: schema.py    Mozilla Public License 2.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, Schema):
            return obj.schema
        if isinstance(obj, dict):
            return {k: self.default(v) for k, v in obj.items()}
        if isinstance(obj, list):
            return [self.default(v) for v in obj]
        return JSONEncoder.default(self, obj)


# TODO: s/Schema/JSONSchema 
Example 73
Project: TA-securitytrails   Author: secops4thewin   File: internals.py    MIT License 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example 74
Project: TA-securitytrails   Author: secops4thewin   File: internals.py    MIT License 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example 75
Project: porm   Author: DeeeFOX   File: utils.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        elif isinstance(obj, decimal.Decimal):
            return float(obj)
        elif isinstance(obj, time):
            return obj.strftime('%H:%M:%S')
        elif isinstance(obj, timedelta):
            sec = int(obj.total_seconds())
            return '{H:02d}:{M:02d}:{S:02d}'.format(H=int(sec / 3600), M=int(sec / 24 % 60), S=sec % 60)
        else:
            return JSONEncoder.default(self, obj) 
Example 76
Project: pyuniprot   Author: cebel   File: make_json_serializable.py    Apache License 2.0 5 votes vote down vote up
def _default(self, obj):
    return getattr(obj.__class__, "to_json", _default.default)(obj) 
Example 77
Project: eventsourcing   Author: johnbywater   File: transcoding.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def decoderpolicy(arg=None):
    """
    Decorator for decoder policy.

    Allows default behaviour to be built up from methods
    registered for different named keys, rather than
    chain of "in dict" queries in a long if-else block.
    """

    def _mutator(func):
        wrapped = func

        decoder_map = {}

        @wraps(wrapped)
        def wrapper(*args, **kwargs):

            d = kwargs.get("d") or args[-1]
            keys = list(d.keys())

            if len(keys) == 1:
                try:
                    decoder_func = decoder_map[keys[0]]
                except KeyError:
                    return d
                else:
                    return decoder_func(d)
            else:
                return d

        def register(key):
            def decorator(decoder_func):
                decoder_map[key] = decoder_func
                return decoder_func

            return decorator

        wrapper.register = register

        return wrapper

    assert isfunction(arg), arg
    return _mutator(arg) 
Example 78
Project: argos   Author: titusjan   File: abstractcti.py    GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, cti, delegate, subEditors=None, parent=None):
        """ Wraps the child widgets in a horizontal layout and appends a reset button.

            Maintains a reference to the ConfigTreeItem (cti) and to delegate, this last reference
            is so that we can command the delegate to commit and close the editor.

            The subEditors must be a list of QWidgets. Note that the sub editors do not yet have
            to be initialized with editor data since setData will be called by the delegate
            after construction. There it can be taken care of.
        """
        super(AbstractCtiEditor, self).__init__(parent=parent)

        # Prevent underlying table cell from being visible if the editor doesn't fill the cell
        self.setAutoFillBackground(True)

        self._subEditors = []
        self.delegate = delegate
        self.cti = cti

        # From the QAbstractItemDelegate.createEditor docs: The returned editor widget should have
        # Qt.StrongFocus; otherwise, QMouseEvents received by the widget will propagate to the view.
        # The view's background will shine through unless the editor paints its own background
        # (e.g., with setAutoFillBackground()).
        self.setFocusPolicy(Qt.StrongFocus)

        self.hBoxLayout = QtWidgets.QHBoxLayout()
        self.hBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.hBoxLayout.setSpacing(0)
        self.setLayout(self.hBoxLayout)

        self.resetButton = QtWidgets.QToolButton()
        self.resetButton.setText("Reset")
        self.resetButton.setToolTip("Reset to default value.")
        self.resetButton.setIcon(QtGui.QIcon(os.path.join(icons_directory(), 'reset-l.svg')))
        self.resetButton.setFocusPolicy(Qt.NoFocus)
        self.resetButton.clicked.connect(self.resetEditorValue)
        self.hBoxLayout.addWidget(self.resetButton, alignment=Qt.AlignRight)

        self.cti.model.sigItemChanged.connect(self.modelItemChanged)

        for subEditor in (subEditors if subEditors is not None else []):
            self.addSubEditor(subEditor) 
Example 79
Project: EncryptedSession   Author: SaintFlipper   File: encrypted_session.py    GNU General Public License v3.0 4 votes vote down vote up
def open_session(self, app, request):
        '''
        @param py: Flask py
        @param request: Flask HTTP Request
        @summary: Sets the current session from the request's session cooke. This overrides the default
        Flask implementation, adding AES decryption of the client-side session cookie.
        '''

        # Get the session cookie
        session_cookie = request.cookies.get(app.session_cookie_name)
        if not session_cookie:
            return self.session_class()

        # Get the crypto key
        crypto_key = app.config['SESSION_CRYPTO_KEY'] if 'SESSION_CRYPTO_KEY' in app.config else app.crypto_key

        # Split the session cookie : <z|u>.<base64 cipher text>.<base64 mac>.<base64 nonce>
        itup = session_cookie.split(".")
        if (len (itup) is not 4):
            return self.session_class()     # Session cookie not in the right format

        try:

            # Compressed data?
            if (itup[0] == 'z'):            # session cookie for compressed data starts with "z."
                is_compressed = True
            else:
                is_compressed = False

            # Decode the cookie parts from base64
            ciphertext = base64.b64decode (bytes(itup[1], 'utf-8'))
            mac = base64.b64decode (bytes(itup[2], 'utf-8'))
            nonce = base64.b64decode (bytes(itup[3], 'utf-8'))

            # Decrypt
            cipher = AES.new (crypto_key, AES.MODE_EAX, nonce)
            data = cipher.decrypt_and_verify (ciphertext, mac)

            # Convert back to a dict and pass that onto the session
            if is_compressed:
                data = zlib.decompress (data)
            session_dict = json.loads (str (data, 'utf-8'), cls=BinaryAwareJSONDecoder)

            return self.session_class (session_dict)

        except ValueError:
            return self.session_class() 
Example 80
Project: EncryptedSession   Author: SaintFlipper   File: encrypted_session.py    GNU General Public License v3.0 4 votes vote down vote up
def save_session(self, app, session, response):
        '''
        @param py: Flask py
        @param session: Flask / Werkzeug Session
        @param response: Flask HTTP Response
        @summary: Saves the current session. This overrides the default Flask implementation, adding
        AES encryption of the client-side session cookie.
        '''

        domain = self.get_cookie_domain(app)
        if not session:
            if session.modified:
                response.delete_cookie (app.session_cookie_name, domain=domain)
            return
        expires = self.get_expiration_time(app, session)

        # Decide whether to compress
        bdict = bytes (json.dumps (dict (session), cls=BinaryAwareJSONEncoder), 'utf-8')
        if (len (bdict) > self.compress_threshold):
            prefix = "z"                                    # session cookie for compressed data starts with "z."
            bdict = zlib.compress (bdict)
        else:
            prefix = "u"                                    # session cookie for uncompressed data starts with "u."

        # Get the crypto key
        crypto_key = app.config['SESSION_CRYPTO_KEY'] if 'SESSION_CRYPTO_KEY' in app.config else app.crypto_key

        # Encrypt using AES in EAX mode
        cipher = AES.new (crypto_key, AES.MODE_EAX)
        ciphertext, mac = cipher.encrypt_and_digest (bdict)
        nonce = cipher.nonce

        # Convert the ciphertext, mac, and nonce to base64
        b64_ciphertext = base64.b64encode (ciphertext)
        b64_mac = base64.b64encode (mac)
        b64_nonce = base64.b64encode (nonce)

        # Create the session cookie as <u|z>.<base64 cipher text>.<base64 mac>.<base64 nonce>
        tup = [prefix, b64_ciphertext.decode(), b64_mac.decode(), b64_nonce.decode()]
        session_cookie = ".".join(tup)

        # Set the session cookie
        response.set_cookie(app.session_cookie_name, session_cookie,
                            expires=expires, httponly=True,
                            domain=domain)