Redis:是否有可能在php / laravel和python之间直接共享日期时间?

时间:2018-05-02 16:01:41

标签: php python laravel redis phpredis

我正在使用Redis(phpredis)在我的Laravel和我的Python应用程序之间共享数据。

在Laravel中,我将特定通道保存在我的数组中:

$data = MyModel::where('start_date','>', "2018-05-02 10:00:00")->get();

// $data = [{'id':1, 'start_date': "2018-05-03 12:00:00", 'name': "}…]

Redis::set("barChannel", json_encode($data));

在Python中,我读了这些数据:

import redis
import json

myredis = redis.Redis()

data = json.loads(myredis.get('barChannel'));
// data = [{'id':1, 'start_date': "2018-05-03 12:00:00", 'name': "}…]

所以基本上数据传递成功但是我的python列表中没有直接datetime值,我有一个string我必须转换。通过上面的例子,我可以使用datetime.datetime.strptime但是在更复杂的数据结构(dicts的嵌套列表)的情况下......转换每个变量都非常痛苦。

有没有办法在Redis中存储日期时间,这可以在Python中被原生识别?

2 个答案:

答案 0 :(得分:1)

在经过一些研究之后,您不会知道Redis仅将其值存储在字符串表示中,因此您唯一的选择是存储序列化数据并在需要时反序列化。

从以下开始:

答案 1 :(得分:0)

上述问题的最新消息。关于使用json模块的两篇优秀帖子解决了我从redis导入深层嵌套日期时间(并将其导出回来)的问题:

How to convert to a Python datetime object with JSON.loads?(进口)

def date_hook(json_dict):
    for (key, value) in json_dict.items():
        try:
            json_dict[key] = datetime.datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
        except:
            pass
    return json_dict

data = json.loads(myredis.get('barChannel'), object_hook=date_hook)

How to overcome "datetime.datetime not JSON serializable"?(出口)

def json_serial(obj):
    """JSON serializer for objects not serializable by default json code"""

    if isinstance(obj, (datetime, date)):
        return obj.strftime('%Y-%m-%d %H:%M:%S')
    raise TypeError ("Type %s not serializable" % type(obj))

json_values = json.dumps(data, default=json_serial, separators=(',', ':'))
myredis.publish('barChannel', json_values);