1

作为 API 文档的一部分,我得到了以下 curl 命令,我正在尝试使用 requests 库来实现它。

curl -v --cookie cookie.txt -X POST -H 'Accept: application/json' -F 'spot[photo]'=@rails.png -F 'spot[description]'=spot_description -F 'spot[location_id]'=9  -F 'spot[categories][]'='See the Sights' -F 'spot[categories][]'='Learn Something' http://some.server.com/api/v1/spots

我的 python 代码看起来像这样:

import requests
import json

_user = 'redacted'
_password = 'redacted'
_session = requests.session()
_server = 'http://some.server.com'

_hdr = {'content-type': 'application/json', 'accept': 'application/json'}

_login_payload = {
    'user': {
        'email': _user,
        'password': _password
    }
}
r = _session.post(_server + "/users/sign_in", data=json.dumps(_login_payload), headers=_hdr)
print json.loads(r.content)

_spot_payload = {
    'spot': {
        'photo': '@rails.gif',
        'description': 'asdfghjkl',
        'location_id': 9,
        'categories': ['See the Sights',]
    }
}
r = _session.post(_server + '/api/v1/spots', data=json.dumps(_spot_payload), headers=_hdr)
print json.loads(r.content)

我听说你可以使用 open('file').read() 来发布文件,但是 json 编码器不太喜欢这样,我不确定是否有解决方法。

4

1 回答 1

3
C:\>cat file.txt
Some text.

当您发出此命令时:

C:\>curl -X POST -H "Accept:application/json" -F "spot[photo]=@file.txt"
-F "spot[description]=spot_description" http://localhost:8888

发送的内容如下所示:

POST / HTTP/1.1 用户代理:curl/7.25.0 (i386-pc-win32) libcurl/7.25.0 OpenSSL/0.9.8u zlib/1.2.6 libssh2/1.4.0 主机:localhost:8888 接受:application/ json 内容长度:325 预期:100 继续内容类型:multipart/form-data;边界=----------------------------e71aebf115cd

------------------------------e71aebf115cd 内容处置:表单数据;名称=“地点[照片]”;filename="file.txt" 内容类型:文本/纯文本

一些文字。------------------------------e71aebf115cd 内容处置:表单数据;名称=“地点[描述]”

spot_description ------------------e71aebf115cd--

如您所见, curl 发送Content-Type设置为multipart/form-data;Requests的请求支持使用相同的Content-Type. 您应该files为此使用参数。

(2.7) C:\>python
Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> requests.__version__
'0.11.1'
>>> requests.post('http://localhost:8888', files={'spot[photo]': open('file.txt', 'rb')}, data={'spot[description]': 'spot_description'})
<Response [200]>

发送的内容如下所示:

POST http://localhost:8888/ HTTP/1.1
Host: localhost:8888
Content-Length: 342
Content-Type: multipart/form-data; boundary=192.168.1.101.1.8000.1334865122.004.1
Accept-Encoding: identity, deflate, compress, gzip
Accept: */*
User-Agent: python-requests/0.11.1

--192.168.1.101.1.8000.1334865122.004.1
Content-Disposition: form-data; name="spot[description]"
Content-Type: text/plain

spot_description
--192.168.1.101.1.8000.1334865122.004.1
Content-Disposition: form-data; name="spot[photo]"; filename="file.txt"
Content-Type: text/plain

Some text.
--192.168.1.101.1.8000.1334865122.004.1--
于 2012-04-19T19:59:33.133 回答