使用Python-Requests库发布文本文件 [英] Using Python-Requests Library to Post a Text File
问题描述
我在使用Python请求库发布文本文件时遇到了麻烦( http://docs.python-requests.org/en/latest/index.html ),您能告诉我我做错了什么吗?
Hi I'm having trouble posting a text file using the Python Requests Library ( http://docs.python-requests.org/en/latest/index.html ), can you let me know what I'm doing wrong?
我尝试搜索相关问题,并发现此使用POST发送文件来自Python脚本,但无法回答我的问题.
I tried searching for related questions and found this Send file using POST from a Python script but it doesn't answer my question.
这是我的代码:
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需要将文本文件发布到其中.
I've tried a few variations on the above and I'm not getting anywhere (new error every time). How do I post this txt file that I just created? The API I'm trying to post to requires a text file to be posted to it.
感谢您的帮助!
推荐答案
files参数需要一个与文件处理程序匹配的文件名字典.在源代码中对此进行了描述(当前为第69行):
The files parameter expects a dict of a filename matching to a file-handler. This is described in the source code (currently line 69):
#: Dictionary of files to multipart upload (``{filename: content}``).
self.files = files
有时最好的文档是代码.
Sometimes the best documentation is the code.
您的最后一行应如下所示:
Your last line should look like the following:
myPostRequest = requests.post("https://someURL.com", files={'mytextfile.txt': savedTextFile})
这篇关于使用Python-Requests库发布文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!