如何使用 Python 请求 post 形式作为 curl PUT -F

How to use Python requests to post form as curl PUT -F

我正在尝试使用 Python 的请求复制 curl PUT -F "file=@someFile" 的使用。 我需要使用的 Content-Type 是:multipart/form-data 我尝试了不同的变体,例如:

r = requests.put(url, headers=headers, files={'file': (full_filename, open(full_filename, 'rb'), content_type)}, verify=False, stream=True)

r = requests.put(url, headers=headers, data={'file': (full_filename, open(full_filename, 'rb'), content_type)}, verify=False, stream=True)

r = requests.put(url, headers=headers, params={'file': (full_filename, open(full_filename, 'rb'), content_type)}, verify=False, stream=True)

在我尝试过的所有方法中,我的 headers 中都有 'Content-Type': 'multipart/form-data'

但对于以上所有内容,我得到 400 作为回应。

我看到一些关于 Whosebug 的问题,但是 none 的答案回答了我的问题,所以我打开一个新的。

感谢 我设法解决了这个问题。我在这里引用他的回答是因为我觉得它非常重要:

You should NEVER set that header yourself. We set the header properly with the boundary. If you set that header, we won't and your server won't know what boundary to expect (since it is added to the header). Remove your custom Content-Type header and you'll be fine.

我喜欢 Requests,但这对我来说是一个非常混乱的实现部分。