Using Python-Requests Library to Post a Text File

和自甴很熟 提交于 2019-12-22 13:31:15

问题


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?

I tried searching for related questions and found this Send file using POST from a Python script but it doesn't answer my question.

Here's my code:

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)

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.

Any help is appreciated!


回答1:


The files parameter expects a dict of a filename matching to a file-handler. This is described in the source code (currently line 69):

Github Source (requests/models.py)

#: 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})


来源:https://stackoverflow.com/questions/8107177/using-python-requests-library-to-post-a-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!