2

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

我尝试搜索相关问题,并使用 Python 脚本中的 POST 找到了这个发送文件,但它没有回答我的问题。

这是我的代码:

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 需要发布一个文本文件。

任何帮助表示赞赏!

4

1 回答 1

5

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

Github 源 (requests/models.py)

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

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

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

myPostRequest = requests.post("https://someURL.com", files={'mytextfile.txt': savedTextFile})
于 2011-11-12T20:12:43.987 回答