【python脚本】获取OneNET数据写入本地文件

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pip install prettytable
import time
import urllib.request as req
import json
import os

# 设备ID、Key
# ESP-12F
deviceId = "1047311396"
APIKey = "z0Yq8d3P16l2SbEwuZcXZu=CidM="

# 上传函数
def OneNet_post_data(info):
    url = "https://api.heclouds.com/devices/" + info[0] + '/datapoints'
    headers = {'api-key': info[1]}
    streams = []
    for i, e in enumerate(info[2]):
        streams.append({"id": e[0], "datapoints": [{"value": e[1]}]})
    data = json.dumps({"datastreams": streams}).encode("utf-8")
    request = json.loads((req.urlopen(req.Request(url, data, headers=headers))).read())
    print(request)

# 获取函数
def OneNet_get_data(info):
    url = "http://api.heclouds.com/devices/" + info[0] + "/datastreams"
    headers = {'api-key': info[1]}
    request = json.loads((req.urlopen(req.Request(url, headers=headers))).read())
    data = request.pop('data')
    print(request)
    return data


if __name__ == '__main__':
    # 准备待上传数据
    upload_data = [
        ["road1", 10],
        ["road2", 20],
        ["road3", 30],
        ["road4", 40],
        ["road5", 50],
        ["road6", 60],
        ["road7", 70],
        ["road8", 80],
        ["road9", 90],
        ["road10", 100],
        ["road11", 110],
        ["road12", 120],
    ]
    # 上传数据
    # OneNet_post_data([deviceId, APIKey, upload_data])
    # 获取数据

    while(1):
        print('=' * 100)
        time.sleep(5)
        get_data = OneNet_get_data([deviceId, APIKey])
        # print(get_data)
        # noinspection PyBroadException
        try:
            # 使用表格美化显示数据
            import prettytable as pt

            tb = pt.PrettyTable()
            tb.field_names = ["id", "update_at", "current_value"]
            for index, element in enumerate(get_data):
                ID = str(element.get('id', ''))
                update_at = str(element.get('update_at', ''))
                current_value = str(element.get('current_value', ''))
                tb.add_row([ID, update_at, current_value])
            print(tb)
        except Exception:
            # 直接显示数据
            data_stream = []
            for index, element in enumerate(get_data):
                ID = str(element.get('id', ''))
                update_at = str(element.get('update_at', ''))
                current_value = str(element.get('current_value', ''))
                # print(ID, update_at, current_value)
                data_dict = {}
                data_dict['ID'] = ID
                data_dict['update_at'] = update_at
                data_dict['current_value'] = current_value
                # print(data_dict)
                data_stream.append(data_dict)

            # print(data_stream)

            with open('data.txt', 'a+', newline='\n') as file:
                # json.dump(data_stream, file, indent=4)
                file.write(str(data_stream)+'\n')

参考资料

Python上传、获取OneNet数据
将字典数据循环保存为本地JSON文件 (python)

你可能感兴趣的:(python,开发语言)