且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用请求库从 url 上传 Python 文件

更新时间:2023-02-23 20:28:04

执行此操作的唯一方法是下载 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…