0

我有一个我编写的应用程序,它从我使用的数据库服务下载文件,然后将文件转换为另一种格式并重新上传。问题在于上传。我正在使用补丁请求,它完成没有错误,但文件从未真正上传。

这是我的代码:

    for person in r['records']:
    try:
        # Get Voicemail and handle conversion if necessary
        vm = person['fields']['Voicemail'][0]['url']
        if '.m4a' in vm:
            vm_name = person['fields']['Voicemail'][0]['filename'].replace('.m4a', '').replace(' ', '')

            # Download file to local machine and convert to .mp3
            r = requests.get(vm, allow_redirects=True)
            open('{}.m4a'.format(vm_name), 'wb').write(r.content)
            bash = 'ffmpeg {0}.mp3 -i {0}.m4a -codec:a libmp3lame -qscale:a 1'.format(vm_name)
            os.system(bash)

            s = requests.Session()
            s.mount('file://', FileAdapter())
            cwd = os.getcwd()
            # url = s.get('file:///{}/{}.mp3'.format(cwd, vm_name))

            # Upload/delete files to server
            r = requests.patch('https://api.airtable.com/v0/{}/People/{}'.format(base_id, person['id']), 
                        json={"fields": {"Voicemail": [{"url": 'file:///{}/{}.mp3'.format(cwd, vm_name)}]}}, 
                        headers={"Authorization": "Bearer {}".format(at_auth), "Content-type": "application/Json"})

            print(r.text)

            # Delete temporary local files
            os.remove('{}.mp3'.format(vm_name))
            os.remove('{}.m4a'.format(vm_name))

...以及的回应r.text

{"id":"recnlJBNEWFMLwYNh","fields":{"Name":"Matthew Sewell","Phone":["reciInRjmNpyTabUS"],"Voicemail":[{"id":"att7YiG4s0Epa3V6o","url":"file:////Users/test/Dropbox/python/projects/business/testing123.mp3","filename":"testing123.mp3"}]},"createdTime":"2018-08-09T00:59:35.000Z"}

我对补丁请求不是很熟悉,因此感谢您的帮助。

4

1 回答 1

0

从另一个答案中无耻地复制粘贴(我标记了这个问题)。这是您可以使用请求上传数据的方式。无论您使用 GET、POST、PATCH 还是其他方式都没有关系:

如果upload_file要成为文件,请使用:

files = {'upload_file': open('file.txt','rb')}
values = {'DB': 'photcat', 'OUT': 'csv', 'SHORT': 'short'}

r = requests.post(url, files=files, data=values)

并将requests发送一个多部分表单 POST 正文,其中 upload_file 字段设置为file.txt文件的内容。

原来的so帖子在这里

于 2018-08-09T02:04:39.987 回答