首页 > python > 是否可以使用python请求库发布音频文件

是否可以使用python请求库发布音频文件 (Is it possible to post audio files with the python requests library)

问题

我正在考虑使用Python Requests库将mp3 发布到api,但是文档中发布文件的所有示例都是针对文本文件的。是否可以将此库用于音频?

解决方法

是的,可以使用库发送任何字节序列:

with open(audiofile, 'rb') as fobj:
    requests.post(url, files={'fieldname', fobj})

事实上,第一多部分编码的文件例如requests文档的帖子的二进制文件:

>>> url = 'http://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}

>>> r = requests.post(url, files=files)
>>> r.text
{
  ...
  "files": {
    "file": "<censored...binary...data>"
  },
  ...
}

问题

I'm considering using the Python Requests library to post mp3s to an api, but all the examples of posting files in the documentation are for text files. Is it possible to use this library for audio?

解决方法

Yes, it is possible to send any sequence of bytes with the library:

with open(audiofile, 'rb') as fobj:
    requests.post(url, files={'fieldname', fobj})

In fact, the first multipart-encoded file example in the requests documentation posts a binary file:

>>> url = 'http://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}

>>> r = requests.post(url, files=files)
>>> r.text
{
  ...
  "files": {
    "file": "<censored...binary...data>"
  },
  ...
}
相似信息