【问题标题】:Redis : is it possible to share datetimes directly between php/laravel and python?Redis:是否可以直接在 php/laravel 和 python 之间共享日期时间?
【发布时间】:2018-10-12 19:35:25
【问题描述】:

我正在使用 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,但是在更复杂的数据结构(嵌套的dict列表)的情况下......转换每个变量非常痛苦。

有没有办法在 Redis 中存储可以在 Python 中本机识别的日期时间?

【问题讨论】:

    标签: php python laravel redis phpredis


    【解决方案1】:

    不,经过很少的研究,您会知道,Redis 仅以字符串表示形式存储其值,因此您唯一的选择是存储序列化数据并在需要时取消序列化。

    从以下开始:

    【讨论】:

    • 我读过关于不可知数据格式的文章,但由于我对整数没有同样的问题,我想知道。
    【解决方案2】:

    关于上述问题的更新。关于使用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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-13
      • 2015-11-28
      • 2010-10-24
      • 2011-06-25
      • 1970-01-01
      相关资源
      最近更新 更多