Last active
October 6, 2020 22:30
-
-
Save ranaroussi/90268aca3bf438d1aabfdb918288c6a9 to your computer and use it in GitHub Desktop.
Redison - extension for redis to get/set json objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# | |
# Redison - an extension for redis to get/set json objects | |
# https://gist.github.com/ranaroussi/90268aca3bf438d1aabfdb918288c6a9/edit | |
# | |
# Copyright 2020 Ran Aroussi | |
# | |
# Licensed under the Apache License, Version 2.0 (the "License"); | |
# you may not use this file except in compliance with the License. | |
# You may obtain a copy of the License at | |
# | |
# http://www.apache.org/licenses/LICENSE-2.0 | |
# | |
# Unless required by applicable law or agreed to in writing, software | |
# distributed under the License is distributed on an "AS IS" BASIS, | |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
# See the License for the specific language governing permissions and | |
# limitations under the License. | |
# | |
import redis | |
import json | |
from datetime import datetime, date | |
from decimal import Decimal | |
def _json_formatter(obj): | |
if isinstance(obj, datetime) or isinstance(obj, date): | |
return obj.isoformat() | |
elif isinstance(obj, Decimal) or isinstance(obj, float): | |
return str(obj) | |
else: | |
return None | |
json_formatter = lambda obj: _json_formatter(obj) | |
class Redison(redis.Redis): | |
""" | |
Usage: | |
cache = redison.Redison.from_url(REDIS_CONN_STR, decode_responses=True) | |
# Set a key | |
# cache.set_json("key", myjson[, **kwargs]) | |
myjson = {"foo": "bar"} | |
cache.set_json("key", myjson, ex=86400) # 24hrs expiry | |
# Get a key: | |
myjson = cache.get_json("key") | |
print(">>", myjson.get("foo")) | |
""" | |
def get_json(self, key): | |
data = self.get(key) | |
if not data: | |
return {} | |
return json.loads(data) | |
def set_json(self, key, data, **kwargs): | |
out = json.dumps( | |
data, default=json_formatter) | |
self.set(key, out, **kwargs) | |
return out |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment