用于gviz api的持续日期时间值

问题描述 投票:0回答:1

我有一个python应用程序,它从MQTT代理收集数据,并通过gviz python API将其呈现给网站:


DESCRIPTION= [      \
              ('Zeit', 'datetime'),     \
              ('Temperatur', 'number'),  \
              ('Feuchtigkeit', 'number'),\
              ('Batterie', 'number')    \
              ]

def sendAnswer(conn):
#protect against the data supplier
    Mutex.acquire()
    Trans = deepcopy(DatArr)
    Mutex.release()
#create and populate the DataTable    
    data_table = gviz_api.DataTable(DESCRIPTION)
    data_table.LoadData(Trans)
    Answer = data_table.ToJSon()
#send ti to the webserver
    lng = len(Answer)
    try:
        conn.sendall(bytes("L{:06d};".format(lng),"UTF-8"))
        conn.sendall(bytes(Answer,"UTF-8"))
    except BaseException:
        # if anything goes wrong, try again next time
        pass

def on_message(client, userdata, message):
    global Last, DatArr
#get the data from the broker
    cur = json.loads(str(message.payload, encoding='utf-8'))
    if cur == Last and len(DatArr)>2 : return
    now = datetime.now()
# protect against the webserver
    Mutex.acquire()
#add the data
    DatArr.append([now, cur["temp"], cur["hum"], cur["bat"]])
#cleanup old values
    Last = cur
    for i in range(len(DatArr)):
        if now - DatArr[0][0] > timedelta(days=1): 
            DatArr.pop(0) 
        else:
            break
    Mutex.release()

这有效,但是我不想将数据保留在python变量中,而是希望将其保存在文件中(最好是JSON)。但是我不能JSON.dump()一个datetime变量,也不能.LoadData()一个字符串到gviz DataTable中。 python gviz也缺少“ addRow()”。有什么建议吗?

非常感谢!

python json google-visualization
1个回答
0
投票

基于此问题的答案:JSON datetime between Python and JavaScript我找到了一个解决方案,并在python模块中实现了它:

import json
import datetime

class DateTimeJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return dict(nested_datetime=obj.isoformat())
        else:
            return super(DateTimeJSONEncoder, self).default(obj)

def datetime_decoder(d):
    if len(d) == 1 and 'nested_datetime' in d: 
        return datetime.datetime.strptime(d['nested_datetime'], '%Y-%m-%dT%H:%M:%S.%f')
    result = {}
    for prop in d:
        if isinstance(d[prop], dict):
            result[prop] = datetime_decoder(d[prop])
        else:
            result[prop] = d[prop]
    return result

类和函数作为命名参数进入像这样的json.dump和json.load函数:

 DatArr = json.load(DatFile, object_hook=djson.datetime_decoder)

json.dump(DatArr, DatFile, cls=djson.DateTimeJSONEncoder)

这将以前的全局变量DatArr保留在json文件DatFile中。感谢上述问题的所有发布者提供的信息。

© www.soinside.com 2019 - 2024. All rights reserved.