I am trying to retrieve data from MySQL in Raspberry Pi 2 and posting that data to a web service using python . I am able to retrieve data from MySQL within the raspberry pi using a python script. However, I am having trouble posting the data to a web service using a separate python script when I try to I try to pass the data values to it. Would anyone tell me what I am doing wrong? Or is there another way that I can do this?
Python code to retrieve data from MySQL in Raspberry Pi(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()
The output that I get is the following:
ID=4, ChannelID=43, TimeStamp=56, RMSVoltage=78
Here is my python code for posting to the web service(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)
This is the output I am getting:
ID=4, ChannelID=43,TimeStamp=56, RMSVoltage=78
{"Message":The request is invalid.","ModelState":{"secondlyReading.ID"["An error has occured."]", secondlyReading.ChannelID"["An error has occured."], "secondlyReading.TimeStamp"["An error has occured."], "secondlyReading.RMSVoltage"["An error has occured."]}}
Could anyone tell me what I did wrong? I am not getting any new data on my web service.
Question : So I need to add the missing
'
?
No , removing not adding!
Your dict
should look like this, I removed 4 '
!
query = {'ID': fetchdata.ID, 'ChannelID': fetchdata.ChannelID, 'TimeStamp': fetchdata.TimeStamp, 'RMSVoltage': fetchdata.RMSVoltage}
How to use dictionaries in Python
About dictionaries in Python Use {} curly brackets to construct the dictionary, and [] square brackets to index it.
Separate the key and value with colons : and with commas , between each pair.
Keys must be quoted
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.