将POST消息中的数据发送到RESTful Web服务

时间:2011-08-18 18:17:54

标签: python web-services rest

我需要在POST消息中将一些JSON数据发送到RESTful Web服务。

我应该使用哪个python模块?我可以参考一些示例代码吗?

3 个答案:

答案 0 :(得分:3)

你有哪些麻烦? JSON,还是POST?

对于JSON,自2.5版以来,json模块已包含在Python中。只需执行json.dumps(my_data)即可将数据变量转换为JSON。

对于POST,标准库中有各种模块,但最好的办法是安装第三方requests库。

答案 1 :(得分:0)

这是我用于发布和获取请求的内容

import httplib
connection =  httplib.HTTPConnection('192.168.38.38:6543')
body_content = 'abcd123456xyz'
connection.request('POST', '/foo/bar/baa.html', body_content)
postResult = connection.getresponse()

connection.request('GET', '/foo/bar/baa.html')
response = connection.getresponse()
getResult = response.read()

它与CLI命令序列相同:

curl -X POST -d "abcd123456xyz" 192.168.38.38:6543/foo/bar/baa.html
curl 192.168.38.38:6543/foo/bar/baa.html

答案 2 :(得分:0)

请求可能是最好的工作库。它肯定胜过urllib和urllib2。您可以在http://pypi.python.org/pypi/requests查看示例并查看示例 或者您可以使用“pip install requests”安装它

还有一些使用Github API的示例,包括请求库和其他https://github.com/issackelly/Consuming-Web-APIs-with-Python-Talk