httpPost Example
This example demonstrates how to allow Ignition to receive data from an external source. It uses a button to send JSON data through an httpPost command and a Python Resource in the Web Dev module to receive the post and do something with the data. This button example is for testing purposes only, the common use-case for posting data is to use another program to post data.
Open the Designer and right-click on the Web Dev object in the Project Browser. Select New Python Resource.
Name the Python resource postjson.
Select the doPost HTTP method from the dropdown in the upper left.
Select the Enabled option.
Copy this code into the doPost function:
postjson Python Resource (Web Dev Section)# take in some JSON data and print it
# expecting 'names' and 'values' that are of the same length
# get the incoming parameters
data = request['postData']
names = data['names']
values = data['values']
# this will print to the wrapper.log file
print names, values
# format the string into HTML
formattedString = "<html><body>"
# loop through and add names and values
for i in range(len(names)):
formattedString += "%s: %s, " %(names[i], values[i])
# remove the last ', ' and add closing html
formattedString = formattedString[:-2]+"</body></html>"
# this will print to the wrapper.log file
print formattedString
# return the value string
return {'html': formattedString}Create a button on a window to test the above code. Copy the code below into your button. Make sure to change the ProjectName variable to the name of your project. If you used any name other than "postjson" for step 1, change the doPostName variable as well.
Call Web Service (Button component on a window)# post data to the web service in a json format
# this allows you to use the 'postData' object in the Python Resource
# create url to post to
projectName = "MyProject"
doPostName = "postjson"
url = "http://localhost:8088/main/system/webdev/%s/%s" %(projectName, doPostName)
# create the dictionary of parameters to pass in
params = {}
params['names'] = ['String','Integer']
params['values'] = ['Hello World', 42]
# encode dictionary to JSON
jsonParams = system.util.jsonEncode(params)
# post to Ignition
postReturn = system.net.httpPost(url,'application/json',jsonParams)
# print return value
print postReturnNow test your button. Make sure to open the console to see the print out, or the wrapper.log file to see any errors caused by the doPost function.