【问题标题】:Is it possible to post audio files with the python requests library是否可以使用 python 请求库发布音频文件
【发布时间】:2014-10-10 07:35:24
【问题描述】:

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

【问题讨论】:

    标签: python rest python-requests


    【解决方案1】:

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

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

    实际上,requests 文档中的first multipart-encoded file example 发布了一个二进制文件:

    >>> url = 'http://httpbin.org/post'
    >>> files = {'file': open('report.xls', 'rb')}
    
    >>> r = requests.post(url, files=files)
    >>> r.text
    {
      ...
      "files": {
        "file": "<censored...binary...data>"
      },
      ...
    }
    

    【讨论】:

    • 好像第一个例子中files={'fieldname', fobj}应该是files={'fieldname': fobj}。否则会出现ValueError: too many values to unpack (expected 2) 错误。
    • @Lane:很好看,是的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-01
    • 2017-08-31
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多