convert an ajax http post to python

痞子三分冷 提交于 2020-01-06 03:33:07

问题


I want to send some data to a server using Python.

I have a working piece of code from jQuery which does what I want:

$.ajax({
    type: "POST",
    contentType: "text/plain",
    url: "http://192.168.50.88/emoncms/nodes/1/tx/values",
    data: "17,58,5,1569,0,3000,236"
});

I need to do the same thing in Python but I can't see how to do it. Here's what I've got at the moment:

import httplib, urllib
newdata = "17,58, 5,1569, 0, 3000, 236"
headers = {"Content-type": "text/plain"}
conn = httplib.HTTPConnection("192.168.50.88")
conn.request("POST", "/emoncms/nodes/1/tx/values", newdata)
response = conn.getresponse()
print response.status, response.reason
conn.close()

This prints: "200 OK" so the basic post is working but my data doesn't reach the server.

Can anyone point me in the right direction?


回答1:


Use requests instead.

import requests
requests.post(
    'http://192.168.50.88/emoncms/nodes/1/tx/values',
    data='17,58, 5,1569, 0, 3000, 236',
    headers={'content-type': 'text/plain'}
)

you can also store the response by doing this...

r = requests.post(...)

and then you can access the response code, any attached data, headers etc from that r variable.

http://docs.python-requests.org/en/latest/




回答2:


So to answer my own question - The problem is the particular target I'm trying to send data to, an energy logging program running on a raspberry pi, needs an api key before it will accept the data.

If anyone's interested the equipment is detailed on http://openenergymonitor.org/

Thanks to atlspin for much clearer code than my own.



来源:https://stackoverflow.com/questions/31614243/convert-an-ajax-http-post-to-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!