问题描述
我正在尝试使用Python 3.7使用文件上传POST操作(“ https://api.podio.com/file/”)将文件上传到Podio。请在下面找到有关代码的详细信息。
# File Upload
fin = open(input_path,'rb')
files = {'source': ('report.txt',fin,'text/plain')}
uploadResponse = requests.post(POdio_BASE_URL + "file/",files=files,headers=bearerHeader)
执行此操作时出现以下错误:-
File upload reponse: {'error_parameters': {},'error_detail': None,'error_propagate': False,'request': {'url': 'http://api.podio.com/file/','query_string': '','method': 'POST'},'error_description': 'Invalid value null (null): must be non empty string','error': 'invalid_value'}
请在下面找到我使用prepare方法捕获的发帖请求(我有意从下面的代码段中删除了承载值)。
req.prepare()
<PreparedRequest [POST]>
special variables:
function variables:
body: b'--5e83f2bb93a03c8b128f6158c00863c4\r\nContent-disposition: form-data; name="source"; filename="report.txt"\r\n\r\ntesting\r\n--5e83f2bb93a03c8b128f6158c00863c4--\r\n'
headers: {'Authorization': 'Bearer ','Content-Length': '155','Content-Type': 'multipart/form-data; boundary=5e83f2bb93a03c8b128f6158c00863c4'}
hooks: {'response': []}
method: 'POST'
path_url: '/file/'
url: 'https://api.podio.com/file/'
_body_position: None
_cookies: <RequestsCookieJar[]>
_encode_files: <function RequestEncodingMixin._encode_files at 0x0000018437560E18>
_encode_params: <function RequestEncodingMixin._encode_params at 0x0000018437560D90>
_get_idna_encoded_host: <function PreparedRequest._get_idna_encoded_host at 0x000001843756C488>
任何对此的指点将不胜感激。预先感谢您的帮助。
解决方法
您可以尝试
filename = 'report.txt'
data = {
'source': open(filename,'rb').read(),'filename': filename
}
headers = bearerHeader
headers['Content-Type'] = 'multipart/form-data'
uploadResponse = requests.post(
PODIO_BASE_URL + "file/",data=data,headers=headers,timeout=1200
)
,
Podio API doc for file upload说它需要两个参数和requests handles it with the files
parameter。
我建议尝试一下:
filename = 'report.txt'
multipart_form_data = {
'source': (filename,open(filename,'rb')),'filename': (filename,None)
}
uploadResponse = requests.post(
PODIO_BASE_URL + "file/",files=multipart_form_data,headers=bearerHeader,timeout=1200
)
,
我在这个问题上停留了一段时间,只有500个神秘的错误可以使用。最终,我将发送给pypodio2
的原始HTTP请求与发送的内容进行了比较,并确定Content-Type
请求的一部分缺少multipart/form-data
。以下内容对我有用(client.access_token
是我的OAuth2令牌,client.base_url
是我的域,file_path
是文本文件的本地路径)。希望这对某人有帮助。
headers = { "authorization": f"OAuth2 {client.access_token}" }
files = {
"source": (file_path,open(file_path,'rb'),"text/plain; charset=utf-8"),"filename": (None,"my_file.txt","text/plain; charset=utf-8")
}
response = requests.post(f"{client.base_url}/file",files=files)