我有一个编写的应用程序,该应用程序从使用的数据库服务中下载文件,然后将文件转换为另一种格式并重新上传。问题出在上传上。我正在使用补丁程序请求,它已完成且没有错误,但是文件从未真正上传过。
这是我的代码:
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"}
我对补丁请求不是很熟悉,因此可以提供任何帮助。
答案 0 :(得分: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
文件的内容。
原始帖子是here