【发布时间】:2026-02-12 15:05:02
【问题描述】:
在 Python 的 requests documentation 中,它建议像这样发送多部分表单数据:
Requests 让上传多部分编码文件变得简单:
>>> url = 'http://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}
>>> r = requests.post(url, files=files)
This question 显示相同的行为。但是,同一作者的this question 使用了with 声明:
with open('data','rb') as payload:
headers = {'content-type': 'application/x-www-form-urlencoded'}
r = requests.post('https://IP_ADDRESS/rest/rest/2', auth=('userid', 'password'),
data=payload, verify=False, headers=headers)
我的直觉是在使用文件时我应该始终使用with 语句;在这种情况下我是否需要它?更清楚地说,我不是寻求关于是否使用 with 的建议。我特别指的是与requests 库的交互,如果我可以像文档暗示的那样省略with 语句。
【问题讨论】:
-
我认为使用
with是一种自动关闭您在with-statement 中打开的连接的方法。你也可以不使用with,但是你需要明确地关闭连接,比如payload.close()。我想。 -
@downvoter 愿意发表评论吗?
-
@Ares 我不是反对者,但那个人可能会这样做,因为这是一个基于意见的问题。
-
@TylerH 我应该澄清一下;我问的是请求和
with之间的交互,不是在寻求意见。
标签: python python-requests with-statement