解决Python向阿里云OSS上传文件时报错400

如题,该问题并不是100%出现。出错时服务器返回信息如下:

<?xml version="1.0" encoding="UTF-8"?>
<Error>
  <Code>InvalidArgument</Code>
  <Message>The bucket POST must contain the specified 'key'. If it is specified, please check the order of the fields</Message>
  <RequestId>C21E709A5EC76E5ED07C0D43</RequestId>
  <HostId>oss.example.com</HostId>
  <ArgumentName>key</ArgumentName>
  <ArgumentValue></ArgumentValue>
</Error>

官网文档对 The bucket POST must contain the specified ‘key’. If it is specified, please check the order of the fields 解释如下:

那么问题就明确了:由于在POST时使用了字典,其中的顺序并不是固定的。当key键排在file键后面时错误便会出现。解决方法也很简单,使用collections.OrderedDict。它是有序字典,可以明确键值对的添加顺序:

import collections

content  = collections.OrderedDict()
content ['key'] = 'file_key'
...
content ['file'] = your_file

这样提交之后键值的顺序便会固定,不再出现上述问题。

上一篇
下一篇