gpt4 book ai didi

python - 如何在不写入磁盘的情况下使用 Python-Requests 上传文本文件

转载 作者:太空狗 更新时间:2023-10-29 21:31:21 29 4
gpt4 key购买 nike

我想在 Python 3 中使用 Python 的 Requests 库在 POST 请求中发送一个文件。我正在尝试像这样发送它:

import requests

file_content = 'This is the text of the file to upload'

r = requests.post('http://endpoint',
params = {
'token': 'api_token',
'message': 'message text',
},
files = {'filename': file_content},
)

但是,服务器响应没有发送任何文件。这应该工作吗?大多数示例涉及传递一个文件对象,但我不想为了上传它而将字符串写出到磁盘。

最佳答案

requests docs向我们提供:

If you want, you can send strings to be received as files:

>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}

>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "some,data,to,send\\nanother,row,to,send\\n"
},
...
}

我将其作为另一个答案发布,因为它涉及不同的方法。

关于python - 如何在不写入磁盘的情况下使用 Python-Requests 上传文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29779986/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com