Python相当于curl用于从文件发布数据

时间:2012-12-20 11:07:58

标签: python curl

我正在寻找下面的curl命令的Python等价物。

curl http://localhost/x/y/update -H 'Content-type: text/xml; charset=utf-8' --data-binary @filename.xml

顺便说一下,我通常使用下面的代码将数据发布为字符串。

curl http://localhost/x/y/update --data '<data>the data is here</data>' -H 'Content-type:text/xml; charset=utf-8'

baseurl = http://localhost/x/y
thedata = '<data>the data is here</data>'

headers = {"Content-type": "text/xml", "charset": "utf-8"}
thequery = urlparse.urljoin(baseurl, thedata, querycontext)
therequest = urllib2.Request(thequery, headers)
theresponse = urllib2.urlopen(therequest)

4 个答案:

答案 0 :(得分:4)

Python requests这是一个很棒的库。你有什么可以简单地完成:

import requests

headers = {'content-type': 'text/xml; charset=utf-8'}
response = requests.post(url, data="<data>the data is here</data>", headers=headers)
fd = open("filename.xml", "w")
fd.write(response.text)
fd.close()

pycurl和python的一些其他url和http客户端库的问题在于它需要比实现相对简单的事情所需的更多努力。 requests它的方式更加用户友好,我认为你正在寻找这个问题。

希望这有帮助

答案 1 :(得分:1)

问题在于上传文件,而被接受的答案只是保存文件

在正确的代码下面:

import requests

 # Here you set the file you want to upload and it's content type 
files = {'upload_file': ('filename.xml', open('filename.xml','rb'), 'text/xml' }

headers = {} # Do not set content type here, let the library do its job

response = requests.post(url, 
              data="<data>the data is here</data>", 
              files=files,
              headers=headers)
fd = open("output-response.txt", "w")
fd.write(response.text)
fd.close()

上面的代码将从filename.xml中读取文件并通过POST上传,然后还将收到的响应存储到output-response.txt

答案 2 :(得分:0)

查看名为pycurl

的curl的python包装器

它实际上被广泛使用,因此有很多关于如何在互联网上使用图书馆的例子。

如果您刚刚开始,那么可能值得查看angry objects website

答案 3 :(得分:0)

使用名为Requests的漂亮的python模块 它可以执行90%的curl选项,而且它也可以在Windows上编译而无需编译。

https://github.com/kennethreitz/requests

与curl,urrlib,urrlib2或httplib,httplib2相比,它非常简单......:)