我已经获得了以下curl命令作为API文档的一部分,我正在尝试使用请求库来实现它。
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编码器不太喜欢这个,我不确定是否可以解决这个问题。< / p>
答案 0 :(得分: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 User-Agent: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-continue 内容类型:multipart / form-data; 边界= ---------------------------- e71aebf115cd
------------------------------ e71aebf115cd Content-Disposition:form-data; NAME = “斑〔照片]”; filename =“file.txt”内容类型: 文本/纯
一些文字。 ------------------------------ e71aebf115cd Content-Disposition:form-data; NAME = “斑点[描述]”
spot_description ------------------------------ e71aebf115cd -
正如您所见,curl发送请求Content-Type
设置为multipart/form-data;
请求support使用相同的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--