【问题标题】:Mulitpart POST requests in Python without filenamePython中没有文件名的多部分POST请求
【发布时间】:2019-02-19 15:51:32
【问题描述】:

我希望从 python API 发送以下类型的 POST 请求:

------WebKitFormBoundarykQ0pCUTfUvTIocvw
Content-Disposition: form-data; name="filename"

SSF_nY4PQT8190207X10Showtest.gz
------WebKitFormBoundarykQ0pCUTfUvTIocvw--

请注意,SSF_nY4PQT8190207X10test.gz 不是我要发送的文件。我要求服务器对此文件执行一些操作。

按照下面的链接,我尝试通过t = s.post(url, headers=headers, files = {'filename': ('', 'content')}, verify=False) 做到这一点

Multipart POST using python requests

https://github.com/requests/requests/issues/935

但是得到这个标题

--63fb60c0045e41439442713330f821ce
Content-Disposition: form-data; name="filename"; filename=""

content
--63fb60c0045e41439442713330f821ce--

如何在我的请求中去掉filename=""

提前感谢您的帮助

【问题讨论】:

  • 您是否尝试过将None 作为文件名传递?不确定这是否可行
  • 这成功了 :) 非常感谢.. 在这上面卡了一个多小时
  • 您能否将其作为答案发送,以便我将其标记为已解决

标签: python python-2.7 python-requests


【解决方案1】:

试着用这个脚本玩一局:

#!/usr/bin/env python3

from requests import Request, Session

s = Session()
files={'filename': 'content'}
url="http://localhost"
req = Request('POST',  url, files=files)

prepped = s.prepare_request(req)
print(prepped.body)

但无论我做什么,Content_Disposition 总是有 Content-Disposition: form-data; name=""; filename="" 参数。

所以我查看了请求源:https://github.com/requests/requests/blob/master/requests/models.py#L165,它把我引向了 Urllib3 https://github.com/urllib3/urllib3/blob/master/src/urllib3/fields.py#L174 ,即使您提供空字符串,这些参数似乎也将始终存在。没有办法覆盖它们。

编辑
来自上述任一 cmets:

#!/usr/bin/env python3

from requests import Request, Session

s = Session()
files={'filename': (None,'content')}
url="http://localhost"
req = Request('POST',  url, files=files)

prepped = s.prepare_request(req)
print(prepped.body)

【讨论】:

  • Mikhail Burshteyn 关于使用 None 代替空字符串的建议对我来说效果很好。考虑此线程已回答并已完成 :) 感谢您的帮助
猜你喜欢
  • 2014-06-01
  • 2020-04-25
  • 1970-01-01
  • 2016-06-13
  • 2013-11-26
  • 1970-01-01
  • 2023-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多