4

以下の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

4 に答える 4

5

Pythonは、この種のもののための優れたライブラリを要求します。あなたが持っていることは、次の方法で簡単に行うことができます。

import requests

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

pycurlとPython用の他のURLおよびhttpクライアントライブラリの問題は、比較的単純なものを実現するために必要なものよりも多くの労力を必要とすることです。よりユーザーフレンドリーな方法を要求し、私はあなたがこの問題で探しているものだと思います。

お役に立てれば

于 2012-12-20T11:23:18.243 に答える
2

質問はファイルのアップロードに関するものですが、受け入れられた答えはファイルに保存するだけでした!

正しいコードの下:

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()

上記のコードは、POSTからファイルを読み取り、 POST経由でアップロードしてから、受信した応答filename.xmlにも保存し ます。output-response.txt

于 2019-04-03T15:30:41.373 に答える
0

pycurlと呼ばれるcurlのPythonラッパーをチェックしてください

それは本当に広く使われているので、インターネット上で図書館をどのように利用するかについての多くの例があります。

あなたが始めたばかりなら、それは怒っているオブジェクトのウェブサイトを見る価値があるかもしれません。

于 2012-12-20T11:15:51.860 に答える
0

Requestsと呼ばれる美しいPythonモジュールを使用します。curlオプションの90%を実行でき、さらにWindowsでコンパイルしなくても機能します。

https://github.com/kennethreitz/requests

curl、urrlib、urrlib2、またはhttplib、httplib2...:)と比較して非常に簡単です。

于 2012-12-20T11:22:26.963 に答える