【问题标题】:Retrieving data from my sql and sending it to a web service using python从我的 sql 中检索数据并使用 python 将其发送到 Web 服务
【发布时间】:2017-08-18 03:19:37
【问题描述】:

我正在尝试从 Raspberry Pi 2 中的 MySQL 检索数据,并使用 python 将该数据发布到 Web 服务。我可以使用 python 脚本从树莓派中的 MySQL 检索数据。但是,当我尝试将数据值传递给它时,我无法使用单独的 python 脚本将数据发布到 Web 服务。有人会告诉我我做错了什么吗?还是有其他方法可以做到这一点?

在 Raspberry Pi 中从 MySQL 检索数据的 Python 代码 (fetchdata.py):

import MySQLdb
import sys
import subprocess

db = MySQLdb.connect("localhost", "root", "1234", "tempdata")
cursor = db.cursor()
sql = "SELECT * FROM webdata"

cursor.execute(sql)
results = cursor.fetchall()
for row in results:
    ID = row[0]
    ChannelID = row[1]
    TimeStamp = row[2]
    RMSVoltage = row[3]

print "ID=%s, ChannelID=%s, TimeStamp=%s, RMSVoltage=%s" % (ID, ChannelID, TimeStamp, RMSVoltage)

db.close()

我得到的输出如下:

ID=4,ChannelID=43,TimeStamp=56,RMSVoltage=78

这是我发布到网络服务的 python 代码(sendjson.py):

import sys
import json
import pprint
import requests
import subprocess
import fetchdata #name of python script that retrieves data from MySQL in RPi

url = 'http://192.168.1.101/TestWebsite/api/SecondlyReadingDatas'
query = {'ID': 'fetchdata.ID, 'ChannelID': fetchdata.ChannelID, 'TimeStamp': fetchdata.TimeStamp', 'RMSVoltage': 'fetchdata.RMSVoltage'}

headers = {'Content-Type': 'application/json'}
r = requests.post(url, headers=headers, data=json.dumps(query))
print(r.text)

这是我得到的输出:

ID=4, ChannelID=43,TimeStamp=56, RMSVoltage=78

{"Message":请求是 无效。","ModelState":{"secondlyReading.ID"["出现错误 发生了。"]", secondlyReading.ChannelID"["发生了错误。"], "secondlyReading.TimeStamp"["发生错误。"], "secondlyReading.RMSVoltage"["发生错误。"]}}

谁能告诉我我做错了什么?我的网络服务没有收到任何新数据。

【问题讨论】:

  • 您的query 字典无效,引号错误。
  • 什么意思? @stovfl
  • 'fetchdata.ID 以单个' 开头,还有其他的。
  • 所以我需要添加缺少的 ' ,这就是你的意思吗?@stovfl

标签: python mysql web-services raspberry-pi2


【解决方案1】:

问题:所以我需要添加缺少的'

,删除不添加!
你的dict 应该是这样的,我删除了 4 '!

query = {'ID': fetchdata.ID, 'ChannelID': fetchdata.ChannelID, 'TimeStamp': fetchdata.TimeStamp, 'RMSVoltage': fetchdata.RMSVoltage}

How to use dictionaries in Python
关于 Python 中的字典 使用 {} 大括号来构造字典,使用 [] 方括号来索引它。
在每对之间用冒号 : 和逗号分隔键和值。
必须引用键

【讨论】:

    猜你喜欢
    • 2020-12-11
    • 2013-11-03
    • 1970-01-01
    • 2012-03-16
    • 1970-01-01
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多