使用请求库从 url 上传 Python 文件 [英] Python file upload from url using requests library

查看:33
本文介绍了使用请求库从 url 上传 Python 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将文件上传到 url.我要上传的文件不在我的电脑上,但我有文件的 url.我想使用请求库上传它.所以,我想做这样的事情:

I want to upload a file to an url. The file I want to upload is not on my computer, but I have the url of the file. I want to upload it using requests library. So, I want to do something like this:

url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)

但是,唯一的区别是,report.xls 文件来自一些不在我电脑中的网址.

But, only difference is, the file report.xls comes from some url which is not in my computer.

推荐答案

执行此操作的唯一方法是下载 URL 的正文,以便您可以上传它.

The only way to do this is to download the body of the URL so you can upload it.

问题是采用 file 的表单需要 HTTP POST 中的文件正文.有人可以编写一个接受 URL 的表单,并自行获取……但这将是一种与接受文件的表单和请求不同的表单和请求(或者,也许,相同的表单),带有可选文件和可选 URL).

The problem is that a form that takes a file is expecting the body of the file in the HTTP POST. Someone could write a form that takes a URL instead, and does the fetching on its own… but that would be a different form and request than the one that takes a file (or, maybe, the same form, with an optional file and an optional URL).

当然,您不必下载并将其保存到文件.您可以将其下载到内存中:

You don't have to download it and save it to a file, of course. You can just download it into memory:

urlsrc = 'http://example.com/source'
rsrc = requests.get(urlsrc)
urldst = 'http://example.com/dest'
rdst = requests.post(urldst, files={'file': rsrc.content})

当然,在某些情况下,您可能总是希望沿文件名或其他一些标题(例如 Content-Type)进行转发.或者,对于大文件,您可能希望从一台服务器流式传输到另一台服务器,而无需下载然后立即上传整个文件.您必须手动执行任何此类操作,但使用 requests 几乎所有事情都很简单,并且在文档中进行了很好的解释.*

Of course in some cases, you might always want to forward along the filename, or some other headers, like the Content-Type. Or, for huge files, you might want to stream from one server to the other without downloading and then uploading the whole file at once. You'll have to do any such things manually, but almost everything is easy with requests, and explained well in the docs.*

* 嗯,最后一个例子不是很简单……你必须从请求中取出原始套接字包装器,然后readwrite,并确保你没有死锁,等等......

* Well, that last example isn't quite easy… you have to get the raw socket-wrappers off the requests and read and write, and make sure you don't deadlock, and so on…

这篇关于使用请求库从 url 上传 Python 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆