我正在尝试将数据从python实时传输到Power Bi中。但是我遇到了错误
TypeError:“字节”类型的对象不可JSON序列化
我将代码放在下面,请指出我做错了什么,因为我不太了解问题所在。
import pandas as pd
from datetime import datetime
from datetime import timedelta
import requests
import json
import time
import random
# function for data_generation
def data_generation():
surr_id = random.randint(1, 3)
speed = random.randint(20, 200)
date = datetime.today().strftime("%Y-%m-%d")
time = datetime.now().isoformat()
return [surr_id, speed, date, time]
if __name__ == '__main__':
REST_API_URL = 'https://api.powerbi.com/beta/513294a0-3e20-41b2-a970-6d30bf1546fa/datasets/f9e99f4c-a928-4599-8551-569997994c1c/rows?key=pbw8cHmVzC9EYGFhyXiFrMlrlIGPhQdqms3CednMDq4d%2BygPOwpxD%2BeqzT9vQVF7sJLEwgACfsIq2v7JtRzVdg%3D%3D'
while True:
data_raw = []
for j in range(1):
row = data_generation()
data_raw.append(row)
print("Raw data - ", data_raw)
# set the header record
HEADER = ["surr_id", "speed", "date", "time"]
data_df = pd.DataFrame(data_raw, columns=HEADER)
data_json = bytes(data_df.to_json(orient='records'), encoding='utf-8')
print("JSON dataset", data_json)
# Post the data on the Power BI API
try:
req = requests.post(REST_API_URL, data=json.dumps(
data_json), headers=HEADER, timeout=5)
print("Data posted in Power BI API")
except requests.exceptions.ConnectionError as e:
req = "No response"
print(req)
time.sleep(3)
答案 0 :(得分:0)
已解决,只需将req = requests.post(REST_API_URL, data=json.dumps(data_json), headers=HEADER, timeout=5)
更改为req = requests.post(url=REST_API_URL, data=data_json)