gpt4 book ai didi

python - 使用 Python-Requests 库发布文本文件

转载 作者:行者123 更新时间:2023-11-28 22:03:54 25 4
gpt4 key购买 nike

您好,我在使用 Python 请求库 (http://docs.python-requests.org/en/latest/index.html) 发布文本文件时遇到问题,您能告诉我我做错了什么吗?

我尝试搜索相关问题并找到了这个 Send file using POST from a Python script但它没有回答我的问题。

这是我的代码:

import codecs
import requests

# Create a text file
savedTextFile = codecs.open('mytextfile.txt', 'w', 'UTF-8')

# Add some text to it
savedTextFile.write("line one text for example\n and line two text for example")

# Post the file THIS IS WHERE I GET REALLY TRIPPED UP
myPostRequest = requests.post("https://someURL.com", files=savedTextFile)

我已经尝试了上面的一些变体,但我没有得到任何结果(每次都有新错误)。如何发布我刚刚创建的这个 txt 文件?我尝试发布到的 API 需要向其发布一个文本文件。

感谢任何帮助!

最佳答案

files 参数需要一个与文件处理程序匹配的文件名字典。这在源代码(当前第 69 行)中有描述:

Github Source (requests/models.py)

#: Dictionary of files to multipart upload (``{filename: content}``).
self.files = files

有时最好的文档就是代码。

您的最后一行应如下所示:

myPostRequest = requests.post("https://someURL.com", files={'mytextfile.txt': savedTextFile})

关于python - 使用 Python-Requests 库发布文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8107177/

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