Python请求发布clyp.it上传文件

时间:2014-09-10 08:18:04

标签: python post python-requests

我正在尝试将音频文件上传到clyp.it网络服务。这里描述了api:http://clyp.it/api。相关摘录:

Uploads are done via a multipart/form-data POST. Consider the following form: 
<form action="http://upload.clyp.it/upload" enctype="multipart/form-data" method="post"> 
    <input type="file" name="audioFile"> 
    <input type="submit" value="Send to Clyp"> 
</form> 

It will create a request that looks like this: 
POST http://upload.clyp.it/upload HTTP/1.1 
Host: upload.clyp.it 
Connection: keep-alive 
Content-Type: multipart/form-data; boundary=---------------------------21632794128452 
Content-Length: 5005 
-----------------------------21632794128452 
Content-Disposition: form-data; name="audioFile"; filename="MyAudioFile.mp3" 
Content-Type: audio/mpeg 
(Audio file data goes here)

我可以通过创建一个带有上面表单块的html文件来上传文件。我希望能够通过python上传这个文件。我一直试图使用&#39;请求&#39;模块(http://docs.python-requests.org/en/latest/

我试过这个:

clyp_file_upload_url = 'https://upload.clyp.it/upload'
music_mp3 = open('/home/jinal/Downloads/music.mp3', 'rb')
send_files = {'audioFile':music_mp3}
r = requests.post(clyp_file_upload_url, files=send_files)
print(r.status_code)

返回通用500错误。我怀疑我没有正确构建帖子请求。我该怎么办?

2 个答案:

答案 0 :(得分:3)

您需要将Content-Type字典参数中每个上传文件的files设置为requests.post(),即

clyp_file_upload_url = 'http://upload.clyp.it/upload'
music_mp3 = open('/home/jinal/Downloads/music.mp3', 'rb')
send_files = {'audioFile': ('music.mp3', music_mp3, 'audio/mpeg')}
r = requests.post(clyp_file_upload_url, files=send_files)
print(r.status_code)

>>> from pprint import pprint
>>> pprint(r.json())
{u'AudioFileId': u'5jahwd0y',
 u'Description': u'#Me #TestOfMp3File #Other',
 u'Duration': 12.408,
 u'Latitude': None,
 u'Longitude': None,
 u'Message': None,
 u'Mp3Url': u'http://a.clyp.it/5jahwd0y.mp3',
 u'OggUrl': u'http://a.clyp.it/5jahwd0y.ogg',
 u'PlaylistId': u'0kpvbr1j',
 u'PlaylistUploadToken': u'd5ec65e0e197d5fe45e7b18371a2e1f0',
 u'SecureMp3Url': u'https://s3.amazonaws.com/a.clyp.it/5jahwd0y.mp3',
 u'SecureOggUrl': u'https://s3.amazonaws.com/a.clyp.it/5jahwd0y.ogg',
 u'Successful': True,
 u'Title': u'Me - Test of MP3 File',
 u'Url': u'http://clyp.it/5jahwd0y'}
  • 请注意,URI方案应为http,而不是https

答案 1 :(得分:1)

看起来有关他们方面的请求格式的一些假设。我猜错误可能是由于缺少文件名造成的。尝试:

send_files = {'audioFile': ('music.mp3', music_mp3)}

看看它是否解决了你的问题。