danglingfarpointer's memoization

仕事周りでの気付き、メモ、愚痴などを書いていきます。

PythonのrequestsでmultipartでPOST

PythonのHTTP clientとしてrequestsという便利なライブラリがあります。それをつかってMultipartデータをPOSTするメモです。

参考: http://stackoverflow.com/questions/12385179/how-to-send-a-multipart-form-data-with-requests-in-python

POSTするデータは、(ファイル名, データ, Content-Type)あるいは(ファイル名, データ, Content-Type, ヘッダー)というタプルで与えます。

クライアントからname, email, imageを送信する例です。

>>> import requests
>>> r = requests.post("http://localhost:8080/add", files = {
     "name": ("", "hoge", "text/plain; charset=UTF-8"),
     "email": ("", "hoge@example.com", "plain/text; charset=UTF-8"),
     "image": ("hoge.png", open('hoge.png', 'rb'), "image/png")
     })

サーバー側での受信結果。ファイル名を空にすると、multipartの各要素のfilenameプロパティが与えられません。

--0a3d87b93d8c468b9b4dc7a493fbeee3
Content-Disposition: form-data; name="image"; filename="hoge.png"
Content-Type: image/png

..................<image data>.............................
--0a3d87b93d8c468b9b4dc7a493fbeee3
Content-Disposition: form-data; name="name"
Content-Type: text/plain; charset=UTF-8

hoge
--0a3d87b93d8c468b9b4dc7a493fbeee3
Content-Disposition: form-data; name="email"
Content-Type: plain/text; charset=UTF-8

hoge@example.com
--0a3d87b93d8c468b9b4dc7a493fbeee3--