Skip to content

Error caching datetime - Object is not JSON serializable #3231

Closed
@jaraco

Description

@jaraco

Today, I wished to cache a datetime (the last time I queried http://ifconfig.co because they throttle to .016Hz). When I tried to store the datetime in the cache, I ran into this error:

tests/test_main.py:37: in throttle_ifconfig
    request.config.cache.set('last ifconfig', datetime.datetime.now())
.tox/python/lib/python3.6/site-packages/_pytest/cacheprovider.py:98: in set
    json.dump(value, f, indent=2, sort_keys=True)
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py:179: in dump
    for chunk in iterable:
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py:437: in _iterencode
    o = _default(o)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <json.encoder.JSONEncoder object at 0x10d3a3438>
o = datetime.datetime(2018, 2, 16, 10, 34, 3, 50186)

    def default(self, o):
        """Implement this method in a subclass such that it returns
            a serializable object for ``o``, or calls the base implementation
            (to raise a ``TypeError``).
    
            For example, to support arbitrary iterators, you could
            implement default like this::
    
                def default(self, o):
                    try:
                        iterable = iter(o)
                    except TypeError:
                        pass
                    else:
                        return list(iterable)
                    # Let the base class default method raise the TypeError
                    return JSONEncoder.default(self, o)
    
            """
        raise TypeError("Object of type '%s' is not JSON serializable" %
>                       o.__class__.__name__)
E       TypeError: Object of type 'datetime' is not JSON serializable

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py:180: TypeError

Obviously, the current behavior expects that only JSON-serializable types are allowed in the cache, which is rather limiting. It would be nice if the cache module allowed for hooks to encode/decode values to allowable JSON.

Metadata

Metadata

Assignees

No one assigned

    Labels

    plugin: cacherelated to the cache builtin plugintype: enhancementnew feature or API change, should be merged into features branch

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions